diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/cpu_event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/cpu_event.h new file mode 100644 index 0000000000000000000000000000000000000000..e7caaf8a932ab4e37a58d9fdf94ac39b148d7bb0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/cpu_event.h @@ -0,0 +1,31 @@ +/* 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_RUNTIME_CPU_EVENT_H_ +#define XLA_RUNTIME_CPU_EVENT_H_ + +namespace xla { +namespace runtime { + +// Typical use case: AsyncValueRef is used to indicate the +// completion of a CPU operation, e.g., data transfer or running a program. +struct CpuEvent { + CpuEvent() = default; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_CPU_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call.h new file mode 100644 index 0000000000000000000000000000000000000000..bb4038217c92a82d095d5d80bbd897a88babc771 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call.h @@ -0,0 +1,1893 @@ +/* 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_RUNTIME_CUSTOM_CALL_H_ +#define XLA_RUNTIME_CUSTOM_CALL_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/dynamic_annotations.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "Eigen/Core" // from @eigen_archive +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringExtras.h" +#include "xla/primitive_util.h" +#include "xla/runtime/async_runtime.h" +#include "xla/runtime/diagnostics.h" +#include "xla/runtime/errors.h" +#include "xla/runtime/ffi/ffi_abi.h" +#include "xla/runtime/logical_result.h" +#include "xla/runtime/map_by_type.h" +#include "xla/runtime/memref_view.h" +#include "xla/runtime/state.h" +#include "xla/runtime/type_id.h" +#include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime +#include "tfrt/concurrency/chain.h" // from @tf_runtime + +namespace xla { +namespace runtime { + +// Forward declare. +struct ExecutionContext; + +// Forward declare template defined below. +template +class CustomCallBinding; + +// Registers mappings from TypeIDs supported by the custom calls to their unique +// names in the given registry. +void PopulateCustomCallTypeIdNames(TypeIDNameRegistry& registry); + +// A type tag to declare MLIR TypeID specializations for types passed to the +// custom calls. We don't want to declare specializations for scalar types +// directly in this translation unit, so we rely on a tag to wrap them. +// +// See explicit TypeID declarations at the end of this file. +template +struct Tagged {}; + +class CustomCall { + public: + // Container for passing data between XLA user and the custom call handler. + using UserData = PtrMapByType; + + // A type for matching all remaining custom call arguments. + class RemainingArgs; + + // A type for passing an argument of different types at the same position, + // and the handler will do the decoding. + class VariantArg; + class VariantAttr; + + // A type for representing tensors with shapes. + template + struct TensorRef { + absl::Span shape; + absl::Span data; + }; + + // An ordinal of a function exported from executable. + struct FunctionOrdinal { + unsigned ordinal; + }; + + // Custom call handler can check arguments and attributes types and names + // at runtime, however this comes at extra cost and can be optionally + // disabled. If the version of the compiler that generated the XLA executable + // doesn't match the custom call handler, it can lead to undefined behavior. + enum class RuntimeChecks : uint8_t { + // Check arguments and attributes types, also check attribute names. It is + // safe to pass extra attributes (if `exact_attrs` is false) to the custom + // call when name checking is enabled, because it will safely skip + // irrelevant attributes. + kDefault = 0, + + // Check only the types of the arguments and attributes. At this check level + // custom calls never check the names of the attributes because it can be + // too expensive, however type checking should prevent catastrophic + // segfaults. This is the recommended checks level in optimized builds. + kLess = 1, + + // Do not check the number of arguments and attributes and their types, and + // do not check that the user data was passed to the custom call. This is + // the most dangerous option, because it blindly reinterprets opaque memory + // passed to the handler, and can easily lead to segfaults if the data + // doesn't match the expected custom call signature. + kNone = 2 + }; + + struct Options { + // Check that attributes passed at run time exactly match the attributes + // defined by the custom call binding. If `false` then custom call handler + // will happily ignore any additional attributes passed at run time. It is + // unsafe to disable run-time checks for custom calls that support non-exact + // attributes, as the custom call handler uses pre-computed attributes + // offsets based on the binding specification. + bool exact_attrs = true; + }; + + static constexpr bool CheckNames(RuntimeChecks checks) { + return checks == RuntimeChecks::kDefault; + } + + static constexpr bool CheckTypes(RuntimeChecks checks) { + return checks != RuntimeChecks::kNone; + } + + static constexpr bool CheckUserData(RuntimeChecks checks) { + return checks != RuntimeChecks::kNone; + } + + template + static bool Isa(RuntimeChecks checks, TypeID type_id) { + return !CheckTypes(checks) || type_id == TypeID::get>(); + } + + template + static bool Isa(RuntimeChecks checks, TypeID type_id) { + return !CheckTypes(checks) || type_id == TypeID::get>() || + Isa(checks, type_id); + } + + virtual ~CustomCall() = default; + + virtual std::string_view name() const = 0; + virtual LogicalResult call(void** args, void** attrs, void** rets, + const UserData* user_data, + const DiagnosticEngine* diagnostic) const = 0; + + static CustomCallBinding<> Bind(std::string callee); + static CustomCallBinding<> Bind(std::string callee, const Options& opts); + + // This is a helper template that allows to convert functions pointers from + // the run time values to compile time values (template arguments) with + // automatic template arguments inference. + // + // Example: + // + // static LogicalResult Foo(int32_t arg) {... } + // + // template + // void call(Callable callable) { callable(42); } + // + // call(Foo); // `Foo` passed as a runtime value + // call(FunctionWrapper()) // `Foo` passed as a template argument + // + // In the first case compiler will not be able to inline `Foo` into the `call` + // body. However in the second case it can do that, because function pointer + // is a statically known value (template non-type argument). + template + struct FunctionWrapper; + + template + struct FunctionWrapper { + ABSL_ATTRIBUTE_ALWAYS_INLINE Ret operator()(Args... args) const { + return fn(args...); + } + }; +}; + +// Forward declare template defined below. +template +class CustomCallHandler; + +namespace internal { + +// A type tag to distinguish arguments tied to the attributes in the +// `CustomCallBinding` variadic template argument. +template +struct Attr {}; + +// A type tag to distinguish arguments tied to the return in the +// `CustomCallBinding` variadic template argument. +template +struct Ret {}; + +// A type tag to distinguish arguments tied to the user data in the +// `CustomCallBinding` variadic template argument. +template +struct UserData {}; + +// A type tag to distinguish arguments tied to the state in the +// `CustomCallBinding` variadic template argument. +template +struct StateTag {}; + +// A type tag to distinguish arguments tied to the constant values in the +// `CustomCallBinding` variadic template argument. +template +struct Value {}; + +// A template for checking if type is a regular argument or one of the special +// arguments wrapped in a type tag (e.g. attr, user data, etc...). +template +struct IsWrapped : std::false_type {}; + +template +struct IsWrapped> : std::true_type {}; + +template +struct IsWrapped> : std::true_type {}; + +template +struct IsWrapped> : std::true_type {}; + +template +struct IsWrapped> : std::true_type {}; + +template +struct IsWrapped> : std::true_type {}; + +template +struct IsResult : std::false_type {}; + +template +struct IsResult> : std::true_type {}; + +// Checks if remaining arguments are in the parameter pack. +template +using HasRemainingArgs = + std::disjunction...>; + +} // namespace internal + +// Custom call binding describes the function signature of the expected custom +// call handler using its variadic template parameter. +// +// Custom call binding: +// CustomCallBinding +// +// Function signature: +// LogicalResult MyHandle(int32_t algo, MemrefView memref); +// +template +class CustomCallBinding { + public: + using Options = CustomCall::Options; + using RuntimeChecks = CustomCall::RuntimeChecks; + + template + CustomCallBinding Arg() && { + return {std::move(*this)}; + } + + CustomCallBinding RemainingArgs() && { + static_assert(!internal::HasRemainingArgs::value, + "remaining arguments can be passed just once"); + return {std::move(*this)}; + } + + template + CustomCallBinding> Attr(std::string attr) && { + attrs_.push_back(std::move(attr)); + return {std::move(*this)}; + } + + template + CustomCallBinding> Ret() && { + return {std::move(*this)}; + } + + template + CustomCallBinding> UserData() && { + static_assert(std::is_pointer::value, "user data must be a pointer"); + return {std::move(*this)}; + } + + template + CustomCallBinding> State(std::string id) && { + attrs_.push_back(std::move(id)); + return {std::move(*this)}; + } + + template + CustomCallBinding> Value(T value) && { + values_.push_back(std::move(value)); + return {std::move(*this)}; + } + + template + std::unique_ptr> To(Fn fn) { + return std::unique_ptr>( + new CustomCallHandler( + std::forward(fn), std::move(callee_), std::move(attrs_), + std::move(values_), opts_)); + } + + private: + template + friend class CustomCallBinding; + friend class CustomCall; + + CustomCallBinding(std::string callee, const Options& opts) + : callee_(std::move(callee)), opts_(opts) { + static_assert(sizeof...(Ts) == 0, "custom call arguments must be empty"); + } + + template + CustomCallBinding(CustomCallBinding&& other) // NOLINT + : callee_(std::move(other.callee_)), + attrs_(std::move(other.attrs_)), + values_(std::move(other.values_)), + opts_(other.opts_) {} + + CustomCallBinding(CustomCallBinding&) = delete; + + std::string callee_; // custom call target + std::vector attrs_; // names of bound attributes + std::vector values_; // values bound to arguments + Options opts_; +}; + +inline CustomCallBinding<> CustomCall::Bind(std::string callee) { + return Bind(std::move(callee), Options()); +} + +inline CustomCallBinding<> CustomCall::Bind(std::string callee, + const Options& opts) { + return CustomCallBinding<>(std::move(callee), opts); +} + +// Custom calls return results to the caller through the template +// specializations of the `Result`. Each template specialization is responsible +// for definining the result encoding/decoding to/from opaque memory. +template +class Result; + +// Custom call arguments decoding must be defined by specializing this template. +// +// Example: decoding for the `MyType` arguments +// +// template +// struct CustomCallArgDecoding { +// static FailureOr Decode(TypeID type_id, void* value); +// }; +// +template +struct CustomCallArgDecoding; + +// Custom call attribute decoding must be defined by specializing this template. +// +// Example: decoding for the `MyType` attributes +// +// template +// struct CustomCallAttrDecoding { +// static FailureOr Decode(std::string_view name, +// TypeID type_id, void* value); +// } +// +template +struct CustomCallAttrDecoding; + +// Custom call returns decoding must be defined by specializing this template. +// +// Example: decoding for the `MyType` arguments +// +// template +// struct CustomCallRetDecoding { +// static FailureOr> Decode(TypeID type_id, void* value); +// }; +// +template +struct CustomCallRetDecoding; + +//===----------------------------------------------------------------------===// +// Helpers for decoding opaque arguments and attributes memory. +//===----------------------------------------------------------------------===// + +namespace internal { + +// Decoded pair of an argument type and opaque value. +struct DecodedArg { + TypeID type_id; + void* value; +}; + +// Decoded triple of an attribute name, type and opaque value. +struct DecodedAttr { + std::string_view name; + TypeID type_id; + void* value; +}; + +// A convenience wrapper around opaque arguments memory. +class DecodedArgs { + public: + explicit DecodedArgs(void** args) { + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(args, sizeof(void*)); + size_ = *reinterpret_cast(args[0]); + if (size_) { + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(args + 1, sizeof(void*)); + type_table_ = reinterpret_cast(args[1]); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(type_table_, size_ * sizeof(void*)); + values_ = args + 2; + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(values_, size_ * sizeof(void*)); + } + } + + ABSL_ATTRIBUTE_ALWAYS_INLINE int64_t size() const { return size_; } + + ABSL_ATTRIBUTE_ALWAYS_INLINE DecodedArg operator[](size_t i) const { + DecodedArg arg; + arg.type_id = TypeID::getFromOpaquePointer(type_table_[i]); + arg.value = values_[i]; + return arg; + } + + private: + int64_t size_; + void** type_table_ = nullptr; + void** values_ = nullptr; +}; + +// A convenience wrapper around opaque attributes memory. +class DecodedAttrs { + public: + explicit DecodedAttrs(void** attrs) : encoded_(attrs + 1) { + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(attrs, sizeof(void*)); + size_ = *reinterpret_cast(attrs[0]); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded_, 3 * size_ * sizeof(void*)); + } + + ABSL_ATTRIBUTE_ALWAYS_INLINE int64_t size() const { return size_; } + + ABSL_ATTRIBUTE_ALWAYS_INLINE DecodedAttr operator[](size_t i) const { + void** attr_base = encoded_ + i * 3; + + DecodedAttr attr; + auto* name = reinterpret_cast*>(attr_base[0]); + attr.name = std::string_view(name->data, name->size); + attr.type_id = TypeID::getFromOpaquePointer(attr_base[1]); + attr.value = attr_base[2]; + + return attr; + } + + private: + void** encoded_; + int64_t size_; +}; + +// Using the same class for decoded returns +using DecodedRet = DecodedArg; +using DecodedRets = DecodedArgs; + +} // namespace internal + +//===----------------------------------------------------------------------===// +// CustomCall remaining arguments wraps the type-erased `DecodedArg` container, +// and provides a type-safe API for accessing individual arguments. +//===----------------------------------------------------------------------===// + +class CustomCall::RemainingArgs { + public: + using RuntimeChecks = CustomCall::RuntimeChecks; + + RemainingArgs(internal::DecodedArgs args, size_t offset) + : args_(args), offset_(offset) { + assert(offset <= args_.size() && "illegal remaining args offset"); + } + + size_t size() const { return args_.size() - offset_; } + bool empty() const { return size() == 0; } + + template + bool isa(size_t index) const { + return args_[index + offset_].type_id == TypeID::get>(); + } + + template + FailureOr get(size_t index) const { + internal::DecodedArg arg = args_[index + offset_]; + return CustomCallArgDecoding::Decode(arg.type_id, arg.value); + } + + private: + internal::DecodedArgs args_; + size_t offset_; +}; + +class CustomCall::VariantArg { + public: + using RuntimeChecks = CustomCall::RuntimeChecks; + + VariantArg(internal::DecodedArgs args, size_t offset) + : args_(args), offset_(offset) { + assert(offset <= args_.size() && "illegal remaining args offset"); + } + + template + bool isa() const { + return args_[offset_].type_id == TypeID::get>(); + } + + template + FailureOr get() const { + internal::DecodedArg arg = args_[offset_]; + return CustomCallArgDecoding::Decode(arg.type_id, arg.value); + } + + private: + internal::DecodedArgs args_; + size_t offset_; +}; + +class CustomCall::VariantAttr { + public: + using RuntimeChecks = CustomCall::RuntimeChecks; + + VariantAttr(std::string_view name, TypeID type_id, void* value) + : name_(name), type_id_(type_id), value_(value) {} + + template + bool isa() const { + return type_id_ == TypeID::get>(); + } + + template + FailureOr get() const { + return CustomCallAttrDecoding::Decode(name_, type_id_, value_); + } + + private: + std::string_view name_; + TypeID type_id_; + void* value_; +}; + +//===----------------------------------------------------------------------===// +// A little bit of template metaprogramming to implement type safe binding +// of custom calls to C++ functions. This is internal implementation details, +// and must not be relied on in any of the client code. +//===----------------------------------------------------------------------===// + +namespace internal { + +// A helper struct to extract the type of the handler argument. +template +struct FnArgType { + using Type = T; +}; + +// Extracts the underlying type from the attribute type tag. +template +struct FnArgType> { + using Type = T; +}; + +// Extracts the underlying type from the return type tag. +template +struct FnArgType> { + using Type = Result; +}; + +// Extracts the underlying type from the user data type tag. +template +struct FnArgType> { + using Type = T; +}; + +// Extracts the underlying type from the state type tag. +template +struct FnArgType> { + using Type = State; +}; + +// Extracts the underlying type from the value type tag. +template +struct FnArgType> { + using Type = T; +}; + +// A template for counting regular arguments in the Ts pack. +template +struct NumArgs; + +template +struct NumArgs { + static constexpr int64_t value = !IsWrapped::value + NumArgs::value; +}; + +template <> +struct NumArgs<> { + static constexpr int64_t value = 0; +}; + +// A template for counting returns in the Ts pack. +template +struct NumRets; + +template +struct NumRets { + static constexpr int64_t value = IsResult::value + NumRets::value; +}; + +template <> +struct NumRets<> { + static constexpr int64_t value = 0; +}; + +// Unwrap return type to get the type expected by result `Set` method. +// +// TODO(ezhulenev): Result template itself should define what type `T` it +// expects to see in the `Set` method, because it's not necessery the same as +// the template type of the result. +template +struct UnwrapRet; + +template +struct UnwrapRet> { + using Type = T; +}; + +// A helper template to concatenate index + index sequence. +template +struct ConsIdx; + +template +struct ConsIdx> { + using Type = std::index_sequence; +}; + +// Get indices of the variadic template type parameters corresponding to +// results. This template will produce an `std::index_sequence` type with +// indices of custom call result arguments. +template +struct IndexRets; + +template +struct IndexRets { + using Is = std::index_sequence<>; +}; + +template +struct IndexRets { + using Is = std::conditional_t< + IsResult::value, + typename ConsIdx::Is>::Type, + typename IndexRets::Is>; +}; + +// Get indices of the variadic template type parameters corresponding to +// all arguments excluding results. +template +struct IndexArgs; + +template +struct IndexArgs { + using Is = std::index_sequence<>; +}; + +template +struct IndexArgs { + using Is = std::conditional_t< + !IsResult::value, + typename ConsIdx::Is>::Type, + typename IndexArgs::Is>; +}; + +template +void SetResultsFromTuple(std::index_sequence, FnArgs fn_args, + Result tuple) { + ((*std::get(fn_args)).Set(std::get(tuple)), ...); +} + +// When decoding input data we need to keep track of how many arguments, +// attributes, and returns we decoded so far to index into the correct data +// structure. +struct DecodingOffsets { + int64_t args = 0; + int64_t attrs = 0; + int64_t rets = 0; + int64_t values = 0; +}; + +struct DecodingContext { + internal::DecodedArgs args; + internal::DecodedRets rets; + internal::DecodedAttrs attrs; + + // Attributes' names and mapping from attrs' offsets to indices in `attrs`. + absl::Span attrs_names; + absl::Span attrs_idx; + + // Values bound to arguments at handler construction time. + absl::Span values; + + // User-provided auxiliary data. + const CustomCall::UserData* user_data; + + // User-provided diagnostic engine for reporting detailed errors. + const DiagnosticEngine* diagnostic; +}; + +template +ABSL_ATTRIBUTE_ALWAYS_INLINE inline FailureOr DecodeUserData( + const CustomCall::UserData* user_data) { + if (!CustomCall::CheckUserData(checks)) return user_data->get(); + + // TODO(ezhulenev): Add an option to request nullable user data, because + // right now we do not distinguish between a user data pointer that doesn't + // exist, and a null pointer passed by the user. + + // Get the requested value if user data was passed to the custom call. + auto* ptr = user_data ? user_data->getIfExists() : nullptr; + if (LLVM_UNLIKELY(!ptr)) return failure(); + return ptr; +} + +template +ABSL_ATTRIBUTE_ALWAYS_INLINE inline FailureOr DecodeAttr( + DecodingOffsets& offsets, absl::Span attrs_names, + absl::Span attrs_idx, internal::DecodedAttrs attrs) { + // Find decoded attribute corresponding for the given attribute index. + int64_t idx = offsets.attrs++; + + // Do not check the attribute name, and decode attribute at the given index. + if (!CustomCall::CheckNames(checks)) { + size_t i = attrs_idx[idx]; + return CustomCallAttrDecoding::Decode( + attrs[i].name, attrs[i].type_id, attrs[i].value); + } + + std::string_view attr_name = attrs_names[idx]; + + // Given that attributes are passed to the custom call handler + // lexicographically sorted by name, we can find the attribute we are + // looking for only between the `attrs_idx` offset and the end of the + // attributes array. + for (size_t i = attrs_idx[idx]; i < attrs.size(); ++i) { + if (LLVM_LIKELY(attrs[i].name == attr_name)) + return CustomCallAttrDecoding::Decode( + attrs[i].name, attrs[i].type_id, attrs[i].value); + } + + // Attribute we were looking for was not passed as an argument. + return failure(); +} + +template +struct Decode { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr call( + DecodingOffsets& offsets, DecodingContext& ctx) { + internal::DecodedArg arg = ctx.args[offsets.args++]; + return CustomCallArgDecoding::Decode(arg.type_id, arg.value); + } +}; + +template +struct Decode, checks> { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> call( + DecodingOffsets& offsets, DecodingContext& ctx) { + internal::DecodedRet ret = ctx.rets[offsets.rets++]; + return CustomCallRetDecoding::Decode(ret.type_id, ret.value); + } +}; + +template +struct Decode, checks> { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr call( + DecodingOffsets& offsets, DecodingContext& ctx) { + return DecodeAttr(offsets, ctx.attrs_names, ctx.attrs_idx, + ctx.attrs); + } +}; + +template +struct Decode, checks> { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr call( + DecodingOffsets& offsets, DecodingContext& ctx) { + using UserDataT = std::remove_pointer_t; + if (auto decoded = DecodeUserData(ctx.user_data); + LLVM_LIKELY(succeeded(decoded))) + return decoded; + return ctx.diagnostic->EmitError(InternalError( + "failed to decode UserData of type %s", typeid(T).name())); + } +}; + +template +struct Decode, checks> { + using Snapshot = typename StateVector::Snapshot; + + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> call( + DecodingOffsets& offsets, DecodingContext& ctx) { + // Get the state snapshot and state id from user data and attributes. + FailureOr snapshot = + DecodeUserData(ctx.user_data); + FailureOr id = DecodeAttr( + offsets, ctx.attrs_names, ctx.attrs_idx, ctx.attrs); + if (LLVM_UNLIKELY(failed(snapshot) || failed(id))) return failure(); + + return (*snapshot)->state(*id); + } +}; + +template +struct Decode, checks> { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr call( + DecodingOffsets& offsets, DecodingContext& ctx) { + return std::any_cast(ctx.values[offsets.values++]); + } +}; + +template +struct Decode { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr call( + DecodingOffsets& offsets, DecodingContext& ctx) { + return CustomCall::RemainingArgs(ctx.args, offsets.args); + } +}; + +template +struct Decode { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr call( + DecodingOffsets& offsets, DecodingContext& ctx) { + return CustomCall::VariantArg(ctx.args, offsets.args++); + } +}; + +} // namespace internal + +// Custom call handler binds concrete custom call implementation of type `Fn` to +// the custom call function signature. `Fn` can be a function pointer, or a +// lambda. +// +// Custom call handler uses the variadic template parameter `Ts` to decode the +// opaque pointers passed to the `call` function into the C++ types that are +// forwarded to the custom call implementation. +template +class CustomCallHandler : public CustomCall { + static constexpr int64_t kSize = sizeof...(Ts); + static constexpr int64_t kNumArgs = internal::NumArgs::value; + static constexpr int64_t kNumRets = internal::NumRets::value; + + template + using FnArgType = typename internal::FnArgType::Type; + + template + using UnwrapRet = typename internal::UnwrapRet::Type; + + // Custom call can signal error using a LogicalError result. + static constexpr bool kIsLogicalErr = + std::is_invocable_r_v...>; + + // Custom call can signal error together with a detailed error message. + static constexpr bool kIsStatusErr = + std::is_invocable_r_v...>; + + // Custom call returns results as `absl::StatusOr>` + // (multiple results) or `absl::StatusOr` (single result). + template + static constexpr bool IsStatusOrInvocable(std::index_sequence, + std::index_sequence) { + // Define a tuple to help extracting type by index. + using ArgsTuple = std::tuple...>; + + // Custom call doesn't have any results. + if constexpr (sizeof...(RetsIs) == 0) return false; + + // Custom call returns a single result. + if constexpr (sizeof...(RetsIs) == 1) { + using StatusOr = + absl::StatusOr>...>; + return std::is_invocable_r_v...>; + } + + // Custom call returns multiple results as a tuple. + if constexpr (sizeof...(RetsIs) > 1) { + using StatusOr = absl::StatusOr< + std::tuple>...>>; + return std::is_invocable_r_v...>; + } + + llvm_unreachable("unsupported result rank"); + } + + static constexpr bool kIsStatusOrResult = + IsStatusOrInvocable(typename internal::IndexRets<0, Ts...>::Is{}, + typename internal::IndexArgs<0, Ts...>::Is{}); + + static_assert(kIsLogicalErr || kIsStatusErr || kIsStatusOrResult, + "incompatible custom call handler types"); + + public: + std::string_view name() const final { return callee_; } + + ABSL_ATTRIBUTE_ALWAYS_INLINE LogicalResult + call(void** args, void** attrs, void** rets, const UserData* user_data, + const DiagnosticEngine* diagnostic) const final { + // Decode arguments and attributes from the opaque pointers. + internal::DecodedArgs decoded_args(args); + internal::DecodedAttrs decoded_attrs(attrs); + internal::DecodedRets decoded_rets(rets); + + int64_t num_args = decoded_args.size(); + int64_t num_attrs = decoded_attrs.size(); + int64_t num_rets = decoded_rets.size(); + + if (LLVM_UNLIKELY(diagnostic == nullptr)) + diagnostic = DiagnosticEngine::DefaultDiagnosticEngine(); + + // If all runtime checks are disabled we are just reinterpreting opaque + // `args`, `attrs` and `rets` memory according to the custom call handler + // signature and skip all checks (these checks will be optimized out). + auto eval = [](bool condition) { + return checks == RuntimeChecks::kNone ? false : condition; + }; + + // Check that the number of passed arguments matches the signature. Each + // individual argument decoding will check the actual type. + if (internal::HasRemainingArgs::value) { + if (LLVM_UNLIKELY(eval(num_args < kNumArgs - 1))) + return diagnostic->EmitError(InvalidArgument( + "Wrong number of arguments: expected at least %d got %d", + kNumArgs - 1, num_args)); + } else { + if (LLVM_UNLIKELY(eval(num_args != kNumArgs))) + return diagnostic->EmitError( + InvalidArgument("Wrong number of arguments: expected %d got %d", + kNumArgs, num_args)); + } + + // Check that the number of returns matches the signature. The return + // decoding will check the actual type. + if (LLVM_UNLIKELY(eval(num_rets != kNumRets))) + return diagnostic->EmitError(InvalidArgument( + "Wrong number of returns: expected %d got %d", kNumRets, num_rets)); + + // Check that we have a correct number of attributes passed to the custom + // call. Each individual attribute decoding will check the name and the + // type of the attribute. + if (LLVM_UNLIKELY(eval(opts_.exact_attrs ? num_attrs != num_encoded_attrs_ + : num_attrs < num_encoded_attrs_))) + return diagnostic->EmitError(InvalidArgument( + "Wrong number of attributes: expected %s%d got %d", + opts_.exact_attrs ? "" : "at least ", num_encoded_attrs_, num_attrs)); + + // Define index sequences to access custom call operands. + using Is = std::make_index_sequence; + using ArgsIs = typename internal::IndexArgs<0, Ts...>::Is; + using RetsIs = typename internal::IndexRets<0, Ts...>::Is; + + return call(decoded_args, decoded_attrs, decoded_rets, user_data, + diagnostic, Is{}, ArgsIs{}, RetsIs{}); + } + + template + ABSL_ATTRIBUTE_ALWAYS_INLINE LogicalResult + call(internal::DecodedArgs args, internal::DecodedAttrs attrs, + internal::DecodedRets rets, const UserData* user_data, + const DiagnosticEngine* diagnostic, std::index_sequence, + std::index_sequence, std::index_sequence) const { + // A helper structure to allow each decoder find the correct offset in the + // arguments, attributes or results. + internal::DecodingOffsets offsets; + + // Package all the data required for decoding custom call operands. + internal::DecodingContext ctx{args, rets, attrs, attrs_, + attrs_idx_, values_, user_data, diagnostic}; + + // Decode all operands into FailureOr containers. It is guaranteed + // that initializer list will be evaluated left-to-right, and we can rely + // on correct offsets computation. + std::tuple>...> fn_args = { + internal::Decode::call(offsets, ctx)...}; + + // Check if all operands and results were decoded. + bool all_decoded = (succeeded(std::get(fn_args)) && ...); + + if (LLVM_UNLIKELY(!all_decoded)) { + std::array decoded = {succeeded(std::get(fn_args))...}; + auto bad_args = llvm::make_filter_range( + llvm::enumerate(decoded), [](auto pair) { return !pair.value(); }); + auto to_str = [](auto pair) { return std::to_string(pair.index()); }; + + return diagnostic->EmitError(InvalidArgument( + "Failed to decode all custom call operands (bad operads at: %s)", + llvm::join(llvm::map_range(bad_args, to_str), ", "))); + } + + // Custom call returns logical result to signal failures. + if constexpr (kIsLogicalErr) { + return fn_(std::move(*std::get(fn_args))...); + } + + // Custom call returns detailed error to signal failures. + if constexpr (kIsStatusErr) { + if (auto st = fn_(std::move(*std::get(fn_args))...); !st.ok()) { + return diagnostic->EmitError(std::move(st)); + } + return success(); + } + + // Custom call returns result(s) as `absl::StatusOr`. + if constexpr (kIsStatusOrResult) { + auto status_or = fn_(std::move(*std::get(fn_args))...); + if (!status_or.ok()) { + return diagnostic->EmitError(status_or.status()); + } + + static_assert(sizeof...(RetsIs) >= 1, "unsupported number or results"); + + if constexpr (sizeof...(RetsIs) == 1) { + (*std::get(fn_args)).Set(status_or.value()); + return success(); + } + + if constexpr (sizeof...(RetsIs) > 1) { + using ResultIs = std::make_index_sequence; + internal::SetResultsFromTuple(ResultIs{}, std::move(fn_args), + std::move(status_or.value())); + return success(); + } + } + + llvm_unreachable("unexpected custom call type"); + } + + private: + template + friend class CustomCallBinding; + + CustomCallHandler(Fn fn, std::string callee, std::vector attrs, + std::vector values, const Options& opts) + : fn_(std::move(fn)), + callee_(std::move(callee)), + attrs_(std::move(attrs)), + values_(std::move(values)), + opts_(opts), + attrs_idx_(attrs_.size()) { + // Sort attributes names and remove duplicates. These unique attributes are + // what we'll be looking for in the encoded custom call attributes. + std::vector sorted = attrs_; + std::sort(sorted.begin(), sorted.end()); + sorted.erase( + std::unique(sorted.begin(), sorted.end(), std::equal_to()), + sorted.end()); + num_encoded_attrs_ = sorted.size(); + + // Find index or every attribute in the sorted attributes vector. + for (size_t i = 0; i < attrs_.size(); ++i) { + std::string_view attr = attrs_[i]; + attrs_idx_[i] = std::distance(sorted.begin(), llvm::find(sorted, attr)); + } + } + + Fn fn_; + std::string callee_; + std::vector attrs_; + std::vector values_; + Options opts_; + + // A mapping from the attribute index to its index in the lexicographically + // sorter vector of attribute names. Attributes passed in the custom call + // handler sorted by the name, we use this index to efficiently find the + // decoded attribute entry. + std::vector attrs_idx_; + + // The number of attributes we expect in the encoded custom call arguments. + // This is not the same as `attrs_.size()` because of potential duplicates, + // e.g. attribute corresponding to state id might be used multiple times. + size_t num_encoded_attrs_; +}; + +template +constexpr int64_t CustomCallHandler::kSize; + +template +constexpr int64_t CustomCallHandler::kNumArgs; + +template +constexpr int64_t CustomCallHandler::kNumRets; + +//===----------------------------------------------------------------------===// +// Custom arguments decoding. +//===----------------------------------------------------------------------===// + +llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const StridedMemrefView&); +llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const MemrefView&); +llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const FlatMemrefView&); + +template +struct CustomCallArgDecoding { + using EncodedMemref = internal::EncodedMemref; + + ABSL_ATTRIBUTE_ALWAYS_INLINE + static FailureOr Decode(TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) { + return failure(); + } + + auto* encoded = reinterpret_cast(value); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + PrimitiveType dtype = static_cast(encoded->dtype); + return StridedMemrefView{dtype, + encoded->data, + {encoded->dims, encoded->rank}, + {encoded->dims + encoded->rank, encoded->rank}}; + } +}; + +template +struct CustomCallArgDecoding { + using EncodedMemref = internal::EncodedMemref; + + ABSL_ATTRIBUTE_ALWAYS_INLINE + static FailureOr Decode(TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) { + return failure(); + } + + auto* encoded = reinterpret_cast(value); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + PrimitiveType dtype = static_cast(encoded->dtype); + return MemrefView{dtype, encoded->data, {encoded->dims, encoded->rank}}; + } +}; + +template +struct CustomCallArgDecoding { + using EncodedMemref = internal::EncodedMemref; + + ABSL_ATTRIBUTE_ALWAYS_INLINE + static FailureOr Decode(TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) { + return failure(); + } + + auto* encoded = reinterpret_cast(value); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + PrimitiveType dtype = static_cast(encoded->dtype); + int64_t size_in_bytes = primitive_util::ByteWidth(dtype); + for (int d = 0; d < encoded->rank; ++d) size_in_bytes *= encoded->dims[d]; + return FlatMemrefView{dtype, encoded->data, size_in_bytes}; + } +}; + +#define XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(T) \ + template \ + struct CustomCallArgDecoding { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode(TypeID type_id, \ + void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(T)); \ + return *reinterpret_cast(value); \ + } \ + } + +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(bool); +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int8_t); +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int16_t); +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int32_t); +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int64_t); +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(float); +XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(double); + +#undef XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING + +// Register decoding for special floating point types defined in Eigen. +#define XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING(T, STORAGE) \ + template \ + struct CustomCallArgDecoding { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode(TypeID type_id, \ + void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + auto* src = reinterpret_cast(value); \ + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(STORAGE)); \ + return Eigen::numext::bit_cast(*src); \ + } \ + } + +XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING(Eigen::bfloat16, uint16_t); +XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING(Eigen::half, uint16_t); + +#undef XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING + +//===----------------------------------------------------------------------===// +// Opaque arguments at run time passed as pointers and decoded by wrapping them +// into a reference type, for example `AsyncValue *` pointer can be wrapped into +// a typed `AsyncValuePtr` pointer wrapper. +//===----------------------------------------------------------------------===// + +#define XLA_RUNTIME_REGISTER_OPAQUE_ARG_DECODING(T, PTR) \ + template \ + struct CustomCallArgDecoding { \ + static_assert(std::is_pointer_v, "must be a pointer"); \ + static_assert(std::is_trivially_destructible_v, \ + "must be a trivially destructible reference type"); \ + \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode(TypeID type_id, \ + void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + auto* src = reinterpret_cast(value); \ + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(PTR)); \ + T ref{*src}; \ + return std::move(ref); \ + } \ + } + +XLA_RUNTIME_REGISTER_OPAQUE_ARG_DECODING(void*, void*); + +//===----------------------------------------------------------------------===// +// Custom call results decoding. +//===----------------------------------------------------------------------===// + +#define XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(T) \ + template <> \ + class Result { \ + public: \ + explicit Result(T* storage) : storage_(storage) {} \ + void Set(T value) { *storage_ = value; } \ + \ + private: \ + T* storage_; \ + }; \ + \ + template \ + struct CustomCallRetDecoding { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> Decode( \ + TypeID type_id, void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + return Result(reinterpret_cast(value)); \ + } \ + }; + +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(bool); +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int8_t); +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int16_t); +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int32_t); +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int64_t); +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(float); +XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(double); + +#undef XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING + +//===----------------------------------------------------------------------===// +// Opaque results at run time passed as pointers, and a typed wrapper binds +// together the reference type and the underlying pointer type. +//===----------------------------------------------------------------------===// + +#define XLA_RUNTIME_REGISTER_OPAQUE_RET_DECODING(T, PTR) \ + template <> \ + class Result { \ + static_assert(std::is_pointer_v, "must be a pointer type"); \ + \ + public: \ + explicit Result(PTR* storage) : storage_(storage) {} \ + void Set(PTR value) { *storage_ = value; } \ + \ + private: \ + PTR* storage_; \ + }; \ + \ + template \ + struct CustomCallRetDecoding { \ + static_assert(std::is_pointer_v, "must be a pointer type"); \ + \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> Decode( \ + TypeID type_id, void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + return Result(reinterpret_cast(value)); \ + } \ + }; + +XLA_RUNTIME_REGISTER_OPAQUE_RET_DECODING(void*, void*); + +//===----------------------------------------------------------------------===// + +// Custom call memref result decoding +template <> +class Result { + using EncodedMemref = internal::EncodedMemref; + + public: + explicit Result(EncodedMemref* storage) : storage_(storage) {} + void Set(MemrefView value) { + assert(IsCompatible(value) && + "Custom call return types is not compatible with types in MLIR"); + storage_->data = value.data; + for (unsigned i = 0; i < storage_->rank; ++i) { + storage_->dims[i] = value.sizes[i]; + } + } + + PrimitiveType GetDType() { return PrimitiveType{storage_->dtype}; } + absl::Span GetDims() { + return absl::Span(storage_->dims, storage_->rank); + } + + private: + bool IsCompatible(MemrefView value) { + bool is_compatible = + storage_->dtype == value.dtype && storage_->rank == value.sizes.size(); + if (!is_compatible) return false; + + for (unsigned i = 0; i < storage_->rank; ++i) { + is_compatible = (storage_->dims[i] == value.sizes[i]) || + (storage_->dims[i] == /*MemrefType::kDynamic=*/-1); + } + return is_compatible; + } + + EncodedMemref* storage_; +}; + +template +struct CustomCallRetDecoding { + using EncodedMemref = internal::EncodedMemref; + + ABSL_ATTRIBUTE_ALWAYS_INLINE + static FailureOr> Decode(TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) return failure(); + + auto* encoded = reinterpret_cast(value); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + return Result(encoded); + } +}; + +//===----------------------------------------------------------------------===// + +// Custom call AsyncValueRef result decoding +#define XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(T) \ + template <> \ + class Result> { \ + public: \ + explicit Result(void** storage) : storage_(storage) {} \ + void Set(tsl::AsyncValueRef value) { \ + auto write = [](const T* v, std::byte* store) { \ + T* store_t = reinterpret_cast(store); \ + *store_t = *v; \ + }; \ + *storage_ = runtime::AsyncRuntime::AsValue( \ + value, sizeof(T), alignof(std::max_align_t), write); \ + } \ + \ + private: \ + void** storage_; \ + }; \ + \ + template \ + struct CustomCallRetDecoding, checks> { \ + LLVM_ATTRIBUTE_ALWAYS_INLINE \ + static FailureOr>> Decode(TypeID type_id, \ + void* value) { \ + if (!CustomCall::Isa>(checks, type_id)) \ + return failure(); \ + return Result>(reinterpret_cast(value)); \ + } \ + }; + +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(bool); +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int8_t); +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int16_t); +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int32_t); +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int64_t); +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(float); +XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(double); + +#undef XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING + +template <> +class Result> { + public: + explicit Result(void** storage) : storage_(storage) {} + void Set(tsl::AsyncValueRef value) { + *storage_ = runtime::AsyncRuntime::AsToken(value); + } + + private: + void** storage_; +}; + +template +struct CustomCallRetDecoding, checks> { + LLVM_ATTRIBUTE_ALWAYS_INLINE + static FailureOr>> Decode( + TypeID type_id, void* value) { + if (!CustomCall::Isa>(checks, type_id)) + return failure(); + + return Result>( + reinterpret_cast(value)); + } +}; + +template <> +class Result> { + using EncodedMemref = internal::EncodedMemref; + + struct MemrefDescriptor { + void* allocated_ptr; + void* aligned_ptr; + int64_t offset; + int64_t dims[]; + }; + + public: + explicit Result(EncodedMemref* storage) : storage_(storage) {} + void Set(tsl::AsyncValueRef value) { + auto write = [this](const MemrefView* view, std::byte* store) { + assert(IsCompatible(*view) && + "Custom call return types is not compatible with types in MLIR"); + MemrefDescriptor* store_t = reinterpret_cast(store); + store_t->allocated_ptr = view->data; + store_t->aligned_ptr = view->data; + store_t->offset = 0; + for (unsigned i = 0; i < storage_->rank; ++i) { + store_t->dims[i] = view->sizes[i]; + } + }; + storage_->data = runtime::AsyncRuntime::AsValue( + value, 3 * sizeof(int64_t) + 2 * storage_->rank * sizeof(int64_t), + alignof(std::max_align_t), write); + } + + PrimitiveType GetDType() { return PrimitiveType{storage_->dtype}; } + absl::Span GetDims() { + return absl::Span(storage_->dims, storage_->rank); + } + + private: + bool IsCompatible(MemrefView value) { + bool is_compatible = + storage_->dtype == value.dtype && storage_->rank == value.sizes.size(); + if (!is_compatible) return false; + + for (unsigned i = 0; i < storage_->rank; ++i) { + is_compatible = (storage_->dims[i] == value.sizes[i]) || + (storage_->dims[i] == /*MemrefType::kDynamic=*/-1); + } + + return is_compatible; + } + + EncodedMemref* storage_; +}; + +template +struct CustomCallRetDecoding, checks> { + using EncodedMemref = internal::EncodedMemref; + + LLVM_ATTRIBUTE_ALWAYS_INLINE + static FailureOr>> Decode( + TypeID type_id, void* value) { + if (!CustomCall::Isa>(checks, type_id)) + return failure(); + + auto* encoded = reinterpret_cast(value); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + return Result>(encoded); + } +}; + +// XLA_RUNTIME_REGISTER_ASYNC_VALUE_RET_DECODING(MemrefView); + +//===----------------------------------------------------------------------===// +// Custom call attributes decoding. +//===----------------------------------------------------------------------===// + +template +struct CustomCallAttrDecoding { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( + std::string_view name, TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) { + return failure(); + } + + auto* encoded = reinterpret_cast*>(value); + return std::string_view(encoded->data, encoded->size); + } +}; + +template +struct CustomCallAttrDecoding { + using FunctionOrdinal = CustomCall::FunctionOrdinal; + + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( + std::string_view name, TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) { + return failure(); + } + + unsigned ordinal = *reinterpret_cast(value); + return FunctionOrdinal{ordinal}; + } +}; + +template +struct CustomCallAttrDecoding, checks> { + using ValueDecoding = CustomCallAttrDecoding; + + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> Decode( + std::string_view name, TypeID type_id, void* value) { + // Convert nullptr to empty optional. + bool is_nullopt = CustomCall::Isa(checks, type_id); + if (is_nullopt && value == nullptr) return std::optional(); + + // Try to decode the underlying value if it is present. + if (auto decoded = ValueDecoding::Decode(name, type_id, value); + succeeded(decoded)) { + return std::optional(std::move(*decoded)); + } + return failure(); + } +}; + +template +struct CustomCallAttrDecoding { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( + std::string_view name, TypeID type_id, void* value) { + return CustomCall::VariantAttr(name, type_id, value); + } +}; + +#define XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(T) \ + template \ + struct CustomCallAttrDecoding { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( \ + std::string_view name, TypeID type_id, void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + return *reinterpret_cast(value); \ + } \ + } + +XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(bool); +XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(int32_t); +XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(int64_t); +XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(float); +XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(double); + +#undef XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING + +// A type tag to represent empty arrays of unknown element type. +struct EmptyArray {}; + +// Both EncodedArray and 1-D EncodedDenseElements can be decoded as an +// absl::Span. Pointers to both EncodedArray and 1-D EncodedDenseElements +// can be dereferenced as a pointer to EncodedArray. +#define XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(T) \ + template \ + struct CustomCallAttrDecoding, checks> { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> Decode( \ + std::string_view name, TypeID type_id, void* value) { \ + if (!CustomCall::Isa, CustomCall::TensorRef, \ + EmptyArray>(checks, type_id)) { \ + return failure(); \ + } \ + \ + auto* encoded = reinterpret_cast*>(value); \ + return absl::Span(encoded->data, encoded->size); \ + } \ + } + +XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(int32_t); +XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(int64_t); +XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(float); +XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(double); + +#undef XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING + +#define XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(T) \ + template \ + struct CustomCallAttrDecoding, checks> { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr> \ + Decode(std::string_view name, TypeID type_id, void* value) { \ + if (!CustomCall::Isa>(checks, type_id)) { \ + return failure(); \ + } \ + \ + auto* encoded = \ + reinterpret_cast*>(value); \ + auto payload = encoded->payload; \ + absl::Span data(payload.data, payload.size); \ + absl::Span shape(encoded->shape, encoded->rank); \ + return CustomCall::TensorRef({shape, data}); \ + } \ + } + +XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(int32_t); +XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(int64_t); +XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(float); +XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(double); + +#undef XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING + +//===----------------------------------------------------------------------===// +// Register an XLA custom call attribute decoding for enum class. At runtime the +// value should be passed as the underlying enum type. +//===----------------------------------------------------------------------===// + +// Example: register decoding for a user-defined enum class +// +// enum class MyEnumType { kFoo, kBar, kBaz }; +// +// XLA_RUNTIME_REGISTER_ENUM_ATTR_DECODING(MyEnumType); +// +#define XLA_RUNTIME_REGISTER_ENUM_ATTR_DECODING(T) \ + template \ + struct CustomCallAttrDecoding { \ + static_assert(std::is_enum::value, "expected enum class"); \ + using U = std::underlying_type_t; \ + \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( \ + std::string_view name, TypeID type_id, void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + return static_cast(*reinterpret_cast(value)); \ + } \ + } + +//===----------------------------------------------------------------------===// +// Register an XLA custom call attribute decoding for aggregate attributes. +//===----------------------------------------------------------------------===// + +template +struct AggregateMember { + using Type = T; + + explicit AggregateMember(std::string_view name) : name(name) {} + std::string_view name; +}; + +// Example: register decoding for a user-defined struct +// +// struct PairOfI64 { int64_t a; int64_t b; }; +// +// XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING( +// PairOfI64, +// AggregateMember("a"), +// AggregateMember("b")); +// +#define XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING(T, ...) \ + template \ + struct CustomCallAttrDecoding { \ + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( \ + std::string_view name, TypeID type_id, void* value) { \ + if (!CustomCall::Isa(checks, type_id)) { \ + return failure(); \ + } \ + \ + auto decoder = internal::AggregateDecoder(__VA_ARGS__); \ + return decltype(decoder)::Decode(reinterpret_cast(value), \ + internal::AggregateNames(__VA_ARGS__)); \ + } \ + } + +namespace internal { +// Decodes aggregate attribute into the object of type `T` that must be +// constructible from the `Ts` types. +template +struct DecodeAggregateAttr { + static constexpr size_t kSize = sizeof...(Ts); + + using RuntimeChecks = CustomCall::RuntimeChecks; + + ABSL_ATTRIBUTE_ALWAYS_INLINE + static FailureOr Decode(void** value, + std::array names) { + internal::DecodedAttrs attrs(value); + return Decode(attrs, names, std::make_index_sequence{}); + } + + template + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( + internal::DecodedAttrs attrs, std::array names, + std::index_sequence) { + // Check that the number of encoded attributes matches the signature. + if (checks != RuntimeChecks::kNone && kSize != attrs.size()) + return failure(); + + // Check that aggregate member names match the expected names. + if (CustomCall::CheckNames(checks)) { + for (unsigned i = 0; i < kSize; ++i) + if (attrs[i].name != names[i]) return failure(); + } + + // Decode all arguments into FailureOr containers. It is guaranteed + // that initializer list will be evaluated left-to-right, and we can rely + // on correct offsets computation. + std::tuple...> members = { + CustomCallAttrDecoding::Decode( + attrs[Is].name, attrs[Is].type_id, attrs[Is].value)...}; + + bool all_decoded = (succeeded(std::get(members)) && ...); + if (LLVM_UNLIKELY(!all_decoded)) return failure(); + + // Forward unpacked members to the type constructor. + return T{std::move(*std::get(members))...}; + } +}; + +template +auto AggregateNames(Members... m) { + return std::array{m.name...}; +} + +template +auto AggregateDecoder(Members... m) { + return DecodeAggregateAttr(); +} + +} // namespace internal + +//===----------------------------------------------------------------------===// +// Register an XLA custom call attribute decoding for dictionary attributes. +//===----------------------------------------------------------------------===// + +// Dictionary attributes are encoded using the same scheme as aggregate +// attributes and as custom call attributes: x length. +class Dictionary { + using RuntimeChecks = CustomCall::RuntimeChecks; + + public: + explicit Dictionary(internal::DecodedAttrs attrs) : attrs_(attrs) {} + + int64_t size() { return attrs_.size(); } + + std::vector keys() { + std::vector attr_keys(attrs_.size()); + for (int64_t i = 0; i < attrs_.size(); ++i) { + attr_keys[i] = attrs_[i].name; + } + return attr_keys; + } + + template + ABSL_ATTRIBUTE_ALWAYS_INLINE FailureOr get(std::string_view name) const { + // TODO(ezhulenev): Use `std::binary_search` because it's guaranteed that + // encoded attributes are sorted by name. + for (int64_t i = 0; i < attrs_.size(); ++i) { + if (auto attr = attrs_[i]; attr.name == name) + return CustomCallAttrDecoding::Decode( + attr.name, attr.type_id, attr.value); + } + return failure(); + } + + private: + internal::DecodedAttrs attrs_; +}; + +template +struct CustomCallAttrDecoding { + ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr Decode( + std::string_view name, TypeID type_id, void* value) { + if (!CustomCall::Isa(checks, type_id)) return failure(); + return Dictionary(internal::DecodedAttrs(reinterpret_cast(value))); + } +}; + +//===----------------------------------------------------------------------===// +// XLA Custom Call helper macro for registering custom call handlers. +//===----------------------------------------------------------------------===// + +#define XLA_RUNTIME_DEFINE_CUSTOM_CALL(fn, impl, checks, bind) \ + static bool fn(::xla::runtime::ExecutionContext* ctx, void** args, \ + void** attrs, void** rets) { \ + static auto* handler = bind.To(impl).release(); \ + return ::xla::runtime::succeeded( \ + xla::runtime::Executable::Call(ctx, *handler, args, attrs, rets)); \ + } + +#define XLA_RUNTIME_DEFINE_CUSTOM_CALL_TEMPLATE(param, fn, impl, checks, bind) \ + template \ + static bool fn(::xla::runtime::ExecutionContext* ctx, void** args, \ + void** attrs, void** rets) { \ + static auto* handler = bind.To(impl).release(); \ + return ::xla::runtime::succeeded( \ + xla::runtime::Executable::Call(ctx, *handler, args, attrs, rets)); \ + } + +//===----------------------------------------------------------------------===// +// Declare/define an explicit specialization for TypeID for types used +// by the custom calls. This forces the compiler to emit a strong definition for +// a class and controls which translation unit and shared object will actually +// have it. +// +// See TypeID for more documentation. +// +// Because custom calls do not "own" the types passed across the function +// boundary, we declare/define specializations for tagged types to avoid +// potential conflicts with other libraries. +//===----------------------------------------------------------------------===// + +#define XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(T) \ + MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::Tagged) + +#define XLA_RUNTIME_DEFINE_EXPLICIT_TYPE_ID(T) \ + MLIR_DEFINE_EXPLICIT_TYPE_ID(::xla::runtime::Tagged) + +} // namespace runtime +} // namespace xla + +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(std::string_view); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::StridedMemrefView); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::MemrefView); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::FlatMemrefView); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::EmptyArray); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::Dictionary); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(int32_t); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(int64_t); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(float); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(double); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID( + tsl::AsyncValueRef); +XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef); + +#endif // XLA_RUNTIME_CUSTOM_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..d82fb51257323f00e3ea7cb6c106920bb4eb6205 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call_registry.h @@ -0,0 +1,76 @@ +/* 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_RUNTIME_CUSTOM_CALL_REGISTRY_H_ +#define XLA_RUNTIME_CUSTOM_CALL_REGISTRY_H_ + +#include +#include +#include + +#include "llvm/ADT/StringMap.h" +#include "xla/runtime/custom_call.h" + +namespace xla { +namespace runtime { + +// Dynamic custom call registry is a container for the custom calls that looks +// up the handler implementing the custom call by name at run time. It is used +// to implement a generic `rt.custom_call` runtime intrinsic. +// +// For low overhead custom calls prefer direct custom calls that linked with the +// compiled executable and bypass by-name look up. +class DynamicCustomCallRegistry { + public: + // The type for custom call registration functions. + using RegistrationFunction = void (*)(DynamicCustomCallRegistry*); + + void Register(std::unique_ptr custom_call); + + class CustomCall* Find(std::string_view callee) const; + + private: + llvm::StringMap> custom_calls_; +}; + +// Direct custom call is a custom call that can be linked directly with the +// compiled executable, and doesn't have to go through the custom call look up +// by name at run time (see CustomCallRegistry). +// +// Direct custom call is a preferred way of implemenenting custom calls with +// low run time overheads, as they will become just an indirect function calls +// once LLVM ORC links them with the executable. +// +// See `ToSymbolsBinding` (in executor.h header) to convert direct custom call +// registry and type name registry to symbols binding. +class DirectCustomCallRegistry { + public: + // Function type corresponding to the direct custom call (custom calls + // linked directly with the compiled executable). + using DirectCustomCall = bool (*)(ExecutionContext* ctx, void** args, + void** attrs, void** rets); + + void Register(std::string_view name, DirectCustomCall custom_call); + + void ForEach(std::function f) const; + + private: + llvm::StringMap custom_calls_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_CUSTOM_CALL_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/async_values_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/async_values_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..2115e947515a45bb17e60a81f7353bbb3fe1d64c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/async_values_cache.h @@ -0,0 +1,113 @@ +/* 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_RUNTIME_DEFAULT_ASYNC_VALUES_CACHE_H_ +#define XLA_RUNTIME_DEFAULT_ASYNC_VALUES_CACHE_H_ + +#include "absl/synchronization/mutex.h" +#include "llvm/ADT/DenseMap.h" +#include "tfrt/concurrency/async_value.h" // from @tf_runtime +#include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime +#include "tfrt/concurrency/chain.h" // from @tf_runtime + +namespace xla { +namespace runtime { + +using tsl::AsyncValue; +using tsl::AsyncValuePtr; +using tsl::AsyncValueRef; +using tsl::Chain; +using tsl::MakeConstructedAsyncValueRef; +using tsl::MakeUnconstructedAsyncValueRef; +using tsl::RunWhenReady; + +template +class AsyncValuesCache { + public: + struct Entry; + + AsyncValuesCache() = default; + + // Returns a pointer to the cached value if it exists, otherwise returns + // nullptr. It is the caller's responsibility to form an async reference and + // extend its lifetime if the lifetime of the cached async value can be + // larger than the lifetime of the cache. + AsyncValuePtr Find(Key key) const; + + // Allocates an async value in the unconstructed state to store the cached + // value with the given key. + // + // The `entry.allocated` value is `true` if the new async value was allocated, + // and the caller is responsible for eventually setting the error or emplacing + // the value. If it is false, then it means that the storage was already + // allocated, and someone else will eventually update it. + // + // The returned `entry.size` value is equal to the size of the cache. If the + // new async value was allocated, it will be reflected in the size. + Entry Allocate(Key key); + + // Returns an async value that becomes available once all entries added to + // the cache are available. + AsyncValueRef AllAvailable() const; + + struct Entry { + AsyncValuePtr ptr; + bool allocated; + size_t size; + }; + + private: + mutable absl::Mutex mu_; + llvm::DenseMap> cache_ ABSL_GUARDED_BY(mu_); +}; + +template +AsyncValuePtr AsyncValuesCache::Find(Key key) const { + absl::MutexLock lock(&mu_); + auto it = cache_.find(key); + return it != cache_.end() ? it->getSecond().AsPtr() : AsyncValuePtr(); +} + +template +auto AsyncValuesCache::Allocate(Key key) -> Entry { + absl::MutexLock lock(&mu_); + auto it = cache_.find(key); + if (it != cache_.end()) + return {it->getSecond().AsPtr(), false, cache_.size()}; + + AsyncValueRef allocated = MakeUnconstructedAsyncValueRef(); + + auto emplaced = cache_.try_emplace(key, std::move(allocated)); + assert(emplaced.second && "emplace must be successful"); + return {emplaced.first->getSecond().AsPtr(), true, cache_.size()}; +} + +template +AsyncValueRef AsyncValuesCache::AllAvailable() const { + absl::MutexLock lock(&mu_); + + llvm::SmallVector avs; + avs.reserve(cache_.size()); + for (auto& it : cache_) avs.push_back(it.getSecond().GetAsyncValue()); + + AsyncValueRef chain = MakeConstructedAsyncValueRef(); + RunWhenReady(avs, [chain]() { chain.SetStateConcrete(); }); + return chain; +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_DEFAULT_ASYNC_VALUES_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/memory_mapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/memory_mapper.h new file mode 100644 index 0000000000000000000000000000000000000000..96ee65606550d2ecd54ca45bc085ff8efc4ba9a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/memory_mapper.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. +==============================================================================*/ + +#ifndef XLA_RUNTIME_DEFAULT_MEMORY_MAPPER_H_ +#define XLA_RUNTIME_DEFAULT_MEMORY_MAPPER_H_ + +#include + +namespace xla { +namespace runtime { + +// Some syscalls can be interrupted by a signal handler; retry if that happens. +template +static auto RetryOnEINTR(FunctionType func, decltype(func()) failure_value) { + using ReturnType = decltype(func()); + ReturnType ret; + do { + ret = func(); + } while (ret == failure_value && errno == EINTR); + return ret; +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_DEFAULT_MEMORY_MAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/diagnostics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/diagnostics.h new file mode 100644 index 0000000000000000000000000000000000000000..8acbd3d6853ec906b8dbe169fdc9d701feb1a3c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/diagnostics.h @@ -0,0 +1,174 @@ +/* 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_RUNTIME_DIAGNOSTICS_H_ +#define XLA_RUNTIME_DIAGNOSTICS_H_ + +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "xla/runtime/logical_result.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace runtime { + +// Forward declare. +class DiagnosticEngine; + +// XLA runtime diagnostic engine enables XLA runtime custom calls and compiled +// programs to pass diagnostic information (e.g. detailed run time error +// information attached to the absl::Status) to the caller via the side channel, +// because the API (and ABI) of the compiled executable is very simple, and +// doesn't allow to pass complex C++ tyopes. +// +// XLA runtime diagnostics borrows a lot of ideas from the MLIR compile time +// diagnostics (which is largely based on the Swift compiler diagnostics), +// however in contrast to MLIR compilation pipelines we need to emit diagnostics +// for the run time events (vs compile time) and correlate them back to the +// location in the input module. +// +// See MLIR Diagnostics documentation: https://mlir.llvm.org/docs/Diagnostics. + +//===----------------------------------------------------------------------===// +// Diagnostic +//===----------------------------------------------------------------------===// + +// TODO(ezhulenev): Add location tracking to diagnostic, so that we can +// correlate emitted diagnostic to the location in the input module, and from +// there rely on the MLIR location to correlate events back to the user program +// (e.g. original JAX program written in Python). +class Diagnostic { + public: + explicit Diagnostic(absl::Status status) : status_(std::move(status)) {} + + Diagnostic(Diagnostic &&) = default; + Diagnostic &operator=(Diagnostic &&) = default; + + absl::Status status() const { return status_; } + + private: + Diagnostic(const Diagnostic &rhs) = delete; + Diagnostic &operator=(const Diagnostic &rhs) = delete; + + absl::Status status_; +}; + +//===----------------------------------------------------------------------===// +// InFlightDiagnostic +//===----------------------------------------------------------------------===// + +// RAII wrapper around constructed, but but not yet emitted diagnostic. In +// flight diagnostic gives an opportunity to build a diagnostic before reporting +// it to the engine, similar to the builder pattern. +class InFlightDiagnostic { + public: + InFlightDiagnostic(InFlightDiagnostic &&other) + : engine_(other.engine_), diagnostic_(std::move(other.diagnostic_)) { + other.diagnostic_.reset(); + other.Abandon(); + } + + ~InFlightDiagnostic() { + if (IsInFlight()) Report(); + } + + void Report(); + void Abandon(); + + // Allow a diagnostic to be converted to 'failure'. + // + // Example: + // + // LogicalResult call(DiagnosticEngine diag, ...) { + // if () return diag.EmitError(InternalError("oops")); + // ... + // } + // + operator LogicalResult() const { // NOLINT + return failure(); + } + template + operator FailureOr() const { // NOLINT + return failure(); + } + + private: + friend class DiagnosticEngine; + + InFlightDiagnostic(const DiagnosticEngine *engine, Diagnostic diagnostic) + : engine_(engine), diagnostic_(std::move(diagnostic)) {} + + InFlightDiagnostic &operator=(const InFlightDiagnostic &) = delete; + InFlightDiagnostic &operator=(InFlightDiagnostic &&) = delete; + + bool IsActive() const { return diagnostic_.has_value(); } + bool IsInFlight() const { return engine_ != nullptr; } + + // Diagnostic engine that will report this diagnostic once its ready. + const DiagnosticEngine *engine_ = nullptr; + std::optional diagnostic_; +}; + +//===----------------------------------------------------------------------===// +// DiagnosticEngine +//===----------------------------------------------------------------------===// + +// Diagnostic engine is responsible for passing diagnostics to the user. +// +// XLA runtime users must set up diagnostic engine to report errors back to the +// caller, e.g. the handler can collect all of the emitted diagnostics into the +// string message, and pass it to the caller as the async error. +// +// Unhandled error diagnostics will be logged with the warning level. +class DiagnosticEngine { + public: + // Diagnostic handler must return success if it consumed the diagnostic, and + // failure if the engine should pass it to the next registered handler. + using HandlerTy = std::function; + + // Returns the default instance of the diagnostic engine. + static const DiagnosticEngine *DefaultDiagnosticEngine(); + + InFlightDiagnostic EmitError(absl::Status status) const { + return InFlightDiagnostic(this, Diagnostic(std::move(status))); + } + + void AddHandler(HandlerTy handler) { + handlers_.push_back(std::move(handler)); + } + + void Emit(Diagnostic diagnostic) const { + for (auto &handler : llvm::reverse(handlers_)) { + if (succeeded(handler(diagnostic))) return; + } + + // Log unhandled errors to the warning log. + LOG(WARNING) << "XLA runtime error: " << diagnostic.status(); + } + + private: + llvm::SmallVector handlers_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_DIAGNOSTICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/errors.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/errors.h new file mode 100644 index 0000000000000000000000000000000000000000..3f29a35423c0f4c2ace24f1807becd09164c3e4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/errors.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_RUNTIME_ERRORS_H_ +#define XLA_RUNTIME_ERRORS_H_ + +#include + +#include "absl/status/status.h" +#include "absl/strings/str_format.h" + +namespace xla { +namespace runtime { + +template +absl::Status InvalidArgument(const absl::FormatSpec& format, + const Args&... args) { + return absl::InvalidArgumentError(absl::StrFormat(format, args...)); +} + +template +absl::Status InternalError(const absl::FormatSpec& format, + const Args&... args) { + return absl::InternalError(absl::StrFormat(format, args...)); +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_ERRORS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/executable.h new file mode 100644 index 0000000000000000000000000000000000000000..05a3abe4618835629c0d841088e1ba8905e5175d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/executable.h @@ -0,0 +1,439 @@ +/* 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_RUNTIME_EXECUTABLE_H_ +#define XLA_RUNTIME_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/status/statusor.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/Support/MemoryBuffer.h" +#include "xla/runtime/arguments.h" +#include "xla/runtime/async_runtime.h" +#include "xla/runtime/custom_call.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/diagnostics.h" +#include "xla/runtime/execution_engine.h" +#include "xla/runtime/logical_result.h" +#include "xla/runtime/memory_mapper.h" +#include "xla/runtime/results.h" +#include "xla/runtime/type_id.h" +#include "xla/runtime/types.h" + +namespace xla { +namespace runtime { + +struct ExecutionContext; + +struct DestroyExecutionContext { + void operator()(ExecutionContext* ctx); +}; + +// If executable has async results, ExecutionReference keeps that +// execution context alive. For sync executables `Execute` always returns +// ExecutionReference with nullptr. +class ExecutionReference + : public std::unique_ptr { + // Bring std::unique_ptr constructors in scope. + using std::unique_ptr::unique_ptr; +}; + +class FunctionRef; +class JitCompiler; + +// Returns a symbols binding for running XLA executable with a custom symbols +// provided by the user. +ExecutionEngine::SymbolsBinding RuntimeSymbolsBinding( + ExecutionEngine::SymbolsBinding custom_binding); + +// Converts a direct custom call and custom type id name registration functions +// (types required by the library) to the execution engine symbols binding. +// Returned symbols binding always includes type id symbols for all +// canonical types supported by the XLA runtime custom calls. +ExecutionEngine::SymbolsBinding ToSymbolsBinding( + std::function custom_calls = {}, + std::function types = {}); + +class Executable { + public: + // Forward declare types defined below. + struct ArgumentsMemoryLayout; + struct ResultsMemoryLayout; + struct CallFrame; + struct ExecuteOpts; + + // Initializes call frame by adding all arguments according to the exported + // function ABI. Also allocates storage for the returned values according to + // the results memory layout. + // + // If `verify_arguments` is true (in debug mode it's always on, independent of + // the argument value) this function also verifies that arguments passed at + // run time matches the exported function signature (e.g. all statically known + // dimensions of the memrefs matches the arguments). Returns an error if finds + // a mismatch. + // + // This function leaves the execution context argument (the first argument of + // an exported function) uninitialized. It will be initialized in the + // `Execute` function right before the actual execution. + absl::Status InitializeCallFrame(unsigned ordinal, ArgumentsRef arguments, + CallFrame* call_frame, + bool verify_arguments = true) const; + + absl::Status InitializeCallFrame(ArgumentsRef arguments, + CallFrame* call_frame, + bool verify_arguments = true) const { + return InitializeCallFrame(0, arguments, call_frame, verify_arguments); + } + + // Converts returned values owned by the call frame using provided result + // converter. If exported function execution finished with an error (error + // flag is `true` in the call frame) returns error for all results (see + // `ResultConverter::ReturnError` documentation). + absl::Status ReturnResults(unsigned ordinal, const ResultConverter& results, + CallFrame* call_frame) const; + + absl::Status ReturnResults(const ResultConverter& results, + CallFrame* call_frame) const { + return ReturnResults(0, results, call_frame); + } + + // Executes exported function exported with given arguments. + // + // If `verify_arguments` is true (in debug mode it's always on, independent of + // the argument value) this function also verifies that arguments passed at + // run time matches the exported function signature. If some of the + // arguments do not match the expected type, this function allocates error + // async values for all results and returns an error. + // + // Returns exported function results via the user-provided results converter. + // If execution completed in the error state, returns error for all results. + absl::StatusOr Execute( + unsigned ordinal, ArgumentsRef arguments, const ResultConverter& results, + const ExecuteOpts& opts, bool verify_arguments = true) const; + + absl::StatusOr Execute( + ArgumentsRef arguments, const ResultConverter& results, + const ExecuteOpts& opts, bool verify_arguments = true) const { + return Execute(0, arguments, results, opts, verify_arguments); + } + + // Executes exported function using user provided call frame. + // + // It is the caller responsibility to handle the compiled function results + // stored in the call frame. + ExecutionReference Execute(unsigned ordinal, CallFrame& call_frame, + const ExecuteOpts& opts) const; + + void Execute(CallFrame& call_frame, const ExecuteOpts& opts) const { + Execute(0, call_frame, opts); + } + + std::string_view name() const { return name_; } + + std::optional specialization() const { return specialization_; } + + // Returns the number of exported functions. Functions are indexed by their + // ordinal number in the [0, num_functions) range. + size_t num_functions() const { return functions_.size(); } + + // Returns a function reference to an exported function with given ordinal. + FunctionRef function_ref(unsigned ordinal) const; + + // Returns true if exported function with given ordinal has async results. + bool IsAsync(unsigned ordinal) const; + bool IsAsync() const { return IsAsync(0); } + + // Returns the name of the exported function with the given ordinal. + std::string_view function_name(unsigned ordinal) const; + std::string_view function_name() const { return function_name(0); } + + // Returns the number of results of the exported function with given ordinal. + unsigned num_results(unsigned ordinal) const; + unsigned num_results() const { return num_results(0); } + + // Signature of the exported function with the given ordinal before lowering + // to the runtime dialects. See JitExecutable::Function's `signature` for + // more details. + const FunctionType& signature(unsigned ordinal) const; + const FunctionType& signature() const { return signature(0); } + + // Signature of the exported function with the given ordinal after lowering it + // from high level dialects to the dialects supported by the XLA runtime. See + // JitExecutable::Function's `signature` for more details. + const FunctionType& runtime_signature(unsigned ordinal) const; + const FunctionType& runtime_signature() const { return runtime_signature(0); } + + std::chrono::milliseconds time_to_compile() const; + + // Get the object file behind this executable (on linux for example, it will + // be https://en.wikipedia.org/wiki/Executable_and_Linkable_Format + // executable). Can be null. + std::unique_ptr obj_file() const; + + // CallFrame provides a pointer-stable storage for packed function arguments + // and storage for returned values. + struct CallFrame { + // Pointers to executable arguments. + llvm::SmallVector args; + + // We use single block of memory to store executable results. We need to be + // able to store pointers to async values and tokens, and strided memrefs + // which at runtime are represented as StridedMemrefType. + // + // Currently we only need to provide result storage for pointers and memref + // sizes and strides (int64_t type). If we'll need to support more complex + // return types we'll have to be more careful about alignment requirements. + static_assert(sizeof(uintptr_t) == sizeof(int64_t), + "uintptr_t size must be the same as int64_t"); + + // Memory where the executable will write its results. + llvm::SmallVector results; + + // Tracks whether any of the outputs were set. + bool has_set_outputs = false; + + // Indicates whether the execution finished with an error. + bool is_error = false; + + // The error message which is available only if `is_error` is true. The + // assumption is that the error message string is owned by the compiled + // binary and the call frame can safely keep a non-owning pointer. + std::string_view error; + }; + + // Requirements for passing arguments to the compiled function. + struct ArgumentsMemoryLayout { + size_t num_args_ptrs = 0; // total number of required pointers + llvm::SmallVector num_ptrs; // num_ptrs for each argument + llvm::SmallVector offsets; // offsets into the args array + }; + + // Requirements for the contiguous block of memory to store compiled function + // results. When we invoke a compiled fuction we allocate a block of memory, + // and pass pointers to pre-computed offsets as output arguments to the + // function. + struct ResultsMemoryLayout { + bool has_async_results = false; // true iff returns async results + size_t size = 0; // number of bytes required + llvm::SmallVector offsets; // offsets in the block of memory + }; + + struct ExecuteOpts { + // Async task runner for executing async runtime tasks. Typically it + // schedules async tasks into the underlying thread pool. It's the caller's + // responsibility to guarantee that it will outlive the execution of all + // async tasks started by the executable. + AsyncTaskRunner* async_task_runner = nullptr; + + // A container for passing arbitrary user-provided data to the custom call + // handlers. Must outlive all async tasks launched by this executable. + const CustomCall::UserData* custom_call_data = nullptr; + + // Dynamically registered custom calls library. These custom calls resolved + // at run time by name. In contrast to custom calls defined by the + // `DirectCustomCallRegistry` which are linked directly with the executable + // at compile time. + const DynamicCustomCallRegistry* custom_call_registry = nullptr; + + // Diagnostic engine is responsible for passing runtime diagnostics back + // to the caller through the diagnostic handler. + const DiagnosticEngine* diagnostic_engine = nullptr; + }; + + // Function specification for loading from the object file. + struct LoadFunction { + std::string name; + FunctionType signature; + FunctionType runtime_signature; + }; + + // Loads executable from an object file. It is the caller responsibility to + // guarantee that signatures do match the compiled function in the object + // file, otherwise it will surely lead to crash. + static absl::StatusOr LoadFromObjFile( + std::string_view name, std::unique_ptr obj_file, + std::vector load_functions, + ExecutionEngine::SymbolsBinding symbols_binding = {}, + std::string_view memory_region_name = ""); + + // Verifies that all arguments types in the exported function signature are + // supported at run time. Returns a pre-computed layout for the function + // arguments. If some arguments are not supported returns an error. + static absl::StatusOr GetArgumentsMemoryLayout( + const FunctionType& signature); + + // Verifies that all results types in the exported function signature are + // supported at run time . Returns a pre-computed layout for the function + // results. If some results are not supported returns an error. + static absl::StatusOr GetResultsMemoryLayout( + const FunctionType& signature); + + // TODO(ezhulenev): The following three functions should be decoupled from + // the executable header file (maybe move them to runtime.h?) so that custom + // call implementations do not have to depend on the `executable` target. + + // Returns the user data passed via the ExecuteOpts to the executable. + static const CustomCall::UserData* GetUserData(ExecutionContext* ctx); + + // Returns the diagnostic engine passed via the ExecuteOpts to the executable. + static const DiagnosticEngine* GetDiagnosticEngine(ExecutionContext* ctx); + + // Calls the custom call handler with the given runtime context, arguments, + // attributes and results. + static LogicalResult Call(ExecutionContext* ctx, CustomCall& call, + void** args, void** attrs, void** rets); + + bool RequiresBlas(int ordinal) const { + return functions_[ordinal].requires_blas; + } + + private: + friend class JitCompiler; // see `mlir/runtime/transforms/jit_compiler.h` + + // Executable exports multiple functions available for users to call into. At + // run time they are referenced by their ordinal, so that we don't depend on + // expensive by-name lookup on the hot path. We keep function name only for + // debugging. Function ordinal is defined by its index in the `functions_` + // vector. + struct Function { + Function(std::string_view name, ExecutionEngine::ExportedFunctionPtr fptr, + FunctionType signature, FunctionType runtime_signature, + ArgumentsMemoryLayout arguments_memory_layout, + ResultsMemoryLayout results_memory_layout, bool requires_blas) + : name(name), + fptr(std::move(fptr)), + signature(std::move(signature)), + runtime_signature(std::move(runtime_signature)), + arguments_memory_layout(std::move(arguments_memory_layout)), + results_memory_layout(std::move(results_memory_layout)), + requires_blas(requires_blas) {} + Function(const Function&) = delete; + Function(Function&&) = default; + + // Exported function name. + std::string name; + + // Pointer to an exported function owned by the execution engine. + ExecutionEngine::ExportedFunctionPtr fptr; + + // Signature of the exported function function before lowering to the + // runtime dialects (see JitExecutable::Function's `signature`). + FunctionType signature; + + // Signature of the exported function after lowering it from high level + // dialects to the dialects supported by the XLA runtime. + // + // - Operands and results types converted to the types with well-defined ABI + // (e.g. tensors converted to memrefs). + // + // - First argument is always an execution context added to the function by + // the lowering pipeline. + // + // From this signatur, Executable infers how to pack runtime arguments + // according to the expected memory layout, and how to convert results + // returned from the JIT-compiled function into high level types (e.g. how + // to convert StridedMemrefType into Tensorflow Tensor). + // + // To infer the type of the returned value, Executable looks at the type + // defined by the `runtime_signature` to get the memory layout of the + // returned value, and at the type defined by the `signature` to get the + // type expected by the runtime. + FunctionType runtime_signature; + + // Memory layout required for passing function arguments. + ArgumentsMemoryLayout arguments_memory_layout; + + // Memory layout for returning function results. + ResultsMemoryLayout results_memory_layout; + + // If this flag is true, then this function is outlined for cuda graph, and + // cuBlas should be initiated when capturing the cuda graph. + bool requires_blas; + }; + + Executable(std::string_view name, + std::unique_ptr memory_mapper, + std::unique_ptr engine, + std::vector functions, + std::optional specialization, + std::chrono::milliseconds time_to_compile) + : name_(name), + memory_mapper_(std::move(memory_mapper)), + engine_(std::move(engine)), + functions_(std::move(functions)), + specialization_(specialization), + time_to_compile_(time_to_compile) { + // All exported functions must have a non-null function pointer. + assert(llvm::all_of(functions_, [](const Function& f) { return f.fptr; })); + } + + std::string name_; // name of the compiled executable + + // Called by `engine_`'s destructor; must appear before it. + std::unique_ptr memory_mapper_; // optional + + // XLA runtime execution engine owns the LLVM ORC jit compilation stack. + std::unique_ptr engine_; + + // Functions exported by this executable, indexed by function ordinal. + std::vector functions_; + + // Specialization id if this executable is a specialization, or an empty + // optional if this executable is a default one. + std::optional specialization_; + + // The time it took to compile this binary. + std::chrono::milliseconds time_to_compile_; +}; + +// Function reference provides a function-like API for a function exported from +// the executabled with the given ordinal. +class FunctionRef { + public: + FunctionRef(const Executable* executable, unsigned ordinal); + + absl::StatusOr operator()( + ArgumentsRef arguments, const ResultConverter& results, + const Executable::ExecuteOpts& opts, bool verify_arguments = true) const; + + bool RequiresBlas() const { return executable_->RequiresBlas(ordinal_); } + + unsigned ordinal() const { return ordinal_; } + + private: + const Executable* executable_; + unsigned ordinal_; +}; + +// Escape slashes, substituting them with double underscores to get a memory +// region name for the XlaRuntimeMemoryMapper. +// +// The profiler's UI might interpret slashes as callchain separators, +// whereas we want the region name to be shown in full. +inline std::string EscapeMemRegionName(std::string_view memory_region_name) { + return llvm::join(llvm::split(memory_region_name, '/'), "__"); +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/execution_engine.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/execution_engine.h new file mode 100644 index 0000000000000000000000000000000000000000..f7e3c299a738e2aaa651e7b14cdf8a2297552064 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/execution_engine.h @@ -0,0 +1,187 @@ +/* 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_RUNTIME_EXECUTION_ENGINE_H_ +#define XLA_RUNTIME_EXECUTION_ENGINE_H_ + +#include +#include +#include +#include +#include + +#include "absl/status/statusor.h" +#include "llvm/ExecutionEngine/JITEventListener.h" +#include "llvm/ExecutionEngine/Orc/LLJIT.h" +#include "llvm/ExecutionEngine/SectionMemoryManager.h" +#include "llvm/Support/MemoryBuffer.h" + +namespace xla { +namespace runtime { + +// A pre-fabricated wrapper around ORC JIT stack for running XLA executables. +// +// It allows to run jit-compiled XLA executables, AOT compile them or load +// previously AOT compiled executables. +// +// XLA executable itself is responsible for the function signature verification, +// arguments packing according to the ABI, results decoding and linking the +// executable with runtime intrinsics. Execution engine only helps with setting +// up ORC JIT stack to support the execution, but itself doesn't know what it is +// executing. +class ExecutionEngine { + public: + // Pointer to a function exported to the Xla executable. + // + // Xla exported function expects all arguments to be passed as an array of + // opaque pointers to the actual values. In C++ it would look like this: + // + // void compute(int32_t arg0, float arg1, ...); + // + // void __xla_compute(void** args) { + // int32_t arg0 = *reinterpret_cast(args[0]); + // float arg1 = *reinterpret_cast(args[1]); + // ... + // compute(arg0, arg1, ...); + // } + // + // This is required to avoid dealing with ABI of the compiled function. See + // `SetUpExportedFunction` for implementation details. + using ExportedFunctionPtr = void (*)(void **); + + // Callback to register symbols with the execution engine (e.g. to register + // custom runtime intrinsics for Gpu integration). + using SymbolsBinding = + std::function; + + // Callback to run optimization passes on the compiled LLVM module. + using OptimizingTransformer = std::function; + + // Callback to construct an optimizing transformer for the given options. + using MakeOptimizingTransformer = + std::function; + + // Compose multiple symbol bindings into a single symbol binding function. + static SymbolsBinding BindAll(std::vector bindings); + + //------------------------------------------------------------------------- // + // Options for creating execution engine from an LLVM module. + //------------------------------------------------------------------------- // + + struct JitOptions { + // User-provided codegen optimization level. + llvm::CodeGenOptLevel opt_level = llvm::CodeGenOptLevel::Default; + + // User-provided target machine specification. + std::shared_ptr target_machine = nullptr; + + // User-provided builder for the optimizing transformer. + MakeOptimizingTransformer make_optimizing_transformer; + + // User-provided memory mapper for allocating memory for executables. + llvm::SectionMemoryManager::MemoryMapper *section_memory_mapper = nullptr; + + // User-provided bindings for symbols. + SymbolsBinding symbols_binding = nullptr; + + // Notify the llvm's global GDB notifications listener. + bool enable_gdb_listener = false; + + // Notify the llvm's global Perf notifications listener. + bool enable_perf_listener = false; + + // Save compiled object file. + bool save_compiled_obj_file = true; + }; + + // Creates a new execution engine by compiling the provided LLVM module to + // a native executable using LLVM ORC stack. + static absl::StatusOr> CreateFromModule( + std::unique_ptr ctx, + std::unique_ptr module, JitOptions options, + absl::Span exported); + + //------------------------------------------------------------------------- // + // Options for creating execution engine from an AOT compiled object file. + //------------------------------------------------------------------------- // + + struct AotOptions { + // User-provided memory mapper for allocating memory for executables. + llvm::SectionMemoryManager::MemoryMapper *section_memory_mapper = nullptr; + + // User-provided bindings for symbols. + SymbolsBinding symbols_binding = nullptr; + + // Notify the llvm's global GDB notifications listener. + bool enable_gdb_listener = true; + + // Notify the llvm's global Perf notifications listener. + bool enable_perf_listener = true; + }; + + // Creates a new execution engine by loading AOT compiled XLA executable + // object file. + static absl::StatusOr> CreateFromObjFile( + std::unique_ptr, AotOptions options, + absl::Span exported); + + //------------------------------------------------------------------------- // + + // Returns a pointer to the exported function. + absl::Span exported() const { return exported_; } + + ExportedFunctionPtr exported(unsigned ordinal) const { + return exported_[ordinal]; + } + + // Return a memory buffer with a object file behind this execution engine. Can + // be null if execution engine didn't save the compiled object file. + std::unique_ptr obj_file() const; + + private: + ExecutionEngine(bool enable_gdb_listener, bool enable_perf_listener); + + // We build execution engine on top of the ORC LLJIT API, which owns all + // compiled/loaded object files and does the linking at run time. + // + // TODO(ezhulenev): Instead of keeping LLJIT alive we should be able to keep + // only llvm::orc::JITDylibSP owning main dylib and the object layer owning + // memory-mapped regions holding object files. Once we are done with + // executable compilation this jit is defunct because it holds an expired + // weak_ptr to an llvm::orc::TargetMachine instance. + std::unique_ptr jit_; + + // Pointers to resolved exported functions. Indexed by function ordinal. + std::vector exported_; + + // Object file behind the compiled executable. Can be null. + std::unique_ptr obj_file_; + + llvm::JITEventListener *gdb_listener_ = nullptr; + llvm::JITEventListener *perf_listener_ = nullptr; +}; + +// Emits an interface function ('exported_name') that wraps all arguments +// of a function ('original_name') into a single pointer to a ptr**, +// thereby exposing a trivial ABI. The original function is also inlined, +// if possible. +absl::Status ExportWithXlaRuntimeAbi(llvm::Module &module, + std::string_view original_name, + std::string_view exported_name); + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_EXECUTION_ENGINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi.h new file mode 100644 index 0000000000000000000000000000000000000000..b21cbb3ec8cb419e97b34314bd4ef3cf21c71997 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi.h @@ -0,0 +1,97 @@ +/* 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_RUNTIME_FFI_H_ +#define XLA_RUNTIME_FFI_H_ + +#include +#include +#include + +#include "xla/runtime/ffi/ffi_c_api.h" +#include "xla/runtime/module.h" + +namespace xla { +namespace runtime { +namespace ffi { + +// Returns FFI modules registered with an XLA runtime. +std::vector FfiModules(); + +// Exports registered FFI modules to the given custom call registry. +void ExportFfiModules(DynamicCustomCallRegistry& registry); + +// XLA runtime wrapper around FFI module. +class FfiModule; + +//===----------------------------------------------------------------------===// +// RAII helpers for the state instantiated by the FFI modules. +//===----------------------------------------------------------------------===// + +// Deletes the FFI module `state` instantiated by the `module`. +struct FfiStateDeleter { + void operator()(XLA_FFI_Module_State* state); + const FfiModule* module; +}; + +// A smart pointer owning `state` instantiated by the `module`. +struct OwnedFfiState + : public std::unique_ptr { + using Base = std::unique_ptr; + OwnedFfiState(const FfiModule* module, XLA_FFI_Module_State* state); +}; + +//===----------------------------------------------------------------------===// +// FFI modules <-> XLA runtime integration via UserData. +//===----------------------------------------------------------------------===// + +// A vector of opaque pointers to FFI modules state that is passed around inside +// `UserData` and enables FFI functions to find their state. +struct FfiStateVector { + std::vector state; // indexed by module id + + // If FFI module instantiates state for each execution, the state vector will + // be the owner of that state for the duration of execution. + std::vector per_execution_state; +}; + +// FfiModulesState is a container that owns the FFI modules state. +class FfiModulesState { + public: + FfiModulesState() = default; + + // Instantiates `FfiModulesState` from the registered FFI module. + static absl::StatusOr Instantiate(); + + absl::StatusOr state_vector() const; + + private: + explicit FfiModulesState(std::vector> state); + + std::vector> state_; +}; + +// Gets the underlying FFI stream from the `user_data`. +XLA_FFI_Stream* GetXlaFfiStream(const CustomCall::UserData* user_data, + const DiagnosticEngine* diagnostic); + +void RegisterXlaFfiStreamProvider( + XLA_FFI_Stream* (*)(const CustomCall::UserData*, const DiagnosticEngine*)); + +} // namespace ffi +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_FFI_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_abi.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_abi.h new file mode 100644 index 0000000000000000000000000000000000000000..3bb01f9a70230854fdecab919bd898673cfe1db5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_abi.h @@ -0,0 +1,62 @@ +/* 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_RUNTIME_FFI_FFI_ABI_H_ +#define XLA_RUNTIME_FFI_FFI_ABI_H_ + +#include + +namespace xla { +namespace runtime { +namespace internal { + +//===----------------------------------------------------------------------===// +// C structures that XLA uses internally to encode arguments and attributes. +//===----------------------------------------------------------------------===// + +// When XLA compiles host-side executable via lowering to LLVM (see `rt-to-llvm` +// pass) it encodes arguments and attributes as `!llvm.struct<...>` types stored +// as LLVM global constants (attributes and statically known arguments) or as +// allocas on the stack. We rely on standard layout C++ structs to reinterpret +// cast arguments and attributes pointers, and convert them to user-friendly C++ +// types (e.g. `EncodedMemref` to `StridedBufferArg`). +// +// See: https://en.cppreference.com/w/cpp/types/is_standard_layout + +struct EncodedMemref { + uint8_t dtype; + uint8_t rank; + void* data; + int64_t dims[]; +}; + +template +struct EncodedArray { + int64_t size; + const T* data; +}; + +template +struct EncodedDenseElements { + struct EncodedArray payload; + int64_t rank; + int64_t shape[]; +}; + +} // namespace internal +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_FFI_FFI_ABI_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_api.h new file mode 100644 index 0000000000000000000000000000000000000000..63a79cd0357ceca9b0805f152aa28acf2c7593b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_api.h @@ -0,0 +1,1270 @@ +/* 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_RUNTIME_FFI_FFI_API_H_ +#define XLA_RUNTIME_FFI_FFI_API_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "xla/runtime/ffi/ffi_abi.h" +#include "xla/runtime/ffi/ffi_c_api.h" + +namespace xla { +namespace runtime { +namespace ffi { + +// Forward declare template defined below. +template +class FfiBinding; + +// Forward declare template defined below. +template +class FfiHandler; + +// FFI arguments allocated by the jit-compiled code and we need to mark all +// memory initialized to suppress memory sanitizer errors. +#if defined(MEMORY_SANITIZER) +#define XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \ + __msan_unpoison(address, size) +#else +#define XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) // empty +#endif // MEMORY_SANITIZER + +//===----------------------------------------------------------------------===// +// Check struct sizes passed across the C API to detect mismatched versions. +//===----------------------------------------------------------------------===// + +namespace internal { +inline void CheckStructSize(std::string_view struct_name, size_t expected_size, + size_t actual_size) { + if (expected_size != actual_size) { + std::cerr << "Unexpected " << struct_name << " size: expected " + << expected_size << " << got " << actual_size + << ". Check installed software versions." << std::endl; + std::abort(); + } +} +} // namespace internal + +#define CHECK_ARGS_SIZE(name, args) \ + internal::CheckStructSize("XLA_FFI_##name##_Args", \ + XLA_FFI_##name##_Args_STRUCT_SIZE, \ + args->struct_size) + +//===----------------------------------------------------------------------===// +// Span is non-owning view into contiguous values of type `T`. +//===----------------------------------------------------------------------===// + +// TODO(ezhulenev): Replace with `std::span` when C++20 is available. +template +class Span { + public: + Span(T* data, size_t size) : data_(data), size_(size) {} + Span(const std::vector>& vec) // NOLINT + : Span(vec.data(), vec.size()) {} + + T& operator[](size_t index) const { return data_[index]; } + + size_t size() const { return size_; } + + T* begin() const { return data_; } + T* end() const { return data_ + size_; } + + private: + T* data_; + size_t size_; +}; + +// A type for representing shaped tensors. +// TODO(ecg): expand API to be compatible with `std::mdspan`, and eventually +// (when C++23 is available) replace with `std::mdspan`. +template +struct MdSpan { + Span shape; + Span data; +}; + +//===----------------------------------------------------------------------===// +// XLA FFI status wrapper around error reporting APIs. +//===----------------------------------------------------------------------===// + +class FfiStatus { + public: + static FfiStatus Ok() { return FfiStatus(); } + + static FfiStatus Internal(std::string message) { + XLA_FFI_Error_Code errc = XLA_FFI_Error_Code_INTERNAL; + return FfiStatus(errc, message); + } + + static FfiStatus InvalidArgument(std::string message) { + XLA_FFI_Error_Code errc = XLA_FFI_Error_Code_INVALID_ARGUMENT; + return FfiStatus(errc, message); + } + + std::optional errc() const { return errc_; } + + std::string_view message() const { + return message_.has_value() ? *message_ : std::string_view(); + } + + const char* message_c_str() const { + return message_.has_value() ? message_->c_str() : ""; + } + + private: + FfiStatus() = default; + + FfiStatus(XLA_FFI_Error_Code errc, std::string message) + : errc_(errc), message_(std::move(message)) {} + + std::optional errc_; + std::optional message_; +}; + +//===----------------------------------------------------------------------===// +// XLA FFI virtual base for implementing FFI functions. +//===----------------------------------------------------------------------===// + +class Ffi { + public: + virtual ~Ffi() = default; + + virtual XLA_FFI_Error* operator()(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, void** args, + void** attrs, void** rets) const = 0; + + static FfiBinding<> Binding(); + + template + static bool Isa(const XLA_FFI_Api* api, XLA_FFI_TypeId type_id); + + template + static bool Isa(const XLA_FFI_Api* api, XLA_FFI_TypeId type_id) { + return Isa(api, type_id) || Isa(api, type_id); + } +}; + +//===----------------------------------------------------------------------===// +// XLA FFI module is a base class for stateful and stateless FFI modules. +//===----------------------------------------------------------------------===// + +class Module { + public: + virtual ~Module() = default; + + struct ExportedFunction { + std::string target; + XLA_FFI_Function* function; + }; + + protected: + Module(const XLA_FFI_Api* api, std::string module_name, + std::vector exported_functions, + XLA_FFI_Module_StateType state_type, + XLA_FFI_Module_CreateState* create_state, + XLA_FFI_Module_DestroyState* destroy_state) + : api_(api), + module_name_(std::move(module_name)), + exported_functions_(std::move(exported_functions)) { + Register(state_type, create_state, destroy_state); + } + + private: + // Register `this` module with the XLA runtime. + void Register(XLA_FFI_Module_StateType state_type, + XLA_FFI_Module_CreateState* create_state, + XLA_FFI_Module_DestroyState* destroy_state) { + XLA_FFI_Module_Register_Args args; + args.struct_size = XLA_FFI_Module_Register_Args_STRUCT_SIZE; + args.priv = nullptr; + args.name = module_name_.c_str(); + args.module = reinterpret_cast(this); + args.state_type = state_type; + args.create_state = create_state; + args.destroy_state = destroy_state; + + std::vector exported_names; + std::vector exported_functions; + for (auto& fn : exported_functions_) { + exported_names.push_back(fn.target.c_str()); + exported_functions.push_back(fn.function); + } + + args.num_exported_functions = exported_functions_.size(); + args.exported_names = exported_names.data(); + args.exported_functions = exported_functions.data(); + + api_->XLA_FFI_Module_Register(&args); + } + + // Module is registered with the XLA runtime behind this API instance, and any + // module manipulation (e.g. export functions) must be done through it. + const XLA_FFI_Api* api_; + + std::string module_name_; + std::vector exported_functions_; +}; + +//===----------------------------------------------------------------------===// +// XLA FFI stateful module is a collection of FFI functions and a state. +//===----------------------------------------------------------------------===// + +template +class StatefulModule : public Module { + public: + // TODO(ezhulenev): To gracefully fail if state can't be created, this has to + // return `FfiStatusOr>`, but we do not have a + // `StatusOr` implementation yet and we can't depend on absl. + virtual std::unique_ptr CreateState() = 0; + + protected: + StatefulModule(const XLA_FFI_Api* api, std::string module_name, + std::vector exported_functions, + bool per_execution_state = false) + : Module(api, std::move(module_name), std::move(exported_functions), + per_execution_state ? XLA_FFI_Module_State_PER_EXECUTION + : XLA_FFI_Module_State_PER_EXECUTABLE, + CreateState, DestroyState) {} + + private: + // Implements `XLA_FFI_Module_CreateState` API function. + static XLA_FFI_Error* CreateState(XLA_FFI_Module_CreateState_Args* args); + + // Implements `XLA_FFI_Module_DestroyState` API function. + static void DestroyState(XLA_FFI_Module_DestroyState_Args* args); +}; + +template +XLA_FFI_Error* StatefulModule::CreateState( + XLA_FFI_Module_CreateState_Args* args) { + CHECK_ARGS_SIZE(Module_CreateState, args); + + auto* module = reinterpret_cast(args->module); + auto* state = module->CreateState().release(); + args->state = reinterpret_cast(state); + return nullptr; // success +} + +template +void StatefulModule::DestroyState( + XLA_FFI_Module_DestroyState_Args* args) { + CHECK_ARGS_SIZE(Module_DestroyState, args); + + delete reinterpret_cast(args->state); +} + +//===----------------------------------------------------------------------===// +// XLA FFI stateless module is a collection of FFI functions without a state. +//===----------------------------------------------------------------------===// + +class StatelessModule : public Module { + protected: + StatelessModule(const XLA_FFI_Api* api, std::string module_name, + std::vector exported_functions) + : Module(api, std::move(module_name), std::move(exported_functions), + /*state_type=*/XLA_FFI_Module_State_PER_EXECUTABLE, + /*create_state=*/nullptr, /*destroy_state=*/nullptr) {} +}; + +//===----------------------------------------------------------------------===// +// Helper macro to define a static module registration. +//===----------------------------------------------------------------------===// + +#define XLA_REGISTER_FFI_MODULE(FUNC) \ + XLA_REGISTER_FFI_MODULE_IMPL(FUNC, __COUNTER__) + +#define XLA_REGISTER_FFI_MODULE_IMPL(FUNC, N) \ + static bool xla_ffi_module_##N##_registered_ = []() { \ + static auto* module = FUNC.release(); \ + return module != nullptr; \ + }() + +//===----------------------------------------------------------------------===// +// Arguments supported by the FFI handlers. +//===----------------------------------------------------------------------===// + +// This enum corresponds to xla::PrimitiveType enum defined in `hlo.proto`. +enum class PrimitiveType : uint8_t { + // Invalid primitive type to serve as default. + PRIMITIVE_TYPE_INVALID = 0, + + // Predicates are two-state booleans. + PRED = 1, + + // Signed integral values of fixed width. + S8 = 2, + S16 = 3, + S32 = 4, + S64 = 5, + + // Unsigned integral values of fixed width. + U8 = 6, + U16 = 7, + U32 = 8, + U64 = 9, + + // Floating-point values of fixed width. + // + // Note: if f16s are not natively supported on the device, they will be + // converted to f16 from f32 at arbitrary points in the computation. + F16 = 10, + F32 = 11, + + // Truncated 16 bit floating-point format. This is similar to IEEE's 16 bit + // floating-point format, but uses 1 bit for the sign, 8 bits for the exponent + // and 7 bits for the mantissa. + BF16 = 16, + + F64 = 12, +}; + +constexpr int ByteWidth(PrimitiveType type) { + switch (type) { + case PrimitiveType::PRED: + return 1; + + case PrimitiveType::S8: + case PrimitiveType::U8: + return 1; + + case PrimitiveType::S16: + case PrimitiveType::U16: + case PrimitiveType::F16: + case PrimitiveType::BF16: + return 2; + + case PrimitiveType::S32: + case PrimitiveType::U32: + case PrimitiveType::F32: + return 4; + + case PrimitiveType::S64: + case PrimitiveType::U64: + case PrimitiveType::F64: + return 8; + + case PrimitiveType::PRIMITIVE_TYPE_INVALID: + assert(false && "Unsupported type"); + return 0; + } +} + +constexpr std::string_view PrimitiveTypeToString(PrimitiveType type) { + switch (type) { + case PrimitiveType::PRIMITIVE_TYPE_INVALID: + return "invalid"; + case PrimitiveType::PRED: + return "pred"; + case PrimitiveType::S8: + return "s8"; + case PrimitiveType::S16: + return "s16"; + case PrimitiveType::S32: + return "s32"; + case PrimitiveType::S64: + return "s64"; + case PrimitiveType::U8: + return "u8"; + case PrimitiveType::U16: + return "u16"; + case PrimitiveType::U32: + return "u32"; + case PrimitiveType::U64: + return "u64"; + case PrimitiveType::F16: + return "f16"; + case PrimitiveType::F32: + return "f32"; + case PrimitiveType::BF16: + return "bf16"; + case PrimitiveType::F64: + return "f64"; + } +} + +// A view into the buffer argument. Buffers with non-identity layouts can be +// decoded only as a StridedBufferArg. +struct StridedBufferArg { + std::string ToString() const; + + PrimitiveType dtype; + void* data; + Span sizes; + Span strides; +}; + +// A view into the buffer argument with an identity (row major) layout. +struct BufferArg { + std::string ToString() const; + + PrimitiveType dtype; + void* data; + Span sizes; +}; + +// A flat view into the buffer argument with an identity (row major) layout. +// If the memref shape and strides are not required, it is cheaper to pass the +// flat buffer argument. +struct FlatBufferArg { + std::string ToString() const; + + PrimitiveType dtype; + void* data; + int64_t size_in_bytes; +}; + +// A type tag to represent dictionary attributes that can be decoded into +// structs using aggregate attribute decoding. +struct Dictionary {}; + +template +bool Ffi::Isa(const XLA_FFI_Api* api, XLA_FFI_TypeId type_id) { +#define ISA(type, name) \ + if constexpr (std::is_same_v) \ + return api->XLA_FFI_Get_##name##_TypeId() == type_id; + + ISA(std::string_view, String); + + ISA(float, Float); + ISA(double, Double); + ISA(bool, Int1); + ISA(int32_t, Int32); + ISA(int64_t, Int64); + + ISA(Span, FloatArray); + ISA(Span, DoubleArray); + ISA(Span, Int32Array); + ISA(Span, Int64Array); + + ISA(MdSpan, FloatTensor); + ISA(MdSpan, DoubleTensor); + ISA(MdSpan, Int32Tensor); + ISA(MdSpan, Int64Tensor); + + ISA(StridedBufferArg, StridedBufferArg); + ISA(BufferArg, BufferArg); + ISA(Dictionary, Dictionary); + + assert(false && "Unsupported type"); + return false; + +#undef ISA +} + +//===----------------------------------------------------------------------===// +// Pretty printing for buffers. +//===----------------------------------------------------------------------===// + +static void PrintArray(std::stringstream& ss, Span arr) { + ss << "["; + for (unsigned i = 0; i < arr.size(); ++i) + (i > 0) ? ss << ", " << arr[i] : ss << arr[i]; + ss << "]"; +} + +inline std::string StridedBufferArg::ToString() const { + std::stringstream ss; + ss << "Buffer: dtype=" << PrimitiveTypeToString(dtype); + ss << " sizes="; + PrintArray(ss, sizes); + ss << " strides="; + PrintArray(ss, strides); + return ss.str(); +} + +inline std::string BufferArg::ToString() const { + std::stringstream ss; + ss << "Buffer: dtype=" << PrimitiveTypeToString(dtype); + ss << " sizes="; + PrintArray(ss, sizes); + return ss.str(); +} + +inline std::string FlatBufferArg::ToString() const { + std::stringstream ss; + ss << "Buffer: dtype=" << PrimitiveTypeToString(dtype); + ss << " size=" << size_in_bytes; + return ss.str(); +} + +//===----------------------------------------------------------------------===// +// FFI binding describes the function signature expected by the FFI handler +// using its variadic template parameter. +// +// FFI binding: +// FfiBinding +// +// Corresponds to the function signature: +// FfiStatus MyHandler(int32_t arg0, float arg1); +// +//===----------------------------------------------------------------------===// + +namespace internal { + +// A type tag to distinguish arguments tied to the attributes in the +// `FfiBinding` variadic template argument. +template +struct AttrTag {}; + +// A type tag to distinguish argument tied to FFI module state. +template +struct StateTag {}; + +// A type tag to distinguish argument tied to XLA runtime stream. +template +struct StreamTag {}; + +// Type tag to distinguish an argument tied to an "ApiPriv" argument +// to `Ffi::Binding`. This is necessary to obtain `XLA_FFI_Api.priv` +// from the foreign function. For example: +// +// static ffi::FfiStatus FooFfi(MyStruct* bar, ffi::BufferArg input) { ... } +// +// XLA_FFI_DEFINE_FUNCTION( +// FFI_Foo, FooFfi, ffi::Ffi::Binding() +// .ApriPriv +// .Arg); +template +struct ApiPrivTag {}; + +// A template for checking if type is a wrapped attribute or user data. +// clang-format off +template struct IsWrapped : std::false_type {}; +template struct IsWrapped> : std::true_type {}; +template struct IsWrapped> : std::true_type {}; +template struct IsWrapped> : std::true_type {}; +template struct IsWrapped> : std::true_type {}; +// clang-format on + +} // namespace internal + +template +class FfiBinding { + public: + template + FfiBinding Arg() && { + return {std::move(*this)}; + } + + template + FfiBinding> Attr(std::string attr) && { + attrs_.push_back(std::move(attr)); + return {std::move(*this)}; + } + + template + FfiBinding> State() && { + return {std::move(*this)}; + } + + template + FfiBinding> Stream() && { + static_assert(std::is_pointer_v, + "T must be a pointer type, e.g. for GPU platform it must be " + "se::gpu::GpuStreamHandle"); + return {std::move(*this)}; + } + + template + FfiBinding> ApiPriv() && { + static_assert(std::is_pointer_v, "T must be a pointer type"); + return {std::move(*this)}; + } + + template + std::unique_ptr> To(Fn fn) { + return std::unique_ptr>( + new FfiHandler(std::forward(fn), std::move(attrs_))); + } + + private: + template + friend class FfiBinding; + friend class Ffi; + + explicit FfiBinding() { + static_assert(sizeof...(Ts) == 0, "ffi arguments must be empty"); + } + + template + FfiBinding(FfiBinding&& other) // NOLINT + : attrs_(std::move(other.attrs_)) {} + + FfiBinding(FfiBinding&) = delete; + + std::vector attrs_; // names of bound attributes +}; + +inline FfiBinding<> Ffi::Binding() { return FfiBinding<>(); } + +//===----------------------------------------------------------------------===// +// Helpers for decoding opaque arguments and attributes' memory. +//===----------------------------------------------------------------------===// + +namespace internal { + +using runtime::internal::EncodedArray; +using runtime::internal::EncodedMemref; + +// Decoded pair of argument type and opaque value. +struct DecodedArg { + XLA_FFI_TypeId type_id; + void* value; +}; + +// Decoded triple of attribute name, type and opaque value. +struct DecodedAttr { + std::string_view name; + XLA_FFI_TypeId type_id; + void* value; +}; + +// A convenience wrapper around opaque arguments memory. +class DecodedArgs { + public: + explicit DecodedArgs(void** args) { + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(args, sizeof(void*)); + size_ = *reinterpret_cast(args[0]); + if (size_) { + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(args + 1, sizeof(void*)); + types_ = reinterpret_cast(args[1]); + values_ = args + 2; + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(types_, size_ * sizeof(void*)); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(values_, size_ * sizeof(void*)); + } + } + + int64_t size() const { return size_; } + + DecodedArg operator[](size_t i) const { + DecodedArg arg; + arg.type_id = types_[i]; + arg.value = values_[i]; + return arg; + } + + private: + int64_t size_; + void** types_ = nullptr; + void** values_ = nullptr; +}; + +// A convenience wrapper around opaque attributes' memory. +class DecodedAttrs { + public: + explicit DecodedAttrs(void** attrs) : encoded_(attrs + 1) { + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(attrs, sizeof(void*)); + size_ = *reinterpret_cast(attrs[0]); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded_, 3 * size_ * sizeof(void*)); + } + + int64_t size() const { return size_; } + + DecodedAttr operator[](size_t i) const { + void** attr_base = encoded_ + i * 3; + + DecodedAttr attr; + auto* name = reinterpret_cast*>(attr_base[0]); + attr.name = std::string_view(name->data, name->size); + attr.type_id = attr_base[1]; + attr.value = attr_base[2]; + + return attr; + } + + private: + void** encoded_; + int64_t size_; +}; + +} // namespace internal + +//===----------------------------------------------------------------------===// +// XLA FFI arguments decoding implementation. +//===----------------------------------------------------------------------===// + +// XLA FFI arguments decoding must be defined by specializing this template. +// +// Example: decoding for the `MyType` arguments +// +// template <> +// struct FfiArgDecoding { +// static std::optional Decode(ExecutionContext* ctx, TypeId type_id, +// void* value); +// }; +// +template +struct FfiArgDecoding; + +// XLA FFI attribute decoding must be defined by specializing this template. +// +// Example: decoding for the `MyType` attributes +// +// template <> +// struct FfiAttrDecoding { +// static std::optional Decode(ExecutionContext* ctx, +// std::string_view name, +// TypeId type_id, void* value); +// } +// +template +struct FfiAttrDecoding; + +namespace internal { + +// When decoding input data we need to keep track of how many arguments, +// attributes, and returns we decoded so far to index into the correct data +// structure. +struct DecodingOffsets { + int64_t args = 0; + int64_t attrs = 0; + int64_t rets = 0; + int64_t values = 0; +}; + +template +struct Decode { + static std::optional call(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, + DecodingOffsets& offsets, + internal::DecodedArgs args, + const std::vector& attrs_names, + const std::vector& attrs_idx, + internal::DecodedAttrs attrs) { + internal::DecodedArg arg = args[offsets.args++]; + return FfiArgDecoding::Decode(api, arg.type_id, arg.value); + } +}; + +template +struct Decode> { + static std::optional call(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, + DecodingOffsets& offsets, + internal::DecodedArgs args, + const std::vector& attrs_names, + const std::vector& attrs_idx, + internal::DecodedAttrs attrs) { + // Find decoded attribute corresponding to the given attribute index. + int64_t idx = offsets.attrs++; + + // Get mapping from the attribute to its index in the sorted array. + size_t i = attrs_idx[idx]; + + // Attribute name does not match. + if (attrs[i].name != attrs_names[idx]) return std::nullopt; + + return FfiAttrDecoding::Decode(api, attrs[i].name, attrs[i].type_id, + attrs[i].value); + } +}; + +template +struct Decode> { + static std::optional call(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, + DecodingOffsets& offsets, internal::DecodedArgs, + const std::vector& attrs_names, + const std::vector& attrs_idx, + internal::DecodedAttrs attrs) { + XLA_FFI_ExecutionContext_GetModuleState_Args args; + args.struct_size = XLA_FFI_ExecutionContext_GetModuleState_Args_STRUCT_SIZE; + args.priv = nullptr; + args.ctx = ctx; + + XLA_FFI_Module_State* state = + api->XLA_FFI_ExecutionContext_GetModuleState(&args); + return reinterpret_cast(state); + } +}; + +template +struct Decode> { + static std::optional call(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, + DecodingOffsets& offsets, internal::DecodedArgs, + const std::vector& attrs_names, + const std::vector& attrs_idx, + internal::DecodedAttrs attrs) { + XLA_FFI_ExecutionContext_GetStream_Args args; + args.struct_size = XLA_FFI_ExecutionContext_GetStream_Args_STRUCT_SIZE; + args.priv = nullptr; + args.ctx = ctx; + + XLA_FFI_Stream* stream = api->XLA_FFI_ExecutionContext_GetStream(&args); + return reinterpret_cast(stream); + } +}; + +template +struct Decode> { + static std::optional call(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, + DecodingOffsets& offsets, internal::DecodedArgs, + const std::vector& attrs_names, + const std::vector& attrs_idx, + internal::DecodedAttrs attrs) { + return reinterpret_cast(api->priv); + } +}; + +} // namespace internal + +//===----------------------------------------------------------------------===// +// Ffi handler binds concrete ffi implementation of type `Fn` to the ffi +// function signature. `Fn` can be a function pointer or a lambda. +// +// Ffi handler uses the variadic template parameter `Ts` to decode the +// opaque pointers passed to the `call` function into the C++ types that are +// forwarded to the ffi implementation. +//===----------------------------------------------------------------------===// + +namespace internal { + +// A helper template to extract the type of the handler argument. +// clang-format off +template struct FnArgType { using Type = T; }; +template struct FnArgType> { using Type = T; }; +template struct FnArgType> { using Type = T*; }; +template struct FnArgType> { using Type = T; }; +template struct FnArgType> { using Type = T; }; +// clang-format on + +// A template for counting regular arguments in the Ts pack. +template +struct NumArgs; +template <> +struct NumArgs<> { + static constexpr int64_t value = 0; +}; + +template +struct NumArgs { + static constexpr int64_t value = !IsWrapped::value + NumArgs::value; +}; + +} // namespace internal + +template +class FfiHandler : public Ffi { + static constexpr int64_t kSize = sizeof...(Ts); + static constexpr int64_t kNumArgs = internal::NumArgs::value; + + template + using FnArgType = typename internal::FnArgType::Type; + + // Check if FFI function returns `FfiStatus`. + static constexpr bool kIsFfiStatusHandler = + std::is_invocable_r_v...>; + static_assert(kIsFfiStatusHandler, "unsupported FFI handler type"); + + static XLA_FFI_Error* ToError(const XLA_FFI_Api* api, FfiStatus status) { + if (!status.errc().has_value()) return nullptr; + + XLA_FFI_Error_Create_Args args; + args.struct_size = XLA_FFI_Error_Create_Args_STRUCT_SIZE; + args.priv = nullptr; + args.errc = *status.errc(); + args.message = status.message_c_str(); + + return api->XLA_FFI_Error_Create(&args); + } + + public: + XLA_FFI_Error* operator()(const XLA_FFI_Api* api, + XLA_FFI_ExecutionContext* ctx, void** args, + void** attrs, void** rets) const final { + // Decode arguments and attributes from the opaque pointers. + internal::DecodedArgs decoded_args(args); + internal::DecodedAttrs decoded_attrs(attrs); + + int64_t num_args = decoded_args.size(); + int64_t num_attrs = decoded_attrs.size(); + + // Check that we have the correct number of arguments passed to the handler. + if (num_args != kNumArgs) { + std::ostringstream err; + err << "Wrong number of arguments: expected " << kNumArgs << " got " + << num_args; + return ToError(api, FfiStatus::InvalidArgument(err.str())); + } + + // Check that we have the correct number of attributes passed to the + // handler. Each individual attribute decoding will check the name and the + // type of the attribute. + if (num_attrs != attrs_.size()) { + std::ostringstream err; + err << "Wrong number of attributes: expected " << attrs_.size() << " got " + << num_attrs; + return ToError(api, FfiStatus::InvalidArgument(err.str())); + } + + // Define index sequence to access ffi handler arguments. + using Is = std::make_index_sequence; + return call(api, ctx, decoded_args, decoded_attrs, Is{}); + } + + private: + template + friend class FfiBinding; + + template + XLA_FFI_Error* call(const XLA_FFI_Api* api, XLA_FFI_ExecutionContext* ctx, + internal::DecodedArgs args, internal::DecodedAttrs attrs, + std::index_sequence) const { + // A helper structure to allow each decoder find the correct offset in the + // arguments, attributes or results. + internal::DecodingOffsets offsets; + + // Decode all operands into `std::optional` containers. It is guaranteed + // that initializer list will be evaluated left-to-right, and we can rely + // on correct offsets computation. + std::tuple>...> fn_args = { + internal::Decode::call(api, ctx, offsets, args, attrs_, attrs_idx_, + attrs)...}; + + // Check if all arguments, attributes and results were decoded; + bool all_decoded = (std::get(fn_args).has_value() && ...); + if (!all_decoded) { + std::array decoded = {std::get(fn_args).has_value()...}; + std::string err = "Failed to decode all FFI operands (bad operands at: "; + for (size_t cnt = 0, idx = 0; idx < kSize; ++idx) { + if (!decoded[idx]) { + if (cnt++) err.append(", "); + err.append(std::to_string(idx)); + } + } + err.append(")"); + return ToError(api, FfiStatus::InvalidArgument(err)); + } + + // Custom call returns `FfiStatus`, we can call it directly. + if constexpr (kIsFfiStatusHandler) { + return ToError(api, fn_(std::move(*std::get(fn_args))...)); + } + + return ToError(api, FfiStatus::Ok()); + } + + FfiHandler(Fn fn, std::vector attrs) + : fn_(std::move(fn)), + attrs_(std::move(attrs)), + attrs_idx_(attrs_.size()) { + // Sort attributes names. + std::vector sorted = attrs_; + std::sort(sorted.begin(), sorted.end()); + + // Find the index of every attribute in the sorted attributes vector. + for (size_t i = 0; i < attrs_.size(); ++i) { + const std::string& attr = attrs_[i]; + attrs_idx_[i] = std::distance( + sorted.begin(), std::find(sorted.begin(), sorted.end(), attr)); + } + } + + Fn fn_; + + std::vector attrs_; + + // A mapping from the attribute index to its index in the lexicographically + // sorted vector of attribute names. Attributes are passed to the ffi handler + // sorted by the name, we use this index to efficiently find the decoded + // attribute entry. + std::vector attrs_idx_; +}; + +//===----------------------------------------------------------------------===// +// XLA FFI arguments decoding. +//===----------------------------------------------------------------------===// + +#define XLA_FFI_REGISTER_SCALAR_ARG_DECODING(T) \ + template <> \ + struct FfiArgDecoding { \ + static std::optional Decode(const XLA_FFI_Api* api, \ + XLA_FFI_TypeId type_id, void* value) { \ + if (!Ffi::Isa(api, type_id)) { \ + return std::nullopt; \ + } \ + \ + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(T)); \ + return *reinterpret_cast(value); \ + } \ + } + +XLA_FFI_REGISTER_SCALAR_ARG_DECODING(int32_t); + +#undef XLA_FFI_REGISTER_SCALAR_ARG_DECODING + +template <> +struct FfiArgDecoding { + using EncodedMemref = internal::EncodedMemref; + + static std::optional Decode(const XLA_FFI_Api* api, + XLA_FFI_TypeId type_id, + void* value) { + if (!Ffi::Isa(api, type_id)) { + return std::nullopt; + } + + auto* encoded = reinterpret_cast(value); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + PrimitiveType dtype = static_cast(encoded->dtype); + return StridedBufferArg{dtype, + encoded->data, + {encoded->dims, encoded->rank}, + {encoded->dims + encoded->rank, encoded->rank}}; + } +}; + +template <> +struct FfiArgDecoding { + using EncodedMemref = internal::EncodedMemref; + + static std::optional Decode(const XLA_FFI_Api* api, + XLA_FFI_TypeId type_id, void* value) { + if (!Ffi::Isa(api, type_id)) { + return std::nullopt; + } + + auto* encoded = reinterpret_cast(value); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + PrimitiveType dtype = static_cast(encoded->dtype); + return BufferArg{dtype, encoded->data, {encoded->dims, encoded->rank}}; + } +}; + +template <> +struct FfiArgDecoding { + using EncodedMemref = internal::EncodedMemref; + + static std::optional Decode(const XLA_FFI_Api* api, + XLA_FFI_TypeId type_id, + void* value) { + if (!Ffi::Isa(api, type_id)) { + return std::nullopt; + } + + auto* encoded = reinterpret_cast(value); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref)); + XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED( + encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t)); + + auto dtype = static_cast(encoded->dtype); + int64_t size_in_bytes = ByteWidth(dtype); + for (int d = 0; d < encoded->rank; ++d) { + size_in_bytes *= encoded->dims[d]; + } + return FlatBufferArg{dtype, encoded->data, size_in_bytes}; + } +}; + +//===----------------------------------------------------------------------===// +// XLA FFI attributes decoding. +//===----------------------------------------------------------------------===// + +#define XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(T) \ + template <> \ + struct FfiAttrDecoding { \ + static std::optional Decode(const XLA_FFI_Api* api, \ + std::string_view name, \ + XLA_FFI_TypeId type_id, void* value) { \ + if (!Ffi::Isa(api, type_id)) { \ + return std::nullopt; \ + } \ + \ + return *reinterpret_cast(value); \ + } \ + } + +XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(float); +XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(double); +XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(bool); +XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(int32_t); +XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(int64_t); + +#undef XLA_FFI_REGISTER_SCALAR_ATTR_DECODING + +// Both EncodedArray and 1-D EncodedDenseElements can be decoded as a Span. +// Pointers to both EncodedArray and 1-D EncodedDenseElements can be +// dereferenced as a pointer to EncodedArray. +#define XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(T) \ + template <> \ + struct FfiAttrDecoding> { \ + static std::optional> Decode(const XLA_FFI_Api* api, \ + std::string_view name, \ + XLA_FFI_TypeId type_id, \ + void* value) { \ + if (!Ffi::Isa, MdSpan>(api, type_id)) { \ + return std::nullopt; \ + } \ + \ + auto* encoded = reinterpret_cast*>(value); \ + return Span(encoded->data, encoded->size); \ + } \ + } + +XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(float); +XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(double); +XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(bool); +XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(int32_t); +XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(int64_t); + +#undef XLA_FFI_REGISTER_ARRAY_ATTR_DECODING + +template <> +struct FfiAttrDecoding { + static std::optional Decode(const XLA_FFI_Api* api, + std::string_view name, + XLA_FFI_TypeId type_id, + void* value) { + if (!Ffi::Isa(api, type_id)) { + return std::nullopt; + } + + auto* encoded = reinterpret_cast*>(value); + return std::string_view(encoded->data, encoded->size); + } +}; + +//===----------------------------------------------------------------------===// +// Register an XLA FFI attribute decoding from dictionaries to structs. +//===----------------------------------------------------------------------===// + +template +struct AggregateMember { + using Type = T; + + explicit AggregateMember(std::string_view name) : name(name) {} + std::string_view name; +}; + +// Example: register decoding for a user-defined struct +// +// struct PairOfI64 { int64_t a; int64_t b; }; +// +// XLA_FFI_REGISTER_AGGREGATE_ATTR_DECODING( +// PairOfI64, +// AggregateMember("a"), +// AggregateMember("b")); +// +#define XLA_FFI_REGISTER_AGGREGATE_ATTR_DECODING(T, ...) \ + template <> \ + struct FfiAttrDecoding { \ + static std::optional Decode(const XLA_FFI_Api* api, \ + std::string_view name, \ + XLA_FFI_TypeId type_id, void* value) { \ + if (!Ffi::Isa(api, type_id)) { \ + return std::nullopt; \ + } \ + \ + auto decoder = internal::AggregateDecoder(__VA_ARGS__); \ + return decltype(decoder)::Decode(api, reinterpret_cast(value), \ + internal::AggregateNames(__VA_ARGS__)); \ + } \ + } + +namespace internal { +// Decodes aggregate attribute into the object of type `T` that must be +// constructible from the `Ts` types. +template +struct DecodeAggregateAttr { + static constexpr size_t kSize = sizeof...(Ts); + + static std::optional Decode(const XLA_FFI_Api* api, void** value, + std::array names) { + internal::DecodedAttrs attrs(value); + return Decode(api, attrs, names, std::make_index_sequence{}); + } + + template + static std::optional Decode(const XLA_FFI_Api* api, + internal::DecodedAttrs attrs, + std::array names, + std::index_sequence) { + // Check that the number of encoded attributes matches the signature. + if (kSize != attrs.size()) return std::nullopt; + + // Check that aggregate member names match the expected names. + for (unsigned i = 0; i < kSize; ++i) + if (attrs[i].name != names[i]) return std::nullopt; + + // Decode all arguments into std::optional containers. It is guaranteed + // that initializer list will be evaluated left-to-right, and we can rely + // on correct offsets computation. + std::tuple...> members = {FfiAttrDecoding::Decode( + api, attrs[Is].name, attrs[Is].type_id, attrs[Is].value)...}; + + bool all_decoded = (std::get(members).has_value() && ...); + if (!all_decoded) return std::nullopt; + + // Forward unpacked members to the type constructor. + return T{std::move(*std::get(members))...}; + } +}; + +template +auto AggregateNames(Members... m) { + return std::array{m.name...}; +} + +template +auto AggregateDecoder(Members... m) { + return DecodeAggregateAttr(); +} + +} // namespace internal + +//===----------------------------------------------------------------------===// +// XLA FFI helper macro for registering FFI implementations. +//===----------------------------------------------------------------------===// + +#define XLA_FFI_DEFINE_FUNCTION(fn, impl, binding) \ + static XLA_FFI_Error* fn(XLA_FFI_Function_Args* args) { \ + ::xla::runtime::ffi::internal::CheckStructSize( \ + "XLA_FFI_Function_Args", XLA_FFI_Function_Args_STRUCT_SIZE, \ + args->struct_size); \ + static auto* handler = binding.To(impl).release(); \ + return (*handler)(args->api, args->ctx, args->args, args->attrs, \ + args->rets); \ + } + +#undef CHECK_ARGS_SIZE + +} // namespace ffi +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_FFI_FFI_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..90c35f0393619bf04e51a3b3b623edb7d596d312 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_c_api.h @@ -0,0 +1,276 @@ +/* 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_RUNTIME_FFI_FFI_C_API_H_ +#define XLA_RUNTIME_FFI_FFI_C_API_H_ + +#include +#include + +// Every struct passed across the C API boundary has its size as a member, and +// we use it as a sanity check for API compatibility. +#define XLA_FFI_STRUCT_SIZE(struct_type, last_field) \ + offsetof(struct_type, last_field) + sizeof(((struct_type*)0)->last_field) + +#ifdef __cplusplus +extern "C" { +#endif + +// Forward declare. +typedef struct XLA_FFI_Api XLA_FFI_Api; + +//===----------------------------------------------------------------------===// +// XLA FFI Type checking. +//===----------------------------------------------------------------------===// + +// XLA FFI passes type ids along with all arguments and attributes so that it +// should be possible to check types at run time inside the FFI handler. +typedef const void* XLA_FFI_TypeId; + +typedef XLA_FFI_TypeId XLA_FFI_Get_TypeId(); + +//===----------------------------------------------------------------------===// +// XLA FFI Error handling. +//===----------------------------------------------------------------------===// + +// XLA FFI handler must return a XLA_FFI_Error*, which is NULL if there is no +// error and set if there is. Caller allocates any returned XLA_FFI_Errors, and +// the XLA FFI is responsible for freeing them. +typedef struct XLA_FFI_Error XLA_FFI_Error; + +// Codes are based on https://abseil.io/docs/cpp/guides/status-codes +typedef enum { + XLA_FFI_Error_Code_CANCELLED = 1, + XLA_FFI_Error_Code_UNKNOWN = 2, + XLA_FFI_Error_Code_INVALID_ARGUMENT = 3, + XLA_FFI_Error_Code_DEADLINE_EXCEEDED = 4, + XLA_FFI_Error_Code_NOT_FOUND = 5, + XLA_FFI_Error_Code_ALREADY_EXISTS = 6, + XLA_FFI_Error_Code_PERMISSION_DENIED = 7, + XLA_FFI_Error_Code_RESOURCE_EXHAUSTED = 8, + XLA_FFI_Error_Code_FAILED_PRECONDITION = 9, + XLA_FFI_Error_Code_ABORTED = 10, + XLA_FFI_Error_Code_OUT_OF_RANGE = 11, + XLA_FFI_Error_Code_UNIMPLEMENTED = 12, + XLA_FFI_Error_Code_INTERNAL = 13, + XLA_FFI_Error_Code_UNAVAILABLE = 14, + XLA_FFI_Error_Code_DATA_LOSS = 15, + XLA_FFI_Error_Code_UNAUTHENTICATED = 16 +} XLA_FFI_Error_Code; + +//===----------------------------------------------------------------------===// +// XLA FFI module defines a set of exported FFI functions and their state. +//===----------------------------------------------------------------------===// + +// XLA FFI module is a way to structure FFI functions together with a state +// required for calling them. XLA runtime executable can be linked with multiple +// of such modules at run time. +typedef struct XLA_FFI_Module XLA_FFI_Module; + +// XLA FFI module state can be instantiated once for each XLA executable, and +// its life time will be bound to the executable iself, or it can be +// instantiated for each separate execution. +typedef enum { + XLA_FFI_Module_State_PER_EXECUTABLE = 1, + XLA_FFI_Module_State_PER_EXECUTION = 2, +} XLA_FFI_Module_StateType; + +// Exported FFI functions will have access to the state object that they can +// use to share data between different function invocations. If the state is +// instantiated for each executable, it is the user's responsibility to +// guarantee that it is thread-safe to use from multiple concurrent executions. +typedef struct XLA_FFI_Module_State XLA_FFI_Module_State; + +// Creates a new per-executable module state. +typedef struct { + size_t struct_size; + void* priv; + XLA_FFI_Module* module; + XLA_FFI_Module_State* state; // out +} XLA_FFI_Module_CreateState_Args; + +const size_t XLA_FFI_Module_CreateState_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_Module_CreateState_Args, state); + +typedef XLA_FFI_Error* XLA_FFI_Module_CreateState( + XLA_FFI_Module_CreateState_Args* args); + +// Destroys a module state. +typedef struct { + size_t struct_size; + void* priv; + XLA_FFI_Module* module; + XLA_FFI_Module_State* state; +} XLA_FFI_Module_DestroyState_Args; + +const size_t XLA_FFI_Module_DestroyState_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_Module_DestroyState_Args, state); + +typedef void XLA_FFI_Module_DestroyState( + XLA_FFI_Module_DestroyState_Args* args); + +//===----------------------------------------------------------------------===// +// XLA FFI Error Reporting APIs. +//===----------------------------------------------------------------------===// + +typedef struct { + size_t struct_size; + void* priv; + const char* message; + XLA_FFI_Error_Code errc; +} XLA_FFI_Error_Create_Args; + +const size_t XLA_FFI_Error_Create_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_Error_Create_Args, message); + +typedef XLA_FFI_Error* XLA_FFI_Error_Create(XLA_FFI_Error_Create_Args* args); + +//===----------------------------------------------------------------------===// +// XLA FFI Stream. +//===----------------------------------------------------------------------===// + +// XLA FFI stream is an opaque handle to the underlying stream executor `Stream` +// implementation. In XLA:GPU it is `se::gpu::GpuStreamHandle` (when running on +// CUDA platform it is a `CUstream`). +typedef struct XLA_FFI_Stream XLA_FFI_Stream; + +//===----------------------------------------------------------------------===// +// XLA FFI Execution Context. +//===----------------------------------------------------------------------===// + +typedef struct XLA_FFI_ExecutionContext XLA_FFI_ExecutionContext; + +// Get `XLA_FFI_Module_State` from the execution context. +typedef struct { + size_t struct_size; + void* priv; + XLA_FFI_ExecutionContext* ctx; +} XLA_FFI_ExecutionContext_GetModuleState_Args; + +const size_t XLA_FFI_ExecutionContext_GetModuleState_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_ExecutionContext_GetModuleState_Args, ctx); + +typedef XLA_FFI_Module_State* XLA_FFI_ExecutionContext_GetModuleState( + XLA_FFI_ExecutionContext_GetModuleState_Args* args); + +// Get `XLA_FFI_Stream` from the execution context. +typedef struct { + size_t struct_size; + void* priv; + XLA_FFI_ExecutionContext* ctx; +} XLA_FFI_ExecutionContext_GetStream_Args; + +const size_t XLA_FFI_ExecutionContext_GetStream_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_ExecutionContext_GetStream_Args, ctx); + +typedef XLA_FFI_Stream* XLA_FFI_ExecutionContext_GetStream( + XLA_FFI_ExecutionContext_GetStream_Args* args); + +//===----------------------------------------------------------------------===// +// XLA FFI Function API. +//===----------------------------------------------------------------------===// + +// Arguments passed to an FFI function. +typedef struct { + size_t struct_size; + void* priv; + const XLA_FFI_Api* api; + XLA_FFI_ExecutionContext* ctx; + void** args; + void** attrs; + void** rets; +} XLA_FFI_Function_Args; + +const size_t XLA_FFI_Function_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_Function_Args, rets); + +// XLA FFI function type that can be exported to a runtime. +typedef XLA_FFI_Error* XLA_FFI_Function(XLA_FFI_Function_Args* args); + +//===----------------------------------------------------------------------===// +// XLA FFI Api. +//===----------------------------------------------------------------------===// + +// Register FFI module with an XLA runtime. +typedef struct { + size_t struct_size; + void* priv; + const char* name; + XLA_FFI_Module* module; + XLA_FFI_Module_StateType state_type; + XLA_FFI_Module_CreateState* create_state; + XLA_FFI_Module_DestroyState* destroy_state; + int64_t num_exported_functions; + const char** exported_names; // length == num_exported_functions + XLA_FFI_Function** exported_functions; // length == num_exported_functions +} XLA_FFI_Module_Register_Args; + +const size_t XLA_FFI_Module_Register_Args_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_Module_Register_Args, exported_functions); + +typedef void XLA_FFI_Module_Register(XLA_FFI_Module_Register_Args* args); + +#define XLA_FFI_API_STRUCT_FIELD(fn_type) fn_type* fn_type + +#define XLA_FFI_API_TYPEID_FIELD(type) \ + XLA_FFI_Get_TypeId* XLA_FFI_Get_##type##_TypeId + +typedef struct XLA_FFI_Api { + size_t struct_size; + void* priv; + + XLA_FFI_API_STRUCT_FIELD(XLA_FFI_Module_Register); + + XLA_FFI_API_STRUCT_FIELD(XLA_FFI_ExecutionContext_GetModuleState); + XLA_FFI_API_STRUCT_FIELD(XLA_FFI_ExecutionContext_GetStream); + + XLA_FFI_API_STRUCT_FIELD(XLA_FFI_Error_Create); + + XLA_FFI_API_TYPEID_FIELD(String); + XLA_FFI_API_TYPEID_FIELD(Float); + XLA_FFI_API_TYPEID_FIELD(Double); + XLA_FFI_API_TYPEID_FIELD(Int1); + XLA_FFI_API_TYPEID_FIELD(Int32); + XLA_FFI_API_TYPEID_FIELD(Int64); + + XLA_FFI_API_TYPEID_FIELD(FloatArray); + XLA_FFI_API_TYPEID_FIELD(DoubleArray); + XLA_FFI_API_TYPEID_FIELD(Int32Array); + XLA_FFI_API_TYPEID_FIELD(Int64Array); + + XLA_FFI_API_TYPEID_FIELD(FloatTensor); + XLA_FFI_API_TYPEID_FIELD(DoubleTensor); + XLA_FFI_API_TYPEID_FIELD(Int32Tensor); + XLA_FFI_API_TYPEID_FIELD(Int64Tensor); + + XLA_FFI_API_TYPEID_FIELD(BufferArg); + XLA_FFI_API_TYPEID_FIELD(StridedBufferArg); + XLA_FFI_API_TYPEID_FIELD(Dictionary); +} XLA_FFI_Api; + +#undef XLA_FFI_API_STRUCT_FIELD +#undef XLA_FFI_API_TYPEID_FIELD + +const size_t XLA_FFI_Api_STRUCT_SIZE = + XLA_FFI_STRUCT_SIZE(XLA_FFI_Api, XLA_FFI_Get_StridedBufferArg_TypeId); + +// Does not pass ownership of returned XLA_FFI_Api* to caller. +const XLA_FFI_Api* GetXlaFfiApi(); + +#ifdef __cplusplus +} +#endif + +#endif // XLA_RUNTIME_FFI_FFI_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/jit_executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/jit_executable.h new file mode 100644 index 0000000000000000000000000000000000000000..5ba3c607b6e6426c5552ad617b9c478696f37681 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/jit_executable.h @@ -0,0 +1,240 @@ +/* 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_RUNTIME_JIT_EXECUTABLE_H_ +#define XLA_RUNTIME_JIT_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/status/statusor.h" +#include "xla/mlir/runtime/transforms/jit_compiler.h" +#include "xla/runtime/async_values_cache.h" // IWYU pragma: keep +#include "xla/runtime/constraints.h" +#include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime +#include "tfrt/concurrency/chain.h" // from @tf_runtime + +namespace xla { +namespace runtime { + +// JitExecutable owns a default executable compiled from the MLIR module (if +// operands constraints allow that), and orchestrates on-demand re-compilation +// for specific argument ranks, shapes or values depending on the operands +// constraints. +class JitExecutable { + public: + using UserData = std::any; + + // XLA program can be specialized and recompiled at runtime to the concrete + // input shapes and sometimes values (e.g. reduction dimension). + enum class Specialization { + // Recompile specialized executables when needed. + kEnabled, + // Completely disable specialized executables (always call default + // executable). + kDisabled, + // Always use specialized executables, and never call default executable + // (only required for getting reproducible results in benchmarks). + kAlways, + }; + + struct Options { + // What level of specialization is enabled at runtime. + Specialization specialization = Specialization::kAlways; + + // Options for the XLA runtime JitCompiler. + JitCompiler::Options compiler; + }; + + // We use `llvm::unique_function` to represent compilation task because it + // allows to capture move-only values. + using CompilationTask = llvm::unique_function; + + // Compilation task runner called at runtime when specialization compilation + // is required with the `TaskFunction` that does the compilation, and updates + // the internal state of the `JitExecutable`. This runner can be used by the + // caller to offload compilation task to the specialized thread pool and + // add tracing events (e.g. add Tensorflow profiler tracing). Task runner must + // call the `TaskFunction`, otherwise it will lead to deadlock. + // + // Caller can pass arbitrary user data to the `GetExecutable` method, and it + // will be passed to the runner if recompilation is required. It is guaranteed + // that the runner will be called in the same thread as `GetExecutable`. + // + using CompilationTaskRunner = + llvm::unique_function, + ArgumentsRef, CompilationTask, UserData)>; + + // Inline compilation task runner runs compilation task in the caller thread. + static void InlineCompilationTaskRunner( + size_t num_specializations, + absl::Span constraints, ArgumentsRef arguments, + CompilationTask task, UserData user_data); + + // TODO(ezhulenev): Currently exported functions must be defined explicitly by + // the user. It should be possible to define exported functions implicitly by + // having `rt.export` operations in the compiled module, and export new + // functions while running compilation pipeline. Also `Executable` potentially + // might have more exported functions than the `JitExecutable` that + // instantiated it. Consider adding "private" exported functions, that are not + // visible through the `Executable` API (e.g. function references might be + // passed to custom calls, but they should not be visible to the client). + static absl::StatusOr Instantiate( + std::string_view mlir_module, Options opts, + absl::Span exported, + std::string_view memory_region_name = "", + CompilationTaskRunner runner = InlineCompilationTaskRunner); + + static absl::StatusOr Instantiate( + std::string_view mlir_module, std::string_view exported, Options opts, + std::string_view memory_region_name = "", + CompilationTaskRunner runner = InlineCompilationTaskRunner) { + return Instantiate(mlir_module, opts, {exported}, memory_region_name, + std::move(runner)); + } + + // Returns default executable that accepts all compatible operands + // (operands rank and all static dimensions should match the operands). + tsl::AsyncValuePtr DefaultExecutable() const; + + // Returns an executable that may be specialized for the arguments. Can return + // default executable if no specialization is required, or if the specialized + // executable is not yet available. + // + // Caller can pass arbitrary data via the `user_data` argument, and it will be + // available to the compilation task runner. This can be used for tracing, + // e.g. to track what user-level requests triggered recompilation. + // + // Returns an error if the arguments do not match the expected function + // signature and specialization is not possible (without trying to compile). + // If specialization is disabled, returns the default executable without + // checking the arguments (the default executable itself will check arguments + // when called). + // + // Async values holding compilation results (executables) cached in the + // JitExecutable, and successive calls with the same arguments are cheap (the + // definition of "same" depend on the argument type specialization and chosen + // hash function, e.g. shaped arguments compared using their symbolic shape). + // If compilation fails, then the returned async value will hold a compilation + // error message. Compilation errors are never retried. + // + // Note: This function never falls back on the default executable if + // specialization compilation fails. + // + // TODO(ezhulenev): Add support for specifying exported function ordinal, + // currently this will always specialize exported function with ordinal 0. + absl::StatusOr> GetExecutable( + ArgumentsRef arguments, UserData user_data = {}, + const SpecializationListener* listener = nullptr); + + // Returns an async value that becomes ready when all executables owned by + // this JitExecutable are compiled (no pending compilation tasks). + tsl::AsyncValueRef AllExecutablesCompiled() const; + + // JitExecutable is move-only type. + JitExecutable(const JitExecutable&) = delete; + JitExecutable(JitExecutable&&) = default; + + std::string_view mlir_module() { return mlir_module_; } + + unsigned num_functions() const { return functions_.size(); } + + private: + // JitExecutable defines multiple exported functions that could be compiled + // into the executable. At run time they are referenced by their ordinal, so + // that we don't depend on expensive by-name lookup on the hot path. Function + // ordinal is defined by its index in the `functions_` vector. + // + // TODO(ezhulenev): Today when JitExecutable instantiates specialized + // executable via call to `GetExecutable` it can only specialize the function + // with ordinal 0. It should be possible to specialize multiple functions, and + // select which functions should be compiled at all. + struct Function { + Function(std::string_view name, FunctionType signature, + absl::Span constraints); + + Function(const Function&) = delete; + Function(Function&&) = default; + + // Exported function name. + std::string name; + + // Signature of the exported function. + // + // This function signature is allowed to have operands and results types + // without a well-defined ABI (e.g. it can have tensors when compiled module + // defined in Tensorflow dialect), and it corresponds to the executable + // definition in one of the high level dialects (e.g. Tensorflow or mHLO). + // + // When compiled module prepared for execution, function operands and + // results are mapped to the types with well-defined ABI (e.g. tensors + // mapped to memrefs). See `runtime_signature` documentation in the + // `Executable::Function` type. + FunctionType signature; + + // Exported function arguments constraints after resolving them using the + // statically known information in the function signature. If constraint + // specified by the argument attribute known to be statically satisfied by + // the argument type (e.g. rank constraint with an operand of statically + // known rank), then the constraint value for that operand will be updated + // to `kResolved`. + llvm::SmallVector constraints; + + // True if any of the arguments has `ArgumentConstraint::kValue` constraint. + bool has_value_constraints; + + // Symbolic shape resolver assigns symbolic dimensions to runtime operands + // based on the exported function signature. + SymbolicShapesResolver symbolic_shapes_resolver; + }; + + JitExecutable(std::string_view mlir_module, Options opts, + std::vector functions, + std::optional default_executable, + std::string_view memory_region_name, + CompilationTaskRunner runner); + + std::string mlir_module_; + Options opts_; + + // Functions exported by this jit executable, indexed by function ordinal. + std::vector functions_; + + // Default executable that was not specialized to any of the arguments. + AsyncValueRef default_executable_; + bool has_default_executable_; + + // Name of the memory region where JIT'ed code is compiled to. + // This allows profilers to correctly label JIT-executed code. + // Note: this feature might only be available on some platforms, e.g. Linux. + std::string memory_region_name_; + + // A custom runner for compiling specializations. + CompilationTaskRunner runner_; + + // Executables specialized for the arguments shapes or/and values. + using Specializations = AsyncValuesCache; + std::unique_ptr specializations_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_JIT_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/logical_result.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/logical_result.h new file mode 100644 index 0000000000000000000000000000000000000000..572c98248bd78455e8f493ea88049714d9f8b9c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/logical_result.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. +==============================================================================*/ + +#ifndef XLA_RUNTIME_LOGICAL_RESULT_H_ +#define XLA_RUNTIME_LOGICAL_RESULT_H_ + +#include "mlir/Support/LogicalResult.h" // from @llvm-project + +namespace xla { +namespace runtime { + +using ::mlir::failure; // NOLINT +using ::mlir::success; // NOLINT + +using ::mlir::failed; // NOLINT +using ::mlir::succeeded; // NOLINT + +using ::mlir::FailureOr; // NOLINT +using ::mlir::LogicalResult; // NOLINT + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_LOGICAL_RESULT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/map_by_type.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/map_by_type.h new file mode 100644 index 0000000000000000000000000000000000000000..e24b0756940c8aa340c7869beb660ce77569d321 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/map_by_type.h @@ -0,0 +1,110 @@ +/* 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_RUNTIME_MAP_BY_TYPE_H_ +#define XLA_RUNTIME_MAP_BY_TYPE_H_ + +#include +#include + +#include "llvm/ADT/SmallVector.h" +#include "xla/runtime/type_id.h" + +namespace xla { +namespace runtime { + +// An optimized map container for storing pointers of different types. +// +// Example: +// +// PtrMapByType map; +// +// int32_t i32 = 0; +// int64_t i64 = 1; +// +// map.insert(&i32); +// map.insert(&i64); +// +// assert(map.contains()); +// assert(map.contains()); +// +template +class PtrMapByType { + public: + PtrMapByType() = default; + + template + explicit PtrMapByType(Ts*... values) { + insert_all(values..., std::make_index_sequence{}); + } + + template + T* insert(T* value) { + size_t id = GetDenseTypeId(); + if (id >= data_.size()) { + data_.resize(id + 1); + } + data_[id] = const_cast*>(value); + return value; + } + + template + void insert_all(Ts*... values) { + insert_all(values..., std::make_index_sequence{}); + } + + template + T* get() const { + size_t id = GetDenseTypeId(); + assert(id < data_.size()); + return reinterpret_cast(data_[id]); + } + + template + T* getIfExists() const { + size_t id = GetDenseTypeId(); + return LLVM_LIKELY(id < data_.size()) ? reinterpret_cast(data_[id]) + : nullptr; + } + + template + bool contains() const { + size_t id = GetDenseTypeId(); + return id < data_.size() && data_[id] != nullptr; + } + + private: + template + static size_t GetDenseTypeId() { + return DenseTypeId::template get(); + } + + template + void insert_all(Ts*... values, std::index_sequence) { + static constexpr size_t kNumInserted = sizeof...(Ts); + if constexpr (kNumInserted > 0) { + std::array ids = {GetDenseTypeId()...}; + data_.resize(1 + *std::max_element(ids.begin(), ids.end()), nullptr); + ((data_[ids[Is]] = const_cast*>(values)), ...); + } + } + + llvm::SmallVector data_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_MAP_BY_TYPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memory_mapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memory_mapper.h new file mode 100644 index 0000000000000000000000000000000000000000..e47a6839d3c7f090e75264fe1fc2eee7b5279741 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memory_mapper.h @@ -0,0 +1,65 @@ +/* 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_RUNTIME_MEMORY_MAPPER_H_ +#define XLA_RUNTIME_MEMORY_MAPPER_H_ + +#include +#include +#include +#include // NOLINT + +#include "tsl/platform/platform.h" + +#if defined(PLATFORM_GOOGLE) +#include "xla/runtime/google/memory_mapper.h" +#else +#include "xla/runtime/default/memory_mapper.h" +#endif + +#include "llvm/ExecutionEngine/SectionMemoryManager.h" + +namespace xla { +namespace runtime { + +// XLA runtime memory mapper allocates memory for XLA executables (object files) +// using `memfd_create` system call, and gives the user-friendly name to the +// file descriptor, so that for example in `perf` it should be possible to +// identify input XLA programs by name. +class XlaRuntimeMemoryMapper final + : public llvm::SectionMemoryManager::MemoryMapper { + public: + static std::unique_ptr Create(std::string_view name); + + llvm::sys::MemoryBlock allocateMappedMemory( + llvm::SectionMemoryManager::AllocationPurpose purpose, size_t len, + const llvm::sys::MemoryBlock* const near_block, unsigned prot_flags, + std::error_code& error_code) final; + + std::error_code protectMappedMemory(const llvm::sys::MemoryBlock& block, + unsigned prot_flags) final; + + std::error_code releaseMappedMemory(llvm::sys::MemoryBlock& block) final; + + private: + explicit XlaRuntimeMemoryMapper(std::string_view name) : name_(name) {} + + std::string name_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_MEMORY_MAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memref_view.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memref_view.h new file mode 100644 index 0000000000000000000000000000000000000000..7bce51a3000ff876ef8892b7873fd7dee49a29be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memref_view.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_RUNTIME_MEMREF_VIEW_H_ +#define XLA_RUNTIME_MEMREF_VIEW_H_ + +#include + +#include "absl/types/span.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace runtime { + +// A view into the memref argument. Corresponds to the MemrefDesc, however it +// doesn't own the sizes/strides vectors, and cheap to pass around. Memrefs with +// non-identity layouts can be decoded only as a StridedMemrefView. +struct StridedMemrefView { + PrimitiveType dtype; + void* data; + absl::Span sizes; + absl::Span strides; +}; + +// A view into the memref argument with an identity (row major) layout. +struct MemrefView { + PrimitiveType dtype; + void* data; + absl::Span sizes; +}; + +// A flat view into memref argument with an identity (row major) layout. If the +// memref shape and strides are not required for the custom call, it's cheaper +// to pass the flat view. +struct FlatMemrefView { + PrimitiveType dtype; + void* data; + int64_t size_in_bytes; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_MEMREF_VIEW_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module.h new file mode 100644 index 0000000000000000000000000000000000000000..7b9b3a060299344e216e95d33905665e41d0106e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module.h @@ -0,0 +1,185 @@ +/* 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_RUNTIME_MODULE_H_ +#define XLA_RUNTIME_MODULE_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace runtime { + +template +class StatefulModule; +class StatelessModule; + +//===---------------------------------------------------------------------===/// +// Xla runtime module. +//===---------------------------------------------------------------------===/// + +// Xla runtime module is a way to structure custom calls (external functions) +// together with the state required for calling them. Xla runtime executable can +// be linked with multiple of such modules at run time. +// +// As an example Xla Gpu has a StreamExecutor-based HAL (hardware abstraction +// layer) implemented as a runtime module. Different Xla backends can require +// different sets of modules for running executables, and some of the modules +// can be shared between backends (e.g. XProf integration). +// +// User-defined modules must inherit from `StatefulModule` or `StatelessModule`. +class Module { + public: + // When a module is instantiated for each runtime executable it can optionally + // create a state object that can be used to implement stateful functions, + // to keep a state between exported functions invocations. State can be + // accessed from different executable invocations running concurrently. + struct State { + virtual ~State() = default; + }; + + // StateRef is a potentially long-lived reference held by the runtime that + // must guarantee that all pointers added to the user data container are + // pointing to live objects (see `InitializeUserData` for more details). + struct StateRef { + virtual ~StateRef() = default; + }; + + virtual ~Module() = default; + + virtual std::string_view name() const = 0; + + // Creates a new per-executable module state. + virtual absl::StatusOr> CreateState() const = 0; + + // Initializes `user_data` with values required for calling functions exported + // from the module. If initializing `user_data` requires creating temporaries, + // then the returned `StateRef` should guarantee their lifetime. Runtime + // itself guarantees that `state` is alive when it calls any of the exported + // functions; this means that `user_data` can safely point to `state`'s + // members. + virtual absl::StatusOr> InitializeUserData( + State* state, CustomCall::UserData& user_data) const = 0; + + // Exports direct custom calls provided by this module to the registry. + virtual void Export(DirectCustomCallRegistry& registry) const {} + + // Exports dynamic custom calls provided by this module to the registry. + virtual void Export(DynamicCustomCallRegistry& registry) const {} + + private: + template + friend class StatefulModule; + friend class StatelessModule; + + Module() = default; +}; + +//===---------------------------------------------------------------------===/// +// Stateful and typed Xla runtime module. +//===---------------------------------------------------------------------===/// + +template +class StatefulModule : public Module { + static_assert(std::is_base_of_v, + "State must be derived from Module::State"); + + static_assert(std::is_base_of_v || std::is_void_v, + "State ref must be `void` or derived from Module::StateRef"); + + public: + std::string_view name() const final { return name_; } + + // Creates a new per-executable module State. + virtual absl::StatusOr> CreateModuleState() const = 0; + + // If state ref is void then UserData initialization must return + // `absl::Status`, otherwise it must return `absl::StatusOr` with a state + // reference value. + virtual std::conditional_t, absl::Status, + absl::StatusOr>> + InitializeUserData(S* state, CustomCall::UserData& user_data) const { + if constexpr (std::is_void_v) { + return absl::OkStatus(); + } else { + return nullptr; + } + } + + protected: + explicit StatefulModule(std::string name) : name_(std::move(name)) {} + + private: + absl::StatusOr> CreateState() const final { + return CreateModuleState(); + } + + absl::StatusOr> InitializeUserData( + State* state, CustomCall::UserData& user_data) const final { + auto initialized = InitializeUserData(dynamic_cast(state), user_data); + + // Convert `absl::OkStatus` to an `absl::StatusOr` with an empty state ref. + if constexpr (std::is_void_v) { + if (initialized.ok()) return nullptr; + } + + return initialized; + } + + std::string name_; +}; + +//===---------------------------------------------------------------------===/// +// Stateless Xla runtime module. +//===---------------------------------------------------------------------===/// + +class StatelessModule : public Module { + public: + std::string_view name() const final { return name_; } + + virtual absl::Status InitializeUserData( + CustomCall::UserData& user_data) const { + return absl::OkStatus(); + } + + protected: + explicit StatelessModule(std::string name) : name_(std::move(name)) {} + + private: + absl::StatusOr> CreateState() const final { + return nullptr; + } + + absl::StatusOr> InitializeUserData( + State* state, CustomCall::UserData& user_data) const final { + if (auto init = InitializeUserData(user_data); !init.ok()) return init; + return nullptr; + } + + std::string name_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_MODULE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..33f76bf4b4d22ca542032e5460c52aff734033d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module_registry.h @@ -0,0 +1,75 @@ +/* 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_RUNTIME_MODULE_REGISTRY_H_ +#define XLA_RUNTIME_MODULE_REGISTRY_H_ + +#include +#include +#include + +#include "xla/runtime/module.h" + +namespace xla { +namespace runtime { + +// Registers Xla runtime module with a global modules registry. +// +// TODO(ezhulenev): We need to support modules restricted for different +// platforms, e.g. we should not instantiate state for GPU modules when +// compiling a CPU executable. Xla today uses a "platform name" (Host, +// CUDA, etc...) for this. +void RegisterModule(std::unique_ptr module); + +// Exports registered modules to the given custom call registry. +// +// TODO(ezhulenev): We also need to support exporting direct custom calls. +void ExportModules(DynamicCustomCallRegistry& registry); + +// Helper macro to define a static module registration. +#define XLA_REGISTER_RUNTIME_MODULE(FUNC) \ + XLA_REGISTER_RUNTIME_MODULE_IMPL(FUNC, __COUNTER__) + +#define XLA_REGISTER_RUNTIME_MODULE_IMPL(FUNC, N) \ + static bool xla_runtime_module_##N##_registered_ = []() { \ + ::xla::runtime::RegisterModule(FUNC); \ + return true; \ + }() + +// Container that owns the state of all registered modules. +class ModulesState { + public: + ModulesState() = default; + + // Instantiates `ModulesState` from the registered module. + // + // TODO(ezhulenev): Take module's platform. + static absl::StatusOr Instantiate(); + + // Initializes `UserData` from the module's state. + absl::StatusOr>> + InitializeUserData(CustomCall::UserData& user_data); + + private: + explicit ModulesState( + std::vector>> state); + + std::vector>> state_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_MODULE_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/results.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/results.h new file mode 100644 index 0000000000000000000000000000000000000000..6afd6cd96174d707d9bf7c05e932a8771b18460d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/results.h @@ -0,0 +1,186 @@ +/* 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_RUNTIME_RESULTS_H_ +#define XLA_RUNTIME_RESULTS_H_ + +#include + +#include "xla/runtime/logical_result.h" +#include "xla/runtime/types.h" + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// Conversions from XLA executable results to C++ types. +//===----------------------------------------------------------------------===// + +// The result type defines its own ABI as a required number of bytes and +// alignment, and executable returns results by writing into the requested +// memory allocated in the call frame. The user is responsible for providing +// a conversion function that converts this opaque memory back to the C++ +// data type. For example memrefs returned as a `StridedMemrefType` structure, +// and it is the user responsibiity to define a conversion function that can +// convert a memref to the run time Tensor/Buffer type. +// +// It is important that the type that is written into the call frame memory has +// a standard memory layout, because we rely on `reinterpret_cast` to reinterpet +// the opaque bytes to a C struct. +// +// See https://en.cppreference.com/w/cpp/types/is_standard_layout + +// Result converter is responsible for taking a pointer to the memory location +// where the executable wrote the result, and converting it to the corresponding +// run time value expected by the caller (e.g. memref descriptor to Tensor). +class ResultConverter { + public: + virtual ~ResultConverter() = default; + + // Converts value `ret` of type `runtime_type` (runtime type derived from the + // original `type`) returned from the executable at `result_index` result + // position using registered conversion functions. Returns a logical result + // telling if the conversion was successful. + virtual LogicalResult ReturnValue(unsigned result_index, const Type* type, + const Type* runtime_type, + void* ret) const = 0; + + // Returns error for all results. This function is called if the runtime + // fails to run the executable, or if the executable returns an error. + // + // This function is not called if an individual `ReturnValue` conversion + // fails. + // + // It is the user's responsibility to handle the case where the return value + // conversion fails, and some error value has to be returned for unhandled + // results, e.g. error async value for unconverted results. + virtual void ReturnError(const absl::Status& error) const = 0; +}; + +//===----------------------------------------------------------------------===// +// Result converter for functions without results (returning void). +//===----------------------------------------------------------------------===// + +struct NoResultConverter : public ResultConverter { + LLVM_ATTRIBUTE_ALWAYS_INLINE + LogicalResult ReturnValue(unsigned, const Type*, const Type*, + void*) const final { + assert(false && "no result converter must never be called"); + return failure(); + } + + void ReturnError(const absl::Status&) const final {} +}; + +//===----------------------------------------------------------------------===// +// Returns results using user-provided set of conversion functions. +//===----------------------------------------------------------------------===// + +template +class ResultConverterSet : public ResultConverter { + static_assert(sizeof...(RetValue), "result converters must be non-empty"); + + static_assert(std::is_invocable_v); + + static_assert(std::conjunction_v< + std::is_invocable_r...>); + + public: + explicit ResultConverterSet(RetError ret_error, RetValue... ret_value) + : ret_error_(std::move(ret_error)), + ret_value_(std::forward(ret_value)...) {} + + LogicalResult ReturnValue(unsigned result_index, const Type* type, + const Type* runtime_type, void* ret) const final { + return ReturnValue<0>(result_index, type, runtime_type, ret); + } + + void ReturnError(const absl::Status& error) const final { ret_error_(error); } + + private: + template + LogicalResult ReturnValue(unsigned result_index, const Type* type, + const Type* runtime_type, void* ret) const { + // Try to call the user-provided converter. + auto& converter = std::get(ret_value_); + if (succeeded(converter(result_index, type, runtime_type, ret))) + return success(); + + // If conversion failed try the next one if available. + if constexpr (idx + 1 < sizeof...(RetValue)) + return ReturnValue(result_index, type, runtime_type, ret); + + return failure(); + } + + RetError ret_error_; + std::tuple ret_value_; +}; + +template +ResultConverterSet(RetError, RetValue...) + -> ResultConverterSet; + +//===----------------------------------------------------------------------===// +// Helper functions for converting results of canonical types. +//===----------------------------------------------------------------------===// + +namespace internal { + +// This struct corresponds to the `llvm.struct` used by memref to llvm lowering +// pass to represent memref descriptors in the compilation pipeline. It is a +// type-erased version of `::mlir::StridedMemRefType` template. +struct MemrefDescriptor { + void* base_ptr; + void* data_ptr; + int64_t offset; + int64_t sizes_and_strides[]; +}; + +} // namespace internal + +// Converts returned memref using user-provided converter. Converter must +// satisfy this concept: +// +// struct Converter { +// ResultType operator()(PrimitiveType element_type, void* base_ptr, +// void* data_ptr, int64_t offset, +// absl::Span dims, +// absl::Span strides); +// }; +// +template +FailureOr ConvertReturnedMemref(const Converter& converter, + const Type* memref_type, void* ret) { + // Check if the runtime type is a valid memref. + auto* memref = llvm::dyn_cast(memref_type); + if (!memref) return failure(); + + PrimitiveType element_type = memref->element_type(); + size_t rank = memref->rank(); + + auto* desc = reinterpret_cast(ret); + absl::Span dims(desc->sizes_and_strides, rank); + absl::Span strides(desc->sizes_and_strides + rank, rank); + + return converter(element_type, desc->base_ptr, desc->data_ptr, desc->offset, + dims, strides); +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_RESULTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..56e81c8910d0c042c0d500b5b753c2c983889c3f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/runtime.h @@ -0,0 +1,66 @@ +/* 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_RUNTIME_RUNTIME_H_ +#define XLA_RUNTIME_RUNTIME_H_ + +#include + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// XLA Runtime <-> XLA Executable integration API. +//===----------------------------------------------------------------------===// + +// This API enables compiled XLA executables to call back into the XLA runtime +// for: +// +// - Returning results back to the caller by writing to result storage +// allocated in the call frame. +// - User friendly error reporting integrated with the high level execution +// model (errors do not crash the compiled binary). +// - Invoking custom calls registered with the XLA runtime. +// +// XLA compilation pipeline sets up passes to convert the regular functions +// to the so called "XLA entrypoint functions" integrated with the runtime using +// the API defined below, e.g. instead of conventional returns all results are +// returned via the `GetResultStorage` API. At MLIR level these operations +// correspond to the `rt` dialect, and converted to LLVM using the `rt-to-llvm` +// conversion pass. +// +// Runtime errors are reported back to the runtime via the `SetError` API. +// The compilation pipeline will automatically convert assertions in the +// entrypoint function into run-time errors. + +// Opaque runtime execution context passed as the first argument to compiled +// executables and passed back to all runtime API methods. +using ExecutionContext = struct ExecutionContext; + +// Returns a pointer to the memory location of the result at the given index. +void *GetResultStorage(ExecutionContext *, int64_t); + +// Sets execution context to an error state. +void SetError(ExecutionContext *, const char *); + +// Calls the custom call function registered with the runtime. Returns true +// if the custom call was successful. +bool CustomCall(ExecutionContext *, const char *target, void **args, + void **attrs, void **rets); + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/state.h new file mode 100644 index 0000000000000000000000000000000000000000..c505dd96ffea72b56bf6213a639f012dd1d1accd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/state.h @@ -0,0 +1,218 @@ +/* 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_RUNTIME_STATE_H_ +#define XLA_RUNTIME_STATE_H_ + +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/synchronization/mutex.h" + +namespace xla { +namespace runtime { + +// Forward declare. +template +class State; + +// StateVector is a container for keeping the state between custom call +// invocations (within same or concurrent calls to `Executable::Execute`). +// +// Every instance of the custom call in the executable must be assigned a unique +// id (dense i64 integer in the [0, num_instances) range), and the state vector +// enables efficient access to value of type `T`, with lazy initialization done +// by the custom call itself. +// +// Custom calls implement special bindings for state arguments: +// +// CustomCall::Bind("foo") +// .State("id_attr_name") +// .To([](State state) { +// FooState foo = state.GetOrCreate(...); +// ... +// }); +// +// State snapshot must be passed via UserData: +// +// StateVector::Snapshot snapshot = ...; +// CustomCall::UserData user_data(&snapshot, ...); +// +// See `custom_call.h` and `custom_call_test.cc` for more examples. +template +class StateVector { + public: + explicit StateVector(size_t reserve = 0); + + // Snapshot wraps the read-only state snapshot (potentially obsolete) and + // falls back on synchronized state access if it can't find an entry in its + // read-only state snapshot. + class Snapshot { + public: + // Returns a state for the given id if it's already available, or tries to + // create a new one using the user-provided `create` function. Returns an + // error if state creation fails. Failures are not cached and always + // retried. + template + absl::StatusOr GetOrCreate(size_t id, F&& create); + + absl::StatusOr Get(size_t id); + + absl::Status Erase(size_t id); + + // Returns a state constructed from this snapshot for a given id. + State state(size_t id) { return State(id, this); } + + private: + friend StateVector; + Snapshot(StateVector& state, std::shared_ptr> snapshot); + + // State vector that this snapshot was taken from. + StateVector& owning_state_; + + // State vector snapshot captured at construction time. It might not contain + // all the latest data available in the `owning_state_`. + std::shared_ptr> maybe_obsolete_snapshot_; + }; + + Snapshot snapshot(); + T* operator[](size_t id); + + private: + mutable absl::Mutex mu_; + + // StateVector owns the values of type `T` indexed by the key. + std::vector> vector_ ABSL_GUARDED_BY(mu_); + + // A read-only snapshot of `vector_` that is updated every time a new entry + // is added to the state vector. + std::shared_ptr> vector_snapshot_ ABSL_GUARDED_BY(mu_); +}; + +template +class State { + using Snapshot = typename StateVector::Snapshot; + + public: + template + absl::StatusOr GetOrCreate(F&& create) { + return snapshot_->GetOrCreate(id_, std::forward(create)); + } + + private: + friend Snapshot; + State(size_t id, Snapshot* snapshot) : id_(id), snapshot_(snapshot) {} + + size_t id_; + Snapshot* snapshot_; +}; + +//===----------------------------------------------------------------------===// + +template +StateVector::StateVector(size_t reserve) + : vector_(reserve), vector_snapshot_(new std::vector(reserve)) {} + +template +StateVector::Snapshot::Snapshot(StateVector& state, + std::shared_ptr> snapshot) + : owning_state_(state), maybe_obsolete_snapshot_(std::move(snapshot)) {} + +template +auto StateVector::snapshot() -> Snapshot { + absl::MutexLock lock(&mu_); + return Snapshot(*this, vector_snapshot_); +} + +template +T* StateVector::operator[](size_t id) { + absl::MutexLock lock(&mu_); + return id < vector_.size() ? vector_[id].get() : nullptr; +} + +template +template +absl::StatusOr StateVector::Snapshot::GetOrCreate(size_t id, + F&& create) { + static_assert(std::is_invocable_r_v, F>); + + // If snapshot already contains the entry, just return it. + std::vector& snapshot = *maybe_obsolete_snapshot_; + if (id < snapshot.size() && snapshot[id]) return snapshot[id]; + + // Otherwise go through the slow synchronized code path. + absl::MutexLock lock(&owning_state_.mu_); + + // Check if value is present in the state vector, and was not captured in + // the snapshot that we have. + std::vector>& state = owning_state_.vector_; + if (id < state.size() && state[id].get()) return state[id].get(); + + // Try to insert a new entry. + absl::StatusOr value = create(); + if (!value.ok()) return value.status(); + + // Update the state vector. + if (id >= state.size()) state.resize(id + 1); + state[id] = std::make_unique(*std::move(value)); + + // And take the new snapshot. + auto new_snapshot = std::make_shared>(state.size()); + for (size_t i = 0; i < state.size(); ++i) (*new_snapshot)[i] = state[i].get(); + + // Update the snapshot owned by the state. + owning_state_.vector_snapshot_ = std::move(new_snapshot); + + return state[id].get(); +} + +template +absl::StatusOr StateVector::Snapshot::Get(size_t id) { + // If snapshot already contains the entry, just return it. + std::vector& snapshot = *maybe_obsolete_snapshot_; + if (id < snapshot.size() && snapshot[id]) return snapshot[id]; + + // Otherwise go through the slow synchronized code path. + absl::MutexLock lock(&owning_state_.mu_); + + // Check if value is present in the state vector, and was not captured in + // the snapshot that we have. + std::vector>& state = owning_state_.vector_; + if (id < state.size() && state[id].get()) return state[id].get(); + + return absl::InternalError("Value not found in state vector"); +} + +template +absl::Status StateVector::Snapshot::Erase(size_t id) { + absl::MutexLock lock(&owning_state_.mu_); + + std::vector>& state = owning_state_.vector_; + if (id < state.size() && state[id].get()) { + state[id].reset(nullptr); + return absl::OkStatus(); + } + + return absl::InternalError("Value not found in state vector"); +} + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/symbolic_shape.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/symbolic_shape.h new file mode 100644 index 0000000000000000000000000000000000000000..9f3e1192001adf97db7efecff6623a4e4062f3f0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/symbolic_shape.h @@ -0,0 +1,117 @@ +/* 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_RUNTIME_SYMBOLIC_SHAPE_H_ +#define XLA_RUNTIME_SYMBOLIC_SHAPE_H_ + +#include + +#include "absl/status/statusor.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SmallVector.h" +#include "xla/runtime/arguments.h" +#include "xla/runtime/constraints.h" + +namespace xla { +namespace runtime { + +// Symbolic shapes resolver computes the symbolic shapes of the arguments based +// on the function signature, and concrete shapes of the arguments at runtime. +// +// Example: dimensions that have the same symbolic shape at runtime. +// +// signature: func @compute(%arg0: tensor, %arg1: tensor memref<123xf32> +// ^ ^ +// symbolic shapes: [-2xf32] [-2xf32] +// +// Each unknown dimension in the function signature will be assigned a symbolic +// dimension. If multiple shaped arguments have unknown dimensions that are the +// same at runtime, they will be assigned the same symbolic dimensions value +// (e.g. `-2` in the example above). +// +// If an unknown dimension at runtime is equal to some statically known +// dimension in the function signature (of any shaped argument), it will be +// resolved to that statically known constant value: +// +// Example: in this example unknown dimension of `arg0` replaced with a `32`. +// +// signature: func @compute(%arg0: tensor, %arg1: tensor<32xf32>) +// ^ ^ +// arguments: memref<32xf32> memref<32xf32> +// ^ ^ +// symbolic shapes: [32xf32] [32xf32] +// +// Unknown dimensions that are `1` at runtime are always materialized as a +// statically known `1` in the symbolic shape. +class SymbolicShapesResolver { + public: + // Dimension size can be symbolic (<= -2) or static. + using SymbolicShape = llvm::SmallVector; + // Dimension size can be dynamic (ShapedType::kDynamic) or static. + using StaticShape = llvm::SmallVector; + + SymbolicShapesResolver(const FunctionType& signature, + absl::Span constraints); + + // Resolves symbolic shapes from the runtime arguments. Returns failure if + // runtime dimensions do not match the statically known dimensions. + absl::StatusOr> Resolve( + ArgumentsRef arguments) const; + + // Resolves symbolic shapes and computes the hash value from the runtime + // arguments. Returns failure if runtime dimensions do not match the + // statically known dimensions. + // + // This function might not return the same hash value as calling `Resolve` and + // then `Hash`, because it might use more efficient hashing algorithm. + absl::StatusOr ResolveHash(ArgumentsRef arguments) const; + + // Replaces all symbolic dimensions with dynamic dimension. + static StaticShape Normalize(const SymbolicShape& shape); + + // Computes a hash value of the symbolic shapes. + static llvm::hash_code Hash(absl::Span symbolic_shapes); + + ArgumentConstraint constraint(size_t index) const; + size_t num_arguments() const; + bool has_argument_sizes(size_t index) const; + const StaticShape& argument_sizes(size_t index) const; + bool seen_static_size(size_t dim) const; + + private: + // Constraints on the function arguments. + llvm::SmallVector constraints_; + + // Statically known sizes of shaped arguments from the function signature. For + // non-shaped arguments (e.g. opaque pointers) we keep empty shape value. + llvm::SmallVector> arguments_sizes_; + + // Values of statically known dimensions sizes in the function signature. + llvm::DenseSet seen_static_sizes_; + + // The iteration order for the arguments when resolving symbolic shapes. + llvm::SmallVector iteration_order_; + + // The iteration order for the arguments when resolving symbolic shapes hash. + llvm::SmallVector hash_iteration_order_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_SYMBOLIC_SHAPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/tracing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/tracing.h new file mode 100644 index 0000000000000000000000000000000000000000..6b9336bcc7be7aff3ee3a484f79c4a4b79701a78 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/tracing.h @@ -0,0 +1,44 @@ +/* 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_RUNTIME_TRACING_H_ +#define XLA_RUNTIME_TRACING_H_ + +#include + +#include "xla/runtime/custom_call.h" +#include "xla/runtime/type_id.h" + +namespace xla { +namespace runtime { + +// XLA run-time representation of the `!rt.hlo_trace` attribute. +struct HloTrace { + std::string_view hlo_op; +}; + +// Registers type id names for tracing attributes. +inline void PopulateTraceTypeIdNames(TypeIDNameRegistry& registry) { + registry.Register>("__type_id_hlo_trace"); +} + +// Register XLA runtime custom calls attribute decoding. +XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING( + HloTrace, AggregateMember("hlo_op")); + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_TRACING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/type_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/type_id.h new file mode 100644 index 0000000000000000000000000000000000000000..e1a430ad05f2637265944da403b38b1e0f77ec0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/type_id.h @@ -0,0 +1,173 @@ +/* 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_RUNTIME_TYPE_ID_H_ +#define XLA_RUNTIME_TYPE_ID_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "mlir/Support/TypeID.h" // from @llvm-project + +namespace mlir { +// Allow TypeID to be used as a key in ABSL map containers. +template +H AbslHashValue(H h, const TypeID& type_id) { + return H::combine(std::move(h), type_id.getAsOpaquePointer()); +} +} // namespace mlir + +namespace xla { +namespace runtime { + +using ::mlir::TypeID; // NOLINT + +//===----------------------------------------------------------------------===// +// Mapping from TypeID to unique symbol name. +//===----------------------------------------------------------------------===// + +// A mapping from TypeID to unique type name, because we do not have any +// standard tools to get a type name in C++. We rely on this mapping to declare +// external symbols corresponding to type ids in compiled XLA executables. +class TypeIDNameRegistry { + public: + TypeIDNameRegistry() = default; + ~TypeIDNameRegistry() = default; + + template + void Register(std::string_view type_name) { + auto inserted = type_id_name_map_.try_emplace(TypeID::get(), type_name); + assert((inserted.second || inserted.first->second == type_name) && + "conflicting typeid name registration"); + (void)inserted; + } + + std::string_view FindTypeIDSymbolName(TypeID type_id); + + void ForEach(std::function f) const { + for (auto& kv : type_id_name_map_) f(kv.second, kv.first); + } + + private: + absl::flat_hash_map type_id_name_map_; +}; + +//===----------------------------------------------------------------------===// +// DenseTypeID for generating sequential type ids. +//===----------------------------------------------------------------------===// + +// Forward declare +template +class DenseTypeId; + +namespace internal { +template +class DenseTypeIdResolver { + friend DenseTypeId; + static size_t get(); +}; +} // namespace internal + +// Use this as DenseTypeId, that way you are +// guaranteed to get contiguous IDs starting at 0 unique to your particular +// use case, as would be appropriate to use for indexes into a vector. +// 'some_type_specific_to_your_use' could (e.g.) be the class that contains +// that particular vector. +template +class DenseTypeId { + public: + template + static size_t get() { + return internal::DenseTypeIdResolver::get(); + } + + private: + // Partial template specialization can't be declared as a friend, so we + // declare all `DenseTypeIdResolver` as a friend. + template + friend class internal::DenseTypeIdResolver; + + static size_t next_id() { + return next_id_.fetch_add(1, std::memory_order_relaxed); + } + + static std::atomic next_id_; +}; + +template +std::atomic DenseTypeId::next_id_; + +namespace internal { +template +size_t DenseTypeIdResolver::get() { + static const size_t id = DenseTypeId::next_id(); + return id; +} +} // namespace internal + +} // namespace runtime +} // namespace xla + +// Declare/define an explicit specialization for DenseTypeId. +// +// This forces the compiler to assign a dense type id for the given type and +// avoids checking the static initialization guard if the type id defined as a +// static variable (default implementation of the DenseTypeIdResolver). +// +// Example: +// +// // Foo.h +// struct FooIdSet {}; +// +// XLA_RUNTIME_DECLARE_EXPLICIT_DENSE_TYPE_ID(FooIdSet, int32_t); +// +// // Foo.cpp +// XLA_RUNTIME_DEFINE_EXPLICIT_DENSE_TYPE_ID(FooIdSet, int32_t); +// +#define XLA_RUNTIME_DECLARE_EXPLICIT_DENSE_TYPE_ID(ID_SET, T) \ + namespace xla { \ + namespace runtime { \ + namespace internal { \ + \ + template <> \ + class DenseTypeIdResolver { \ + public: \ + static size_t get() { return id; } \ + \ + private: \ + static size_t id; \ + }; \ + \ + } /* namespace internal */ \ + } /* namespace runtime */ \ + } /* namespace xla */ + +#define XLA_RUNTIME_DEFINE_EXPLICIT_DENSE_TYPE_ID(ID_SET, T) \ + namespace xla { \ + namespace runtime { \ + namespace internal { \ + \ + size_t DenseTypeIdResolver::id = DenseTypeId::next_id(); \ + \ + } /* namespace internal */ \ + } /* namespace runtime */ \ + } /* namespace xla */ + +#endif // XLA_RUNTIME_TYPE_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/types.h new file mode 100644 index 0000000000000000000000000000000000000000..4cca54fa0f923ebcbcdaf556940aecb509987a57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/types.h @@ -0,0 +1,326 @@ +/* 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_RUNTIME_TYPES_H_ +#define XLA_RUNTIME_TYPES_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "llvm/Support/ExtensibleRTTI.h" +#include "llvm/Support/raw_ostream.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace runtime { + +//===----------------------------------------------------------------------===// +// Canonical XLA runtime types for the executable arguments. +//===----------------------------------------------------------------------===// + +// Types supported by the compiled function signature. We do rely on the LLVM +// style RTTI (https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html) to avoid +// dependency on the MLIR types at runtime, because we don't want to depend +// on any of the compiler implementation details at runtime and we want to +// support lightweight loading and execution of AOT compiled programs. +// +// We rely on the RTTI for the open class hierarchies, because we want to allow +// users to define their own types for the arguments. +// +// If the type can be passed to the compiled function as an argument or returned +// as a result, it must define its own ABI. The ABI is defined by the MLIR to +// LLVM lowering pipeline and the runtime integration (see `runtime.h`). +class Type : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + // Arguments to compiled functions passed as a set of pointers. For example + // memref descriptor passed in as a set of pointers to data, sizes and + // strides. See `Argument::Pack` implementation for details (in `argument.h`). + struct ArgumentAbi { + size_t num_ptrs; + }; + + // Compiled function returns results by writing into the pre-allocated storage + // of the given size with the requested alignment. Runtime pre-allocates + // memory required for all results in the call frame. + struct ResultAbi { + size_t size; + + // TODO(ezhulenev): Add alignment to the result ABI. Alignment is an + // important part of the result ABI that we ignore today. It all doesn't + // crash only because all results happen to have a size that is multiple of + // 8 bytes, and because of that all of the results are properly aligned. + // Results memory layout in the call frame should take in account base + // pointer alignment and alignment requirements of all results. + }; + + // Returns an Abi if the type can be used as an argument. + virtual absl::StatusOr AsArgument() const { + return absl::UnimplementedError("argument ABI is not implemented"); + } + + // Returns an Abi if the type can be returned as a result. + virtual absl::StatusOr AsResult() const { + return absl::UnimplementedError("result ABI is not implemented"); + } + + virtual std::string ToString() const = 0; + + protected: + Type() = default; +}; + +inline llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const Type& type) { + return os << type.ToString(); +} + +//===----------------------------------------------------------------------===// +// Async Token type corresponding to the mlir::async::TokenType +//===----------------------------------------------------------------------===// + +class AsyncTokenType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + absl::StatusOr AsArgument() const final; + absl::StatusOr AsResult() const final; + + std::string ToString() const final; +}; + +//===----------------------------------------------------------------------===// +// Async Value type corresponding to the mlir::async::ValueType. +//===----------------------------------------------------------------------===// + +class AsyncValueType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + explicit AsyncValueType(std::unique_ptr value_type) + : value_type_(std::move(value_type)) {} + + const Type& value_type() const { return *value_type_; } + + absl::StatusOr AsArgument() const final; + absl::StatusOr AsResult() const final; + + std::string ToString() const final; + + private: + std::unique_ptr value_type_; +}; + +//===----------------------------------------------------------------------===// +// Scalar type corresponding to mlir::IntegerType or mlir::FloatType. +//===----------------------------------------------------------------------===// + +class ScalarType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + explicit ScalarType(PrimitiveType type) : type_(type) {} + + PrimitiveType type() const { return type_; } + + absl::StatusOr AsArgument() const final; + absl::StatusOr AsResult() const final; + + std::string ToString() const final; + + private: + PrimitiveType type_; +}; + +//===----------------------------------------------------------------------===// +// Tuple type corresponding to mlir::TupleType. +//===----------------------------------------------------------------------===// + +class TupleType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + explicit TupleType(llvm::SmallVector> elems) + : elems_(std::move(elems)) {} + + std::string ToString() const final; + + // Note: the AsArgument() and AsResult() methods are unimplemented, because + // this type is not meant to be used without expansion at run time. + + private: + llvm::SmallVector> elems_; +}; + +//===----------------------------------------------------------------------===// +// Ranked Tensor type corresponding to the mlir::RankedTensorType. +//===----------------------------------------------------------------------===// + +class RankedTensorType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + static constexpr int64_t kDynamic = std::numeric_limits::min(); + + static constexpr bool IsDynamic(int64_t dim) { return dim == kDynamic; } + + RankedTensorType(absl::Span sizes, PrimitiveType element_type) + : sizes_(sizes.begin(), sizes.end()), element_type_(element_type) {} + + absl::Span sizes() const { return sizes_; } + unsigned rank() const { return sizes_.size(); } + PrimitiveType element_type() const { return element_type_; } + + std::string ToString() const final; + + private: + std::vector sizes_; + PrimitiveType element_type_; +}; + +//===----------------------------------------------------------------------===// +// Unranked Tensor type corresponding to the mlir::UnrankedTensorType. +//===----------------------------------------------------------------------===// + +class UnrankedTensorType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + explicit UnrankedTensorType(PrimitiveType element_type) + : element_type_(element_type) {} + + PrimitiveType element_type() const { return element_type_; } + + std::string ToString() const final; + + private: + PrimitiveType element_type_; +}; + +//===----------------------------------------------------------------------===// +// Ranked Memref type corresponding to the mlir::MemrefType. +//===----------------------------------------------------------------------===// + +class MemrefType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + static constexpr int64_t kDynamic = std::numeric_limits::min(); + + static constexpr bool IsDynamic(int64_t dim) { return dim == kDynamic; } + + MemrefType(absl::Span sizes, PrimitiveType element_type) + : sizes_(sizes.begin(), sizes.end()), element_type_(element_type) {} + + absl::Span sizes() const { return sizes_; } + int64_t size(size_t dim) const { return sizes_[dim]; } + unsigned rank() const { return sizes_.size(); } + PrimitiveType element_type() const { return element_type_; } + + absl::StatusOr AsArgument() const final; + absl::StatusOr AsResult() const final; + + std::string ToString() const final; + + private: + std::vector sizes_; + PrimitiveType element_type_; +}; + +//===----------------------------------------------------------------------===// +// Unranked Memref type corresponding to the mlir::UnrankedMemrefType. +//===----------------------------------------------------------------------===// + +class UnrankedMemrefType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + explicit UnrankedMemrefType(PrimitiveType element_type) + : element_type_(element_type) {} + + PrimitiveType element_type() const { return element_type_; } + + std::string ToString() const final; + + private: + PrimitiveType element_type_; +}; + +//===----------------------------------------------------------------------===// +// Corresponds to the RT dialect's ExecutionContextType. +//===----------------------------------------------------------------------===// + +class ExecutionContextOperandType + : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + absl::StatusOr AsArgument() const final; + + std::string ToString() const final; +}; + +//===----------------------------------------------------------------------===// +// Corresponds to the RT dialect's OpaqueType. +//===----------------------------------------------------------------------===// + +class OpaqueOperandType : public llvm::RTTIExtends { + public: + static constexpr char ID = 0; // NOLINT + + absl::StatusOr AsArgument() const final; + + std::string ToString() const final; +}; + +//===----------------------------------------------------------------------===// +// Compiled function signature type corresponding to the mlir::FunctionType. +//===----------------------------------------------------------------------===// + +// TODO(ezhulenev): Make function type copyable (replace std::unique_ptr with +// std::shared ptr). +class FunctionType { + public: + const Type* operand(unsigned index) const { return operands_[index].get(); } + const Type* result(unsigned index) const { return results_[index].get(); } + + unsigned num_operands() const { return operands_.size(); } + unsigned num_results() const { return results_.size(); } + + FunctionType(std::vector> operands, + std::vector> results) + : operands_(std::move(operands)), results_(std::move(results)) {} + + void insert_operand(unsigned index, std::unique_ptr operand) { + operands_.insert(operands_.begin() + index, std::move(operand)); + } + + void insert_result(unsigned index, std::unique_ptr result) { + results_.insert(results_.begin() + index, std::move(result)); + } + + private: + std::vector> operands_; + std::vector> results_; +}; + +} // namespace runtime +} // namespace xla + +#endif // XLA_RUNTIME_TYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/algebraic_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/algebraic_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..23207449735e5f650b91cb9a49068886aa77843b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/algebraic_simplifier.h @@ -0,0 +1,617 @@ +/* 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_SERVICE_ALGEBRAIC_SIMPLIFIER_H_ +#define XLA_SERVICE_ALGEBRAIC_SIMPLIFIER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/util.h" + +namespace xla { + +class AlgebraicSimplifierOptions { + public: + // Platform dependent callback to determine if a reshape `from_shape` to + // `to_shape` is a bitcast. + using ReshapeIsBitcastCallback = + std::function; + // Platform dependent callback to determine if a set of reverse dimensions is + // lowerable + using ConvIsLowerableCallback = std::function; + + explicit AlgebraicSimplifierOptions( + ReshapeIsBitcastCallback reshape_is_bitcast_callback = {}, + ConvIsLowerableCallback conv_is_lowerable_callback = {}) + : reshape_is_bitcast_callback_(std::move(reshape_is_bitcast_callback)), + conv_is_lowerable_callback_(std::move(conv_is_lowerable_callback)) {} + + // Use the platform specific callback if set. It is not sensible to return + // true here if the options are not layout sensitive. + bool ReshapeIsBitcast(const Shape& from_shape, const Shape& to_shape) const { + if (!is_layout_sensitive_) { + return false; + } + if (!reshape_is_bitcast_callback_) { + return ShapeUtil::ReshapeIsBitcast(from_shape, to_shape); + } + return reshape_is_bitcast_callback_(from_shape, to_shape); + } + + // Use the platform specific callback if set. Otherwise, return true. + bool ConvIsLowerable(HloInstruction* reverse_dims) const { + if (!conv_is_lowerable_callback_) { + return true; + } + return conv_is_lowerable_callback_(reverse_dims); + } + + // If is_layout_sensitive is true, then the simplifier preserves layout during + // transformation. Otherwise, layout is ignored. + void set_is_layout_sensitive(bool is_layout_sensitive) { + is_layout_sensitive_ = is_layout_sensitive; + } + + bool is_layout_sensitive() const { return is_layout_sensitive_; } + + void set_use_associative_reordering(bool use_associative_reordering) { + use_associative_reordering_ = use_associative_reordering; + } + + bool use_associative_reordering() const { + return use_associative_reordering_; + } + + void set_associative_reordering_threshold( + double associative_reordering_threshold) { + associative_reordering_threshold_ = associative_reordering_threshold; + } + + double associative_reordering_threshold() const { + return associative_reordering_threshold_; + } + + // Enable dot simplification on platforms where it is profitable. + void set_enable_dot_strength_reduction(bool enable_dot_strength_reduction) { + enable_dot_strength_reduction_ = enable_dot_strength_reduction; + } + + bool enable_dot_strength_reduction() const { + return enable_dot_strength_reduction_; + } + + // Enable dot->multiple rewrite for dot as an outer-product + void set_enable_dot_to_multiply_rewrite(bool enable_dot_to_multiply_rewrite) { + enable_dot_to_multiply_rewrite_ = enable_dot_to_multiply_rewrite; + } + + bool enable_dot_to_multiply_rewrite() const { + return enable_dot_to_multiply_rewrite_; + } + + // This platform will not run the DotDecomposer to canonicalize dots. + void set_supports_non_canonical_dots(bool supports_non_canonical_dots) { + supports_non_canonical_dots_ = supports_non_canonical_dots; + } + bool supports_non_canonical_dots() const { + return supports_non_canonical_dots_; + } + + // Enable convolution simplification on platforms where it is profitable. + void set_enable_conv_simplification(bool enable_conv_simplification) { + enable_conv_simplification_ = enable_conv_simplification; + } + bool enable_conv_simplification() const { + return enable_conv_simplification_; + } + + // Enable convolution operand swapping on platforms where it is supported. + void set_enable_conv_operand_swap(bool enable_conv_operand_swap) { + enable_conv_operand_swap_ = enable_conv_operand_swap; + } + bool enable_conv_operand_swap() const { return enable_conv_operand_swap_; } + + // Move constant scalar multiply to one operand or output of convolutions with + // the smallest tensor size, to reduce the number of scalar multiply. + void set_enable_scalar_multiply_reduction( + bool enable_scalar_multiply_reduction) { + enable_scalar_multiply_reduction_ = enable_scalar_multiply_reduction; + } + + bool enable_scalar_multiply_reduction() const { + return enable_scalar_multiply_reduction_; + } + + // Also the algebraic simplifer to treat floating point values like real + // numbers. + void set_enable_floats_are_real(bool enable_floats_are_real) { + enable_floats_are_real_ = enable_floats_are_real; + } + + bool enable_floats_are_real() const { return enable_floats_are_real_; } + + // If enable_window_reduce_replacement is true, the kReduceWindow instruction + // can be optimized by replacement with simpler operations. + void set_enable_window_reduce_to_reduce_replacement( + bool enable_window_reduce_to_reduce_replacement) { + enable_window_reduce_to_reduce_replacement_ = + enable_window_reduce_to_reduce_replacement; + } + + bool enable_window_reduce_to_reduce_replacement() const { + return enable_window_reduce_to_reduce_replacement_; + } + + // Sets the size of a gather operand that can be unrolled into many selects. + void set_very_small_gather_size(int64_t size) { + very_small_gather_size_ = size; + } + + int64_t very_small_gather_size() const { return very_small_gather_size_; } + + void set_cudnn_batchnorm_forward_training_metadata(const std::string& c) { + metadata_.cudnn_batchnorm_forward_training_metadata = c; + } + + const std::string& get_cudnn_batchnorm_forward_training_metadata() const { + return metadata_.cudnn_batchnorm_forward_training_metadata; + } + + void set_enable_reduce_of_reshape(bool enable_reduce_of_reshape) { + enable_reduce_of_reshape_ = enable_reduce_of_reshape; + } + + bool enable_reduce_of_reshape() const { return enable_reduce_of_reshape_; } + + void set_enable_negative_padding_replacement( + bool enable_negative_padding_replacement) { + enable_negative_padding_replacement_ = enable_negative_padding_replacement; + } + + bool enable_negative_padding_replacement() const { + return enable_negative_padding_replacement_; + } + + void set_enable_sink_broadcast(bool enable_sink_broadcast) { + enable_sink_broadcast_ = enable_sink_broadcast; + } + + bool enable_sink_broadcast() const { return enable_sink_broadcast_; } + + // If true, always simplify reduce(transpose(x)) and reduce(reshape(x)), even + // if the transpose/reshape has multiple users. This can be beneficial + // on platforms where the extra transpose/reshape isn't as expensive as + // the optimization benefits brought about by simplifying the graph. + bool unconditionally_simplify_reduce_of_transpose_or_reshape() const { + return unconditionally_simplify_reduce_of_transpose_or_reshape_; + } + void set_unconditionally_simplify_reduce_of_transpose_or_reshape(bool val) { + unconditionally_simplify_reduce_of_transpose_or_reshape_ = val; + } + + // If true, min(x, NaN) = NaN. If false, min(x, NaN) = x. + // + // TODO(b/209827141): Remove this and make minmax_propagate_nan + // unconditionally true. + bool minmax_propagate_nan() const { return minmax_propagate_nan_; } + void set_minmax_propagate_nan(bool val) { minmax_propagate_nan_ = val; } + + // When true, always replaces Reduce(concat({a,b,...})) with + // map(reduce(a),map(reduce(b),...,)). If false, only does the replacement if + // the shapes of a,b,... have the same dimensions. + bool enable_unconditional_reduce_of_concat_replacement() const { + return enable_unconditional_reduce_of_concat_replacement_; + } + void set_enable_unconditional_reduce_of_concat_replacement( + bool enable_unconditional_reduce_of_concat_replacement) { + enable_unconditional_reduce_of_concat_replacement_ = + enable_unconditional_reduce_of_concat_replacement; + } + + private: + // Metadata struct can be used to store any metadata information encapsulated + // with the AlgebraicSimplierOptions that can be later used in an + // AlgebraicSimplifier pass. For example, + // cudnn_batchnorm_forward_training_metadata can be used to store the name of + // a custom call. If the custom call is + // __cudnn$batchNormalizationForwardTraining, the output with index 2 is + // guaranteed to be positive. This property has been used to recursively + // determine if the operand of an instruction is always positive. + struct Metadata { + std::string cudnn_batchnorm_forward_training_metadata{""}; + Metadata() {} + }; + ReshapeIsBitcastCallback reshape_is_bitcast_callback_; + ConvIsLowerableCallback conv_is_lowerable_callback_; + bool is_layout_sensitive_{false}; + bool enable_dot_strength_reduction_{true}; + bool supports_non_canonical_dots_{true}; + bool enable_dot_to_multiply_rewrite_{true}; + bool enable_conv_simplification_{true}; + bool enable_conv_operand_swap_{true}; + bool enable_scalar_multiply_reduction_{false}; + bool enable_floats_are_real_{false}; + bool enable_window_reduce_to_reduce_replacement_{true}; + bool enable_reduce_of_reshape_{true}; + bool enable_negative_padding_replacement_{true}; + bool enable_sink_broadcast_{true}; + bool unconditionally_simplify_reduce_of_transpose_or_reshape_{false}; + int64_t very_small_gather_size_{4}; + bool minmax_propagate_nan_{true}; + bool enable_unconditional_reduce_of_concat_replacement_{true}; + bool use_associative_reordering_{false}; + double associative_reordering_threshold_{2.0}; + Metadata metadata_; +}; + +// A pass which performs algebraic simplifications. +class AlgebraicSimplifier : public HloModulePass { + public: + // If is_layout_sensitive is true, then the simplifier preserves layout during + // transformation. Otherwise, layout is ignored. + explicit AlgebraicSimplifier(const AlgebraicSimplifierOptions& options) + : options_(options) {} + ~AlgebraicSimplifier() override = default; + absl::string_view name() const override { return "algsimp"; } + + // Run algebraic simplification on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Create constant from literal with tiles and element size updated in the + // constant's layout. + std::unique_ptr CreateConstantWithLayoutUpdated( + Literal literal) { + auto constant = HloInstruction::CreateConstant(std::move(literal)); + UpdateLayout(constant->mutable_shape()); + return constant; + } + + protected: + AlgebraicSimplifierOptions options_; +}; + +// AlgebraicSimplifierVisitor traverses the HLO computation and reduces certain +// algebraic expressions to simplified forms. Note: This only supports +// simplifications that simply look at the operands of an instruction. For the +// more general case a worklist based approach would be needed. +class AlgebraicSimplifierVisitor : public DfsHloRewriteVisitor { + public: + explicit AlgebraicSimplifierVisitor(const AlgebraicSimplifierOptions& options, + AlgebraicSimplifier* simplifier) + : options_(options), simplifier_(simplifier) {} + + Status HandleAbs(HloInstruction* abs) override; + + Status HandleAdd(HloInstruction* add) override; + + Status HandleAnd(HloInstruction* logical_and) override; + + Status HandleBitcast(HloInstruction* bitcast) override; + + Status HandleBitcastConvert(HloInstruction* bitcast) override; + + Status HandleBroadcast(HloInstruction* broadcast) override; + + Status HandleCompare(HloInstruction* compare) override; + + Status HandleConcatenate(HloInstruction* concatenate) override; + + Status HandleConstant(HloInstruction* constant) override; + + Status HandleCopy(HloInstruction* copy) override; + + Status HandleConvert(HloInstruction* convert) override; + + Status HandleComplex(HloInstruction* complex) override; + + Status HandleReal(HloInstruction* real) override; + + Status HandleImag(HloInstruction* imag) override; + + Status HandleIota(HloInstruction* instruction) override; + + Status HandleConvolution(HloInstruction* convolution) override; + + Status HandleDivide(HloInstruction* divide) override; + + Status HandleDot(HloInstruction* dot) override; + + Status HandleGather(HloInstruction* gather) override; + + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + + Status HandleLog(HloInstruction* log) override; + + Status HandleMaximum(HloInstruction* maximum) override; + + Status HandleMinimum(HloInstruction* minimum) override; + + Status HandleClamp(HloInstruction* clamp) override; + + Status HandleMultiply(HloInstruction* multiply) override; + + Status HandleNegate(HloInstruction* negate) override; + + Status HandleNot(HloInstruction* logical_not) override; + + Status HandleOptimizationBarrier(HloInstruction* barrier) override; + + Status HandleOr(HloInstruction* logical_or) override; + + Status HandlePad(HloInstruction* pad) override; + + Status HandlePower(HloInstruction* power) override; + + Status HandleRemainder(HloInstruction* remainder) override; + + Status HandleReshape(HloInstruction* reshape) override; + + Status HandleReduce(HloInstruction* hlo) override; + + Status HandleReduceWindow(HloInstruction* hlo) override; + + Status HandleReverse(HloInstruction* reverse) override; + + Status HandleRsqrt(HloInstruction* rsqrt) override; + + Status HandleSlice(HloInstruction* slice) override; + + Status HandleSqrt(HloInstruction* sqrt) override; + + Status HandleDynamicSlice(HloInstruction* dynamic_slice) override; + + Status HandleDynamicUpdateSlice( + HloInstruction* dynamic_update_slice) override; + Status HandleScatter(HloInstruction* hlo) override; + + Status HandleSelect(HloInstruction* select) override; + + Status HandleSort(HloInstruction* sort) override; + + Status HandleTranspose(HloInstruction* transpose) override; + + Status HandleSubtract(HloInstruction* sub) override; + + Status HandleMap(HloInstruction* map) override; + + // Runs the visitor on a computation. + bool Run(HloComputation* computation, + const AlgebraicSimplifierOptions& options, + AlgebraicSimplifier* simplifier); + + // Compute a function that maps from bitcasted dimensions to the resulting + // ones. Returns the function as a vector if successful; std::optional + // otherwise. + static std::optional>> ComputeBitcastDimMap( + const Shape& bitcast_shape, const Shape& operand_shape); + // Invert the directions of the given bitcast dimension map. + static std::vector> InvertBitcastDimMap( + const Shape& original_shape, const Shape& bitcast_shape, + const std::vector>& original_map); + + // Modify the layout dimensions of result_shape, so that it becomes the + // re-shaped result of applying bitcast to the original_shape, by using + // dim_map to re-shape layout dimensions of original_shape. Returns the + // result_shape with modified layout if the conversion succeeds; Returns + // std::nullopt if fails. + static std::optional ReshapeLayoutDimensions( + const Shape& original_shape, const Shape& result_shape, + const std::vector>& original_map, + const std::vector>& result_map); + + // Allow backend constraints on tiling etc. to invalidate optimizations. + virtual bool IsValidLayout(const Shape& shape) { return true; } + // Allow backend targets to determine whether a layout is inefficient. + virtual bool ShouldStrengthReduceDotToReduce(const HloInstruction* hlo) { + return true; + } + + protected: + // The backend-specific options selected for the algebraic simplifier. + const AlgebraicSimplifierOptions& options_; + + private: + // Removes degenerate dimension from dot. + StatusOr RemoveDegenerateDimensionFromDot(HloInstruction* dot); + + // Moves the transpose to the broadcast if possible. Can also be called with a + // bitcast transpose. + Status SimplifyTransposeOfBroadcast(HloInstruction* transpose, + absl::Span dimensions); + + // Converts to primitive type if the input hlo is not that type, otherwise + // returns the original hlo. + HloInstruction* AsType(HloInstruction* hlo, + const PrimitiveType element_type) { + if (hlo->shape().element_type() == element_type) { + return hlo; + } + Shape changed_shape = + ShapeUtil::ChangeElementType(hlo->shape(), element_type); + simplifier_->UpdateLayout(&changed_shape); + return computation_->AddInstruction( + HloInstruction::CreateConvert(changed_shape, hlo)); + } + + // Transposes a dot operand such that the batch dimensions are the most major, + // and the contracting dimensions are most minor. + StatusOr NormalizeDotOperandToBatchMajorAndContractingMinor( + HloInstruction* dot_operand, absl::Span batch_dimensions, + absl::Span contracting_dimensions); + + // Simplify dot(transpose(a), transpose(b)) to transpose(dot(b,a)) (or + // transpose(dot(a,b)) if only the batch dims are transposed). + // + // Requires the dot has been canonicalized by DotDecomposer into + // + // LHS [batch dims..., non-contracting dim, contracting dim] + // RHS [batch dims..., contracting dim, non-contracting dim]. + StatusOr RemoveTransposesFromDotOperands(HloInstruction* dot); + + // Helper method to perform and add reduction on a list of dimensions. + HloInstruction* AddReduce(HloInstruction* hlo, absl::Span dims, + PrimitiveType type); + + // Move scalar multiply to the smallest side of convolution to + // reduce multiply computations. + Status ScalarMultiplyReduction(HloInstruction* dot); + + // Convenience method for replacing an instruction with a bitcast. If operand + // is not null, then the bitcast will use the specified operand instead of the + // operand of the instruction. + void ReplaceWithBitcast(HloInstruction* instruction, + HloInstruction* operand = nullptr); + + // Change copy(bitcast...(copy)) into copy(bitcast) or bitcast(copy) so that + // the replicated copies are combined when allowed by layout/tiling assignment + // constraints. + bool SwapCopyBitcastCopy(HloInstruction* root_copy); + + // Replace old instruction with new instruction if old and new instructions + // are compatible (have the same shape and replacement preserves sharding). + // Updates uses and root instruction. Returns whether a replacement was made. + bool ReplaceInstructionIfCompatible(HloInstruction* old_instruction, + HloInstruction* new_instruction); + // Similar to above but tuplizes `new_instructions` if there are more than 1 + // instructions. + bool ReplaceInstructionIfCompatible( + HloInstruction* old_instruction, + absl::Span new_instructions); + + // Returns whether the shape of the output of the given instructions are the + // same for the purposes of simplification. If options_.is_layout_sensitive() + // is true, then this tests shape equality including layout + // (ShapeUtil::Equal). If options_.is_layout_sensitive() is false, then the + // tests shape compatibility (ShapeUtil::Compatible). + bool SameShape(const HloInstruction* lhs, const HloInstruction* rhs) const; + + // Same as above but takes shape arguments directly. + bool SameShape(const Shape& lhs, const Shape& rhs) const; + + // A Broadcast that feeds an element-wise operation with a unique non-scalar + // operand can sink to after the operation. + StatusOr TryToSinkBroadcastAfterOpWithUniqueNonScalarOperand( + HloInstruction* broadcast); + + StatusOr OptimizeDotOfConcat(HloInstruction* dot); + StatusOr OptimizeDotOfConcatHelper( + HloInstruction* dot, HloInstruction* lhs, int64_t lhs_contracting_dim, + HloInstruction* rhs, int64_t rhs_contracting_dim, bool swapped); + + StatusOr OptimizeDotOfGather(HloInstruction* dot); + + StatusOr OptimizeDotOfReorderContractingDims( + HloInstruction* dot); + + StatusOr AssociativeReorderDotOperator(HloInstruction* dot); + + HloComputation* GetOrCreateScalarAddComputation(PrimitiveType type) { + HloComputation*& scalar_add_computation = scalar_add_computations_[type]; + if (scalar_add_computation) { + return scalar_add_computation; + } + + HloComputation::Builder b("scalar_add_computation"); + Shape shape = ShapeUtil::MakeShape(type, {}); + simplifier_->UpdateLayout(&shape); + auto scalar_lhs = b.AddInstruction( + HloInstruction::CreateParameter(0, shape, "scalar_lhs")); + auto scalar_rhs = b.AddInstruction( + HloInstruction::CreateParameter(1, shape, "scalar_rhs")); + auto scalar_op = b.AddInstruction(HloInstruction::CreateBinary( + shape, HloOpcode::kAdd, scalar_lhs, scalar_rhs)); + scalar_add_computation = + computation_->parent()->AddEmbeddedComputation(b.Build(scalar_op)); + return scalar_add_computation; + } + + // Tries to fold a kPad in the input or filter into the convolution + // instruction's window. + virtual StatusOr FoldConvInputPad(HloInstruction* convolution); + StatusOr FoldConvFilterPad(HloInstruction* convolution); + + // Tries to swap convolution operands if they would result in a more efficient + // convolution. + StatusOr SwapConvOperands(HloInstruction* convolution); + + // Tries to use a kDot in place of the given convolution. + StatusOr SimplifyConvToDot(HloInstruction* convolution); + // Tries to use a multiplication in place of the given convolution. + StatusOr SimplifyConvToMultiply(HloInstruction* convolution); + + // Tries to simplify a slice where the result of the slice is a scalar. + StatusOr TrySimplifyScalarSlice(HloInstruction* slice); + + // Tries to convert slice(reshape(X)) into reshape(slice(X)) + StatusOr TryToReorderSliceAndReshape(HloInstruction* slice); + + // Tries to convert slice(reverse(X)) into reverse(slice(X)) + StatusOr TryToReorderSliceAndReverse(HloInstruction* slice); + + // Tries to simplify `(and (< a N) (< a K))` in cases where `N <= K` into + // `(< a N)`. This is crucial for being able to figure out the loop trip + // count. + // + // Assumes that the input is conjunction. + StatusOr TrySimplifyTautologicalCompare(HloInstruction* conjunction); + + // Tries to simlplify (bitcast-convert (concat (bitcast-convert A) ...)) where + // the types of inner and outer bitcast-convert cancel out. + StatusOr TrySimplifyTautologicalBitcastConvert(HloInstruction* bitcast); + + // Tries to remove surrounding converts around a binary op where the op has a + // more precise type than its inputs and output. + // + // convert(bin_op(convert(data1), + // convert(data2))) + // where TS is a smaller point type than TL (ex, TS=fp16, TL=fp32) + // -> + // bin_op(data1, data2) + Status TryRemoveUpcastAndDowncastSurroundingBinaryOp( + HloInstruction* convert_instruction); + + // Useful when we want to use the same visitor over multiple computations. + void ResetState(HloComputation* computation); + + // Current HloComputation instance the AlgebraicSimplifierVisitor is + // traversing. + HloComputation* computation_; + + // Cached computation for adding two scalars of a given type. + absl::flat_hash_map scalar_add_computations_; + + AlgebraicSimplifier* simplifier_ = nullptr; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALGEBRAIC_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_broadcast_reorder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_broadcast_reorder.h new file mode 100644 index 0000000000000000000000000000000000000000..57b63518e2e817576b89e8b530958b81cc4fdb72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_broadcast_reorder.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_ALL_GATHER_BROADCAST_REORDER_H_ +#define XLA_SERVICE_ALL_GATHER_BROADCAST_REORDER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// A pass that reorders all-gather(broadcast(x)) -> broadcast(all-gather(x)). +// The intent is to reduce the size of all-gather when possible by doing an +// all-gather on the (smaller) pre-broadcasted data and then applying the +// broadcast. +class AllGatherBroadcastReorder : public HloModulePass { + public: + absl::string_view name() const override { return "all-gather-bcast-reorder"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_GATHER_BROADCAST_REORDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_combiner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_combiner.h new file mode 100644 index 0000000000000000000000000000000000000000..148f82b1810c3d3532b5251160904a5a6eb4dcc6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_combiner.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_ALL_GATHER_COMBINER_H_ +#define XLA_SERVICE_ALL_GATHER_COMBINER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Combines small non-dependent AllGather ops into larger combined +// AllGather ops. A typical AllGather implementation has a minimum +// latency-induced time for a AllGather op so a single combined op can be +// more efficient than many small ones. +class AllGatherCombiner : public HloModulePass { + public: + AllGatherCombiner(int64_t combine_threshold_in_bytes, + int64_t combine_threshold_count, bool combine_by_dim); + + absl::string_view name() const override { return "all-gather-combiner"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Combine all gather ops up to this threshold. + int64_t combine_threshold_in_bytes_; + + // Combine all gather ops up to this threshold (number of operands). + int64_t combine_threshold_count_; + + // Combine all-gather ops with the same gather dimension. + bool combine_by_dim_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_GATHER_COMBINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..e08c638385eaa943ef1e3630fc5e3104c0aa8d72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_decomposer.h @@ -0,0 +1,50 @@ +/* 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_SERVICE_ALL_GATHER_DECOMPOSER_H_ +#define XLA_SERVICE_ALL_GATHER_DECOMPOSER_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// AllGatherDecomposer is a pass which converts unsupported all-gathers into +// dynamic-update-slices and all-reduces. +class AllGatherDecomposer : public HloModulePass { + public: + explicit AllGatherDecomposer( + std::function should_decompose) + : should_decompose_(std::move(should_decompose)) {} + AllGatherDecomposer() + : should_decompose_( + [](const HloAllGatherInstruction& ag) { return true; }) {} + absl::string_view name() const override { return "all_gather_decomposer"; } + + // Run AllGatherDecomposer pass on computations in 'module'. + // Returns whether the 'module' was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + std::function should_decompose_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_GATHER_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_combiner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_combiner.h new file mode 100644 index 0000000000000000000000000000000000000000..abc7cdd2e1499b99a44b8243f60b55084dbe3ec7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_combiner.h @@ -0,0 +1,54 @@ +/* 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_SERVICE_ALL_REDUCE_COMBINER_H_ +#define XLA_SERVICE_ALL_REDUCE_COMBINER_H_ + +#include "absl/strings/string_view.h" +#include "xla/array2d.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Combines small non-dependent AllReduce ops into larger combined +// AllReduce ops. A typical AllReduce implementation has a minimum +// latency-induced time for a AllReduce op so a single combined op can be +// more efficient than many small ones. +class AllReduceCombiner : public HloModulePass { + public: + AllReduceCombiner(int64_t combine_threshold_in_bytes, + int64_t combine_threshold_count); + + absl::string_view name() const override { return "all-reduce-combiner"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Combine all reduce ops up to this threshold. + int64_t combine_threshold_in_bytes_; + + // Combine all reduce ops up to this threshold (number of operands). + int64_t combine_threshold_count_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_REDUCE_COMBINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_contiguous.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_contiguous.h new file mode 100644 index 0000000000000000000000000000000000000000..dd89e97041dd10c897d8d23a24d0e5f641d7a207 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_contiguous.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_ALL_REDUCE_CONTIGUOUS_H_ +#define XLA_SERVICE_ALL_REDUCE_CONTIGUOUS_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Concatenates all-reduce operands together, so the all-reduce is performed +// over a single, contiguous buffer. +class AllReduceContiguous : public HloModulePass { + public: + absl::string_view name() const override { return "all-reduce-contiguous"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_REDUCE_CONTIGUOUS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_folder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_folder.h new file mode 100644 index 0000000000000000000000000000000000000000..c603cc42eb74264be5fbf879bf699e4b7b65ee82 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_folder.h @@ -0,0 +1,48 @@ +/* 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_SERVICE_ALL_REDUCE_FOLDER_H_ +#define XLA_SERVICE_ALL_REDUCE_FOLDER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// A pass that folds an all-reduce feeding into another all-reduce by expanding +// the replica groups. As an example: +// +// ar0 = all-reduce(x) replica_groups={{0,1},{2,3},{4,5},{6,7}} +// ar1 = all-reduce(all-reduce0) replica_groups={{0,2},{1,3},{4,6},{5,7}} +// +// Can be combined into a single all-reduce: +// +// ar1 = all-reduce(x) replica_groups={{0,1,2,3},{4,5,6,7}} +// + +class AllReduceFolder : public HloModulePass { + public: + absl::string_view name() const override { return "all-reduce-folder"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_REDUCE_FOLDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_key.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_key.h new file mode 100644 index 0000000000000000000000000000000000000000..126b182499af04929992f89403f6697a178a83ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_key.h @@ -0,0 +1,43 @@ +/* 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_SERVICE_ALL_REDUCE_KEY_H_ +#define XLA_SERVICE_ALL_REDUCE_KEY_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_domain_map.h" + +namespace xla { + +// Encapsulates all of the properties which must match for two all-reduce +// instructions to be compatible with each other (and hence be possible to +// combine the instructions). +using AllReduceKey = + std::tuple>>; + +std::optional GetAllReduceKey( + const HloInstruction* instruction, const HloDomainMap* domain_map = nullptr, + bool ignore_replica_groups = false); + +} // namespace xla + +#endif // XLA_SERVICE_ALL_REDUCE_KEY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_promotion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_promotion.h new file mode 100644 index 0000000000000000000000000000000000000000..83a3d3facad3e1006bef346d951b0cdcb9e9e6cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_promotion.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_ALL_REDUCE_PROMOTION_H_ +#define XLA_SERVICE_ALL_REDUCE_PROMOTION_H_ + +#include +#include "xla/service/change_op_data_type.h" + +namespace xla { + +class AllReducePromotion : public HloModulePass { + public: + explicit AllReducePromotion( + absl::Span const> from_to_types); + absl::string_view name() const override { return "all-reduce-promotion"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + ChangeOpDataType pass_; +}; + +} // namespace xla +#endif // XLA_SERVICE_ALL_REDUCE_PROMOTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_reassociate.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_reassociate.h new file mode 100644 index 0000000000000000000000000000000000000000..7f030c3fd1b2e8e19f8eaa09b3b5dfc413ad88d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_reassociate.h @@ -0,0 +1,53 @@ +/* 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_SERVICE_ALL_REDUCE_REASSOCIATE_H_ +#define XLA_SERVICE_ALL_REDUCE_REASSOCIATE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// A pass that reassociates all-reduce feeding into compatible elementwise +// operations. As an example: add(all-reduce(x), all-reduce(y)) will be replaced +// with all-reduce(add(x,y)). Mathematically, this is replacing +// add(x0, x1, ... xk) + add(y0, y1, ... yk) with +// add((x0+y0), (x1+y), ... (xk+yk) +// +// i.e., reassociating the reduction operation. + +class AllReduceReassociate : public HloModulePass { + public: + explicit AllReduceReassociate(bool reassociate_converted_ar = false) + : reassociate_converted_ar_(reassociate_converted_ar) {} + + absl::string_view name() const override { return "all-reduce-reassociate"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Specify whether we should reassociate allreduces that are consumed by + // Convert nodes. + bool reassociate_converted_ar_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_REDUCE_REASSOCIATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_to_all_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_to_all_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..33313cadf25de700d70069e88aee1a3d86cd76e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_to_all_decomposer.h @@ -0,0 +1,46 @@ +/* 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_SERVICE_ALL_TO_ALL_DECOMPOSER_H_ +#define XLA_SERVICE_ALL_TO_ALL_DECOMPOSER_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// AllToAllDecomposer is a pass which converts unsupported array all_to_all +// into tuple all_to_all or array all_to_all with a minimum rank where the split +// dimension is the size of the replica_groups. +class AllToAllDecomposer : public OpExpanderPass { + public: + explicit AllToAllDecomposer(bool decompose_to_tuple = true, + int64_t min_array_rank = 0) + : decompose_to_tuple_(decompose_to_tuple), + min_array_rank_(min_array_rank) {} + ~AllToAllDecomposer() override = default; + absl::string_view name() const override { return "all_to_all_decomposer"; } + + private: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + StatusOr ExpandInstruction( + HloInstruction* instruction) override; + bool decompose_to_tuple_; + int64_t min_array_rank_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALL_TO_ALL_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/allocation_tracker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/allocation_tracker.h new file mode 100644 index 0000000000000000000000000000000000000000..efbbdd68240c579d53aa9cd60cbfb7648d8e2d71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/allocation_tracker.h @@ -0,0 +1,154 @@ +/* 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_SERVICE_ALLOCATION_TRACKER_H_ +#define XLA_SERVICE_ALLOCATION_TRACKER_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/service/backend.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Tracks allocations for the XLA service; allocations can be registered +// with shape/device/tag and resolved from a handle for later use. +class AllocationTracker { + public: + // The allocator is used for deallocating memory when allocations are + // deregistered. All registered allocations must have the same platform as the + // allocator. + AllocationTracker(Backend* backend) : backend_(backend), next_handle_(1) {} + + // Registers a shaped buffer of device memory, and returns a corresponding + // handle that can be used for talking to XLA clients. The given shaped buffer + // will be treated as the buffer corresponding to the only replica. + StatusOr Register(ScopedShapedBuffer shaped_buffer, + const std::string& tag); + + // Registers a vector of shaped buffers of device memory, one per replica, and + // returns a corresponding handle that can be used for talking to XLA clients. + StatusOr RegisterReplicatedBuffers( + std::vector replicated_buffers, + const std::string& tag); + + // Unregister the allocation for the given data handle. + Status Unregister(const GlobalDataHandle& data); + + // Returns a vector of global data handles that point to the tuple elements. + StatusOr> DeconstructTuple( + const GlobalDataHandle& Data); + + // Resolve a handle from an XLA client to a vector of shaped buffers, one per + // replica, or provide an error status to say whether any of those buffers + // were not found (or found, but found deallocated). + StatusOr> Resolve( + const GlobalDataHandle& data) const; + + // Resolves a handle from an XLA client and replica id to a shaped buffer, or + // provide an error status to say whether it was not found (or found, but + // found deallocated). + StatusOr ResolveForReplica(const GlobalDataHandle& data, + int replica_id) const; + + private: + // Data structure encapsulating single memory allocation on the device. + struct Allocation { + // The pointer to this allocation. + se::OwningDeviceMemory device_memory; + + // This is the number of times this memory allocation is referred to by + // registered data handles. + int ref_count; + }; + + // Internal helper which resolves the given GlobalDataHandle to a + // list of ScopedShapedBuffers. + StatusOr> ResolveInternal( + const GlobalDataHandle& data) const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // Internal helper which registers a vector of shaped buffers, one per + // replica. ShapedBufferTy is either ScopedShapedBuffer or ShapedBuffer. If + // it's ShapedBuffer, all of the given buffers must already be tracked by this + // object -- presumably this is a call from DeconstructTuple. + template + StatusOr RegisterInternal( + std::vector replicated_buffers, const std::string& tag) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // Adds the given device address to the allocation tracker, or if it already + // exists, then increment its reference count. + void AddAllocationOrIncrementRefCount(se::DeviceMemoryBase device_memory, + int device_ordinal) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // Decrements the reference count of the given device memory. Then, if it is + // zero, deallocate the memory. + Status DecrementRefCount(se::DeviceMemoryBase device_memory, + int device_ordinal) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // A map from device memory opaque value to allocation. One such map is + // maintained per device ordinal. + using AllocationMap = absl::flat_hash_map; + + mutable absl::Mutex mutex_; + + // Backend to use with this tracker. The backend supplies the memory allocator + // to use when deallocating memory. + Backend* backend_; + + // The next handle to assign to an allocation, guarded by the same mutex as + // the mapping as they'll be mutated at the same time. + int64_t next_handle_ ABSL_GUARDED_BY(mutex_); + + // A map from device ordinal to AllocationMap. + absl::flat_hash_map opaque_to_allocation_map_ + ABSL_GUARDED_BY(mutex_); + + // A map from data handle to a vector of shaped buffers that represent the + // buffers for different replicas. + // + // The ShapedBuffers in this map's vectors need to be unique_ptrs, because our + // public API returns pointers to them. We expect the concrete class to be + // ShapedBuffer and never ScopedShapedBuffer; deallocation of buffers is + // handled by opaque_to_allocation_map_. + // + // The elements of the vectors need to be unique_ptrs because we return + // pointers to them. (In theory we could use std::list or something instead, + // but we also want to be able to null out these elements.) + // + // The reason that the elements can't be unique_ptrs is + // the existence of DeconstructTuple(). This function allows us to create a + // non-owning "view" into a tuple's sub-buffers. The sub-buffers are then + // free'd when both the view *and* the original tuple are Unregistered. This + // refcounting is managed in opaque_to_allocation_map_. + absl::flat_hash_map>> + handle_to_shaped_buffers_ ABSL_GUARDED_BY(mutex_); + + AllocationTracker(const AllocationTracker&) = delete; + AllocationTracker& operator=(const AllocationTracker&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ALLOCATION_TRACKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/async_collective_creator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/async_collective_creator.h new file mode 100644 index 0000000000000000000000000000000000000000..25ff6931905aa881cd40edb8ef898ff38c3919ca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/async_collective_creator.h @@ -0,0 +1,60 @@ +/* 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_SERVICE_ASYNC_COLLECTIVE_CREATOR_H_ +#define XLA_SERVICE_ASYNC_COLLECTIVE_CREATOR_H_ + +#include +#include +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Transforms each all-reduce instruction to a pair of all-reduce-start and +// all-reduce-done. +class AsyncCollectiveCreator : public HloModulePass { + public: + // Function to query the shape of the "context" for collectives that use + // HLO async-start/async-done. + using ContextShapeQuery = + std::function(const HloInstruction*)>; + struct CollectiveCreatorConfig { + HloPredicate convert_all_reduce = HloPredicateFalse; + HloPredicate convert_all_gather = HloPredicateFalse; + HloPredicate convert_collective_permute = HloPredicateFalse; + HloPredicate convert_all_to_all = HloPredicateFalse; + HloPredicate convert_reduce_scatter = HloPredicateFalse; + ContextShapeQuery get_context_shapes = [](const HloInstruction*) { + return std::vector{}; + }; + }; + explicit AsyncCollectiveCreator(CollectiveCreatorConfig creator_config) + : config_(std::move(creator_config)) {} + absl::string_view name() const override { return "async-collective-creator"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + CollectiveCreatorConfig config_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ASYNC_COLLECTIVE_CREATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/backend.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/backend.h new file mode 100644 index 0000000000000000000000000000000000000000..8e2e2f89ef97babe1372b2da6521939519235b62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/backend.h @@ -0,0 +1,208 @@ +/* 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_SERVICE_BACKEND_H_ +#define XLA_SERVICE_BACKEND_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "xla/service/compiler.h" +#include "xla/service/computation_placer.h" +#include "xla/service/stream_pool.h" +#include "xla/service/transfer_manager.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +namespace Eigen { +struct ThreadPoolDevice; +} + +namespace xla { + +// Options to configure the backend when it is created. +class BackendOptions { + public: + // Set the platform backing the backend, or nullptr for the default platform. + BackendOptions& set_platform(se::Platform* platform); + se::Platform* platform() const; + + // Sets the thread pool size for parallel execution of an individual operator. + // The default value of -1 will result in initializing the thread pool with + // the number of threads equal to the number of cores in the system. + BackendOptions& set_intra_op_parallelism_threads(int num_threads); + int intra_op_parallelism_threads() const; + + // Sets the allowed_devices for selectively constructing stream executors + // on the platform. + BackendOptions& set_allowed_devices( + const std::optional>& allowed_devices); + const std::optional>& allowed_devices() const; + + private: + se::Platform* platform_ = nullptr; + int intra_op_parallelism_threads_ = -1; + std::optional> allowed_devices_; +}; + +// Class which encapsulates an XLA backend. It includes everything necessary +// to compile and execute computations on a particular platform. +// +// It also offers a pooling API for creation/use of initialized streams: +// +// StreamPool::Ptr stream = backend->BorrowStream().value(); +class Backend { + public: + // Creates a new backend. + static StatusOr> CreateBackend( + const BackendOptions& options); + + // Creates a backend for the default platform. The default platform is defined + // in PlatformUtil. + static StatusOr> CreateDefaultBackend(); + + ~Backend(); + + // Accessors for the various objects. + se::Platform* platform() const { return platform_; } + Compiler* compiler() const { return compiler_; } + se::DeviceMemoryAllocator* memory_allocator() const { + return memory_allocator_.get(); + } + std::shared_ptr shared_memory_allocator() const { + return memory_allocator_; + } + TransferManager* transfer_manager() const { return transfer_manager_; } + ComputationPlacer* computation_placer() const { return computation_placer_; } + + // Returns the number of devices of the platform type which are visible. Not + // all of these devices may be usable by XLA. + int device_count() const { return stream_executors_.size(); } + + // Returns the device ordinal number of the default device. + int default_device_ordinal() const; + + // Returns stream executors of all supported devices for this backend. The + // executors are ordered by the device ordinal. + const std::vector& stream_executors() const { + return stream_executors_; + } + + // Returns the stream executor for the given device ordinal. + StatusOr stream_executor(int device_ordinal) const; + + // Returns the stream executor for the default device ordinal. This stream + // executor can only be used when the number of computations is 1 (replication + // can be > 1). + se::StreamExecutor* default_stream_executor() const { + CHECK(!stream_executors_.empty()); + return stream_executors_[0]; + } + + // Borrows a stream for use by the caller with a given priority, either by + // grabbing it from an internal pool, or by constructing/initializating it, + // and returns the result to the caller. + StatusOr BorrowStream( + int device_ordinal, + se::StreamPriority priority = se::StreamPriority::Default); + StatusOr BorrowStream( + se::StreamExecutor* executor, + se::StreamPriority priority = se::StreamPriority::Default); + StatusOr> BorrowStreams( + int device_ordinal, int num_streams, + se::StreamPriority priority = se::StreamPriority::Default); + + // Returns a function to borrow streams with a given priority, + // as `BorrowStreams` above does. + // Purely for convenience, the caller could rather make this anonymous + // function itself. + std::function>(int, int, + se::StreamPriority)> + StreamBorrowerWithPriority() { + return [this](int device_ordinal, int num_streams, + se::StreamPriority priority) { + return BorrowStreams(device_ordinal, num_streams, priority); + }; + } + + // Returns whether the given device ordinal of the backend is supported. + bool device_ordinal_supported(int device_ordinal) const { + return (device_ordinal >= 0 && device_ordinal < device_count() && + stream_executors_[device_ordinal] != nullptr); + } + + // Return a string identifier for the given device, eg: "GPU:3". + std::string device_name(int device_ordinal) const { + return absl::StrCat(platform_->Name(), ":", device_ordinal); + } + + // Returns true if the devices with the given ordinals are equivalent from + // XLA's perspective. That is, an executable compiled for one device would + // be equivalent to an executable compiled for the other. + StatusOr devices_equivalent(int device_ordinal_a, int device_ordinal_b); + + // For the host platform, returns the configured eigen threadpool device to be + // used for scheduling work. For other platforms, returns NULL. + const Eigen::ThreadPoolDevice* eigen_intra_op_thread_pool_device() const; + tsl::thread::ThreadPool* eigen_intra_op_thread_pool() const; + + // Resets the devices associated with this backend. + Status ResetDevices(); + + private: + Backend(se::Platform* platform, Compiler* compiler, + absl::Span stream_executors, + TransferManager* transfer_manager, + ComputationPlacer* computation_placer, + int intra_op_parallelism_threads); + Backend(const Backend&) = delete; + Backend& operator=(const Backend&) = delete; + + se::Platform* platform_; + Compiler* compiler_; + TransferManager* transfer_manager_; + ComputationPlacer* computation_placer_; + + // Vector of stream executors. stream_executors_[0] is the default executor. + std::vector stream_executors_; + + absl::Mutex mu_; + + // Mapping from stream executor to stream pools, used by `BorrowStream` above. + absl::flat_hash_map> + stream_pools_ ABSL_GUARDED_BY(mu_); + + // The default memory allocator to use. + // This must be a shared_ptr, as this is passed all the way down to the + // cluster compilation. This allows asynchronous compilation to hold a + // referecence until the compilation is finished. + std::shared_ptr memory_allocator_; + + // For the CPU backend, an Eigen threadpool device for use by Eigen code. + struct IntraOpThreadPool; + std::unique_ptr intra_op_thread_pool_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_BACKEND_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batch_dot_simplification.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batch_dot_simplification.h new file mode 100644 index 0000000000000000000000000000000000000000..eecf8f705914d781b64ff1dec3a9def0d3b27856 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batch_dot_simplification.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 XLA_SERVICE_BATCH_DOT_SIMPLIFICATION_H_ +#define XLA_SERVICE_BATCH_DOT_SIMPLIFICATION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +// Simplifies batch dot operations. +// +// Normally these would live in the algebraic simplifier, but we want to run +// this to fixpoint (this pass reaches fixed point in one execution) before we +// run the DotDecomposer. +class BatchDotSimplification : public HloModulePass { + public: + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + absl::string_view name() const override; + + private: + StatusOr ElideDegenerateBatchDimensionFromBatchDot( + HloInstruction* batch_dot); +}; +} // namespace xla + +#endif // XLA_SERVICE_BATCH_DOT_SIMPLIFICATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batchnorm_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batchnorm_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..0e47fbc99fcc59ab4e2a6a7faa86a63ee535a4f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batchnorm_expander.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_BATCHNORM_EXPANDER_H_ +#define XLA_SERVICE_BATCHNORM_EXPANDER_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which rewrites batch norm operations into more operations. Breaking a +// big operation into smaller operations helps leverage our generic fusion +// logic. +class BatchNormExpander : public HloModulePass { + public: + // When use_fusion is set, a multi-output fusion node is created. + explicit BatchNormExpander(bool rewrite_training_op = false, + bool rewrite_inference_op = false, + bool rewrite_grad_op = false) + : rewrite_training_op_(rewrite_training_op), + rewrite_inference_op_(rewrite_inference_op), + rewrite_grad_op_(rewrite_grad_op) {} + ~BatchNormExpander() override = default; + absl::string_view name() const override { return "batchnorm_expander"; } + + // Run operation expander on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + bool rewrite_training_op_; + bool rewrite_inference_op_; + bool rewrite_grad_op_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_BATCHNORM_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/bitcast_dtypes_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/bitcast_dtypes_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..3d07c7541bf344e11c755e83d1cf211f66c81e05 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/bitcast_dtypes_expander.h @@ -0,0 +1,45 @@ +/* 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. +==============================================================================*/ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/op_expander_pass.h" +#include "xla/statusor.h" + +#ifndef XLA_SERVICE_BITCAST_DTYPES_EXPANDER_H_ +#define XLA_SERVICE_BITCAST_DTYPES_EXPANDER_H_ + +namespace xla { + +// A pass which expands bitcast-convert between differently sized dtypes to a +// reduction. +class BitcastDtypesExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "bitcast_dtypes_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; + + private: + absl::flat_hash_map computation_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_BITCAST_DTYPES_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/broadcast_canonicalizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/broadcast_canonicalizer.h new file mode 100644 index 0000000000000000000000000000000000000000..30a7dbaabcc243059f02c7599104ef0610142ec5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/broadcast_canonicalizer.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_BROADCAST_CANONICALIZER_H_ +#define XLA_SERVICE_BROADCAST_CANONICALIZER_H_ + +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This transform ensures that dimensions in all broadcast operations are +// sorted. +class BroadcastCanonicalizer : public HloModulePass { + public: + explicit BroadcastCanonicalizer(); + + absl::string_view name() const override { return "broadcast_canonicalizer"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_BROADCAST_CANONICALIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..0c8ebed0d295ad6079af9378380605fab3bbc252 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.h @@ -0,0 +1,793 @@ +/* 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_SERVICE_BUFFER_ASSIGNMENT_H_ +#define XLA_SERVICE_BUFFER_ASSIGNMENT_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.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/hlo/utils/hlo_live_range.h" +#include "xla/service/buffer_assignment.pb.h" +#include "xla/service/heap_simulator.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_alias_analysis.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/logical_buffer.h" +#include "xla/service/memory_space_assignment/memory_space_assignment.h" +#include "xla/service/tuple_points_to_analysis.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Walk the call graph of the HLO module and place each computation into either +// thread_local_computations or global_computations depending upon whether the +// computation requires thread-local allocations or global allocations. The +// elements in thread_local_computations and global_computations are in post +// order (if computation A has an instruction which calls computation B, then A +// will appear after B in the vector). +Status GatherComputationsByAllocationType( + const HloModule* module, + std::vector* thread_local_computations, + std::vector* global_computations); + +// This class abstracts an allocation of contiguous memory which can hold the +// values described by LogicalBuffers. Each LogicalBuffer occupies a sub-range +// of the allocation, represented by a Slice. A single BufferAllocation may hold +// LogicalBuffers with disjoint liveness, which may have overlapping Slices. A +// single BufferAllocation may also hold LogicalBuffers with overlapping +// liveness, which must have disjoint Slices. +// +// The abstraction includes information required by the backends for allocation, +// use, and deallocation of the buffer. This includes the LogicalBuffers which +// are held in this allocation through the execution of the computation. +class BufferAllocation { + public: + // Holds a unique identifier for each allocation. Values are assigned + // contiguously and can be used as array indexes. + using Index = int64_t; + + BufferAllocation(Index index, int64_t size, LogicalBuffer::Color color) + : index_(index), size_(size), color_(color) {} + ~BufferAllocation() {} + + // Returns the index of this allocation. + Index index() const { return index_; } + + // Whether this allocation is used in a parallel calling context such as + // inside of a map or reduce computation. Such allocations need to be thread + // local. + bool is_thread_local() const { return is_thread_local_; } + void set_is_thread_local(bool is_thread_local) { + is_thread_local_ = is_thread_local; + } + + // Whether this allocation can be used by more than one logical buffer. + bool is_reusable() const { + // We do not reuse thread-local buffers for now, because they are + // dynamically allocated and their lifetimes are hard to compute. + // + // TODO(b/34669761): Don't reuse tuple buffers because the GPU backend + // assumes longer buffer liveness than indicated by the analysis. + return !is_thread_local() && !is_tuple(); + } + + // Whether this allocation is readonly i.e. backed by memory we cannot write + // to. + bool is_readonly() const { + // Entry parameters are generally readonly, except when they are aliased + // with any output. + return (is_entry_computation_parameter() && + !is_parameter_aliased_with_output_) || + is_constant(); + } + + bool is_tuple() const { return is_tuple_; } + void set_is_tuple(bool is_tuple) { is_tuple_ = is_tuple; } + + // Whether this allocation holds a LogicalBuffer from a parameter of the entry + // computation. These buffers have lifetimes which may be longer than the + // XLA computation. + bool is_entry_computation_parameter() const { + return is_entry_computation_parameter_; + } + + // Whether this allocation holds a constant. On the CPU and GPU backends + // constant allocations are not allocated dynamically, instead we resolve + // references to these buffer allocations to a global in the readonly section + // of the binary. + bool is_constant() const { return is_constant_; } + + // If this allocation holds a Buffer from a parameter of the entry + // computation, this methods returns the parameter number. CHECKs otherwise. + int64_t parameter_number() const { + CHECK(is_entry_computation_parameter_); + return parameter_number_; + } + + // If this allocation is for a parameter of the entry computation, this + // function returns which subshape of the parameter the allocation is for. + const ShapeIndex& param_shape_index() const { + CHECK(is_entry_computation_parameter_); + return param_shape_index_; + } + + // Returns whether this allocation is assigned a LogicalBuffer which may + // be live out of the entry computation. + bool maybe_live_out() const { return maybe_live_out_; } + + void set_maybe_live_out(bool value) { maybe_live_out_ = value; } + + // Returns the size of the allocation. Necessarily this must be at least as + // large as any LogicalBuffer assigned to this allocation. + int64_t size() const { return size_; } + + // Returns the color of the allocation. Only logical buffers with a matching + // color can reside in this allocation. + LogicalBuffer::Color color() const { return color_; } + + struct OffsetSize { + int64_t offset = 0; + int64_t size = 0; + }; + + // Access to the logical buffers assigned to this allocation, and their + // associated logical offsets and sizes. + const absl::flat_hash_map& assigned_buffers() + const { + return assigned_buffers_; + } + + // A Slice represents a contiguous portion of a memory allocation. It is used + // to identify the memory range that a LogicalBuffer corresponds to. + class Slice { + public: + Slice() {} + Slice(const BufferAllocation* allocation, int64_t offset, int64_t size) + : allocation_(allocation), offset_(offset), size_(size) {} + + const BufferAllocation* allocation() const { return allocation_; } + Index index() const { return allocation_->index(); } + int64_t offset() const { return offset_; } + int64_t size() const { return size_; } + + bool operator==(const Slice& other) const { + return index() == other.index() && offset_ == other.offset_ && + size_ == other.size_; + } + bool operator!=(const Slice& other) const { return !(*this == other); } + bool operator<(const Slice& other) const { + if (index() != other.index()) return index() < other.index(); + if (offset_ != other.offset_) return offset_ < other.offset_; + return size_ < other.size_; + } + + // Returns true iff this slice's memory range has a non-empty intersection + // with the other slice's memory range. + bool OverlapsWith(const Slice& other) const { + const int64_t end = offset_ + size_; + const int64_t other_end = other.offset_ + other.size_; + return index() == other.index() && offset_ < other_end && + end > other.offset_; + } + + template + friend H AbslHashValue(H h, const Slice& s) { + return H::combine(std::move(h), s.index(), s.offset(), s.size()); + } + + std::string ToString() const; + + private: + const BufferAllocation* allocation_ = nullptr; + int64_t offset_ = 0; + int64_t size_ = 0; + }; + + // GetSlice returns the Slice of contiguous memory that holds the value + // described by the given 'buffer'. + // REQUIRES: 'buffer' must be assigned to this allocation. + Slice GetSlice(const HloValue& buffer) const; + + std::string ToString() const; + BufferAllocationProto ToProto() const; + + // Whether the buffer is a parameter to or live out of the entry computation. + bool IsInputOrOutput() const { + return is_entry_computation_parameter() || maybe_live_out(); + } + + // Whether the buffer is a temporary buffer allocated before + // Executable::ExecuteOnStream. + bool IsPreallocatedTempBuffer() const { + // Parameters do not need temporary buffers. + return !is_entry_computation_parameter() && + // LogicalBuffers that maybe pointed to by the output should live out + // of the computation. + !maybe_live_out() && + // Thread-local buffers are allocated using `alloca`s. + !is_thread_local() && + // Constant buffers are allocated as global values. + !is_constant(); + } + + // Add a heap trace which was used to assign slices to logical buffers in this + // allocation. A single BufferAllocation may include multiple heap traces + // in the case of the temporary block where there is a heap trace per + // computation. + void AddHeapTrace(const HeapSimulatorTrace& heap_trace) { + heap_traces_.push_back(heap_trace); + heap_traces_.back().set_buffer_allocation_index(index()); + } + + // Return the set of heap traces used to assign slices to logical buffers in + // this allocation. + const std::vector HeapTraces() const { + return heap_traces_; + } + + // Returns the LogicalBuffers which are live at the point of peak memory usage + // for this allocation. The point of peak memory usage is the point at which + // the total size of all live logical buffers is maximal. If peak memory is + // reached at multiple points, the set of logical buffers live at the earliest + // maximal point is returned. The vector is stably sorted by + // BufferValue::Index. + const std::vector& PeakMemoryLogicalBuffers() const { + return peak_buffers_; + } + + // Get the number of bytes lost to fragmentation. This is equal to the + // difference between the size of the allocation and the size of the maximal + // live set. + int64_t fragmentation_bytes() const { return fragmentation_bytes_; } + + bool operator==(const BufferAllocation& other) const { + return index_ == other.index_; + } + bool operator!=(const BufferAllocation& other) const { + return !(*this == other); + } + bool operator<(const BufferAllocation& other) const { + return index() < other.index(); + } + + void set_entry_computation_parameter(int64_t parameter_number, + ShapeIndex param_shape_index, + bool parameter_aliased_with_output) { + is_entry_computation_parameter_ = true; + is_parameter_aliased_with_output_ = parameter_aliased_with_output; + parameter_number_ = parameter_number; + param_shape_index_ = std::move(param_shape_index); + } + + void set_constant(bool is_constant) { is_constant_ = is_constant; } + + private: + // Only BufferAssigner and BufferAssignment can modify BufferAllocation. + friend class BufferAssigner; + friend class BufferAssignment; + + // Adds a LogicalBuffer to the set assigned to this buffer. + void AddAssignment(const HloValue& buffer, int64_t offset, int64_t size); + + void set_index(Index index) { index_ = index; } + void set_size(int64_t size) { size_ = size; } + + // The index of the allocation in the BufferAssignment. + Index index_; + + // Size of the allocation in bytes. + int64_t size_; + + // Whether this buffer needs to be thread-local. + bool is_thread_local_ = false; + + // Whether this buffer holds a tuple. + bool is_tuple_ = false; + + // Color of the allocation. + LogicalBuffer::Color color_; + + // Whether this allocation holds an entry computation parameter. Entry + // computation parameters are special because they have lifetimes which may + // outlast the computation. + bool is_entry_computation_parameter_ = false; + + // Whether this entry computation parameter is aliased with output. + bool is_parameter_aliased_with_output_ = false; + + // If this allocation holds an entry computation parameter, this field + // indicates the index (starting from 0) of the parameter. + int64_t parameter_number_ = 0; + + // If this buffer is for an entry computation parameter, which subshape of the + // parameter is it for? + ShapeIndex param_shape_index_; + + // Whether the allocation contains a LogicalBuffer which may be live-out of + // the entry computation. Note that this flag is conservatively computed by + // TuplePointsToAnalysis. That is, an allocation marked `maybe_live_out_` + // might not actually escape. + bool maybe_live_out_ = false; + + // See comment on the is_constant() accessor. + bool is_constant_ = false; + + // Mapping from the set of buffers assigned to this allocation to their + // logical offsets and sizes. + absl::flat_hash_map assigned_buffers_; + + int64_t fragmentation_bytes_ = 0; + std::vector heap_traces_; + + // Set of buffers live at the point of peak memory usage for this allocation. + std::vector peak_buffers_; +}; + +// Add stream operators for nicer output of CHECK/RET_CHECK failures. +std::ostream& operator<<(std::ostream& out, const BufferAllocation& s); +std::ostream& operator<<(std::ostream& out, const BufferAllocation::Slice& s); + +// This class encapsulates an assignment of the LogicalBuffers in an XLA +// module to a set of BufferAllocations. +class BufferAssignment { + public: + // This is a think wrapper around BufferIsolationConfig. Please see the + // documentation for BufferIsolationConfig for details on how buffer isolation + // works. hlo_value_compare is the concrete implementation of the HloValue + // comparison that uses the isolation_order_salt value in the + // BufferIsolationConfig. + struct BufferIsolationOptions { + std::function hlo_value_compare; + buffer_assignment::BufferIsolationConfig config; + }; + + // Returns the vector containing all buffer allocations in this assignment. + const std::vector& Allocations() const { + return allocations_; + } + + // This is similar to copying Allocations(), but since it's moved out, it + // preserves the addresses. Since BufferAllocation::Slice keeps a + // BufferAllocation*, and some backends keep BufferAllocation::Slice in + // xla::Executables, migrating off the use of addresses can be hard. + std::vector ReleaseAllocations() { + return std::move(allocations_); + } + + // Returns the total size allocation holding all temporary buffers. + int64_t temp_allocation_total_size() const { + return temp_allocation_total_size_; + } + + uint64_t multiheap_size_constraint_per_heap() const { + return multiheap_size_constraint_per_heap_; + } + + // Returns whether the given buffer has been assigned an allocation. + bool HasAllocation(const HloValue& value) const; + + // Returns whether the given (logical) buffer with the id has been assigned an + // allocation. + bool HasAllocation(HloValue::Id value_id) const; + + bool HasAllocation(const HloBuffer& buffer) const; + + // Returns the allocation that a particular LogicalBuffer has been assigned + // to. CHECKs if buffer has not been assigned an allocation. + const BufferAllocation& GetAssignedAllocation(const HloValue& value) const; + + const BufferAllocation& GetAssignedAllocation( + const HloBuffer& hlo_buffer) const; + + // Returns the allocation with the given index. CHECKs if no allocation exists + // with the given index. + const BufferAllocation& GetAllocation(BufferAllocation::Index index) const; + + // Returns the allocation with the given instruction and shape index. nullptr + // if no allocation exists. + const BufferAllocation* GetInstructionAllocation( + const HloInstruction* hlo, const ShapeIndex& shape_index) const; + + // Builds and returns a vector containing the slices which might contain the + // subvalue at the given index of given instruction. + std::set GetAllSlices( + const HloInstruction* instruction, const ShapeIndex& index) const; + + // Convenience function which returns whether the buffer of the + // instruction at the given index is assigned an allocation. + bool HasAllocationAt(const HloInstruction* instruction, + const ShapeIndex& index) const; + + // Convenience function which returns whether the top-level buffer of the + // instruction (index == {}) is assigned an allocation. + bool HasTopLevelAllocation(const HloInstruction* instruction) const; + + // Convenience function which returns the unique slice containing the buffer + // at the given index of the given instruction. If a slice is not assigned or + // the slice cannot be determined at compile time then an error is returned. + StatusOr GetUniqueSlice( + const HloInstruction* instruction, const ShapeIndex& index) const; + // Like GetUniqueSlice but fixes the index to the top-level of the shape + // (index = {}). + StatusOr GetUniqueTopLevelSlice( + const HloInstruction* instruction) const; + // Like GetUniqueTopLevelSlice but returns the slice for the output of the + // entry computation of the HLO module (ie, the result of the XLA + // computation). + StatusOr GetUniqueTopLevelOutputSlice() const; + + // Returns the set BufferValues which may be the source of the value at the + // given index and instruction. + const std::vector& GetSourceBuffers( + const HloInstruction* instruction, const ShapeIndex& index) const { + return dataflow_analysis().GetValueSet(instruction, index).values(); + } + + // Returns true if 'hlo_a{shape_index_a}' and 'hlo_b{shape_index_b}' + // share the same BufferAllocation::Slice. + // Returns false otherwise. + // REQUIRES: BufferAssignment assigned allocations to both instructions. + bool SharesSliceAtIndex(const HloInstruction* hlo_a, + const ShapeIndex& shape_index_a, + const HloInstruction* hlo_b, + const ShapeIndex& shape_index_b) const; + + // Returns true if the top-level buffers of hlo_a and hlo_b are the same. + // REQUIRES: HasTopLevelAllocation(hlo_a) && HasTopLevelAllocation(hlo_b). + bool SharesTopLevelSlice(const HloInstruction* hlo_a, + const HloInstruction* hlo_b) const { + return SharesSliceAtIndex(hlo_a, {}, hlo_b, {}); + } + + // Returns true if hlo_a and hlo_b both have at least one buffer assigned for + // their top-level and each of their nested shape indices, and if hlo_a's + // buffers are all different from hlo_b's buffers. + bool HaveDisjointSlices(const HloInstruction* hlo_a, + const HloInstruction* hlo_b) const; + + const HloDataflowAnalysis& dataflow_analysis() const { + return alias_analysis_->dataflow_analysis(); + } + + HloAliasAnalysis& alias_analysis() const { return *alias_analysis_; } + + const HloOrdering& hlo_ordering() const { return *hlo_ordering_; } + + // Returns the HloLiveRange object used to construct this assignment. + const HloLiveRange& hlo_live_range() const { return *hlo_live_range_; } + + std::string ToString() const; + // Verbose string tailored to debugging OOMs, includes the Hlo op metadata for + // every buffer associated with each allocation. + std::string ToVerboseString(size_t max_buffers_to_show) const; + std::string BufferInfoString() const; + + // Convert BufferAssignment to or from a proto. + BufferAssignmentProto ToProto() const; + static StatusOr> FromProto( + const BufferAssignmentProto& proto, const HloModule* module, + BufferValue::SizeFunction buffer_size, + HloDataflowAnalysis::CanShareBuffer can_share_buffer); + + // Statistics for the assignment. Values initialized to -1 are not always + // collected; fragmentation is only collected for instructions that have a + // sequential total ordering. + struct Stats { + int64_t parameter_allocation_count = 0; + int64_t parameter_allocation_bytes = 0; + int64_t constant_allocation_count = 0; + int64_t constant_allocation_bytes = 0; + int64_t maybe_live_out_allocation_count = 0; + int64_t maybe_live_out_allocation_bytes = 0; + int64_t preallocated_temp_allocation_count = 0; + int64_t preallocated_temp_allocation_bytes = 0; + int64_t preallocated_temp_fragmentation_bytes = -1; + int64_t total_allocation_count = 0; + int64_t total_allocation_bytes = 0; + int64_t total_fragmentation_bytes = -1; + + std::string ToString() const; + }; + const Stats& GetStats() const { return stats_; } + + private: + // Only BufferAssigner can build or modify BufferAssignments. + friend class BufferAssigner; + + BufferAssignment(const HloModule* module, + std::unique_ptr hlo_ordering, + BufferValue::SizeFunction buffer_size, + LogicalBuffer::AlignmentFunction color_alignment, + std::unique_ptr alias_analysis, + std::unique_ptr hlo_live_range) + : module_(module), + hlo_ordering_(std::move(hlo_ordering)), + buffer_size_(std::move(buffer_size)), + color_alignment_(std::move(color_alignment)), + alias_analysis_(std::move(alias_analysis)), + hlo_live_range_(std::move(hlo_live_range)) { + int32_t raw_value = module->config() + .debug_options() + .xla_multiheap_size_constraint_per_heap(); + // -1 means no constraint. + multiheap_size_constraint_per_heap_ = + (raw_value == -1) ? UINT64_MAX : raw_value; + } + + // Creates and returns a new BufferAllocation, with no assigned + // LogicalBuffers. Ownership is maintained internally. + BufferAllocation* NewEmptyAllocation(int64_t size, + LogicalBuffer::Color color); + + // Helper that calls NewEmptyAllocation and AddAssignment in one call, + // creating an allocation containing a single LogicalBuffer. + BufferAllocation* NewAllocation(const HloBuffer& buffer, int64_t size); + + // Adds a LogicalBuffer to the set assigned to the given allocation. + void AddAssignment(BufferAllocation* allocation, const HloBuffer& buffer, + int64_t offset, int64_t size); + + void AddAssignment(BufferAllocation* allocation, const HloValue& value, + int64_t offset, int64_t size); + + // Returns the HloModule used to construct this assignment. + const HloModule& module() const { return *module_; } + + // Mutable accessors for allocations. + BufferAllocation* GetMutableAssignedAllocation(const HloBuffer& buffer); + BufferAllocation* GetMutableAllocation(BufferAllocation::Index index); + + int64_t HloBufferSize(const HloBuffer& buffer) { + auto iter = cached_buffer_sizes_.find(buffer.id()); + if (iter != cached_buffer_sizes_.end()) return iter->second; + int64_t result = 0; + for (const HloValue* value : buffer.values()) { + result = std::max(result, buffer_size_(*value)); + } + cached_buffer_sizes_.insert({buffer.id(), result}); + return result; + } + + // Combines allocations of temporary buffers into one big BufferAllocation. + void CombineTempAllocations( + const absl::flat_hash_set& private_stack_colors); + + // Computes stats for the assignment, to be retrieved by GetStats. + Status ComputeSummaryStats(); + + // The vector of buffer allocations. Indexed by BufferAllocation::Index. + std::vector allocations_; + + // The total size of all temporary buffers. + int64_t temp_allocation_total_size_ = 0; + + uint64_t multiheap_size_constraint_per_heap_; + + // Maps Buffers to the index of the BufferAllocation which holds the buffer. + absl::flat_hash_map + allocation_index_for_value_; + + const HloModule* module_; + + const std::unique_ptr hlo_ordering_; + + // Function which returns the buffer size for a given logical buffer (shape). + BufferValue::SizeFunction buffer_size_; + + // Function which returns the alignment for a given logical buffer color. + LogicalBuffer::AlignmentFunction color_alignment_; + + std::unique_ptr alias_analysis_; + + std::unique_ptr hlo_live_range_; + + Stats stats_; + + absl::flat_hash_map cached_buffer_sizes_; + + BufferAssignment(const BufferAssignment&) = delete; + BufferAssignment& operator=(const BufferAssignment&) = delete; +}; + +// A class which constructs a buffer assignment. +class BufferAssigner { + public: + using Colorer = std::function; + using MustNotLiveOut = + std::function; + using PrivateStacks = absl::flat_hash_map>; + + static Colorer DefaultColorer() { + return [](HloAliasAnalysis* alias_analysis, const HloOrdering&) { + for (HloValue* value : alias_analysis->dataflow_analysis().values()) { + const HloPosition& defining_position = value->defining_position(); + if (defining_position.shape().has_layout()) { + value->set_color(BufferValue::Color( + defining_position.shape().layout().memory_space())); + } else { + value->set_color(BufferValue::Color(0)); + } + } + return OkStatus(); + }; + } + + // Returns false if a buffer cannot be assigned to given allocation. + + // Build and return a BufferAssignment for the given module. The given + // HloOrdering is used to determine buffer liveness. buffer_size and + // color_alignment are functions which returns the size and alignment of a + // LogicalBuffer. If preset_assignments is provided, those pre-set assignment + // offsets will be used. The caller guarantees that those assignments are + // valid and they do not overwrite each other. + static StatusOr> Run( + const HloModule* module, std::unique_ptr hlo_ordering, + BufferValue::SizeFunction buffer_size, + LogicalBuffer::AlignmentFunction color_alignment, + bool allocate_buffers_for_constants = false, + Colorer colorer = DefaultColorer(), + std::optional must_not_live_out = std::nullopt, + HloDataflowAnalysis::CanShareBuffer can_share_buffer = nullptr, + std::unique_ptr + preset_assignments = {}, + const PrivateStacks& private_stacks = {}, + GlobalDecreasingSizeBestFitHeap::BufferIntervalCompare + heap_buffer_interval_compare = nullptr, + std::optional + isolation_options = std::nullopt); + + private: + BufferAssigner(bool allocate_buffers_for_constants, Colorer colorer, + std::optional must_not_live_out, + std::unique_ptr + preset_assignments) + : allocate_buffers_for_constants_(allocate_buffers_for_constants), + colorer_(colorer), + must_not_live_out_(must_not_live_out), + preset_assignments_(std::move(preset_assignments)) {} + virtual ~BufferAssigner() = default; + + // Create a buffer assignment. + StatusOr> CreateAssignment( + const HloModule* module, std::unique_ptr hlo_ordering, + BufferValue::SizeFunction buffer_size, + LogicalBuffer::AlignmentFunction color_alignment, + HloDataflowAnalysis::CanShareBuffer can_share_buffer, + const PrivateStacks& private_stacks, + GlobalDecreasingSizeBestFitHeap::BufferIntervalCompare + heap_buffer_interval_compare, + std::optional + isolation_options); + + // Assigns buffers to the instructions in the given computations. "assignment" + // is modified to reflect the new buffer assignments. If is_thread_local is + // true, then all assigned buffers have the is_thread_local flag set to + // true. + Status AssignBuffersForComputations( + const std::vector& computations, + bool is_thread_local, + absl::flat_hash_map>* + buffers_to_assign_sequentially, + BufferAssignment* assignment); + + // Returns true if buffer's live range interferences with buffer2's. + bool LiveRangeInterferes(const HloValue* buffer1, const HloValue* buffer2, + BufferAssignment* assignment); + + // Assigns pre-set assignments, if provided. These assignments will be added + // to assigned_buffers and skip buffer allocation. + Status AssignPresetBuffers( + absl::flat_hash_set* assigned_buffers, + BufferAssignment* assignment); + + // Assigns a single hlo buffer to an HLO allocation. + Status AssignSingleHloBuffer( + const HloBuffer* hlo_buffer, bool is_thread_local, + absl::flat_hash_map>* + buffers_to_assign_sequentially, + std::vector* allocation_indices, + BufferAssignment* assignment); + + // Assigns 'buffers_to_assign_sequentially' using heap simulation, assuming + // the HLO instructions will be executed in the sequential order given by + // assignment->liveness().hlo_ordering().SequentialOrder. If + // 'run_whole_module_heap_simulation' is true, the heap simulation will be run + // assuming all global computations are sequentially ordered. + Status AssignBuffersWithSequentialOrdering( + const absl::flat_hash_map>& + buffers_to_assign_sequentially, + bool run_whole_module_heap_simulation, BufferAssignment* assignment, + const PrivateStacks& private_stacks, + GlobalDecreasingSizeBestFitHeap::BufferIntervalCompare + heap_buffer_interval_compare, + std::optional + isolation_options); + + // Isolates the buffers packed by heap simulator using the provided isolation + // options. Please see the documentation for BufferIsolationConfig for more + // details. + void IsolateHeapBuffers( + std::optional isolation_options, + const BufferAssignment* assignment, LogicalBuffer::Color color, + HeapSimulator::Result& result) const; + + // Uses the results of the heap simulator to create a single allocation, with + // LogicalBuffers packed to specific offsets. + void AssignBuffersFromHeapSimulator( + HeapSimulator::Result& result, BufferAssignment* assignment, + LogicalBuffer::Color color, + std::optional + isolation_options); + + // Tries to assign the given instruction to the given buffer. Returns if the + // assignment was successful. + bool MaybeAssignBuffer(BufferAllocation* allocation, const HloBuffer& buffer, + BufferAssignment* assignment); + + // Split a set of buffers into several sets, each of which contains buffers + // colored with the same color. + absl::flat_hash_map> + SplitBuffersByColor( + const absl::flat_hash_set& buffers) const; + + // Split a set of buffers into several sets, each of which contains buffers + // with defining instructions that are dominated by the given private stack + // computation. This function CHECK-fails if there are outstanding buffers + // that do not have a dominating private stack computation. + absl::flat_hash_map> + SplitBuffersByPrivateStackComputation( + const absl::flat_hash_set& buffers, + absl::Span private_stack_computations, + const CallGraph& call_graph) const; + + // If true, allocate buffers for constant instructions. + bool allocate_buffers_for_constants_; + + // Functor used to assign colors to newly allocated logical buffers. + Colorer colorer_; + + // An optional function that returns true if the given instruction can't live + // out of a computation. + std::optional must_not_live_out_; + + // Description of any buffer offsets that are already set by an earlier pass. + std::unique_ptr + preset_assignments_; + + BufferAssigner(const BufferAssigner&) = delete; + BufferAssigner& operator=(const BufferAssigner&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_BUFFER_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..20b9973fcff7e9c49d69c84a4c50226fd3e248e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.pb.h @@ -0,0 +1,416 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/buffer_assignment.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fbuffer_5fassignment_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fbuffer_5fassignment_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_xla_2fservice_2fbuffer_5fassignment_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fbuffer_5fassignment_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fbuffer_5fassignment_2eproto; +namespace xla { +namespace buffer_assignment { +class BufferIsolationConfig; +struct BufferIsolationConfigDefaultTypeInternal; +extern BufferIsolationConfigDefaultTypeInternal _BufferIsolationConfig_default_instance_; +} // namespace buffer_assignment +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::buffer_assignment::BufferIsolationConfig* Arena::CreateMaybeMessage<::xla::buffer_assignment::BufferIsolationConfig>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace buffer_assignment { + +// =================================================================== + +class BufferIsolationConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.buffer_assignment.BufferIsolationConfig) */ { + public: + inline BufferIsolationConfig() : BufferIsolationConfig(nullptr) {} + ~BufferIsolationConfig() override; + explicit PROTOBUF_CONSTEXPR BufferIsolationConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BufferIsolationConfig(const BufferIsolationConfig& from); + BufferIsolationConfig(BufferIsolationConfig&& from) noexcept + : BufferIsolationConfig() { + *this = ::std::move(from); + } + + inline BufferIsolationConfig& operator=(const BufferIsolationConfig& from) { + CopyFrom(from); + return *this; + } + inline BufferIsolationConfig& operator=(BufferIsolationConfig&& 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 BufferIsolationConfig& default_instance() { + return *internal_default_instance(); + } + static inline const BufferIsolationConfig* internal_default_instance() { + return reinterpret_cast( + &_BufferIsolationConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(BufferIsolationConfig& a, BufferIsolationConfig& b) { + a.Swap(&b); + } + inline void Swap(BufferIsolationConfig* 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(BufferIsolationConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BufferIsolationConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BufferIsolationConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BufferIsolationConfig& from) { + BufferIsolationConfig::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(BufferIsolationConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.buffer_assignment.BufferIsolationConfig"; + } + protected: + explicit BufferIsolationConfig(::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 { + kIsolationColorsFieldNumber = 5, + kBaseOffsetBytesFieldNumber = 1, + kIsolationFuelFieldNumber = 2, + kIsolationPaddingBytesFieldNumber = 3, + kIsolationOrderSaltFieldNumber = 4, + }; + // repeated int32 isolation_colors = 5; + int isolation_colors_size() const; + private: + int _internal_isolation_colors_size() const; + public: + void clear_isolation_colors(); + private: + int32_t _internal_isolation_colors(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + _internal_isolation_colors() const; + void _internal_add_isolation_colors(int32_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + _internal_mutable_isolation_colors(); + public: + int32_t isolation_colors(int index) const; + void set_isolation_colors(int index, int32_t value); + void add_isolation_colors(int32_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + isolation_colors() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + mutable_isolation_colors(); + + // int64 base_offset_bytes = 1; + void clear_base_offset_bytes(); + int64_t base_offset_bytes() const; + void set_base_offset_bytes(int64_t value); + private: + int64_t _internal_base_offset_bytes() const; + void _internal_set_base_offset_bytes(int64_t value); + public: + + // int64 isolation_fuel = 2; + void clear_isolation_fuel(); + int64_t isolation_fuel() const; + void set_isolation_fuel(int64_t value); + private: + int64_t _internal_isolation_fuel() const; + void _internal_set_isolation_fuel(int64_t value); + public: + + // int64 isolation_padding_bytes = 3; + void clear_isolation_padding_bytes(); + int64_t isolation_padding_bytes() const; + void set_isolation_padding_bytes(int64_t value); + private: + int64_t _internal_isolation_padding_bytes() const; + void _internal_set_isolation_padding_bytes(int64_t value); + public: + + // uint64 isolation_order_salt = 4; + void clear_isolation_order_salt(); + uint64_t isolation_order_salt() const; + void set_isolation_order_salt(uint64_t value); + private: + uint64_t _internal_isolation_order_salt() const; + void _internal_set_isolation_order_salt(uint64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.buffer_assignment.BufferIsolationConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > isolation_colors_; + mutable std::atomic _isolation_colors_cached_byte_size_; + int64_t base_offset_bytes_; + int64_t isolation_fuel_; + int64_t isolation_padding_bytes_; + uint64_t isolation_order_salt_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fbuffer_5fassignment_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// BufferIsolationConfig + +// int64 base_offset_bytes = 1; +inline void BufferIsolationConfig::clear_base_offset_bytes() { + _impl_.base_offset_bytes_ = int64_t{0}; +} +inline int64_t BufferIsolationConfig::_internal_base_offset_bytes() const { + return _impl_.base_offset_bytes_; +} +inline int64_t BufferIsolationConfig::base_offset_bytes() const { + // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.base_offset_bytes) + return _internal_base_offset_bytes(); +} +inline void BufferIsolationConfig::_internal_set_base_offset_bytes(int64_t value) { + + _impl_.base_offset_bytes_ = value; +} +inline void BufferIsolationConfig::set_base_offset_bytes(int64_t value) { + _internal_set_base_offset_bytes(value); + // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.base_offset_bytes) +} + +// int64 isolation_fuel = 2; +inline void BufferIsolationConfig::clear_isolation_fuel() { + _impl_.isolation_fuel_ = int64_t{0}; +} +inline int64_t BufferIsolationConfig::_internal_isolation_fuel() const { + return _impl_.isolation_fuel_; +} +inline int64_t BufferIsolationConfig::isolation_fuel() const { + // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_fuel) + return _internal_isolation_fuel(); +} +inline void BufferIsolationConfig::_internal_set_isolation_fuel(int64_t value) { + + _impl_.isolation_fuel_ = value; +} +inline void BufferIsolationConfig::set_isolation_fuel(int64_t value) { + _internal_set_isolation_fuel(value); + // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_fuel) +} + +// int64 isolation_padding_bytes = 3; +inline void BufferIsolationConfig::clear_isolation_padding_bytes() { + _impl_.isolation_padding_bytes_ = int64_t{0}; +} +inline int64_t BufferIsolationConfig::_internal_isolation_padding_bytes() const { + return _impl_.isolation_padding_bytes_; +} +inline int64_t BufferIsolationConfig::isolation_padding_bytes() const { + // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_padding_bytes) + return _internal_isolation_padding_bytes(); +} +inline void BufferIsolationConfig::_internal_set_isolation_padding_bytes(int64_t value) { + + _impl_.isolation_padding_bytes_ = value; +} +inline void BufferIsolationConfig::set_isolation_padding_bytes(int64_t value) { + _internal_set_isolation_padding_bytes(value); + // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_padding_bytes) +} + +// uint64 isolation_order_salt = 4; +inline void BufferIsolationConfig::clear_isolation_order_salt() { + _impl_.isolation_order_salt_ = uint64_t{0u}; +} +inline uint64_t BufferIsolationConfig::_internal_isolation_order_salt() const { + return _impl_.isolation_order_salt_; +} +inline uint64_t BufferIsolationConfig::isolation_order_salt() const { + // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_order_salt) + return _internal_isolation_order_salt(); +} +inline void BufferIsolationConfig::_internal_set_isolation_order_salt(uint64_t value) { + + _impl_.isolation_order_salt_ = value; +} +inline void BufferIsolationConfig::set_isolation_order_salt(uint64_t value) { + _internal_set_isolation_order_salt(value); + // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_order_salt) +} + +// repeated int32 isolation_colors = 5; +inline int BufferIsolationConfig::_internal_isolation_colors_size() const { + return _impl_.isolation_colors_.size(); +} +inline int BufferIsolationConfig::isolation_colors_size() const { + return _internal_isolation_colors_size(); +} +inline void BufferIsolationConfig::clear_isolation_colors() { + _impl_.isolation_colors_.Clear(); +} +inline int32_t BufferIsolationConfig::_internal_isolation_colors(int index) const { + return _impl_.isolation_colors_.Get(index); +} +inline int32_t BufferIsolationConfig::isolation_colors(int index) const { + // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_colors) + return _internal_isolation_colors(index); +} +inline void BufferIsolationConfig::set_isolation_colors(int index, int32_t value) { + _impl_.isolation_colors_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_colors) +} +inline void BufferIsolationConfig::_internal_add_isolation_colors(int32_t value) { + _impl_.isolation_colors_.Add(value); +} +inline void BufferIsolationConfig::add_isolation_colors(int32_t value) { + _internal_add_isolation_colors(value); + // @@protoc_insertion_point(field_add:xla.buffer_assignment.BufferIsolationConfig.isolation_colors) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +BufferIsolationConfig::_internal_isolation_colors() const { + return _impl_.isolation_colors_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +BufferIsolationConfig::isolation_colors() const { + // @@protoc_insertion_point(field_list:xla.buffer_assignment.BufferIsolationConfig.isolation_colors) + return _internal_isolation_colors(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +BufferIsolationConfig::_internal_mutable_isolation_colors() { + return &_impl_.isolation_colors_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +BufferIsolationConfig::mutable_isolation_colors() { + // @@protoc_insertion_point(field_mutable_list:xla.buffer_assignment.BufferIsolationConfig.isolation_colors) + return _internal_mutable_isolation_colors(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace buffer_assignment +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fbuffer_5fassignment_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value.h new file mode 100644 index 0000000000000000000000000000000000000000..1a9e8737410617e6573cf4524a73d7ae76c9ea22 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value.h @@ -0,0 +1,183 @@ +/* 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_SERVICE_BUFFER_VALUE_H_ +#define XLA_SERVICE_BUFFER_VALUE_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Abstract class describing a value used by one of the dataflow analyses - +// TuplePointsToAnalysis or HloDataflowAnalysis. +// TODO(b/78906445) Delete this class when TuplePointsToAnalysis is unused. +// +// XLA arrays are trivially a single BufferValue. Tuples are made up of more +// than one BufferValue: an BufferValue for the pointer vector, and an +// BufferValue for each child element. +// +// Every BufferValue is defined by a particular instruction and most +// instructions define only a single BufferValue. Instructions which define a +// single BufferValue include array-shaped instructions such as Add but also +// includes Tuple-shaped instructions such as Tuple. The Tuple instruction +// defines a single BufferValue which is a vector of pointers to the values +// containing the Tuple instruction's operands. Though the result of the Tuple +// instruction includes multiple values only the top-level BufferValue (the +// vector of pointers) is defined by the Tuple instruction. The values +// containing the tuple elements are defined by earlier instructions, usually +// the operands of the Tuple instruction. +// +// Instructions which construct both the tuple *and* the tuple elements define +// more than one BufferValue. This includes (at least) tuple-shaped Constant, +// Parameter, Infeed and While instructions. These tuple-shaped instructions do +// not assemble a tuple from existing BufferValues like the Tuple instruction +// does, but rather define all the BufferValues in the tuple. +// +// Some instructions, such as Bitcast, define no buffers. These instructions +// simply forward buffers from their operands. +// +// The BufferValue object describes which HLO instruction defines a buffer and +// where within that instruction's output shape the buffer is defined. The +// location within the output shape is indicated by BufferValue::index() which +// is defined identically to the index used in ShapeUtil::GetSubshape(). +// Examples: +// +// %add = Add(%foo, %bar) +// %tuple_constant = Constant({1, {42, 43}}) +// +// %add defines a single array-shaped buffer BufferValue(%add, {}) which holds +// the array result of the add operation. The nested-tuple-shaped +// %tuple_constant defines 5 buffers described by the following BufferValue +// objects: +// +// BufferValue(%tuple_constant, {}) // "Top-level" buffer: vector of +// // pointers to BufferValues at +// // indices {0} and {1} +// BufferValue(%tuple_constant, {0}) // Holds value "1" +// BufferValue(%tuple_constant, {1}) // Holds nested tuple: vector of +// // pointers to BufferValues at +// // indices {1, 0} and {1, 1} +// BufferValue(%tuple_constant, {1, 0}) // Holds value "42" +// BufferValue(%tuple_constant, {1, 1}) // Holds value "43" + +class BufferValue { + public: + using Color = int64_t; + + // Id is a unique identifier for the BufferValue to facilitate efficient + // collections of BufferValues with stable iteration order. + using Id = int64_t; + + // Functions which return the size and alignment of a logical buffer in bytes. + using SizeFunction = std::function; + using AlignmentFunction = std::function; + + // Prevent value being copied, allowing comparison by pointer, + BufferValue(const BufferValue&) = delete; + BufferValue& operator=(const BufferValue&) = delete; + // ... but allow moves. + BufferValue(BufferValue&&) = default; + BufferValue& operator=(BufferValue&&) = default; + + virtual ~BufferValue() {} + + Id id() const { return id_; } + + // Return the instruction that defines the buffer. + virtual HloInstruction* instruction() const = 0; + + // Return the index within the output of the instruction where the buffer is + // defined. Index used defined as in ShapeUtil::GetSubshape() + virtual const ShapeIndex& index() const = 0; + + // Return the color of the BufferValue. Differently colored buffers can not be + // parts of the same allocation. + ABSL_DEPRECATED("Use Layout::memory_space instead.") + Color color() const { + CHECK_NE(color_, kInvalidColor) + << "Should not query the color of a buffer that was never colored"; + return color_; + } + + ABSL_DEPRECATED("Use Layout::memory_space instead.") + void set_color(Color color) { + CHECK_NE(color, kInvalidColor) + << "Should not set the color of a buffer to the invalid color"; + color_ = color; + } + + ABSL_DEPRECATED("Use Layout::memory_space instead.") + bool has_color() const { return color_ != kInvalidColor; } + + // Return the shape of the buffer. This reference points into the shape field + // of the instruction defining the buffer. Therefore, the returned shape will + // contain the layout of instruction, if any. + virtual const Shape& shape() const = 0; + + // Returns true if this buffer is the top-level output buffer of the defining + // HLO instruction. This is equivalent to index == {}. + bool IsTopLevel() const { return index().empty(); } + + // Whether this buffer contains a tuple. + bool IsTuple() const { return is_tuple_; } + + // Whether this buffer contains an array. + bool IsArray() const { return is_array_; } + + bool operator<(const BufferValue& other) const { return id_ < other.id_; } + + virtual std::string ToString() const = 0; + + // TODO(lauj) rename LogicalBufferProto to BufferValueProto. + LogicalBufferProto ToProto(const SizeFunction& size_fn) const; + + // Returns the LogicalBufferProto::Location that serializes the given + // instruction and index. + static LogicalBufferProto::Location ToLocationProto( + const HloInstruction& instruction, const ShapeIndex& index); + + static constexpr Color kInvalidColor = -1; + + protected: + BufferValue(HloInstruction* instruction, const ShapeIndex& index, Id id); + + private: + // The defining instruction and index are not stored here; they can be found + // in the LogicalBuffer and HloValue subclasses. This class exists only to + // support migrations from TuplePointsToAnalysis to HloDataflowAnalysis, by + // allowing abstract use of LogicalBuffer or HloValue. After those migrations + // are complete, this class should be deleted (b/78906445). Because we plan to + // delete LogicalBuffer and this class, we don't refactor all the shared + // features from LogicalBuffer and HloValue into this class. + Id id_ : 62; + bool is_array_ : 1; + bool is_tuple_ : 1; + Color color_ = kInvalidColor; +}; + +std::ostream& operator<<(std::ostream& out, const BufferValue& buffer); + +} // namespace xla + +#endif // XLA_SERVICE_BUFFER_VALUE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value_containers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value_containers.h new file mode 100644 index 0000000000000000000000000000000000000000..fe81e31d74422eb2b586610ca32228dac437f51a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value_containers.h @@ -0,0 +1,55 @@ +/* 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_SERVICE_BUFFER_VALUE_CONTAINERS_H_ +#define XLA_SERVICE_BUFFER_VALUE_CONTAINERS_H_ + +#include "absl/container/flat_hash_set.h" +#include "xla/service/buffer_value.h" +#include "xla/service/logical_buffer.h" +#include "tsl/lib/gtl/compactptrset.h" + +namespace xla { + +// Define various containers of BufferValues, and utilities to convert from +// containers of LogicalBuffers to containers of BufferValues. + +using BufferValueCompactPointerSet = + tsl::gtl::CompactPointerSet; +template +BufferValueCompactPointerSet ToBufferValueCompactPointerSet( + const LogicalBufferContainerT& logical_buffer_container) { + BufferValueCompactPointerSet output; + for (const LogicalBuffer* buffer : logical_buffer_container) { + output.insert(buffer); + } + return output; +} + +using BufferValueFlatSet = absl::flat_hash_set; +template +BufferValueFlatSet ToBufferValueFlatSet( + const LogicalBufferContainerT& logical_buffer_container) { + BufferValueFlatSet output; + output.reserve(logical_buffer_container.size()); + for (const LogicalBuffer* buffer : logical_buffer_container) { + output.insert(buffer); + } + return output; +} + +} // namespace xla + +#endif // XLA_SERVICE_BUFFER_VALUE_CONTAINERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_graph.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..9cce636926c301a67265942df35c2cedd643dd66 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_graph.h @@ -0,0 +1,386 @@ +/* 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. +==============================================================================*/ + +// Call graph for an HLO module. + +#ifndef XLA_SERVICE_CALL_GRAPH_H_ +#define XLA_SERVICE_CALL_GRAPH_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/functional/function_ref.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" + +namespace xla { + +// The context in which a computation is called by another computation. +enum class CallContext { + // In an embedded call context, the body of the function cannot allocate + // buffers. + kEmbedded, + + // A control flow call context can allocate buffers. + kControlFlow, + + // A computation is called from both an embedded and control flow context. + kBoth, + + // During call graph construction kNone is used to indicate that the context + // has not been determined. This is the top value for the context + // lattice. After construction, no call sites or call graph nodes should have + // this value. + kNone +}; + +std::string CallContextToString(CallContext context); +std::ostream& operator<<(std::ostream& out, const CallContext& context); + +CallContext GetInstructionCallContext(HloOpcode opcode); + +// Represents an HLO instruction which calls one or more computations. +class CallSite { + public: + CallSite(HloInstruction* instruction, + absl::Span called_computations, + CallContext context) + : instruction_(CHECK_NOTNULL(instruction)), + called_computations_(called_computations.begin(), + called_computations.end()), + context_(context) {} + + // Returns the instruction associated with this call site. + HloInstruction* instruction() const { return instruction_; } + + // Returns the computations called at this call site. + absl::Span called_computations() const { + return called_computations_; + } + + // Returns the context in which computations are called at this call site. + CallContext context() const { return context_; } + + std::string ToString() const; + + private: + // The calling instruction. + HloInstruction* instruction_; + + // The computations called by this callsite. + const absl::InlinedVector called_computations_; + + // The context in which the computations are called. + const CallContext context_; +}; + +// A node in the call graph representing an HLO computation. +class CallGraphNode { + public: + explicit CallGraphNode(HloComputation* computation); + + // Returns the computation represented by this call graph node. + HloComputation* computation() const { return computation_; } + + // Returns the call sites in this computation. These are the instructions in + // this computation which call other computations. + absl::Span callsites() const { return callsites_; } + + // Returns the callsite associated with the given instruction. If this + // instruction calls no computations nullptr is returned. + // Prerequisite: instruction is in the computation associated with this call + // graph node. + const CallSite* GetCallSite(const HloInstruction* instruction) const; + + // Returns the computations called by this computation. + absl::Span callees() const { return callees_; } + + // Returns the call sites in other computations which call this computation. + absl::Span caller_callsites() const { + return caller_callsites_; + } + + // Returns the computations which call this computation. + absl::Span callers() const { return callers_; } + + // Returns the context in which this computation is called. + CallContext context() const { return context_; } + + // Returns the depth of this node in the call graph. The depth is defined as + // the length of the longest call chain from a computation with no callers + // (usually the entry computation node) to this node. + int depth() const { return depth_; } + + absl::string_view ToString() const; + + CallGraphNode(const CallGraphNode&) = delete; + CallGraphNode& operator=(const CallGraphNode&) = delete; + CallGraphNode(CallGraphNode&&) = default; + CallGraphNode& operator=(CallGraphNode&&) = default; + + private: + // Only CallGraph can modify CallGraphNode. + friend class CallGraph; + + // Sets the context in which this computation is called. + void set_context(CallContext value) { context_ = value; } + + // Sets the depth of this node in the graph. + void set_depth(int value) { depth_ = value; } + + // Adds a callsite which calls this computation. Updates callers to include + // the calling computation. + void AddCallerCallSite(const CallSite& caller_callsite); + + // If instruction calls any computations adds a call site for this instruction + // to the call graph node. If the instruction calls no computations then no + // call site is added. + void AddCallSiteForInstruction( + HloInstruction* instruction, + const absl::flat_hash_set& execution_threads = {}); + + // Computation represented by this call graph node. + HloComputation* computation_; + + // The computations called by this computation. The vector is used for a + // stable ordering and the set enables fast membership testing. + absl::InlinedVector callees_; + absl::flat_hash_set callee_set_; + + // The computations which call this computation. The vector is used for a + // stable ordering and the set enables fast membership testing. + absl::InlinedVector callers_; + absl::flat_hash_set caller_set_; + + // The call sites in this computation + absl::InlinedVector callsites_; + + // The map from instruction to index in callsites_ for looking up the callsite + // (if any) associated with a particular instruction in this computation. + absl::flat_hash_map callsite_instructions_; + + // The call sites in other computations which call this computation. + absl::InlinedVector caller_callsites_; + + // The context in which this computation is called. + CallContext context_ = CallContext::kNone; + + // The depth of this node in the call graph. + int depth_ = 0; +}; + +// The call graph for an HLO module. The graph includes a node for each +// computation in the module. +class CallGraph { + public: + using VisitorFunction = absl::FunctionRef; + + // Builds and returns a call graph for the given HLO module. If a non-empty + // execution_threads is provided, only computations that are in + // execution_threads will be part of the returned call graph. + static std::unique_ptr Build( + const HloModule* module, + const absl::flat_hash_set& execution_threads = {}); + + // Returns the node associated with the given computation. + const CallGraphNode& GetNode(const HloComputation* computation) const; + CallGraphNode& GetNode(const HloComputation* computation); + + // Returns the vector of all nodes in the call graph. + const std::vector& nodes() const { return nodes_; } + + // Calls the given function on each node in the call graph. Nodes are visited + // in post order (callees before callers). If visit_unreachable_nodes is true + // then all nodes in the call graph are visited. Otherwise only those nodes + // reachable from the entry computation are visited. + Status VisitNodes(VisitorFunction visitor_func, + bool visit_unreachable_nodes = true) const; + + // Returns true if 'a' dominates 'b' in the call graph. Computation 'a' + // dominates computation 'b' iff all callgraph paths in the caller-to-callee + // direction from a root computation to 'b' pass through computation + // 'a'. Trivially, a computation dominates itself. + bool Dominates(const HloComputation* a, const HloComputation* b) const; + + // Returns whether 'instruction' is contained in 'computation' either directly + // ('instruction->parent' is 'computation') or indirectly ('computation' + // dominates 'instruction->parent' in the call graph). + bool InstructionIsNestedIn(const HloInstruction* instruction, + const HloComputation* computation) const { + return Dominates(computation, instruction->parent()); + } + + // Returns the nearest call graph ancestors of instructions 'a' and 'b' for + // which the ancestors are in the same computation. An instruction is an call + // graph ancestor of 'a' if the instruction calls the computation containing + // 'a' either directly or transitively. Degeneratively an instruction is an + // ancestor of itself. nullptr is returned if there is no common ancestor or + // if the caller chain of 'a' or 'b' diverges (has multiple callers) before + // the nearest common ancestor. + // + // Example: + // + // Entry computation: + // %x = Call(A, {Constant(42.0)}) + // %y = Call(B, {%x}) + // + // Computation A: + // %a = Negate(Param()) + // + // Computation B: + // %b = Exp(Param()); + // + // If called with %a and %b, this function would return (%x, %y). %x is an + // ancestor of %a, and %y is an ancestor of %b, and %x and %y are in the same + // computation. + std::pair NearestAncestorsInSameComputation( + HloInstruction* a, HloInstruction* b) const; + + // Given a set of instructions within a computation, returns nearest common + // ancestors as Hlo instructions (There could be multiple nearest common + // ancestors in a DAG). If the given instructions are not in the same + // computation, this function would report FAILURE. + // + // Unlike the `NearestAncestorsInSameComputation` defined above, it: + // + // (1) Only compute the nearest common ancestors within a computation, instead + // of across computations (that's the function + // `ComputationsNearestCommonAncestors` that defined below). + // + // (2) Takes in **a set of** Hlo instructions, instead of two Hlo + // instructions, and find their nearest common ancestors. + // + // Example: + // + // Computation A: + // %p0 = Param(0) + // %p1 = Param(1) + // %p2 = Param(2) + // %add0 = Add(%p0, %p1) + // %mul0 = Mul(%p1, %p2) + // %sub0 = Sub(%add0, %mul0) + // + // If called with {%p0, %p1}, this function would return {%add0}. + // + // Please check the detailed example in + // `CallGraphTest.NearestCommonAncestorInstructions`. + absl::flat_hash_set NearestCommonAncestorInstructions( + std::vector instructions); + + // Given a set of computations within a module, returns nearest common + // ancestors as Hlo computations (There could be multiple nearest common + // ancestors in a DAG). + // + // Entry_computation: + // %x = Call(A, {Constant(42.0)}) + // %y = Call(B, {%x}) + // + // Computation_A: + // %a = Negate(Param()) + // + // Computation_B: + // %b = Exp(Param()); + // + // If called with {Computation_A, Computation_B}, this function would return + // {Entry_computation}. + // + // Please check the detailed example in + // `CallGraphTest.NearestCommonAncestorComputations`. + absl::flat_hash_set NearestCommonAncestorComputations( + std::vector computations); + + // A template helper function that computes the nearest common ancestors among + // instructions/computations. `T` can be either `HloInstruction` or + // `HloComputation`. Computing nearest common ancestors are basically the same + // for HloInstruction and HloComputation. The only difference is that they + // require different ways to access the ancestors of one node. Specifically, + // the ancestors are users_instruction for instructions, and are + // caller_computations for computations. + // + // The overall idea is to conduct BFS from the `starting_nodes`, and keep + // track of the visited ancestors of each node. For each BFS step, we check if + // there is a common node in all the visited ancestors, and if yes, that + // common node is the nearest ancestor we are looking for. Note that, since we + // are traversing DAG, there could be multiple nearest common ancestors. And + // there must be at least one common ancestor (i.e., entry computations among + // computations or root instruction among instructions). + template + absl::flat_hash_set NearestCommonAncestorsHelper( + std::vector& starting_nodes); + + // Returns whether the call graph is flattened. A call graph is flattened if + // every computation called in a sequential context (eg, kWhile or kCall) has + // zero or one callsite, and no computation is called from both a parallel and + // sequential context. The call graph of a module can be flattened with + // FlattenCallGraph. + bool IsFlattened() const; + + // Returns a vector of instructions calling the passed computation. + // (Often a vector of size 1.) + std::vector GetComputationCallers( + const HloComputation* c) const; + + std::string ToString() const; + + private: + explicit CallGraph( + const HloModule* module, + const absl::flat_hash_set& execution_threads = {}); + + // Not copyable. + CallGraph(const CallGraph&) = delete; + CallGraph& operator=(const CallGraph&) = delete; + + // Sets the call contexts for every node in the graph. + void SetCallContexts(); + + // Sets the call node depths for every node in the graph. + void SetNodeDepths(); + + // Helper method for VisitNodes(). Traverses the call graph from 'node' in DFS + // post order (callee before caller) calling visitor_func on each node. Adds + // nodes to 'visited' as each node is visited. Skips nodes already in + // 'visited'. + Status VisitNodesInternal( + VisitorFunction visitor_func, const CallGraphNode& node, + absl::flat_hash_set* visited) const; + + // Recursive helper for computing whether 'a' dominates 'b' in the call + // graph. 'b_ancestor' is the currently visited node (which starts at 'b'), + // and 'visited' is the set of computations which have been visited. + bool DominatesHelper( + const HloComputation* a, const HloComputation* b, + absl::flat_hash_set* visited) const; + + // The HLO module represented by this call graph. + const HloModule* module_ = nullptr; + + // Vector of all nodes in the call graph. + std::vector nodes_; + + // Map from HLO computation to the index of the corresponding call graph node + // in nodes_. + absl::flat_hash_map node_indices_; + + // The execution threads that the call graph is built for. + absl::flat_hash_set execution_threads_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CALL_GRAPH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_inliner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_inliner.h new file mode 100644 index 0000000000000000000000000000000000000000..f203b2f52eeb651426cfe28b73c29eec33b4cb9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_inliner.h @@ -0,0 +1,58 @@ +/* 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_SERVICE_CALL_INLINER_H_ +#define XLA_SERVICE_CALL_INLINER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// For every kCall operation in the main computation, we inline the body of the +// called function, and proceed recursively. +class CallInliner : public HloModulePass { + public: + using InlinedInstructionMap = + absl::flat_hash_map; + + // Inlines one call instruction. Returns a mapping from the original + // instructions to their inlined versions. + static StatusOr Inline(HloInstruction* call); + + // If single_call_site is true, only functions with a single call site will be + // inlined. + // If update_domain is true, the exit domains could be updated for calls which + // are being inlined if necessary. + explicit CallInliner(bool single_call_site = false, + bool update_domain = false) + : single_call_site_(single_call_site), update_domain_(update_domain) {} + ~CallInliner() override = default; + absl::string_view name() const override { return "CallInliner"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + bool single_call_site_; + bool update_domain_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CALL_INLINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/change_op_data_type.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/change_op_data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..d72567306fd6127f06598653cd1a30668946f339 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/change_op_data_type.h @@ -0,0 +1,79 @@ +/* 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_SERVICE_CHANGE_OP_DATA_TYPE_H_ +#define XLA_SERVICE_CHANGE_OP_DATA_TYPE_H_ + +#include +#include +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Changes `from_ty op(from_ty a, from_ty b)` into +// `from_ty convert(op(to_ty convert(a), to_ty convert(b)))`. +// +// One place where this pass is useful is for fp16 dots/convs in XLA:CPU. +// Although XLA:CPU supports fp16 dots/convs, they are significantly slower than +// fp32 convs. This pass lets us run the fp16 dot/conv as "convert to fp32, +// run in fp32, then convert back to fp16". (This is of course not +// mathematically the same, but it's close enough for our purposes.) +// +// This pass only considers ops that match `op_matcher` and where all operands +// have type `from_ty`. It will not do the correct thing for ops like +// dynamic-slice where only some of the arguments should be converted; it's up +// to you to avoid matching such ops with `op_matcher`. +// +// The pass support multiple pairs and will apply the transform +// if all operands match one of the types in from_ty. +// +// It uses provided `cloner` to clone an instruction with shape and converted +// operands. If the cloner is not provided, it will uses `CloneWithNewOperands`. +class ChangeOpDataType : public HloModulePass { + public: + using HloCloner = std::function( + const HloInstruction*, const Shape&, absl::Span)>; + ChangeOpDataType( + absl::Span const> from_to_types, + HloPredicate op_matcher, HloCloner cloner = nullptr) + : op_matcher_(op_matcher), cloner_(cloner) { + for (const std::pair& pair : from_to_types) { + to_type_map_[pair.first] = pair.second; + } + } + + ChangeOpDataType(PrimitiveType from_ty, PrimitiveType to_ty, + HloPredicate op_matcher, HloCloner cloner = nullptr) + : op_matcher_(op_matcher), cloner_(cloner) { + to_type_map_[from_ty] = to_ty; + } + + absl::string_view name() const override { return "change-op-data-type"; } + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // map with key = from_type and value = to_type. + absl::flat_hash_map to_type_map_; + HloPredicate op_matcher_; + HloCloner cloner_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CHANGE_OP_DATA_TYPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/channel_tracker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/channel_tracker.h new file mode 100644 index 0000000000000000000000000000000000000000..8d4e8fc6a0155ad979a37ef890adf3eb80bb61f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/channel_tracker.h @@ -0,0 +1,51 @@ +/* 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_SERVICE_CHANNEL_TRACKER_H_ +#define XLA_SERVICE_CHANNEL_TRACKER_H_ + +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Tracks channels between computations in the XLA service. Channels +// are associated with a unique handle and can be resolved from the handle for +// later use. +// +// TODO(b/34027823): Destruct channels when all the associated computations that +// communicate via each channel are destructed. +class ChannelTracker { + public: + ChannelTracker() = default; + + // Creates a new Channel object and returns the corresponding + // ChannelHandle for it. + StatusOr NewChannel(ChannelHandle::ChannelType type); + + private: + // Guards the channel mapping. + absl::Mutex channel_mutex_; + + // The next sequence number to assign to a channel. + int64_t next_channel_ ABSL_GUARDED_BY(channel_mutex_) = 1; + + ChannelTracker(const ChannelTracker&) = delete; + ChannelTracker& operator=(const ChannelTracker&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CHANNEL_TRACKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cholesky_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cholesky_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..bf91721b03c3234991594b485693ca2585a9948b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cholesky_expander.h @@ -0,0 +1,48 @@ +/* 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_SERVICE_CHOLESKY_EXPANDER_H_ +#define XLA_SERVICE_CHOLESKY_EXPANDER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/client/xla_builder.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +class CholeskyExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "cholesky_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; + + virtual StatusOr> CholeskyUnblocked( + XlaOp a, PrecisionConfig::Precision precision); + + private: + XlaOp BuildCholesky(XlaOp a, int64_t block_size, + PrecisionConfig::Precision precision); + + // Mapping from op signatures to existing computations. + absl::flat_hash_map computation_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CHOLESKY_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_combiner_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_combiner_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..c22ba04cc79553f9a3a2df444241f9166923443c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_combiner_utils.h @@ -0,0 +1,154 @@ +/* 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_SERVICE_COLLECTIVE_COMBINER_UTILS_H_ +#define XLA_SERVICE_COLLECTIVE_COMBINER_UTILS_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/functional/function_ref.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/hlo/ir/hlo_reachability.h" +#include "xla/service/hlo_domain_map.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/errors.h" + +namespace xla { + +// Combines instructions with matching keys together. +// +// Instructions are combined in topological post-order. +// +// `key_fn` should return equal keys for two instructions that might be combined +// together. Instructions will be combined until the threshold for output byte +// size or instruction count is reached. +template +StatusOr CombineInstructionsByKey( + HloComputation* computation, + absl::FunctionRef(const HloInstruction*)> key_fn, + absl::FunctionRef)> combine_fn, + int64_t combine_threshold_bytes, int64_t combine_threshold_count) { + // Cache keys for each instruction and build sets of instructions with the + // same key that might be combined together. + absl::flat_hash_map keys; + absl::flat_hash_map> groups; + + for (HloInstruction* instruction : computation->instructions()) { + std::optional key = key_fn(instruction); + if (key) { + keys.insert({instruction, *key}); + groups[*key].insert(instruction); + } + } + + bool changed = false; + + // Keys are removed after the instruction is combined (or never will be). + while (!keys.empty()) { + std::vector to_combine; + int64_t to_combine_bytes = 0; + absl::flat_hash_set* group = nullptr; + + // Recompute reachability after every combine group because we can't + // maintain a cross group topological order to be able to rely on the + // transitive dependencies to detect cycles. + std::unique_ptr reachability = + HloReachabilityMap::Build(computation); + + for (HloInstruction* instruction : + computation->MakeInstructionPostOrder()) { + auto it = keys.find(instruction); + if (it == keys.end()) continue; + + // If this is the first instruction, set the active group. + if (to_combine.empty()) { + group = &groups.find(it->second)->second; + } + + // Check instruction is in the active group. + if (group->find(instruction) == group->end()) { + continue; + } + + VLOG(1) << "Considering HLO " << instruction->ToString() + << " with current set size of " << to_combine_bytes + << " and current operand count of " << to_combine.size(); + + // We do not handle ops that have more than one operand since that is + // simpler and this pass is the only way to generate such ops. + if (instruction->operands().size() != 1) { + VLOG(1) << "Skipping due to " << instruction->operands().size() + << " operands"; + keys.erase(it); + continue; + } + + TF_RET_CHECK(instruction->shape().IsArray()); + int64_t instruction_bytes = ShapeUtil::ByteSizeOf(instruction->shape()); + + // If the instruction is greater than the threshold, then we can never + // combine it with anything. + if (instruction_bytes > combine_threshold_bytes) { + VLOG(1) << "Size " << instruction_bytes << " above threshold."; + keys.erase(it); + continue; + } + + if (to_combine_bytes + instruction_bytes > combine_threshold_bytes) { + VLOG(1) << "Combined size threshold exceeded."; + break; + } + + // We can't combine dependent instructions. + bool is_reachable = + absl::c_any_of(to_combine, [&](HloInstruction* to_combine_inst) { + return reachability->IsReachable(to_combine_inst, instruction); + }); + if (is_reachable) { + VLOG(1) << "Instruction is reachable."; + break; + } + + VLOG(1) << "Adding instruction to set."; + to_combine.push_back(instruction); + to_combine_bytes += instruction_bytes; + keys.erase(it); + + if (to_combine.size() >= combine_threshold_count) { + VLOG(1) << "Combined count threshold reached."; + break; + } + } + + if (to_combine.size() > 1) { + TF_RETURN_IF_ERROR(combine_fn(to_combine)); + changed = true; + } + } + + return changed; +} + +} // namespace xla + +#endif // XLA_SERVICE_COLLECTIVE_COMBINER_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_decomposer_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_decomposer_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6aaedfd79f1d1e8755ea5e2cc96bc311d5c28f27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_decomposer_utils.h @@ -0,0 +1,35 @@ +/* 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. +==============================================================================*/ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/collective_ops_utils.h" + +#ifndef XLA_SERVICE_COLLECTIVE_DECOMPOSER_UTILS_H_ +#define XLA_SERVICE_COLLECTIVE_DECOMPOSER_UTILS_H_ + +namespace xla { + +StatusOr> +CreateStartIndicesForCollectiveDecomposition( + CollectiveOpGroupMode group_mode, + absl::Span replica_groups, const Shape &shard_shape, + int64_t shard_dimension, HloComputation *computation, + std::function update_layout = nullptr); + +} // namespace xla + +#endif // XLA_SERVICE_COLLECTIVE_DECOMPOSER_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_ops_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_ops_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6917e34adc2225915380d524c19b20af00811778 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_ops_utils.h @@ -0,0 +1,440 @@ +/* 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_SERVICE_COLLECTIVE_OPS_UTILS_H_ +#define XLA_SERVICE_COLLECTIVE_OPS_UTILS_H_ + +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "xla/executable_run_options.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/computation_placer.h" +#include "xla/service/global_device_id.h" +#include "xla/service/pattern_matcher.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory.h" +#include "tsl/platform/blocking_counter.h" + +namespace xla { + +enum class ReductionKind { SUM, PRODUCT, MIN, MAX }; + +// Attempts to match instruction to one of the possible cases for ReductionKind. +std::optional MatchReductionInstruction( + const HloInstruction* hlo); + +// Attempts to match computation to one of the possible cases in ReductionKind. +std::optional MatchReductionComputation( + const HloComputation* computation); + +// Returns the reduction identity value for a certain ReductionKind and +// PrimitiveType. +std::optional GetReductionIdentity(ReductionKind kind, + PrimitiveType type); + +// Figures out which IDs are participating in the collective subgroup. +// An empty `groups` indicates that all [0, total_participant_count) IDs +// are participating. Note that for CollectiveOpGroupMode::kFlattenedID, +// groups cannot be empty, so `total_participant_count` is an optional. +StatusOr> GetParticipatingIDs( + int current_id, std::optional total_participant_count, + absl::Span groups); + +// There are broadly 4 modes that collective communication ops use to describe +// which sets of devices are participating with a given device in the operation. +// These modes are determined by the values of channel_id (optional) and +// use_global_device_ids (optional). The modes are as follows: +// +// kCrossReplica: +// implied by: no channel id, use_global_device_ids = false, or +// no channel_id, no use_global_device_ids: +// replica_groups contain replica_id, group contains all replicas for the +// current partition +// +// kCrossPartition: +// implied by: channel_id is set, no use_global_device_ids: +// replica_groups contain partition_id, group contains all partitions for the +// current replica. +// +// kCrossReplicaAndPartition: +// implied by: channel_id is set, use_global_device_ids = false: +// replica_groups contain replica_id, group contains all replicas for all +// partitions (as opposed to just current partition). +// +// kFlattenedID: +// implied by: channel_id is set, use_global_device_ids = true: +// replica_groups contain flattened-ids, group contains devices that are +// listed in the flattened-id list. +// +// Rest of the combinations are invalid. +// +// Since the actual value of channel_id does not matter, we use a bool argument +// `has_channel_id`, and optional for use_global_device_ids. +// Note that use_global_device_ids true requires channel_id to be set as well. +// Additionally, if use_global_device_ids = true, replica groups cannot be +// empty (verified in the HLO verifier). +enum class CollectiveOpGroupMode { + kCrossReplica, + kCrossPartition, + kCrossReplicaAndPartition, + kFlattenedID, +}; + +absl::string_view CollectiveOpGroupModeToString( + CollectiveOpGroupMode group_mode); + +// Returns the group formation mode implied by (a) whether the operation has +// channel_id and (b) if it has use_global_device_ids and if yes, its value. +StatusOr GetCollectiveOpGroupMode( + bool has_channel_id, std::optional use_global_device_ids); + +// Figures out subgroups of participating devices from given replica_groups and +// group_mode. +// +// Returns list of participants, where each participant is a list of +// GlobalDeviceIds. +// +// For example: +// device_assignment={{33, 34}, {44, 45}, {55, 56}} 3 replicas 2 partitions +// group_mode=CollectiveOpGroupMode::kCrossReplica +// replica_groups={{0}, {1, 2}} +// +// This functions returns {{33, 34}, {44, 45, 55, 56}} +// There are 2 subgroups of participating devices {33, 34}, {44, 45, 55, 56}. +StatusOr>> +GetParticipatingDevicesGroups(const DeviceAssignment& device_assignment, + absl::Span replica_groups, + CollectiveOpGroupMode group_mode); + +// Same as above, except that it returns the flattened id in the replica groups +// instead of device id. +StatusOr> GetParticipatingFlattenedIdGroups( + const DeviceAssignment& device_assignment, + absl::Span replica_groups, + CollectiveOpGroupMode group_mode); + +// Same as above, but take replica/partition count instead of device assignment. +StatusOr> GetParticipatingFlattenedIdGroups( + absl::Span replica_groups, + CollectiveOpGroupMode replica_group_mode, int replica_count, + int partition_count); + +// Figures out which devices are participating in the collective subgroup. +StatusOr> GetParticipatingDevices( + GlobalDeviceId device_id, const DeviceAssignment& device_assignment, + absl::Span replica_groups, + CollectiveOpGroupMode group_mode); + +// Figures out how many ranks are participating in each collective subgroup. +StatusOr> GetPariticipantCountsForReplicaGroups( + int64_t num_replicas, int64_t num_partitions, + absl::Span replica_groups, + CollectiveOpGroupMode group_mode); + +// Returns true if the two replica group are orthogonal. +bool ReplicaGroupsOrthogonal(absl::Span first, + absl::Span second); + +// Returns true if the two replica group are Equal. +bool ReplicaGroupsEqual(absl::Span first, + absl::Span second); + +// A custom call target that can be used to create a nop that can legally +// replace a collective op. +inline constexpr absl::string_view kNopCustomCallTarget = "AllocateBuffer"; +// A custom call target that can be used to create a nop that can legally +// replace a collective op and it returns a token. +inline constexpr absl::string_view kNopReturnTokenCustomCallTarget = + "NopReturnToken"; + +// Returns true if instruction is a collective op or a collective fusion. +bool IsCollective(const HloInstruction* instruction); + +// Key that identifies a particular Rendezvous object in our global hashtable. +// This determines which calls to ExecuteOnStream communicate with each other. +// The rules are as follows. +// +// * Only ops with the same RunId can communicate with each other. (This is the +// whole purpose of RunId). +// +// * Only ops with the same set of participating replicas can communicate with +// each other. This is how we separate out different replica groups (e.g. a +// single AllReduce HLO might do two reductions, between say GPUs {0,2} and +// {1,3}). +// +// * Only ops with the same opcode can communicate with each other. At the +// moment we only support kAllReduce, so we don't check for this explicitly. +// +// * For cross-module all-reduces (i.e. instr->channel_id().has_value()), +// only ops with the same value for channel_id() can communicate with each +// other. +// +// * For cross-replica (i.e. same-module) all-reduces (i.e. +// !channel_id().has_value()), only ops from the same module (as +// identified by its unique_id()) can communicate with each other. +// +struct RendezvousKey { + enum CollectiveOpKind { + kCrossModule, + kCrossReplica, + }; + + explicit RendezvousKey(const RunId& run_id, + std::vector global_devices, + int num_local_participants, + CollectiveOpKind collective_op_kind, int64_t op_id) + : run_id(run_id), + global_devices(std::move(global_devices)), + num_local_participants(num_local_participants), + collective_op_kind(collective_op_kind), + op_id(op_id) {} + + template + friend H AbslHashValue(H h, const RendezvousKey& k) { + return H::combine(std::move(h), k.run_id, k.global_devices, + k.num_local_participants, k.collective_op_kind, k.op_id); + } + friend bool operator==(const RendezvousKey& a, const RendezvousKey& b) { + return a.run_id == b.run_id && a.global_devices == b.global_devices && + a.num_local_participants == b.num_local_participants && + a.collective_op_kind == b.collective_op_kind && // + a.op_id == b.op_id; + } + friend bool operator!=(const RendezvousKey& a, const RendezvousKey& b) { + return !(a == b); + } + + absl::string_view CollectiveOpKindString() const { + switch (collective_op_kind) { + case kCrossModule: + return "cross_module"; + case kCrossReplica: + return "cross_replica"; + } + } + + std::string ToString() const { + return absl::StrFormat( + "RendezvousKey{run_id=%s, global_devices=[%s], " + "num_local_participants=%d, collective_op_kind=%s, op_id=%d}", + run_id.ToString(), GlobalDeviceIdsToString(global_devices), + num_local_participants, CollectiveOpKindString(), op_id); + } + + RunId run_id; + std::vector global_devices; + int num_local_participants; + CollectiveOpKind collective_op_kind; + int64_t op_id; +}; + +template +void WaitAndLogIfStuck(tsl::BlockingCounter* counter, const DescFn& desc_fn) { + VLOG(3) << "Begin: " << desc_fn(); + const std::chrono::milliseconds timeout(5000); + bool ok = counter->WaitFor(timeout); + if (ok) { + VLOG(3) << "Finished: " << desc_fn(); + return; + } + LOG(ERROR) << "This thread has been waiting for " << timeout.count() + << "ms for and may be stuck: " << desc_fn(); + counter->Wait(); + LOG(ERROR) << "Thread is unstuck! Warning above was a false-positive. " + "Perhaps the timeout is too short: " + << desc_fn(); +} + +// Participant data for each rendezvous. +struct ParticipantData { + explicit ParticipantData(const RendezvousKey& rendezvous_key) + : rendezvous_key(rendezvous_key) {} + + virtual ~ParticipantData() {} + + RendezvousKey rendezvous_key; + + virtual std::string ToString() const = 0; +}; + +// Encapsulates parameters to Rendezvous::SubmitParticipant. +struct AllReduceParticipantData : ParticipantData { + AllReduceParticipantData(const RendezvousKey& rendezvous_key_p, + int64_t device_ordinal_p, se::Stream* stream_p) + : ParticipantData(rendezvous_key_p), + device_ordinal(device_ordinal_p), + stream(stream_p) {} + + // TODO(b/125951860): We should vet that we're buffer allocating such that + // source_buffer == destination_buffer if that avoids a NCCL copy (will depend + // on how well the NCCL in-place implementation performs vs the out-of-place + // implementation). + struct Buffer { + int64_t element_count; + se::DeviceMemoryBase source_data; + se::DeviceMemoryBase destination_data; + PrimitiveType primitive_type; + }; + int64_t device_ordinal; + se::Stream* stream; + std::vector buffers; + + ReductionKind reduction_kind; + + // For each local all-reduce participant a (global ID, local device ordinal) + // pair for the participant. Participants are in no particular order. + std::vector> local_devices; + + std::string ToString() const override { + std::vector buffer_strs; + buffer_strs.reserve(buffers.size()); + for (const Buffer& buffer : buffers) { + buffer_strs.push_back( + absl::StrFormat("{element_count=%d}", buffer.element_count)); + } + return absl::StrFormat( + "AllReduceParticipantData{buffers=[%s], rendezvous_key=%s, " + "device_ordinal=%d, stream=%p}", + absl::StrJoin(buffer_strs, ","), rendezvous_key.ToString(), + device_ordinal, stream); + } +}; + +// The set of threads that want to do a collective op together all pick the same +// Rendezvous object out of the global cache and call SubmitParticipant. +// +// The Rendezvous instance handles waiting for all threads to join, ensuring +// that a clique exists for the desired set of GPUs, etc. +// +// Rendezvous objects can only be used once. +// +// I: Participant data. +// O: Participant output. +template ::value>> +class Rendezvous { + public: + virtual ~Rendezvous() {} + explicit Rendezvous(const RendezvousKey& k) : key_(k) {} + + // Submit a participant to the rendezvous. We get the rendezvous from + // `rendezvous_getter`, which we can then use to drop the existing reference. + static StatusOr SubmitParticipant( + absl::FunctionRef>()> rendezvous_getter, + I participant) { + std::shared_ptr> rendezvous = rendezvous_getter(); + TF_ASSIGN_OR_RETURN(auto p, rendezvous->SubmitParticipant(participant)); + + // Drop our reference to the Rendezvous and wait for all other threads to do + // the same. If we didn't do this, one of the threads could run past this + // point, reenter ExecuteOnStream for another all-reduce, and attempt to + // reuse the Rendezvous! + // + // An alternative way of accomplishing this goal would be to implement + // RefcountingHashMap::erase() and call it during SubmitParticipant. But + // erase() is deceptively complex to implement correctly. + std::shared_ptr blocking_counter = p.second; + rendezvous.reset(); + blocking_counter->DecrementCount(); + xla::WaitAndLogIfStuck(blocking_counter.get(), [&] { + return absl::StrFormat( + "participant waiting for all threads to drop their reference to the " + "rendezvous: %p", + rendezvous.get()); + }); + return std::move(p.first); + } + + protected: + // Returns domain-specific output O and whether this replica is primary. + virtual StatusOr RunCollectiveOp(const I& participant) = 0; + + // Initialize the rendezvous by the first ("primary") thread which reaches the + // barrier. Returns whether this thread is primary. + bool InitializationBarrier() { + absl::MutexLock lock(&mu_); + if (!initialized_) { + initialized_ = true; + return true; + } + return false; + } + + absl::Mutex mu_; + + bool initialized_ ABSL_GUARDED_BY(mu_) = false; + + std::vector participants_ ABSL_GUARDED_BY(mu_); + + private: + // Runs the all-reduce on the given thread. If successful, returns + // - a handle to the clique that was used, so that the caller may keep the + // clique alive if it chooses. + // - a BlockingCounter initialized to the number of participants, so that + // the caller can coordinate with the participants one last time if it + // chooses. This is useful for coordinating destruction of the Rendezvous. + StatusOr>> + SubmitParticipant(const I& participant) { + { + absl::MutexLock lock(&mu_); + CHECK(!initialized_); + + // Spot check for consistent replica counts among submitting threads. + if (!participants_.empty() && + participants_.back().rendezvous_key != participant.rendezvous_key) { + return InvalidArgument( + "Mismatch among all-reduce participants. Expected same " + "replica-count, element-count, and rendezvous-key but were %s and " + "%s", + participants_.back().ToString(), participant.ToString()); + } + participants_.push_back(participant); + } + + // Wait for all participants to arrive. + all_participants_present_.DecrementCount(); + WaitAndLogIfStuck(&all_participants_present_, [&] { + return absl::StrFormat( + "participant %s waiting for all participants to arrive at rendezvous " + "%s", + participant.ToString(), key_.ToString()); + }); + + TF_ASSIGN_OR_RETURN(O output, RunCollectiveOp(participant)); + return std::make_pair(std::move(output), returned_blocking_counter_); + } + + const RendezvousKey key_; + + tsl::BlockingCounter all_participants_present_{key_.num_local_participants}; + + // tsl::BlockingCounter returned by SubmitParticipant. + std::shared_ptr returned_blocking_counter_{ + std::make_shared(key_.num_local_participants)}; +}; + +constexpr char kSendRecvSourceTargetPairsAttr[] = + "_xla_send_recv_source_target_pairs"; + +} // end namespace xla + +#endif // XLA_SERVICE_COLLECTIVE_OPS_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_opt_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_opt_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..d26c2ab1ad50dddb3987d75717b77c2abf73bbac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_opt_utils.h @@ -0,0 +1,66 @@ +/* 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_SERVICE_COLLECTIVE_OPT_UTILS_H_ +#define XLA_SERVICE_COLLECTIVE_OPT_UTILS_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" + +namespace xla { + +struct ReduceScatterSpec { + int64_t split_dim; + int64_t sharded_partitions = 1; + int64_t sharded_replicas = 1; + int64_t group_size; + std::vector original_split_dims; + HloInstruction* dynamic_slice; +}; + +// Matches the given all-reduce operation to a reduce-scatter pattern. +std::optional MatchReduceScatter( + const HloAllReduceInstruction* ar, int64_t num_partitions, + int64_t num_replicas, bool allow_multiple_split_dims = false, + bool allow_intervening_reshape = false, int64_t min_rank = 1, + HloPredicate match_partition_id = HloPredicateIsOp, + HloPredicate match_replica_id = HloPredicateIsOp); + +// Check whether AG(ICI) and its single user DS(ICI) can be canceled out. +bool AllGatherDynamicSliceCancellation( + const HloAllGatherInstruction* ag, int64_t num_partitions, + int64_t num_replicas, bool allow_multiple_split_dims = false, + bool allow_intervening_reshape = false, int64_t min_rank = 1, + HloPredicate match_partition_id = HloPredicateIsOp, + HloPredicate match_replica_id = HloPredicateIsOp); + +// Check if a given instruction (AllReduce or AllGather) matches a DynamicSlice; +// the DynamicSlice has to be the only user of the given instruction. +std::optional MatchWithDynamicSlice( + const HloChannelInstruction* instruction, int64_t num_partitions, + int64_t num_replicas, bool allow_multiple_split_dims = false, + bool allow_intervening_reshape = false, int64_t min_rank = 1, + HloPredicate match_partition_id = HloPredicateIsOp, + HloPredicate match_replica_id = HloPredicateIsOp, + bool is_constrain_layout = false, bool use_global_device_ids = false, + bool is_cross_module = false); + +} // namespace xla + +#endif // XLA_SERVICE_COLLECTIVE_OPT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_permute_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_permute_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..321c5e12758191f13a286ee7bef882d85d8381ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_permute_decomposer.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_COLLECTIVE_PERMUTE_DECOMPOSER_H_ +#define XLA_SERVICE_COLLECTIVE_PERMUTE_DECOMPOSER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// CollectivePermuteDecomposer is a pass that converts asynchronous +// CollectivePermute operations without any cycle in the (source, target) +// relationship to Send/Recv. We currently restrict this transformation to +// CollectivePermuteStart with one input and without any context data. +// +// before transformation: +// start = (, ) collective-permute-start(data), +// source_target_pairs={...} +// done = collective-permute-done(start) +// +// after transformation: +// after-all = token[] after-all() +// recv = (, token[]) recv(after-all), channel_id=0, +// frontend_attributes={_xla_send_recv_source_target_pairs="{...}"} +// send = (, token[]) send(data, after-all), channel_id=0, +// control-predecessors={recv}, frontend_attributes={ +// _xla_send_recv_source_target_pairs="{...}"} +// recv-done = (, token[]) recv-done(recv), channel_id=0 +// send-done = token[] send-done(send), channel_id=0, +// control-predecessors={recv-done} +// done = get-tuple-element(recv-done), index=0 +// +class CollectivePermuteDecomposer : public HloModulePass { + public: + explicit CollectivePermuteDecomposer(int64_t threshold_in_bytes) + : threshold_in_bytes_(threshold_in_bytes) {} + absl::string_view name() const override { + return "collective-permute-decomposer"; + } + + using HloPassInterface::Run; + // Runs CollectivePermuteDecomposer pass on computations in 'module'. + // Returns whether the 'module' was changed. + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Transform only if the size of the collective permute is >= threshold. + int64_t threshold_in_bytes_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COLLECTIVE_PERMUTE_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_pipeliner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_pipeliner.h new file mode 100644 index 0000000000000000000000000000000000000000..d1de7133d6757fab77451ebb3ff5336a89005b9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collective_pipeliner.h @@ -0,0 +1,119 @@ +/* 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_SERVICE_COLLECTIVE_PIPELINER_H_ +#define XLA_SERVICE_COLLECTIVE_PIPELINER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// This transformation peels off loop iterations of models with stacked layers +// that perform data parallelism using reduce-scatter/all-reduce/all-gather. +// Collective instructions are pushed to the next iteration in which they can +// overlap with the entirely of the next layer rather than with a more limited +// amount of computation in the current iteration. An example of transformation +// is this: +// +// while (i < LAYERS) { +// p0 = param(0) +// p1 = param(1) +// x = computation(p0) +// xg = all-reduce(x) +// y = computation(p1) +// yg = all-reduce(y) +// } +// +// to +// +// x_prev = computation(p0) +// y_prev = computation(p1) +// i = i + 1 +// while (i < LAYERS, x_prev, y_prev) { +// p0 = param(0) +// p1 = param(1) +// xg = all-reduce(x_prev) +// yg = all-reduce(y_prev) +// x = computation(p0) +// y = computation(p1) +// x_prev = x +// y_prev = y +// } +class CollectivePipeliner : public HloModulePass { + public: + enum PipeliningDirection { + kBackward, + kForward, + kForwardSink, + }; + struct Config { + int64_t level_to_operate_on = 0; + // Maximum number of HLOs to pipeline per loop. (Meant to help controlling + // memory pressure manually). + int64_t max_pipelining_per_loop = 0; + bool last_run = true; + // The pipeliner should try to pipeline instructions that have a tree of + // uses of allowed instructions. This could increase memory pressure as + // multiple instructions might have to be saved to be pushed to the next + // iteration. + bool pipeline_use_tree = false; + bool process_different_sized_ops = false; + PipeliningDirection pipelining_direction = PipeliningDirection::kForward; + HloPredicate should_process; + }; + static const char* const kInsertedByPreviousStep; + static const char* const kSunkByPreviousStep; + explicit CollectivePipeliner(const Config& config) : config_(config) {} + CollectivePipeliner(CollectivePipeliner&& other) = default; + CollectivePipeliner& operator=(CollectivePipeliner&& other) = default; + absl::string_view GetPipelineDirectionString(PipeliningDirection direction) { + switch (direction) { + case PipeliningDirection::kForward: { + return "forward"; + } + case PipeliningDirection::kBackward: { + return "backward"; + } + case PipeliningDirection::kForwardSink: { + return "forwardsink"; + } + } + } + + absl::string_view name() const override { + if (config_.pipelining_direction == kForward) { + return "collective-pipeliner-forward"; + } else if (config_.pipelining_direction == kBackward) { + return "collective-pipeliner-backward"; + } else { + return "collective-pipeliner-forwardsink"; + } + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const Config config_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COLLECTIVE_PIPELINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collectives_schedule_linearizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collectives_schedule_linearizer.h new file mode 100644 index 0000000000000000000000000000000000000000..33c5866145c8884bb58957f1b84b3e170ebff5cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/collectives_schedule_linearizer.h @@ -0,0 +1,52 @@ +/* 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_SERVICE_COLLECTIVES_SCHEDULE_LINEARIZER_H_ +#define XLA_SERVICE_COLLECTIVES_SCHEDULE_LINEARIZER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/util.h" + +namespace xla { + +// Enforces a total order on all collectives present in the module, based on the +// order given to the instructions. +// +// Does not insert inter-computation dependencies, only linearizes the order +// within each computation. +class CollectivesScheduleLinearizer : public HloModulePass { + public: + explicit CollectivesScheduleLinearizer(HloModulePredicate is_enabled = {}) + : is_enabled_(is_enabled) {} + + absl::string_view name() const override { + return "collectives-schedule-linearizer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + HloModulePredicate is_enabled_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COLLECTIVES_SCHEDULE_LINEARIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/comparison_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/comparison_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..2d42393484d648fdf404ec02bbb132facf319938 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/comparison_expander.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_COMPARISON_EXPANDER_H_ +#define XLA_SERVICE_COMPARISON_EXPANDER_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// A pass which performs expansion of the comparison operator to support total +// order comparison of floating point numbers. +class ComparisonExpander : public OpExpanderPass { + public: + explicit ComparisonExpander() = default; + ~ComparisonExpander() override = default; + absl::string_view name() const override { return "comparison-expander"; } + + private: + // Returns `true` if `instruction` should be expanded by this pass. + bool InstructionMatchesPattern(HloInstruction* instruction) override; + // Returns a replacement for `instruction`, or nullptr if no replacement is + // needed (e.g. only the to_apply subcomputation of the instruction was + // modified). + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPARISON_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..c76cacea6ba08940be28ec51fcd4ef7dffb4fce0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_cache.h @@ -0,0 +1,60 @@ +/* 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_SERVICE_COMPILATION_CACHE_H_ +#define XLA_SERVICE_COMPILATION_CACHE_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/service/executable.h" +#include "xla/service/hlo_module_config.h" +#include "xla/types.h" + +namespace xla { + +// A cache which stores Executables indexed by computation handle and version. +// +// TODO(b/119042872): Provide mechanism for removing computations from the +// compilation cache. +class CompilationCache { + public: + CompilationCache() {} + + ExecutionHandle Insert(std::unique_ptr executable); + + // Lookup the Executable for the specified handle in the cache. Return a + // shared_ptr to the Executable if it exists in the cache. + StatusOr> LookUp( + const ExecutionHandle& handle) const; + + protected: + mutable absl::Mutex mutex_; + + using CacheKey = int64_t; + + absl::flat_hash_map> cache_ + ABSL_GUARDED_BY(mutex_); + + private: + CompilationCache(const CompilationCache&) = delete; + CompilationCache& operator=(const CompilationCache&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPILATION_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_environments.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_environments.h new file mode 100644 index 0000000000000000000000000000000000000000..d3778a96c8553f112d0d28ec7e8c417994aa38fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_environments.h @@ -0,0 +1,151 @@ +/* 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_SERVICE_COMPILATION_ENVIRONMENTS_H_ +#define XLA_SERVICE_COMPILATION_ENVIRONMENTS_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/statusor.h" +#include "xla/xla.pb.h" +#include "tsl/platform/casts.h" +#include "tsl/platform/protobuf.h" + +namespace xla { + +// A class for holding CompilationEnvironments, i.e., protos holding the values +// of command line flags and environment variables that affect compilation. +// +// CompilationEnvironments uses lazy initialization, (see GetEnv() for more +// details). Lazy initialization is used so we can avoid: +// A) Requiring every code path to explitily construct all needed compilation +// environments, particularly when the default constructed environment is +// all we need AND +// B) Requiring CompilationEnvironments to implicitly construct all needed +// environments, thereby requiring it to statically know the types of all +// such environments +// +// CompilationEnvironments is not thread-safe. +class CompilationEnvironments { + public: + using ProcessNewEnvFn = std::function( + std::unique_ptr)>; + + CompilationEnvironments() = default; + CompilationEnvironments(const CompilationEnvironments& rhs) { *this = rhs; } + CompilationEnvironments& operator=(const CompilationEnvironments& rhs); + ~CompilationEnvironments() = default; + + // Deserializes the given CompilationEnvironments proto. + static StatusOr> CreateFromProto( + const CompilationEnvironmentsProto& proto); + + // Whenever an environment is added to CompilationEnvironments, even when + // GetEnv() adds a lazily initialized one, it is passed to the function + // registered by this method, corresponding to the environment's proto + // descriptor. The result is the environment that is used by + // CompilationEnvironments. This allows environment authors to + // do things like populate missing fields in an added environment. + // + // Users of CompilationEnvironments must register their `ProcessNewEnvFn` + // function via this method for each type of CompilationEnvironment they wish + // to use in code. + // + // The input env to a ProcessNewEnvFn may be null. + // + // REQUIRES: + // - The output is *not* allowed to be null, even for null input. + static void RegisterProcessNewEnvFn( + const tsl::protobuf::Descriptor* descriptor, + ProcessNewEnvFn process_new_env); + + // Adds env to the list of CompilationEnvironments. If an environment with + // the same proto descriptor has already been added, env will replace it. + // + // All added environments are processed via registered ProcessNewEnvFns. If + // such a function was not regitered for env's proto descriptor or env's + // proto type is unknown, an error will be returned. + Status AddEnv(std::unique_ptr env); + + // Returns the CompilationEnvironment corresponding to T. If such an + // environment has not been added, ProcessNewEnvFn(nullptr) will be added and + // returned. + // + // GetMutableEnv()/GetEnv() are not const because they can perform lazy + // initialization, thereby modifying the CompilationEnvironments's data + // members. + template + T& GetMutableEnv(); + template + const T& GetEnv(); + + // Removes all added environments. + void Clear() { environments_.clear(); } + + // Serializes this CompilationEnvironments into a protobuf message. + CompilationEnvironmentsProto ToProto() const; + + private: + // Returns the ProcessNewEnvFn for the given env type. Returns nullptr if no + // ProcessNewEnvFn has been registered for the env type. + static ProcessNewEnvFn GetProcessNewEnvFn( + const tsl::protobuf::Descriptor& descriptor); + + // Called by GetEnv(), when it lazily creates a new environment, to globally + // track stats about how many such environments are created by + // CompilationEnvironments. + static void DefaultEnvCreatedByCompilationEnvironments( + std::string_view env_type); + + // Called by AddEnv(), to globally track stats about how many environments + // are added to CompilationEnvironments. + static void EnvAdded(std::string_view env_type); + + Status AddEnvImpl(const tsl::protobuf::Descriptor& descriptor, + std::unique_ptr env); + + absl::flat_hash_map> + environments_; +}; + +// ----- Template implementation below ----- + +template +T& CompilationEnvironments::GetMutableEnv() { + auto descriptor = T::descriptor(); + auto it = environments_.find(descriptor); + if (it == environments_.end()) { + TF_CHECK_OK(AddEnvImpl(*descriptor, nullptr)); + DefaultEnvCreatedByCompilationEnvironments(descriptor->full_name()); + it = environments_.find(descriptor); + } + return tensorflow::down_cast(*it->second); +} + +template +const T& CompilationEnvironments::GetEnv() { + return GetMutableEnv(); +} + +} // namespace xla + +#endif // XLA_SERVICE_COMPILATION_ENVIRONMENTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_stats.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..f37d597be5c6e89cdb9cb9331cfc348f6d756e35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compilation_stats.h @@ -0,0 +1,54 @@ +/* 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_SERVICE_COMPILATION_STATS_H_ +#define XLA_SERVICE_COMPILATION_STATS_H_ + +#include +#include + +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" + +namespace xla { + +// This class is used to collect information about HLO passes and print some +// statistics at the end of compilation. From HloPassPipeline, we call StartPass +// before the execution of a pass, and EndPass after. Currently, we only collect +// timing information and how many times each pass was run. In the future, we +// can add more things, such as the size of the HLO graph after each pass. +class CompilationStats { + public: + virtual ~CompilationStats() = default; + + static std::unique_ptr MakeNoopStats(); + + static std::unique_ptr MakeStats(); + + virtual void StartPass(absl::string_view pass_name) = 0; + + virtual void EndPass(absl::string_view pass_name) = 0; + + virtual void CompilationReport() = 0; + + virtual int GetPassesSize() = 0; + + virtual void RecordPassError(absl::string_view pass_name, + absl::string_view err) = 0; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPILATION_STATS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compile_only_service.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compile_only_service.h new file mode 100644 index 0000000000000000000000000000000000000000..3032710eb38dd0fb4bcaa4b0a467b73105528c0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compile_only_service.h @@ -0,0 +1,98 @@ +/* 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_SERVICE_COMPILE_ONLY_SERVICE_H_ +#define XLA_SERVICE_COMPILE_ONLY_SERVICE_H_ + +#include "xla/service/backend.h" +#include "xla/service/compiler.h" +#include "xla/service/service.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// An XLA Service specialization for ahead-of-time compilation. This only +// instantiates a Compiler object for the relevant platform; it does not +// instantiate or require an execution backend. +class CompileOnlyService : public Service { + public: + // Factory for creating a CompileOnlyService. The parameter platform is the + // platform that the service should target. If platform is null then the + // default platform is used. + static StatusOr> NewService( + se::Platform* platform); + static StatusOr> NewService( + const ServiceOptions& options); + + // A description of a xla computation to compile using CompileAheadOfTime. + struct AotXlaComputationInstance { + HloModuleProto computation; + std::vector argument_layouts; + Shape result_layout; + }; + + // Compiles a list of xla computations for ahead-of-time execution. This is + // intended for use in static compilation. See + // |CompileOnlyClient::CompileAheadOfTime| for additional details. + StatusOr>> + CompileAheadOfTime(absl::Span computations, + const AotCompilationOptions& options, + std::unique_ptr* metadata); + + Status GetDeviceHandles(const GetDeviceHandlesRequest* arg, + GetDeviceHandlesResponse* result) override { + return Unimplemented("CompileOnlyService does not support devices."); + } + Status WaitForExecution(const WaitForExecutionRequest* arg, + WaitForExecutionResponse* result) override { + return Unimplemented("CompileOnlyService does not support execution."); + } + Status TransferToServer(const TransferToServerRequest* arg, + TransferToServerResponse* result) override { + return Unimplemented( + "CompileOnlyService does not support device data transfers."); + } + Status TransferToInfeed(const TransferToInfeedRequest* arg, + TransferToInfeedResponse* result) override { + return Unimplemented( + "CompileOnlyService does not support device data transfers."); + } + Status TransferFromOutfeed(const TransferFromOutfeedRequest* arg, + TransferFromOutfeedResponse* result) override { + return Unimplemented( + "CompileOnlyService does not support device data transfers."); + } + Status ResetDevice(const ResetDeviceRequest* arg, + ResetDeviceResponse* result) override { + return Unimplemented("CompileOnlyService does not support devices."); + } + + private: + explicit CompileOnlyService(const ServiceOptions& options, + Compiler* compiler); + CompileOnlyService(const CompileOnlyService&) = delete; + void operator=(const CompileOnlyService&) = delete; + + // The compiler for the target platform. This is included in place of + // the Service::execute_backend_'s compiler, since execute_backend_ is a + // nullptr in CompileOnlyService. + Compiler* compiler_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPILE_ONLY_SERVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compile_time_cap.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compile_time_cap.h new file mode 100644 index 0000000000000000000000000000000000000000..75da192e7e56a10c2f63ad641d15aa8a1f2d6098 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compile_time_cap.h @@ -0,0 +1,63 @@ +/* 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_SERVICE_COMPILE_TIME_CAP_H_ +#define XLA_SERVICE_COMPILE_TIME_CAP_H_ +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" + +namespace xla { +// Provide a common way to bound compiler analyses that potentially have +// overhead that is non-linear to the number of instructions in a module. +class BoundNonLinearCompilerAnalysis { + public: + // Sampling_rate specifies the proportion of all instructions expected to be + // analyzed. e.g., if sampling_rate_=2, then every other instructions are + // expected to be analyzed. If sample_rate <= 0, the analysis will be always + // allowed to complete. Each analysis is allowed at least a constant number of + // abstract cost units, before it is considered for early termination. + explicit BoundNonLinearCompilerAnalysis(HloModule* m, + absl::string_view pass_name, + std::optional sampling_rate) + : analysis_allowance_( + (!sampling_rate.has_value() || sampling_rate.value() <= 0 || + m->config().GetAnalysisAllowance(pass_name) < 0) + ? -1 + : std::max(m->config().GetAnalysisAllowance(pass_name), + m->instruction_count() / sampling_rate.value())) {} + // Return whether the cost is deducted successfully. If not, the analysis + // should be terminated as its overhead is too high. + bool DeductCost(int64_t cost_now) { + if (analysis_allowance_ > 0 && cost_now > 0) { + analysis_allowance_ -= cost_now; + if (analysis_allowance_ < 0) { + analysis_allowance_ = 0; + } + } + return analysis_allowance_ != 0; + } + + bool ContinueAnalysis() const { return analysis_allowance_ != 0; } + int64_t analysis_allowance() const { return analysis_allowance_; } + + private: + int64_t analysis_allowance_; +}; + +}; // namespace xla + +#endif // XLA_SERVICE_COMPILE_TIME_CAP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..b06b47a0e266cb8ed495dd5b103fe58c9cb253c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/compiler.h @@ -0,0 +1,437 @@ +/* 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 compiler API is used by the XLA service to generate executables that +// run on a given platform. This is a registry and abstract interface, for +// pluggability by the various platforms. + +#ifndef XLA_SERVICE_COMPILER_H_ +#define XLA_SERVICE_COMPILER_H_ + +#include +#include +#include +#include +#include +#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_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_module_group.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/buffer_value.h" +#include "xla/service/computation_placer.h" +#include "xla/service/executable.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/metrics_hook_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/protobuf.h" +#include "tsl/platform/threadpool.h" + +namespace xla { + +// The following types are used for ahead of time compilation. + +// Contains the object file data created as a result of ahead-of-time +// computation. +using ObjectFileData = std::vector; + +class Compiler; + +// Abstract superclass describing the result of an ahead-of-time compilation. +class AotCompilationResult { + public: + AotCompilationResult(const AotCompilationResult&) = delete; + AotCompilationResult& operator=(AotCompilationResult const&) = delete; + + virtual ~AotCompilationResult() = default; + + virtual StatusOr SerializeAsString() const { + return Unimplemented("SerializeAsString unimplemented."); + } + + virtual StatusOr> LoadExecutable( + Compiler* compiler, se::StreamExecutor* executor) const { + return Unimplemented("LoadExecutable unimplemented."); + } + + protected: + AotCompilationResult() = default; +}; + +// Abstract superclass describing options to an ahead-of-time compilation. +class AotCompilationOptions { + public: + AotCompilationOptions(const AotCompilationOptions&) = delete; + AotCompilationOptions& operator=(AotCompilationOptions const&) = delete; + + explicit AotCompilationOptions(se::Platform::Id platform_id) + : platform_id_(platform_id), debug_options_(GetDebugOptionsFromFlags()) {} + virtual ~AotCompilationOptions() = default; + + // Returns the ID of the platform to which these options apply. + virtual se::Platform::Id PlatformId() const { return platform_id_; } + + virtual int64_t replica_count() const { return 0; } + virtual int64_t num_cores() const { return 0; } + virtual bool use_spmd_partitioning() const { return false; } + virtual bool use_auto_spmd_partitioning() const { return false; } + virtual std::vector auto_spmd_partitioning_mesh_shape() const { + return {}; + } + virtual std::vector auto_spmd_partitioning_mesh_ids() const { + return {}; + } + virtual bool deduplicate_hlo() const { return false; } + virtual PrecisionConfig::Precision matrix_unit_operand_precision() const { + return PrecisionConfig::DEFAULT; + } + + // Optional allocator that may be used for allocating temp space on the device + // during compilation. + se::DeviceMemoryAllocator* device_allocator() const { + return device_allocator_; + } + void set_device_allocator(se::DeviceMemoryAllocator* device_allocator) { + device_allocator_ = device_allocator; + } + + const DebugOptions& debug_options() const { return debug_options_; } + DebugOptions* mutable_debug_options() { return &debug_options_; } + + bool has_static_device_assignment() const { + return static_device_assignment_.has_value(); + } + const DeviceAssignment& static_device_assignment() const { + CHECK(static_device_assignment_.has_value()); + return *static_device_assignment_; + } + void set_static_device_assignment(const DeviceAssignment& device_assignment) { + static_device_assignment_ = device_assignment; + } + + FusionConfigCollection fusion_config_collection() const { + return fusion_config_collection_; + } + void set_fusion_config_collection( + FusionConfigCollection fusion_config_collection) { + fusion_config_collection_ = fusion_config_collection; + } + + const std::vector>& fusion_config() const { + return fusion_config_; + } + void set_fusion_config(const std::vector>& fusion_config) { + fusion_config_ = fusion_config; + } + + se::StreamExecutor* executor() const { return executor_; } + void set_executor(se::StreamExecutor* executor) { executor_ = executor; } + + // Optional profile_version and cache key may be used to trigger recompilation + // when a compilation cache is used. + int64_t profile_version() const { return profile_version_; } + void set_profile_version(int64_t profile_version) { + profile_version_ = profile_version; + } + + absl::string_view cache_key() const { return cache_key_; } + void set_cache_key(absl::string_view cache_key) { + cache_key_ = std::string(cache_key); + } + + bool run_backend_only() const { return run_backend_only_; } + void set_run_backend_only(bool run_backend_only) { + run_backend_only_ = run_backend_only; + } + + bool sanitize_dataflow() const { return sanitize_dataflow_; } + void set_sanitize_dataflow(bool sanitize_dataflow) { + sanitize_dataflow_ = sanitize_dataflow; + } + + const std::vector& sanitize_abilists_dataflow() const { + return sanitize_abilists_dataflow_; + } + void set_sanitize_abilists_dataflow( + const std::vector& abilists) { + sanitize_abilists_dataflow_ = abilists; + } + + const std::any& target_config() const { return target_config_; } + void set_target_config(std::any target_config) { + target_config_ = std::move(target_config); + } + + protected: + AotCompilationOptions(); + + private: + se::Platform::Id platform_id_; + se::DeviceMemoryAllocator* device_allocator_ = nullptr; + DebugOptions debug_options_; + std::optional static_device_assignment_; + std::vector> fusion_config_; + FusionConfigCollection fusion_config_collection_ = + FusionConfigCollection::kOff; + se::StreamExecutor* executor_ = nullptr; + int64_t profile_version_ = 0; + std::string cache_key_; + bool run_backend_only_ = false; + bool sanitize_dataflow_ = false; + std::vector sanitize_abilists_dataflow_; + // Contains target-specific information required by AOT compilation. + std::any target_config_; +}; + +// Abstract superclass describing metadata produced during ahead-of-time +// compilation. +class AotCompilationMetadata { + public: + AotCompilationMetadata(const AotCompilationMetadata&) = delete; + AotCompilationMetadata& operator=(AotCompilationMetadata const&) = delete; + virtual std::string ToString() const { return ""; } + virtual ~AotCompilationMetadata() = default; + + protected: + AotCompilationMetadata() = default; +}; + +// Abstract compiler interface that is subclassed for compilation on a +// particular platform. +// +// The compiler ties together high level optimization (HLO) and low level +// optimization (LLO) / codegen (CG) to generate efficient executables for the +// target platform. +// +// The platform-based compiler singletons are registered via module initializers +// in their corresponding XLA compiler libraries, and are registered via the +// RegisterCompilerFactory API below. +// +// Thread-safety: subclasses of Compiler must be thread-safe, as multiple +// XLA clients may be requesting compilation concurrently for a given +// platform. +class Compiler { + public: + struct CompileOptions { + // If device_allocator is not null, the compiler may use it to allocate temp + // space on the device for use during compilation. For example, the + // compiler may allocate buffers on the device and then run variants of a + // given algorithm over those buffers, to see which variant is fastest. Any + // space allocated will be deallocated before the compilation returns. + se::DeviceMemoryAllocator* device_allocator = nullptr; + + // An optional thread pool for parallel compilation. + tsl::thread::ThreadPool* thread_pool = nullptr; + + std::function, Shape>>( + const HloModule& module)> + layout_canonicalization_callback = {}; + + bool is_autotuning_compilation = false; + }; + + virtual ~Compiler() = default; + + // Returns the ID of the platform that this compiler targets. + virtual se::Platform::Id PlatformId() const = 0; + + // Runs Hlo passes to optimize the given Hlo module, returns the optimized + // module. + virtual StatusOr> RunHloPasses( + std::unique_ptr module, se::StreamExecutor* executor, + const CompileOptions& options) = 0; + StatusOr> RunHloPasses( + std::unique_ptr module, se::StreamExecutor* executor, + se::DeviceMemoryAllocator* device_allocator) { + return RunHloPasses(std::move(module), executor, + CompileOptions{device_allocator}); + } + + // Performs scheduling and buffer assignment and returns the buffer + // assignments. + // The returned 'BufferAssignment' retains a pointer to the 'HloModule', so + // the module must live at least as long as the buffer assignments. + virtual StatusOr> AssignBuffers( + HloModule* module, se::StreamExecutor* executor) { + return Unimplemented("This compiler does not support this method"); + } + + // Compiles the HLO module for execution on a device given by the executor, + // and returns an executable object or an error status. No HLO passes are + // applied to module. Generally a module should be passed through RunHloPasses + // prior to calling this method because some HLO passes are required for + // correctness. Takes ownership of the HLO module. + // + // The compiler may optionally specialize to the individual device + // (not just type of device) indicated by the executor. + virtual StatusOr> RunBackend( + std::unique_ptr module, se::StreamExecutor* executor, + const CompileOptions& options) = 0; + StatusOr> RunBackend( + std::unique_ptr module, se::StreamExecutor* executor, + se::DeviceMemoryAllocator* device_allocator) { + return RunBackend(std::move(module), executor, + CompileOptions{device_allocator}); + } + + // The following two interfaces are same as the above two, except they + // facilitate the loading of buffer assignment from proto if available. + + // Note: The default implementation of the API here does not utilize the given + // buffer assignment. Different backends are a expected to override the + // following method to achieve this functionality. + virtual StatusOr> RunBackendWithBufferAssignment( + std::unique_ptr module, + const BufferAssignmentProto* /*buffer_assignment_proto*/, + se::StreamExecutor* executor, const CompileOptions& options) { + LOG(WARNING) << "Ignoring the buffer assignment proto provided."; + return RunBackend(std::move(module), executor, options); + } + + StatusOr> RunBackendWithBufferAssignment( + std::unique_ptr module, + const BufferAssignmentProto* buffer_assignment_proto, + se::StreamExecutor* executor, + se::DeviceMemoryAllocator* device_allocator) { + return RunBackendWithBufferAssignment(std::move(module), + buffer_assignment_proto, executor, + CompileOptions{device_allocator}); + } + + // Returns a (deserialized) AotCompilationResult from a serialized + // AotCompilationResult. + virtual StatusOr> + LoadAotCompilationResult(const std::string& serialized_aot_result) { + return Unimplemented("LoadAotCompilationResult unimplemented."); + } + + // Compiles a set of HLO modules that can run in parallel, potentially + // communicating data between the modules, and returns a corresponding + // sequence of executable objects. + // + // TODO(b/68666782): Remove this method after adding support for multiple + // modules to RunHloPasses and RunBackends. + virtual StatusOr>> Compile( + std::unique_ptr module_group, + std::vector> stream_exec, + const CompileOptions& options) = 0; + StatusOr>> Compile( + std::unique_ptr module_group, + std::vector> stream_exec, + se::DeviceMemoryAllocator* device_allocator) { + return Compile(std::move(module_group), stream_exec, + CompileOptions{device_allocator}); + } + + // Returns the backend configurations that the backend will consider for the + // given HLO. Returns no configurations if the backend does not support + // configurations for the given HLO. + // + // The stream executor is passed in to provide information about the hardware + // that the backend configurations would be targeting. + virtual std::vector> + ComputeBackendConfigs(const HloInstruction& hlo, + se::StreamExecutor* executor) const; + + // Returns the backend configuration that the backend chooses by default for + // the given HLO. Returns no configuration if the backend does not support + // configurations for the given HLO. + // + // The stream executor is passed in to provide information about the hardware + // that the backend configurations would be targeting. + virtual std::unique_ptr ComputeDefaultBackendConfig( + const HloInstruction& hlo, se::StreamExecutor* executor) const; + + // Compiles the HLO module group for ahead-of-time execution. This is + // intended for use in static compilation. + virtual StatusOr>> + CompileAheadOfTime(std::unique_ptr module_group, + const AotCompilationOptions& options) = 0; + + // Similar to CompileAheadOfTime above but AotCompilationMetadata + // has an argument that can be populated during compilation. + virtual StatusOr>> + CompileAheadOfTime(std::unique_ptr module_group, + const AotCompilationOptions& options, + std::unique_ptr* metadata); + + ///// + // The Compiler class also serves as a point to register compiler objects + // for the various platforms. + + using CompilerFactory = std::function()>; + + // Registers the compiler singleton for the platform. This is assumed to + // be a singleton, so no ownership is transferred. + // + // Precondition: a platform kind must not be registered more than once. + static void RegisterCompilerFactory(se::Platform::Id platform_id, + CompilerFactory compiler_factory); + + // Returns the compiler singleton pointer if it is available for the given + // platform, or an error status if it is not. + static StatusOr GetForPlatform(const se::Platform* platform); + + // Returns a function that computes the size in bytes of the logical + // buffer that contains a shape. + virtual HloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const = 0; + + // Returns a function that computes the size in bytes of a given + // logical buffer. + std::function BufferSizeBytesFunction() { + HloCostAnalysis::ShapeSizeFunction shape_size = ShapeSizeBytesFunction(); + return [shape_size](const BufferValue& buffer) { + return shape_size(buffer.shape()); + }; + } + + virtual Shape DefaultDeviceShapeRepresentation(const Shape& shape) const { + return shape; + } + + // Returns an AotCompilationResult of the executable for serialization. + virtual StatusOr> Export( + Executable* executable) const { + return Unimplemented("Export unimplemented"); + } + + // Returns a MetricsHookInterface object used to instrument Compiler's + // compilation stages. + virtual std::unique_ptr CreateMetricsHook( + absl::string_view filename_prefix) const; + + private: + // Mutex that guards the platform-compiler map. + static absl::Mutex platform_compiler_mutex_; + + // Map from platform kind to compiler factory. + static absl::flat_hash_map* + GetPlatformCompilerFactories(); + + // Map from platform kind to compiler instance, if we made one already (based + // on the factories above). + static absl::flat_hash_map>* + GetPlatformCompilers(); +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/computation_layout.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/computation_layout.h new file mode 100644 index 0000000000000000000000000000000000000000..572aaac669e3583775cb2bee7f88a42ad3cd7c93 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/computation_layout.h @@ -0,0 +1,116 @@ +/* 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_SERVICE_COMPUTATION_LAYOUT_H_ +#define XLA_SERVICE_COMPUTATION_LAYOUT_H_ + +#include +#include +#include +#include + +#include "xla/printer.h" +#include "xla/shape_layout.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Class which contains the layouts of the parameters and results of a +// computation. The layouts are stored as ShapeLayouts with immutable shapes and +// mutable layouts. +class ComputationLayout { + public: + // Creates a new ComputationLayout with the given result layout. + explicit ComputationLayout(ShapeLayout result_layout) + : result_layout_(std::move(result_layout)) {} + + // Constructs a ComputationLayout from a ProgramShape. The layouts of the + // parameters and results are set to the default layout. Layouts in the + // ProgramShape are ignored if ignore_layouts is true. + explicit ComputationLayout(const ProgramShape& program_shape, + bool ignore_layouts = true); + + // Adds a new parameter layout to the computation layout. + void add_parameter_layout(ShapeLayout shape_layout) { + parameter_layouts_.push_back(std::move(shape_layout)); + } + + // Returns the layout of a particular parameter. + const ShapeLayout& parameter_layout(int64_t param_no) const { + return parameter_layouts_[param_no]; + } + ShapeLayout* mutable_parameter_layout(int64_t param_no) { + return ¶meter_layouts_[param_no]; + } + + // Returns the number of parameters in the computation. + int parameter_count() const { return parameter_layouts_.size(); } + + // Returns the ShapeLayouts of the parameters of the computation. + const std::vector& parameter_layouts() const { + return parameter_layouts_; + } + + // Returns the ShapeLayout of a result of the computation. + const ShapeLayout& result_layout() const { return result_layout_; } + ShapeLayout* mutable_result_layout() { return &result_layout_; } + + // Returns the shape of the particular parameter or result of the computation + // with layout. + const Shape& parameter_shape(int64_t param_no) const { + return parameter_layouts_[param_no].shape(); + } + const Shape& result_shape() const { return result_layout_.shape(); } + + // Sets layouts of all parameters and the result to the default layout. + void SetToDefaultLayout(); + + void SetToDefaultLayoutIfEmpty(); + + // Returns true if all layouts (parameters and result) have been set. + bool LayoutIsSet() const; + + // Prints a string representation of this object. + void Print(Printer* printer) const; + + // Returns a string representation of this object. + std::string ToString() const; + + // Create a ProgramShape proto based on the parameter and result shapes held + // within this object. + ProgramShape ComputeProgramShape() const; + + bool operator==(const ComputationLayout& other) const; + bool operator!=(const ComputationLayout& other) const; + + template + friend H AbslHashValue(H h, const ComputationLayout& computation_layout) { + h = H::combine(std::move(h), computation_layout.result_layout_.shape()); + for (const auto& parameter_layout : computation_layout.parameter_layouts_) { + h = H::combine(std::move(h), parameter_layout.shape()); + } + h = H::combine(std::move(h), computation_layout.parameter_layouts_.size()); + return h; + } + + private: + std::vector parameter_layouts_; + ShapeLayout result_layout_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPUTATION_LAYOUT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/computation_placer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/computation_placer.h new file mode 100644 index 0000000000000000000000000000000000000000..2e6b5e3eeb4cb396722a8b15401ca9ce7cc5843f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/computation_placer.h @@ -0,0 +1,130 @@ +/* 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_SERVICE_COMPUTATION_PLACER_H_ +#define XLA_SERVICE_COMPUTATION_PLACER_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/array2d.h" +#include "xla/service/global_device_id.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/platform.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { + +// Class that represents the device assignment for a set of XLA replicated +// computations. For R replicas and C computations, R * C devices are required +// execute the computation in parallel. The assigned device ids can be accessed +// by assignment(replica, computation). +class DeviceAssignment : public Array2D { + public: + DeviceAssignment() {} + DeviceAssignment(int replica_count, int computation_count) + : Array2D(replica_count, computation_count, -1) { + CHECK_GT(replica_count, 0); + CHECK_GT(computation_count, 0); + } + + int replica_count() const { return height(); } + int computation_count() const { return width(); } + + // The logical ID of a device is its (replica ID, computation ID) pair. + struct LogicalID { + int replica_id; + int computation_id; + }; + + // Finds the (replica ID, computation ID) pair for the given device. + StatusOr LogicalIdForDevice(GlobalDeviceId device_id) const; + // Finds the replica ID for the given device. + StatusOr ReplicaIdForDevice(GlobalDeviceId device_id) const; + // Returns a map from device ID to logical ID. Querying this map is much more + // efficient than `LogicalIdForDevice` if queried repeatedly. + absl::flat_hash_map GetDeviceToLogicalIdMap() + const; + + // Protocol buffer serialization and deserialization. + Status Serialize(DeviceAssignmentProto* proto) const; + + // Return a std::unique_ptr instead of a DeviceAssignment + // directly because one of the supported TF platforms (mac) does not compile + // due to a StatusOr of an incomplete type (DeviceAssignment). + static StatusOr> Deserialize( + const DeviceAssignmentProto& proto); + + std::string ToString() const; +}; + +// A generic implementation of the XLA computation placer, which assigns device +// ids to a set of replicated computations. +class ComputationPlacer { + public: + ComputationPlacer() {} + virtual ~ComputationPlacer() {} + + // Returns the device id assigned to the given replica and computation + // instance for [replica_count x computation_count] setup. The returned device + // id must match the assignment from PlaceReplicatedComputation(). + virtual StatusOr DeviceId(int replica, int computation, + int replica_count, int computation_count); + + // Returns the device ids assigned to a set of replicated computations, given + // the number of replicas and the number of computations. + virtual StatusOr AssignDevices(int replica_count, + int computation_count); + + using ComputationPlacerCreationFunction = + std::unique_ptr (*)(); + + // Registers a computation placer creation function for a particular platform. + static void RegisterComputationPlacer( + se::Platform::Id platform_id, + ComputationPlacerCreationFunction creation_function); + + // Returns the computation placer singleton pointer if it is available for the + // given platform, or an error status if it is not. + static StatusOr GetForPlatform( + const se::Platform* platform); + + private: + // The mutex that guards the platform-to-computation placer map. + static absl::Mutex platform_computation_placer_mutex_; + + // State kept for each kind of ComputationPlacer. Registration functions set + // up creation_function, and then we use that to lazily create "placer" the + // first time GetForPlatform is invoked for a particular id. + struct State { + std::unique_ptr placer; + ComputationPlacerCreationFunction creation_function = nullptr; + }; + + // Map from platform kind to computation placer singleton. + static std::map* GetPlatformComputationPlacers(); + + ComputationPlacer(const ComputationPlacer&) = delete; + ComputationPlacer& operator=(const ComputationPlacer&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COMPUTATION_PLACER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_canonicalizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_canonicalizer.h new file mode 100644 index 0000000000000000000000000000000000000000..86cab823277e3e868b3994e524ee26872f068fef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_canonicalizer.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_CONDITIONAL_CANONICALIZER_H_ +#define XLA_SERVICE_CONDITIONAL_CANONICALIZER_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Canonicalize output of conditionals, make non-tuple outputs into tuple with +// single element output. After this pass, all conditional instructions have +// tuple outputs. +class ConditionalCanonicalizer : public HloModulePass { + public: + absl::string_view name() const override { + return "conditional canonicalizer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; +} // namespace xla + +#endif // XLA_SERVICE_CONDITIONAL_CANONICALIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..6faee234f23b2a4af298f61ca3f0db6df28f0f69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_simplifier.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_CONDITIONAL_SIMPLIFIER_H_ +#define XLA_SERVICE_CONDITIONAL_SIMPLIFIER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass that removes kConditional with a constant predicate, replacing them +// with their true or false computation as appropriate. +class ConditionalSimplifier : public HloModulePass { + public: + absl::string_view name() const override { return "simplify-conditional"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr TryRemoveConditional(HloInstruction* conditional); +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONDITIONAL_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_to_select.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_to_select.h new file mode 100644 index 0000000000000000000000000000000000000000..c66abcfb36116845f2aa6f5141cbee65e9ff5398 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/conditional_to_select.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_CONDITIONAL_TO_SELECT_H_ +#define XLA_SERVICE_CONDITIONAL_TO_SELECT_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which transforms conditionals to selects in places where conditionals +// are legal, but not currently supported by the backends (e.g. inside kMap) +class ConditionalToSelect : public HloModulePass { + public: + ~ConditionalToSelect() override = default; + absl::string_view name() const override { return "conditional-to-select"; } + + // Run conditional to select on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONDITIONAL_TO_SELECT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/constant_value.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/constant_value.h new file mode 100644 index 0000000000000000000000000000000000000000..97f3a8ff0479547131268ca0efb2865de5fd099e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/constant_value.h @@ -0,0 +1,87 @@ +/* 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_SERVICE_CONSTANT_VALUE_H_ +#define XLA_SERVICE_CONSTANT_VALUE_H_ + +#include + +#include "xla/literal.h" +#include "xla/statusor.h" +#include "xla/util.h" + +namespace xla { + +// Class used to represent a constant. Can contain signed/unsigned values +// and values of many types type erasing the actual type and handling corner +// cases like going out of bound. +class ConstantValue { + public: + // Constructor makes sure the extra bits of the value are masked away. Handles + // signed and unsigned cases. + ConstantValue(uint64_t value, int32_t bitwidth, bool is_signed) + : value_(is_signed + ? absl::bit_cast( + absl::bit_cast( + value << (8 * sizeof(uint64_t) - bitwidth)) >> + (8 * sizeof(uint64_t) - bitwidth)) + : KeepLowerBits(value, bitwidth)), + bitwidth_(bitwidth), + is_signed_(is_signed) {} + static ConstantValue GetZero(int32_t bitwidth, bool is_signed) { + return ConstantValue(0, bitwidth, is_signed); + } + static ConstantValue GetOne(int32_t bitwidth, bool is_signed) { + return ConstantValue(1, bitwidth, is_signed); + } + static ConstantValue GetSigned(int64_t value, int32_t bitwidth) { + return ConstantValue(absl::bit_cast(value), bitwidth, + /*is_signed=*/true); + } + static ConstantValue GetUnsigned(uint64_t value, int32_t bitwidth) { + return ConstantValue(value, bitwidth, /*is_signed=*/false); + } + static StatusOr FromLiteral(const Literal& literal); + ConstantValue add(const ConstantValue& other) const { + return ConstantValue(value_ + other.value_, bitwidth_, is_signed_); + } + ConstantValue sub(const ConstantValue& other) const { + return ConstantValue(value_ - other.value_, bitwidth_, is_signed_); + } + ConstantValue div(const ConstantValue& other) const; + ConstantValue mod(const ConstantValue& other) const; + ConstantValue mul(const ConstantValue& other) const; + bool lt(const ConstantValue& other) const; + bool gt(const ConstantValue& other) const; + bool eq(const ConstantValue& other) const { return *this == other; } + int64_t GetSignedValue() const { return absl::bit_cast(value_); } + uint64_t GetUnsignedValue() const { return value_; } + int32_t GetBitwidth() const { return bitwidth_; } + bool IsSigned() const { return is_signed_; } + bool operator==(const ConstantValue& other) const { + return value_ == other.value_ && bitwidth_ == other.bitwidth_ && + is_signed_ == other.is_signed_; + } + std::string ToString() const; + + private: + uint64_t value_; + int32_t bitwidth_; + bool is_signed_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONSTANT_VALUE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convert_async_collectives_to_sync.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convert_async_collectives_to_sync.h new file mode 100644 index 0000000000000000000000000000000000000000..14db7a185e09e1e616d30badac7c59a4d2238f6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convert_async_collectives_to_sync.h @@ -0,0 +1,66 @@ +/* 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_SERVICE_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ +#define XLA_SERVICE_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ + +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Convert asynchronous collectives to synchronous (after HLO scheduling) if +// there are no compute operations overlapping with them. + +class ConvertAsyncCollectivesToSync : public HloModulePass { + public: + explicit ConvertAsyncCollectivesToSync(HloPredicate is_nop = {}) + : is_nop_(is_nop) {} + absl::string_view name() const override { + return "convert-async-collectives-to-sync"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + virtual Status ConvertAsyncInstructionsToSync( + HloComputation* computation, + absl::Span> async_pairs) + const { + return ReplaceAsyncInstructionsWithSync(computation, async_pairs); + } + + // Helper utility to replace a list of pairs of async-start/done ops in a + // computation with their synchronous variants and update the schedule. + static Status ReplaceAsyncInstructionsWithSync( + HloComputation* computation, + absl::Span> + async_pairs); + + static constexpr char kAsyncCollectiveNameAttributeName[] = + "async_collective_name"; + + private: + StatusOr RunOnComputation(HloComputation* computation); + HloPredicate is_nop_; +}; +} // namespace xla + +#endif // XLA_SERVICE_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convert_mover.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convert_mover.h new file mode 100644 index 0000000000000000000000000000000000000000..0c47e2c97843af8d1e9e6fa9f4eb3c6545e072ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convert_mover.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_SERVICE_CONVERT_MOVER_H_ +#define XLA_SERVICE_CONVERT_MOVER_H_ + +#include +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Moves narrowing conversions up the graph and widening conversions down the +// graph, when we can do so with no effect on numerics. Motivations: +// +// - It's preferable to spend more of our time in lower precision and less of +// our time in higher precision. +// +// - Moving these converts exposes optimization opportunities. For example, in +// reshape(convert-big-to-small(reshape(convert-small-to-big(x)))), we can +// commute one of the converts with one of the reshapes. This leaves us with +// convert(convert(reshape(reshape))), which can probably be simplified +// further by algsimp. +class ConvertMover : public HloModulePass { + public: + ConvertMover() = default; + + absl::string_view name() const override { return "convert-mover"; } + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONVERT_MOVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_4d_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_4d_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..baa4ce43edfa8b730a9dabae901b2fe682e3d46c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_4d_expander.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_CONVOLUTION_4D_EXPANDER_H_ +#define XLA_SERVICE_CONVOLUTION_4D_EXPANDER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/op_expander_pass.h" +#include "xla/statusor.h" + +namespace xla { + +class Convolution4DExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "convolution_4d_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONVOLUTION_4D_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_group_converter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_group_converter.h new file mode 100644 index 0000000000000000000000000000000000000000..a55633effe73d4db3018b4aa9125efb96f16bb0b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_group_converter.h @@ -0,0 +1,69 @@ +/* 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_SERVICE_CONVOLUTION_GROUP_CONVERTER_H_ +#define XLA_SERVICE_CONVOLUTION_GROUP_CONVERTER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/status_macros.h" + +namespace xla { + +// A pass which rewrites convolutions with feature_group_count > 1 into +// convolutions with feature_group_count = 1. +class ConvolutionGroupConverter : public HloModulePass { + public: + ConvolutionGroupConverter(std::function should_expand, + std::function is_cost_viable, + bool convert_batch_groups_only, + bool filter_expansion = true) + : should_expand_(should_expand), + is_cost_viable_(is_cost_viable), + convert_batch_groups_only_(convert_batch_groups_only), + filter_expansion_(filter_expansion) {} + + absl::string_view name() const override { + return "convolution-group-converter"; + } + + // Run convolution rewriting on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Predicate that determines whether this pass should rewrite a given + // convolution. + std::function should_expand_; + + // Lambda containing cost model that decides whether to expand + // batch_group_count. + std::function is_cost_viable_; + + // Decides whether to convert batch groups or feature groups. + bool convert_batch_groups_only_; + + // Tells whether filter expansion is required. + bool filter_expansion_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONVOLUTION_GROUP_CONVERTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_pred_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_pred_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..df6ea22ca6683f6f6dea4dca8fcbda3cca5670df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/convolution_pred_expander.h @@ -0,0 +1,44 @@ +/* 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_SERVICE_CONVOLUTION_PRED_EXPANDER_H_ +#define XLA_SERVICE_CONVOLUTION_PRED_EXPANDER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/op_expander_pass.h" +#include "xla/statusor.h" + +namespace xla { + +// A pass that rewrites boolean convolutions to floating point and converts the +// result back to boolean. This is necessary, as the convolutions on GPUs are +// implemented using custom call to cuDNN, which only supports FP and S8 inputs. +class ConvolutionPredExpander : public OpExpanderPass { + public: + absl::string_view name() const override { + return "convolution-pred-expander"; + } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CONVOLUTION_PRED_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/copy_insertion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/copy_insertion.h new file mode 100644 index 0000000000000000000000000000000000000000..9cb49ddbb936d4c5422f073f4de53441d2bf9034 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/copy_insertion.h @@ -0,0 +1,117 @@ +/* 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_SERVICE_COPY_INSERTION_H_ +#define XLA_SERVICE_COPY_INSERTION_H_ + +#include "xla/hlo/ir/hlo_computation.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_pass_interface.h" + +namespace xla { + +// Copy insertion is a legalization HLO pass which inserts copies (kCopy +// instructions) to eliminate several kinds of problems in the HLO module. +// +// (1) Entry parameter or a constant live out of the entry computation. Entry +// computation arguments and constants have different lifetimes than the +// computation result and cannot share the same allocation. Parameters and +// constants live out of non-entry computations do not need copies. +// +// (2) Different values which are simultaneously live and which must be held +// in the same buffer. This can occur in while bodies. Specifically, the +// while loop state (the arguments to the while instruction) is updated +// in-place and the update may clobber the value from the previous +// iteration before the previous value is dead. Computations called from +// kCall instructions do not need such copies because kCall has no update +// in-place semantics. +// +// (3) The buffer set of the root instruction of the entry computation must be +// unambiguous and distinct. That is, InstructionAliasSet::IsAmbiguous and +// InstructionAliasSet::IsDistinct return true. +class CopyInsertion : public HloModulePass { + public: + absl::string_view name() const override { return "copy-insertion"; } + static constexpr int64_t kUseRegionAnalysisLimit = 0; + + // backend specific function that decides whether an instruction + // can share buffer with its operand. + // + // TODO(b/80315712): Find a better way to tell whether a fusion can share + // buffer. + explicit CopyInsertion( + const HloDataflowAnalysis::CanShareBuffer& can_share_buffer = nullptr, + int64_t use_region_based_live_range_analysis = kUseRegionAnalysisLimit) + : can_share_buffer_(can_share_buffer), + use_region_based_live_range_analysis_( + use_region_based_live_range_analysis) {} + + // Run the pass on the given module. Returns whether the module was changed + // (copies were inserted). + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Try to remove as many copies from the module as possible without + // introducing live range interference. Only copy instructions that are + // eligible for copy elision are considered for removal. + // If check_live_range_ordering is true, check that live ranges are ordered + // in all the existing aliased buffers. + Status RemoveUnnecessaryCopies( + HloModule* module, bool check_live_range_ordering = false, + const absl::flat_hash_set& execution_threads = {}); + + // Add copies to address special constraints on the roots of computations not + // related to live range interference: + // + // (1) Entry computation root must be unambiguous and distinct. + // + // (2) Any computation called by a kCall instruction must have an + // unambiguous root. + // + // (3) Constants and parameters cannot be live out of the entry computation + // + Status AddSpecialCaseCopies( + HloModule* module, + const absl::flat_hash_set& execution_threads = {}); + + protected: + // Override which requires the caller to pass in a call graph. + virtual Status AddSpecialCaseCopies( + const CallGraph& call_graph, + const absl::flat_hash_set& execution_threads, + HloModule* module); + + // Add copies for conditional instructions. + virtual Status AddCopiesForConditional(const HloAliasAnalysis& alias_analysis, + HloInstruction* conditional); + + // Backend specific function that decides whether an instruction can share + // buffer with its operand. + HloDataflowAnalysis::CanShareBuffer can_share_buffer_; + + private: + Status AddCopiesToResolveInterference( + HloModule* module, + const absl::flat_hash_set& execution_threads); + int64_t use_region_based_live_range_analysis_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_COPY_INSERTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/backend_config.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/backend_config.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..410b81d175d6356737135972450ae09a2a85d886 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/backend_config.pb.h @@ -0,0 +1,690 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/cpu/backend_config.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fbackend_5fconfig_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 +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto; +namespace xla { +namespace cpu { +class BackendConfig; +struct BackendConfigDefaultTypeInternal; +extern BackendConfigDefaultTypeInternal _BackendConfig_default_instance_; +class OneDnnMatMulConfig; +struct OneDnnMatMulConfigDefaultTypeInternal; +extern OneDnnMatMulConfigDefaultTypeInternal _OneDnnMatMulConfig_default_instance_; +} // namespace cpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::cpu::BackendConfig* Arena::CreateMaybeMessage<::xla::cpu::BackendConfig>(Arena*); +template<> ::xla::cpu::OneDnnMatMulConfig* Arena::CreateMaybeMessage<::xla::cpu::OneDnnMatMulConfig>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace cpu { + +enum OneDnnMatMulConfig_FusionKind : int { + OneDnnMatMulConfig_FusionKind_UNDEFINED = 0, + OneDnnMatMulConfig_FusionKind_BIAS = 1, + OneDnnMatMulConfig_FusionKind_RELU = 2, + OneDnnMatMulConfig_FusionKind_TANH = 3, + OneDnnMatMulConfig_FusionKind_GELU_ERF = 4, + OneDnnMatMulConfig_FusionKind_GELU_TANH = 5, + OneDnnMatMulConfig_FusionKind_OneDnnMatMulConfig_FusionKind_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + OneDnnMatMulConfig_FusionKind_OneDnnMatMulConfig_FusionKind_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool OneDnnMatMulConfig_FusionKind_IsValid(int value); +constexpr OneDnnMatMulConfig_FusionKind OneDnnMatMulConfig_FusionKind_FusionKind_MIN = OneDnnMatMulConfig_FusionKind_UNDEFINED; +constexpr OneDnnMatMulConfig_FusionKind OneDnnMatMulConfig_FusionKind_FusionKind_MAX = OneDnnMatMulConfig_FusionKind_GELU_TANH; +constexpr int OneDnnMatMulConfig_FusionKind_FusionKind_ARRAYSIZE = OneDnnMatMulConfig_FusionKind_FusionKind_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* OneDnnMatMulConfig_FusionKind_descriptor(); +template +inline const std::string& OneDnnMatMulConfig_FusionKind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function OneDnnMatMulConfig_FusionKind_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + OneDnnMatMulConfig_FusionKind_descriptor(), enum_t_value); +} +inline bool OneDnnMatMulConfig_FusionKind_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, OneDnnMatMulConfig_FusionKind* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + OneDnnMatMulConfig_FusionKind_descriptor(), name, value); +} +// =================================================================== + +class BackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.cpu.BackendConfig) */ { + public: + inline BackendConfig() : BackendConfig(nullptr) {} + ~BackendConfig() override; + explicit PROTOBUF_CONSTEXPR BackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BackendConfig(const BackendConfig& from); + BackendConfig(BackendConfig&& from) noexcept + : BackendConfig() { + *this = ::std::move(from); + } + + inline BackendConfig& operator=(const BackendConfig& from) { + CopyFrom(from); + return *this; + } + inline BackendConfig& operator=(BackendConfig&& 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 BackendConfig& default_instance() { + return *internal_default_instance(); + } + static inline const BackendConfig* internal_default_instance() { + return reinterpret_cast( + &_BackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(BackendConfig& a, BackendConfig& b) { + a.Swap(&b); + } + inline void Swap(BackendConfig* 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(BackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BackendConfig& from) { + BackendConfig::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(BackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.cpu.BackendConfig"; + } + protected: + explicit BackendConfig(::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 { + kOuterDimensionPartitionsFieldNumber = 1, + kOnednnMatmulConfigFieldNumber = 2, + }; + // repeated int64 outer_dimension_partitions = 1; + int outer_dimension_partitions_size() const; + private: + int _internal_outer_dimension_partitions_size() const; + public: + void clear_outer_dimension_partitions(); + private: + int64_t _internal_outer_dimension_partitions(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_outer_dimension_partitions() const; + void _internal_add_outer_dimension_partitions(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_outer_dimension_partitions(); + public: + int64_t outer_dimension_partitions(int index) const; + void set_outer_dimension_partitions(int index, int64_t value); + void add_outer_dimension_partitions(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + outer_dimension_partitions() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_outer_dimension_partitions(); + + // .xla.cpu.OneDnnMatMulConfig onednn_matmul_config = 2; + bool has_onednn_matmul_config() const; + private: + bool _internal_has_onednn_matmul_config() const; + public: + void clear_onednn_matmul_config(); + const ::xla::cpu::OneDnnMatMulConfig& onednn_matmul_config() const; + PROTOBUF_NODISCARD ::xla::cpu::OneDnnMatMulConfig* release_onednn_matmul_config(); + ::xla::cpu::OneDnnMatMulConfig* mutable_onednn_matmul_config(); + void set_allocated_onednn_matmul_config(::xla::cpu::OneDnnMatMulConfig* onednn_matmul_config); + private: + const ::xla::cpu::OneDnnMatMulConfig& _internal_onednn_matmul_config() const; + ::xla::cpu::OneDnnMatMulConfig* _internal_mutable_onednn_matmul_config(); + public: + void unsafe_arena_set_allocated_onednn_matmul_config( + ::xla::cpu::OneDnnMatMulConfig* onednn_matmul_config); + ::xla::cpu::OneDnnMatMulConfig* unsafe_arena_release_onednn_matmul_config(); + + // @@protoc_insertion_point(class_scope:xla.cpu.BackendConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > outer_dimension_partitions_; + mutable std::atomic _outer_dimension_partitions_cached_byte_size_; + ::xla::cpu::OneDnnMatMulConfig* onednn_matmul_config_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto; +}; +// ------------------------------------------------------------------- + +class OneDnnMatMulConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.cpu.OneDnnMatMulConfig) */ { + public: + inline OneDnnMatMulConfig() : OneDnnMatMulConfig(nullptr) {} + ~OneDnnMatMulConfig() override; + explicit PROTOBUF_CONSTEXPR OneDnnMatMulConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + OneDnnMatMulConfig(const OneDnnMatMulConfig& from); + OneDnnMatMulConfig(OneDnnMatMulConfig&& from) noexcept + : OneDnnMatMulConfig() { + *this = ::std::move(from); + } + + inline OneDnnMatMulConfig& operator=(const OneDnnMatMulConfig& from) { + CopyFrom(from); + return *this; + } + inline OneDnnMatMulConfig& operator=(OneDnnMatMulConfig&& 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 OneDnnMatMulConfig& default_instance() { + return *internal_default_instance(); + } + static inline const OneDnnMatMulConfig* internal_default_instance() { + return reinterpret_cast( + &_OneDnnMatMulConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(OneDnnMatMulConfig& a, OneDnnMatMulConfig& b) { + a.Swap(&b); + } + inline void Swap(OneDnnMatMulConfig* 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(OneDnnMatMulConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + OneDnnMatMulConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const OneDnnMatMulConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const OneDnnMatMulConfig& from) { + OneDnnMatMulConfig::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(OneDnnMatMulConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.cpu.OneDnnMatMulConfig"; + } + protected: + explicit OneDnnMatMulConfig(::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 OneDnnMatMulConfig_FusionKind FusionKind; + static constexpr FusionKind UNDEFINED = + OneDnnMatMulConfig_FusionKind_UNDEFINED; + static constexpr FusionKind BIAS = + OneDnnMatMulConfig_FusionKind_BIAS; + static constexpr FusionKind RELU = + OneDnnMatMulConfig_FusionKind_RELU; + static constexpr FusionKind TANH = + OneDnnMatMulConfig_FusionKind_TANH; + static constexpr FusionKind GELU_ERF = + OneDnnMatMulConfig_FusionKind_GELU_ERF; + static constexpr FusionKind GELU_TANH = + OneDnnMatMulConfig_FusionKind_GELU_TANH; + static inline bool FusionKind_IsValid(int value) { + return OneDnnMatMulConfig_FusionKind_IsValid(value); + } + static constexpr FusionKind FusionKind_MIN = + OneDnnMatMulConfig_FusionKind_FusionKind_MIN; + static constexpr FusionKind FusionKind_MAX = + OneDnnMatMulConfig_FusionKind_FusionKind_MAX; + static constexpr int FusionKind_ARRAYSIZE = + OneDnnMatMulConfig_FusionKind_FusionKind_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + FusionKind_descriptor() { + return OneDnnMatMulConfig_FusionKind_descriptor(); + } + template + static inline const std::string& FusionKind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FusionKind_Name."); + return OneDnnMatMulConfig_FusionKind_Name(enum_t_value); + } + static inline bool FusionKind_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + FusionKind* value) { + return OneDnnMatMulConfig_FusionKind_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kFusedOpsFieldNumber = 3, + }; + // repeated .xla.cpu.OneDnnMatMulConfig.FusionKind fused_ops = 3; + int fused_ops_size() const; + private: + int _internal_fused_ops_size() const; + public: + void clear_fused_ops(); + private: + ::xla::cpu::OneDnnMatMulConfig_FusionKind _internal_fused_ops(int index) const; + void _internal_add_fused_ops(::xla::cpu::OneDnnMatMulConfig_FusionKind value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField* _internal_mutable_fused_ops(); + public: + ::xla::cpu::OneDnnMatMulConfig_FusionKind fused_ops(int index) const; + void set_fused_ops(int index, ::xla::cpu::OneDnnMatMulConfig_FusionKind value); + void add_fused_ops(::xla::cpu::OneDnnMatMulConfig_FusionKind value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField& fused_ops() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField* mutable_fused_ops(); + + // @@protoc_insertion_point(class_scope:xla.cpu.OneDnnMatMulConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField fused_ops_; + mutable std::atomic _fused_ops_cached_byte_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// BackendConfig + +// repeated int64 outer_dimension_partitions = 1; +inline int BackendConfig::_internal_outer_dimension_partitions_size() const { + return _impl_.outer_dimension_partitions_.size(); +} +inline int BackendConfig::outer_dimension_partitions_size() const { + return _internal_outer_dimension_partitions_size(); +} +inline void BackendConfig::clear_outer_dimension_partitions() { + _impl_.outer_dimension_partitions_.Clear(); +} +inline int64_t BackendConfig::_internal_outer_dimension_partitions(int index) const { + return _impl_.outer_dimension_partitions_.Get(index); +} +inline int64_t BackendConfig::outer_dimension_partitions(int index) const { + // @@protoc_insertion_point(field_get:xla.cpu.BackendConfig.outer_dimension_partitions) + return _internal_outer_dimension_partitions(index); +} +inline void BackendConfig::set_outer_dimension_partitions(int index, int64_t value) { + _impl_.outer_dimension_partitions_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.cpu.BackendConfig.outer_dimension_partitions) +} +inline void BackendConfig::_internal_add_outer_dimension_partitions(int64_t value) { + _impl_.outer_dimension_partitions_.Add(value); +} +inline void BackendConfig::add_outer_dimension_partitions(int64_t value) { + _internal_add_outer_dimension_partitions(value); + // @@protoc_insertion_point(field_add:xla.cpu.BackendConfig.outer_dimension_partitions) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +BackendConfig::_internal_outer_dimension_partitions() const { + return _impl_.outer_dimension_partitions_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +BackendConfig::outer_dimension_partitions() const { + // @@protoc_insertion_point(field_list:xla.cpu.BackendConfig.outer_dimension_partitions) + return _internal_outer_dimension_partitions(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +BackendConfig::_internal_mutable_outer_dimension_partitions() { + return &_impl_.outer_dimension_partitions_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +BackendConfig::mutable_outer_dimension_partitions() { + // @@protoc_insertion_point(field_mutable_list:xla.cpu.BackendConfig.outer_dimension_partitions) + return _internal_mutable_outer_dimension_partitions(); +} + +// .xla.cpu.OneDnnMatMulConfig onednn_matmul_config = 2; +inline bool BackendConfig::_internal_has_onednn_matmul_config() const { + return this != internal_default_instance() && _impl_.onednn_matmul_config_ != nullptr; +} +inline bool BackendConfig::has_onednn_matmul_config() const { + return _internal_has_onednn_matmul_config(); +} +inline void BackendConfig::clear_onednn_matmul_config() { + if (GetArenaForAllocation() == nullptr && _impl_.onednn_matmul_config_ != nullptr) { + delete _impl_.onednn_matmul_config_; + } + _impl_.onednn_matmul_config_ = nullptr; +} +inline const ::xla::cpu::OneDnnMatMulConfig& BackendConfig::_internal_onednn_matmul_config() const { + const ::xla::cpu::OneDnnMatMulConfig* p = _impl_.onednn_matmul_config_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::cpu::_OneDnnMatMulConfig_default_instance_); +} +inline const ::xla::cpu::OneDnnMatMulConfig& BackendConfig::onednn_matmul_config() const { + // @@protoc_insertion_point(field_get:xla.cpu.BackendConfig.onednn_matmul_config) + return _internal_onednn_matmul_config(); +} +inline void BackendConfig::unsafe_arena_set_allocated_onednn_matmul_config( + ::xla::cpu::OneDnnMatMulConfig* onednn_matmul_config) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.onednn_matmul_config_); + } + _impl_.onednn_matmul_config_ = onednn_matmul_config; + if (onednn_matmul_config) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.cpu.BackendConfig.onednn_matmul_config) +} +inline ::xla::cpu::OneDnnMatMulConfig* BackendConfig::release_onednn_matmul_config() { + + ::xla::cpu::OneDnnMatMulConfig* temp = _impl_.onednn_matmul_config_; + _impl_.onednn_matmul_config_ = 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::cpu::OneDnnMatMulConfig* BackendConfig::unsafe_arena_release_onednn_matmul_config() { + // @@protoc_insertion_point(field_release:xla.cpu.BackendConfig.onednn_matmul_config) + + ::xla::cpu::OneDnnMatMulConfig* temp = _impl_.onednn_matmul_config_; + _impl_.onednn_matmul_config_ = nullptr; + return temp; +} +inline ::xla::cpu::OneDnnMatMulConfig* BackendConfig::_internal_mutable_onednn_matmul_config() { + + if (_impl_.onednn_matmul_config_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::cpu::OneDnnMatMulConfig>(GetArenaForAllocation()); + _impl_.onednn_matmul_config_ = p; + } + return _impl_.onednn_matmul_config_; +} +inline ::xla::cpu::OneDnnMatMulConfig* BackendConfig::mutable_onednn_matmul_config() { + ::xla::cpu::OneDnnMatMulConfig* _msg = _internal_mutable_onednn_matmul_config(); + // @@protoc_insertion_point(field_mutable:xla.cpu.BackendConfig.onednn_matmul_config) + return _msg; +} +inline void BackendConfig::set_allocated_onednn_matmul_config(::xla::cpu::OneDnnMatMulConfig* onednn_matmul_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.onednn_matmul_config_; + } + if (onednn_matmul_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(onednn_matmul_config); + if (message_arena != submessage_arena) { + onednn_matmul_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, onednn_matmul_config, submessage_arena); + } + + } else { + + } + _impl_.onednn_matmul_config_ = onednn_matmul_config; + // @@protoc_insertion_point(field_set_allocated:xla.cpu.BackendConfig.onednn_matmul_config) +} + +// ------------------------------------------------------------------- + +// OneDnnMatMulConfig + +// repeated .xla.cpu.OneDnnMatMulConfig.FusionKind fused_ops = 3; +inline int OneDnnMatMulConfig::_internal_fused_ops_size() const { + return _impl_.fused_ops_.size(); +} +inline int OneDnnMatMulConfig::fused_ops_size() const { + return _internal_fused_ops_size(); +} +inline void OneDnnMatMulConfig::clear_fused_ops() { + _impl_.fused_ops_.Clear(); +} +inline ::xla::cpu::OneDnnMatMulConfig_FusionKind OneDnnMatMulConfig::_internal_fused_ops(int index) const { + return static_cast< ::xla::cpu::OneDnnMatMulConfig_FusionKind >(_impl_.fused_ops_.Get(index)); +} +inline ::xla::cpu::OneDnnMatMulConfig_FusionKind OneDnnMatMulConfig::fused_ops(int index) const { + // @@protoc_insertion_point(field_get:xla.cpu.OneDnnMatMulConfig.fused_ops) + return _internal_fused_ops(index); +} +inline void OneDnnMatMulConfig::set_fused_ops(int index, ::xla::cpu::OneDnnMatMulConfig_FusionKind value) { + _impl_.fused_ops_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.cpu.OneDnnMatMulConfig.fused_ops) +} +inline void OneDnnMatMulConfig::_internal_add_fused_ops(::xla::cpu::OneDnnMatMulConfig_FusionKind value) { + _impl_.fused_ops_.Add(value); +} +inline void OneDnnMatMulConfig::add_fused_ops(::xla::cpu::OneDnnMatMulConfig_FusionKind value) { + _internal_add_fused_ops(value); + // @@protoc_insertion_point(field_add:xla.cpu.OneDnnMatMulConfig.fused_ops) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField& +OneDnnMatMulConfig::fused_ops() const { + // @@protoc_insertion_point(field_list:xla.cpu.OneDnnMatMulConfig.fused_ops) + return _impl_.fused_ops_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField* +OneDnnMatMulConfig::_internal_mutable_fused_ops() { + return &_impl_.fused_ops_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField* +OneDnnMatMulConfig::mutable_fused_ops() { + // @@protoc_insertion_point(field_mutable_list:xla.cpu.OneDnnMatMulConfig.fused_ops) + return _internal_mutable_fused_ops(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace cpu +} // namespace xla + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::xla::cpu::OneDnnMatMulConfig_FusionKind> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::cpu::OneDnnMatMulConfig_FusionKind>() { + return ::xla::cpu::OneDnnMatMulConfig_FusionKind_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fbackend_5fconfig_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/buffer_desc.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/buffer_desc.h new file mode 100644 index 0000000000000000000000000000000000000000..ec2e03b3dc8e5421fbcc3898ac32c00f3f874437 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/buffer_desc.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_CPU_BUFFER_DESC_H_ +#define XLA_SERVICE_CPU_BUFFER_DESC_H_ + +#include + +namespace xla { +namespace cpu { + +// BufferDesc for passing raw `buffer` (i.e. void ptr + size) arguments. +class BufferDesc { + public: + BufferDesc(void* data, size_t size) : data_(data), size_(size) {} + void* data() const { return data_; } + size_t size() const { return size_; } + + private: + void* data_; + size_t size_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_BUFFER_DESC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/buffer_info_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/buffer_info_util.h new file mode 100644 index 0000000000000000000000000000000000000000..5c3bf93e2182fa4eeeed1e7110cf7df5b690eccf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/buffer_info_util.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_CPU_BUFFER_INFO_UTIL_H_ +#define XLA_SERVICE_CPU_BUFFER_INFO_UTIL_H_ + +#include "absl/types/span.h" +#include "xla/cpu_function_runtime.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/buffer_assignment.h" + +namespace xla { +namespace cpu { +// Creates and returns a list of BufferInfo instances containing relevant +// information from `buffer_assignment`. +std::vector +CreateBufferInfosFromBufferAssignment( + const HloModule& module, const BufferAssignment& buffer_assignment); + +// Creates and returns a table containing the mapping from entry computation +// parameters to buffer allocation indices. +// +// If this function returns V then entry parameter i has buffer allocation index +// V[i]. +std::vector CreateArgIndexTableFromBufferInfos( + absl::Span buffer_infos); + +std::vector CreateResultIndexTableFromBufferInfos( + absl::Span buffer_infos); +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_BUFFER_INFO_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/compiler_functor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/compiler_functor.h new file mode 100644 index 0000000000000000000000000000000000000000..107492790e875463ed12b90f35df3d1d486bd54e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/compiler_functor.h @@ -0,0 +1,87 @@ +/* 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_SERVICE_CPU_COMPILER_FUNCTOR_H_ +#define XLA_SERVICE_CPU_COMPILER_FUNCTOR_H_ + +#include +#include +#include +#include + +#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" +#include "llvm/IR/LegacyPassManager.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Operator.h" +#include "llvm/Object/ObjectFile.h" +#include "llvm/Target/TargetMachine.h" +#include "xla/service/llvm_compiler.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace cpu { + +// Functor class for compiling an LLVM module down to an object file. For use by +// Orc JIT compile layer. +class CompilerFunctor : public llvm::orc::IRCompileLayer::IRCompiler { + public: + explicit CompilerFunctor( + llvm::TargetMachine* target_machine, int opt_level, + bool optimize_for_size, bool disable_expensive_passes, + bool disable_slp_vectorizer, llvm::FastMathFlags fast_math_flags, + LLVMCompiler::ModuleHook pre_optimization_hook = nullptr, + LLVMCompiler::ModuleHook post_optimization_hook = nullptr, + std::function post_codegen_hook = + nullptr, + bool dfsan_enabled = false, + const std::vector& dfsan_abi_list_files = {}, + const std::vector& convert_to_xla_runtime_abi = {}) + : IRCompiler(llvm::orc::IRSymbolMapper::ManglingOptions()), + target_machine_(target_machine), + opt_level_(opt_level), + optimize_for_size_(optimize_for_size), + disable_expensive_passes_(disable_expensive_passes), + disable_slp_vectorizer_(disable_slp_vectorizer), + fast_math_flags_(fast_math_flags), + pre_optimization_hook_(std::move(pre_optimization_hook)), + post_optimization_hook_(std::move(post_optimization_hook)), + post_codegen_hook_(std::move(post_codegen_hook)), + dfsan_enabled_(dfsan_enabled), + dfsan_abi_list_files_(dfsan_abi_list_files), + convert_to_xla_runtime_abi_(convert_to_xla_runtime_abi) {} + + // Compile a Module to an ObjectFile. + llvm::Expected> operator()( + llvm::Module& module) override; + + private: + llvm::TargetMachine* target_machine_; + const unsigned opt_level_; + const bool optimize_for_size_; + const bool disable_expensive_passes_; + const bool disable_slp_vectorizer_; + const llvm::FastMathFlags fast_math_flags_; + LLVMCompiler::ModuleHook pre_optimization_hook_; + LLVMCompiler::ModuleHook post_optimization_hook_; + std::function post_codegen_hook_; + const bool dfsan_enabled_ = false; + const std::vector dfsan_abi_list_files_; + const std::vector convert_to_xla_runtime_abi_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_COMPILER_FUNCTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/conv_canonicalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/conv_canonicalization.h new file mode 100644 index 0000000000000000000000000000000000000000..7e7ad06b8e91405966b6eb93c1d7988579918abc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/conv_canonicalization.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_CPU_CONV_CANONICALIZATION_H_ +#define XLA_SERVICE_CPU_CONV_CANONICALIZATION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/cpu/target_machine_features.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace cpu { + +// An HLO pass that canonicalizes the dimension numbers of all top-level +// convolutions in the given module. +// +// In order to hit the fast path of using Eigen's convolution implementation, a +// convolution's dimension numbers need to satisfy certain constraints (so +// called canonical convolutions). This pass expands non-canonical convolutions +// into reshapes and canonical convolutions, so that these non-canonical +// convolutions can run faster. +class ConvCanonicalization : public HloModulePass { + public: + explicit ConvCanonicalization( + const TargetMachineFeatures* target_machine_features) + : target_machine_features_(*target_machine_features) {} + + ~ConvCanonicalization() override {} + absl::string_view name() const override { + return "convolution-canonicalization"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const TargetMachineFeatures& target_machine_features_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_CONV_CANONICALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..a6bce23d574b2fe952c1dc31356fd1b866a8995b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_compiler.h @@ -0,0 +1,251 @@ +/* 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_SERVICE_CPU_CPU_COMPILER_H_ +#define XLA_SERVICE_CPU_CPU_COMPILER_H_ + +#include +#include +#include +#include +#include + +#include "llvm/Target/TargetMachine.h" +#include "xla/cpu_function_runtime.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_module_group.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/compiler.h" +#include "xla/service/cpu/executable.pb.h" +#include "xla/service/cpu/target_machine_features.h" +#include "xla/service/executable.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_profile_printer_data.pb.h" +#include "xla/service/llvm_compiler.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/util.h" + +namespace xla { +namespace cpu { + +class CpuExecutable; +class XlaFrameworkMapping; + +// This class wraps the configurability options that LLVM exposes including: the +// target triple, the target cpu and the target features. It also includes the +// desired linkage name for the computation entry point. +class CpuAotCompilationOptions : public AotCompilationOptions { + public: + // Relocation models available for compilation. + enum class RelocationModel { + // Corresponds to the -fno-pic compiler option. + Static, + // Corresponds to the -fpic compiler option. + SmallPic, + // Corresponds to the -fPIC compiler option. + BigPic, + // Corresponds to the -fpie compiler option. + SmallPie, + // Corresponds to the -fPIE compiler option. + BigPie + }; + + CpuAotCompilationOptions(std::string triple, std::string cpu_name, + std::string features, std::string entry_point_name, + RelocationModel relocation_model); + + ~CpuAotCompilationOptions() override; + + se::Platform::Id PlatformId() const override; + + // The triple used for compilation, similar to clang's -target flag. + const std::string& triple() const { return triple_; } + // The CPU name used for compilation, similar to clang's -mcpu flag. + const std::string& cpu_name() const { return cpu_name_; } + // The target features used for compilation ("+avx2", "+neon", etc). + const std::string& features() const { return features_; } + // The name to be used for the compiled code's entry point. + const std::string& entry_point_name() const { return entry_point_name_; } + // The relocation model used for compilation. + RelocationModel relocation_model() const { return relocation_model_; } + + bool use_mlir_hlo_lowering() const { return use_mlir_hlo_lowering_; } + void set_use_mlir_hlo_lowering(bool value) { use_mlir_hlo_lowering_ = value; } + + private: + const std::string triple_; + const std::string cpu_name_; + const std::string features_; + const std::string entry_point_name_; + const RelocationModel relocation_model_; + bool use_mlir_hlo_lowering_ = false; +}; + +class CpuXlaRuntimeAotCompilationResult : public AotCompilationResult { + public: + CpuXlaRuntimeAotCompilationResult(HloModuleProto hlo, + std::string_view obj_file, + std::string_view mlir_module, + XlaFrameworkMapping xla_framework_mapping); + + explicit CpuXlaRuntimeAotCompilationResult( + XlaRuntimeCpuExecutableProto executable) + : xla_runtime_cpu_executable_(executable) {} + + StatusOr SerializeAsString() const override { + return xla_runtime_cpu_executable_.SerializeAsString(); + } + + static StatusOr> + FromString(const std::string& serialized) { + XlaRuntimeCpuExecutableProto xla_runtime_cpu_executable; + if (!xla_runtime_cpu_executable.ParseFromString(serialized)) { + return InternalError("Failed to parse serialized JitRtExecutableProto."); + } + return std::make_unique( + xla_runtime_cpu_executable); + } + + StatusOr> LoadExecutable( + Compiler* compiler, se::StreamExecutor* executor) const override; + + private: + XlaRuntimeCpuExecutableProto xla_runtime_cpu_executable_; +}; + +class CpuAotCompilationResult : public AotCompilationResult { + public: + CpuAotCompilationResult( + ObjectFileData object_file_data, + std::vector buffer_infos, + int64_t result_buffer_index, + std::unique_ptr hlo_profile_printer_data); + ~CpuAotCompilationResult() override = default; + + HloProfilePrinterData* hlo_profile_printer_data() const { + return hlo_profile_printer_data_.get(); + } + + const ObjectFileData& object_file_data() const { return object_file_data_; } + const std::vector& buffer_infos() const { + return buffer_infos_; + } + int64_t result_buffer_index() const { return result_buffer_index_; } + + private: + // Contains the compiled computation: an object file. + const ObjectFileData object_file_data_; + + // A list of BufferInfo objects describing the buffers used by the XLA + // computation. + const std::vector buffer_infos_; + + // Contains which buffer index into |buffer_sizes| was designated to the + // result of the computation. This buffer should be passed into the output + // parameter when calling the compiled computation. + const int64_t result_buffer_index_; + + // Contains an instance of HloProfilePrinterData if HLO profiling is enabled, + // otherwise is nullptr. + std::unique_ptr hlo_profile_printer_data_; +}; + +// CPU-targeting implementation of the XLA Compiler interface. +// +// The compiler translates XLA HLO code into LLVM IR and uses LLVM's JIT +// infrastructure to create an executable "blob" that can then be returned +// wrapped in CpuExecutable and actually invoked. +class CpuCompiler : public LLVMCompiler { + public: + CpuCompiler(); + explicit CpuCompiler(bool allow_sparse_shapes); + ~CpuCompiler() override = default; + + StatusOr>> Compile( + std::unique_ptr module_group, + std::vector> stream_execs, + const CompileOptions& options) override; + + StatusOr> RunHloPasses( + std::unique_ptr module, se::StreamExecutor* stream_exec, + const CompileOptions& options) override; + + StatusOr> AssignBuffers( + HloModule* module, se::StreamExecutor* stream_exec) override; + + StatusOr> RunBackend( + std::unique_ptr module, se::StreamExecutor* stream_exec, + const CompileOptions& options) override; + + StatusOr>> + CompileAheadOfTime(std::unique_ptr module_group, + const AotCompilationOptions& options) override; + + se::Platform::Id PlatformId() const override; + + HloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const override; + + StatusOr> Export( + Executable* executable) const override; + + // Returns a (deserialized) AotCompilationResult from a serialized + // AotCompilationResult. + StatusOr> LoadAotCompilationResult( + const std::string& serialized_aot_result) override { + return CpuXlaRuntimeAotCompilationResult::FromString(serialized_aot_result); + } + + StatusOr> CompileXlaRuntimeCpuExecutable( + std::unique_ptr module); + + private: + // Initialize the LLVM target. + static void InitializeLLVMTarget(); + + // Runs the HLO passes which are necessary for both optimizations and + // correctness. + Status RunHloPasses(HloModule* module, bool is_aot_compile, + llvm::TargetMachine* target_machine, + bool is_mlir_compile = false); + + // Runs HLO passes up to and including layout assignment. + Status RunHloPassesThroughLayoutAssn( + HloModule* module, bool /*is_aot_compile*/, + LLVMTargetMachineFeatures* target_machine_features, + bool is_mlir_compile = false); + + // Runs HLO passes after layout assignment. + Status RunHloPassesAfterLayoutAssn( + HloModule* module, bool is_aot_compile, + LLVMTargetMachineFeatures* target_machine_features, bool is_mlir_compile); + + StatusOr> CompileLegacyCpuExecutable( + std::unique_ptr module); + + CpuCompiler(const CpuCompiler&) = delete; + CpuCompiler& operator=(const CpuCompiler&) = delete; + + // Flag that can be used to override bail-out on sparse shapes. + // When set, buffer assignment assigns zero sizes to these shapes. + const bool allow_sparse_shapes_ = false; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_executable.h new file mode 100644 index 0000000000000000000000000000000000000000..d7d40051569e8127885443a35c84c2d717a5f2a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_executable.h @@ -0,0 +1,296 @@ +/* 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_SERVICE_CPU_CPU_EXECUTABLE_H_ +#define XLA_SERVICE_CPU_CPU_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/runtime/executable.h" +#include "xla/runtime/ffi.h" +#include "xla/runtime/jit_executable.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/cpu/buffer_desc.h" +#include "xla/service/cpu/simple_orc_jit.h" +#include "xla/service/cpu/xla_framework.h" +#include "xla/service/custom_call_status_internal.h" +#include "xla/service/executable.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_execution_profile.h" +#include "xla/service/shaped_buffer.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 { +namespace cpu { + +class XlaRuntimeCpuExecutable { + using FfiModulesState = ::xla::runtime::ffi::FfiModulesState; + + public: + explicit XlaRuntimeCpuExecutable( + std::unique_ptr jit_executable, + const XlaFrameworkMapping& xla_framework_mapping, + FfiModulesState ffi_modules_state) + : executable_(std::move(jit_executable)), + xla_framework_mapping_(xla_framework_mapping), + ffi_modules_state_(std::move(ffi_modules_state)) { + runtime::ffi::ExportFfiModules(dynamic_custom_calls_); + } + + explicit XlaRuntimeCpuExecutable( + std::unique_ptr executable, + const XlaFrameworkMapping& xla_framework_mapping, + FfiModulesState ffi_modules_state) + : executable_(std::move(executable)), + xla_framework_mapping_(xla_framework_mapping), + ffi_modules_state_(std::move(ffi_modules_state)) { + runtime::ffi::ExportFfiModules(dynamic_custom_calls_); + } + + Status Execute(const std::vector& descriptor_table, + const ExecutableRunOptions* run_options); + + runtime::Executable& GetExecutable() { + if (std::holds_alternative>( + executable_)) { + runtime::JitExecutable* jit_executable = + std::get>(executable_).get(); + return *jit_executable->DefaultExecutable(); + } else { + runtime::Executable* aot_executable = + std::get>(executable_).get(); + return *aot_executable; + } + } + + StatusOr GetObjFile() const { + if (!std::holds_alternative>( + executable_)) { + return InternalError("No JitExecutable"); + } + + runtime::JitExecutable* jit_executable = + std::get>(executable_).get(); + std::unique_ptr obj_file = + jit_executable->DefaultExecutable()->obj_file(); + if (!obj_file) + return InternalError("XlaRuntimeCpuExecutable didn't save the obj file"); + + return std::string_view(obj_file->getBuffer()); + } + + StatusOr GetMlirModule() const { + if (!std::holds_alternative>( + executable_)) { + return InternalError("No JitExecutable"); + } + + runtime::JitExecutable* jit_executable = + std::get>(executable_).get(); + return jit_executable->mlir_module(); + } + + XlaFrameworkMapping xla_framework_mapping() { return xla_framework_mapping_; } + + private: + // In JIT compilation mode `JitExecutable` is used. In AOT compilation mode + // `Executable` is used. + std::variant, + std::unique_ptr> + executable_; + + XlaFrameworkMapping xla_framework_mapping_; + + // Keeps an executable state for all registered FFI modules. + FfiModulesState ffi_modules_state_; + + // Dynamic custom calls exported from XLA runtime modules (and FFI modules). + runtime::DynamicCustomCallRegistry dynamic_custom_calls_; +}; + +// CPU-targeting implementation of the XLA Executable interface. +// +// Wraps a JIT-ed object that can be executed "on device". We JIT for the host +// architecture, so JIT-ed code and host code share the same ABI. +class CpuExecutable : public Executable { + public: + static StatusOr> Create( + std::unique_ptr jit, + std::unique_ptr assignment, + std::unique_ptr hlo_module, + const std::string& entry_function_name, + std::unique_ptr hlo_profile_printer_data, + std::unique_ptr hlo_profile_index_map); + // XLA Runtime factory method. + static StatusOr> Create( + std::unique_ptr hlo_module, + std::unique_ptr hlo_profile_printer_data, + std::unique_ptr hlo_profile_index_map, + std::unique_ptr assignment, + std::unique_ptr xla_runtime_executable); + + ~CpuExecutable() override; + + bool IsXlaRuntime() const { return xla_runtime_executable_ != nullptr; } + + Status ExecuteXlaRuntime( + const std::vector& descriptor_table, + const ExecutableRunOptions* run_options = nullptr) const { + return xla_runtime_executable_->Execute(descriptor_table, run_options); + } + + StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + std::vector arguments, + HloExecutionProfile* hlo_execution_profile) override; + + // Calls the generated function performing the computation with the given + // arguments using the supplied buffers. + Status ExecuteComputeFunction( + const ExecutableRunOptions* run_options, + absl::Span buffers, + HloExecutionProfile* hlo_execution_profile); + + // Returns an Executable that is loaded from an object file (XLA program + // compiled to a native function using the XLA Runtime stack). + static StatusOr> LoadFromObjFile( + std::unique_ptr hlo_module, absl::string_view obj_file, + absl::string_view mlir_module, + std::unique_ptr buffer_assignment, + XlaFrameworkMapping xla_framework_mapping, + runtime::JitExecutable::Options opts); + + // This should be called after set_ir_module_string. + const std::string& ir_module_string() const { return ir_module_string_; } + + void set_ir_module_string(const std::string& ir_module_string) { + ir_module_string_ = ir_module_string; + } + + static int64_t ShapeSizeBytes(const Shape& shape); + + // Type of the computation function we expect in the JIT. + using ComputeFunctionType = + void (*)(void* /*result*/, const ExecutableRunOptions* /*run_options*/, + const void** /*args*/, void** /*buffer_table*/, + XlaCustomCallStatus* /*status*/, int64_t* /*profile_counters*/); + + const ComputeFunctionType& compute_function() const { + return compute_function_; + } + + const BufferAssignment& buffer_assignment() const { return *assignment_; } + + int64_t SizeOfGeneratedCodeInBytes() const override; + + StatusOr GetObjFile() const { + if (!IsXlaRuntime()) return Unimplemented("Not an XLA Runtime executable"); + return xla_runtime_executable_->GetObjFile(); + } + + StatusOr GetMlirModule() const { + if (!IsXlaRuntime()) return Unimplemented("Not an XLA Runtime executable"); + return xla_runtime_executable_->GetMlirModule(); + } + + StatusOr GetXlaFrameworkMapping() const { + if (!IsXlaRuntime()) return Unimplemented("Not an XLA Runtime executable"); + return xla_runtime_executable_->xla_framework_mapping(); + } + + private: + // Creates an array suitable for passing as the "buffer_table" argument to the + // JIT compiled function pointer. + // + // Returns (unowning_buffers, owning_buffers) where: + // + // - unowning_buffers.data() can be passed as the buffer_table argument as-is + // and includes pointers to the scratch storage required by the + // computation, the live-out buffer into which the result will be written + // and entry computation parameters. + // + // - owning_buffers contains owning pointers to the buffers that were + // allocated by this routine. This routine allocates buffers for temporary + // storage and the live-out buffer into which the computation writes it + // result. + // + // - buffers_to_free: buffers whose ownership was donated by the caller that + // are to be freed by the caller. + StatusOr> CreateBufferTable( + se::DeviceMemoryAllocator* memory_allocator, int device_ordinal, + absl::Span arguments); + + // Creates an Execution output holding ScopedShapedBuffer for holding the + // result of the computation, moving buffers out of allocated_buffers and into + // the result as appropriate. The addresses are set according to buffer + // assignment. + StatusOr CreateResultShapedBuffer( + const ServiceExecutableRunOptions* run_options, + absl::Span buffers, + absl::Span arguments); + + // Returns the instruction value set of the root instruction of the entry + // computation. Uses dataflow analysis from buffer assignment. + const InstructionValueSet& GetRootValueSet() const; + + // The JIT containing compiled modules. + std::unique_ptr jit_; + + // Buffer assignment for the buffers we need to allocate. + const std::unique_ptr assignment_; + + std::shared_ptr buffer_assignment_; + + // The LLVM IR, in string format, of the unoptimized module generated for this + // CpuExecutable. We save a string instead of an llvm::Module* because leaving + // llvm::Module* in a singleton can cause the heap checker to emit false + // positives. + std::string ir_module_string_; + + // Unique identifier. + std::string module_name_; + + ComputeFunctionType compute_function_; + + // Entry function name for the computation. + const std::string entry_function_name_; + + // If not null, XLA Runtime is enabled. + std::unique_ptr xla_runtime_executable_; + + CpuExecutable(std::unique_ptr hlo_module, + std::unique_ptr hlo_profile_printer_data, + std::unique_ptr hlo_profile_index_map, + std::unique_ptr assignment); + CpuExecutable(const CpuExecutable&) = delete; + CpuExecutable& operator=(const CpuExecutable&) = delete; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_instruction_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_instruction_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..1e090cb69b3967f840bf7c6b3b91edd655e83db9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_instruction_fusion.h @@ -0,0 +1,60 @@ +/* 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_SERVICE_CPU_CPU_INSTRUCTION_FUSION_H_ +#define XLA_SERVICE_CPU_CPU_INSTRUCTION_FUSION_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/fusion_node_indexing_evaluation.h" +#include "xla/service/instruction_fusion.h" + +namespace xla { +namespace cpu { + +class CpuInstructionFusion : public InstructionFusion { + public: + CpuInstructionFusion() + : InstructionFusion(CpuInstructionFusion::IsExpensive) {} + ~CpuInstructionFusion() override = default; + + using HloPassInterface::Run; + StatusOr Run(HloModule* module, + const absl::flat_hash_set& + execution_threads) override { + fusion_node_evaluations_.clear(); + return InstructionFusion::Run(module, execution_threads); + } + + protected: + FusionDecision ShouldFuse(HloInstruction* consumer, + int64_t operand_index) override; + HloInstruction::FusionKind ChooseKind( + const HloInstruction* producer, const HloInstruction* consumer) override; + + private: + HloInstruction* FuseInstruction(HloInstruction* fusion_instruction, + HloInstruction* producer) override; + + // Keep track of the number of times each instruction inside a fusion node is + // indexed with different index vectors. + absl::flat_hash_map + fusion_node_evaluations_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_INSTRUCTION_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_layout_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_layout_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..3c0bdb7fc2ea32150aef8ecfef76adc1278026ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_layout_assignment.h @@ -0,0 +1,48 @@ +/* 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_SERVICE_CPU_CPU_LAYOUT_ASSIGNMENT_H_ +#define XLA_SERVICE_CPU_CPU_LAYOUT_ASSIGNMENT_H_ + +#include "xla/service/computation_layout.h" +#include "xla/service/cpu/target_machine_features.h" +#include "xla/service/layout_assignment.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace cpu { + +// CPU-specific layout assignment pass which preassigns layouts to satisfy +// layout constraints for operands and results of library calls. +class CpuLayoutAssignment : public LayoutAssignment { + public: + explicit CpuLayoutAssignment( + ComputationLayout* entry_computation_layout, + const TargetMachineFeatures* target_machine_features, + ChannelLayoutConstraints* channel_constraints = nullptr) + : LayoutAssignment(entry_computation_layout, channel_constraints), + target_machine_features_(*target_machine_features) {} + ~CpuLayoutAssignment() override {} + + protected: + Status AddBackendConstraints(LayoutConstraints* constraints) override; + + const TargetMachineFeatures& target_machine_features_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_LAYOUT_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_options.h new file mode 100644 index 0000000000000000000000000000000000000000..41b60b0f71da6cf71acd110f1794e9ca520158ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_options.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_CPU_CPU_OPTIONS_H_ +#define XLA_SERVICE_CPU_CPU_OPTIONS_H_ + +#include "xla/service/hlo_module_config.h" + +// Helper functions for querying options that are specific to the CPU backend. + +namespace xla { +namespace cpu { +namespace options { + +bool OptimizeForSizeRequested(const HloModuleConfig& config); +bool VectorizedReduceDisabled(const HloModuleConfig& config); +bool SlpVectorizerDisabled(const HloModuleConfig& config); +bool ForceEnableExperimentalLlvmIrGemm(const HloModuleConfig& config); +std::optional LlvmIrGemvTilingFactor(const HloModuleConfig& config); +std::optional> LlvmIrGemmTileSize( + const HloModuleConfig& config); + +} // namespace options +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..e483b8c9e8a41f82314ddfd660ed469901146e68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_runtime.h @@ -0,0 +1,207 @@ +/* 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. +==============================================================================*/ + +// This header declares functions which may be called by the generated code on +// the CPU. Calls to these functions must be resolved explicitly in the JIT in +// xla::cpu::SimpleResolver. It also defines a per-CpuExecutable context +// which is used to cache expensive state and resources utilized by the +// aforementioned functions. +// +// Other functions are declared in individual libraries as well, such as +// runtime_conv2d and runtime_matmul. As individual libraries, callers for +// ahead-of-time compilation can link only the required subset. + +#ifndef XLA_SERVICE_CPU_CPU_RUNTIME_H_ +#define XLA_SERVICE_CPU_CPU_RUNTIME_H_ + +#include "xla/executable_run_options.h" +#include "xla/service/cpu/xfeed_manager.h" + +namespace xla { +namespace cpu { +namespace runtime { + +// Names of runtime functions. These get resolved from the generated code to the +// right symbol at link time in one of two ways: +// 1. When using the JIT, the symbol resolver (SimpleResolver in +// third_party/tensorflow/compiler/xla/service/cpu/simple_orc_jit.cc) maps +// this symbol name to +// the actual symbol. +// 2. When using ahead-of-time compilation, the linker can resolve the name +// because it is a symbol in the cpu_runtime library. +extern const char* const kEigenMatMulF16SymbolName; +extern const char* const kEigenMatMulF32SymbolName; +extern const char* const kEigenMatMulF64SymbolName; +extern const char* const kEigenMatMulC64SymbolName; +extern const char* const kEigenMatMulC128SymbolName; +extern const char* const kEigenMatMulS32SymbolName; +extern const char* const kEigenBatchMatMulF32SymbolName; +extern const char* const kMKLConv2DF32SymbolName; +extern const char* const kACLConv2DF32SymbolName; +extern const char* const kACLMatMulF32SymbolName; +extern const char* const kACLBatchMatMulF32SymbolName; +extern const char* const kEigenConv2DF16SymbolName; +extern const char* const kEigenConv2DF32SymbolName; +extern const char* const kEigenConv3DF16SymbolName; +extern const char* const kEigenConv3DF32SymbolName; +extern const char* const kEigenFftSymbolName; +extern const char* const kEigenSingleThreadedFftSymbolName; +extern const char* const kEigenSingleThreadedMatMulF16SymbolName; +extern const char* const kEigenSingleThreadedMatMulF32SymbolName; +extern const char* const kEigenSingleThreadedMatMulF64SymbolName; +extern const char* const kEigenSingleThreadedMatMulC64SymbolName; +extern const char* const kEigenSingleThreadedMatMulC128SymbolName; +extern const char* const kEigenSingleThreadedMatMulS32SymbolName; +extern const char* const kEigenSingleThreadedConv2DF16SymbolName; +extern const char* const kEigenSingleThreadedConv2DF32SymbolName; +extern const char* const kEigenSingleThreadedConv3DF16SymbolName; +extern const char* const kEigenSingleThreadedConv3DF32SymbolName; +extern const char* const kAcquireInfeedBufferForDequeueSymbolName; +extern const char* const kReleaseInfeedBufferAfterDequeueSymbolName; +extern const char* const kAcquireOutfeedBufferForPopulationSymbolName; +extern const char* const kReleaseOutfeedBufferAfterPopulationSymbolName; +extern const char* const kParallelForkJoinSymbolName; +extern const char* const kPrintfToStderrSymbolName; +extern const char* const kStatusIsSuccessSymbolName; +extern const char* const kKeyValueSortSymbolName; +extern const char* const kTopKF32SymbolName; +extern const char* const kAllReduceSymbolName; +extern const char* const kCollectivePermuteSymbolName; +extern const char* const kPartitionIdSymbolName; +extern const char* const kReplicaIdSymbolName; +extern const char* const kTracingStartSymbolName; +extern const char* const kTracingEndSymbolName; +extern const char* const kAllToAllSymbolName; +extern const char* const kOneDnnMatMulSymbolName; + +// All symbol names for XLA CPU runtime functions need to start with this +// prefix. +extern const char* const kXlaCpuRuntimeSymbolNamePrefix; + +// Returns the infeed manager used by the CPU runtime for the CPU device +// `device_ordinal`. Note the device ordinal does not name a CPU +XfeedManager* GetXfeedManager(int device_ordinal); + +} // namespace runtime +} // namespace cpu +} // namespace xla + +extern "C" { + +extern int __xla_cpu_runtime_PrintfToStderr(const char* format, ...); + +extern int64_t __xla_cpu_runtime_TracingStart( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + const char* name); +extern void __xla_cpu_runtime_TracingEnd( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, int64_t id); + +// Some things common to all of the runtime entry points below: +// +// * The shape pointer and shape_length reflect values that can be deserialized +// via llvm_ir::DecodeSelfDescribingShapeConstant. This is the way we pass +// reified type information from the generated program to the runtime, which +// helps check the type safety and contract for the emitted-code/runtime +// communication. +// +// * run_options is used to look up the device ordinal for the stream executor +// we're executing under. If it is null the device ordinal is assumed to be +// 0 (this behavior helps in writing tests). + +// Note: in the runtime entry points below, the shape pointer and shape_length +// reflect values that can be deserialized via +// llvm_ir::DecodeSelfDescribingShapeConstant. This is the way we pass reified +// type information from the generated program to the runtime, which helps check +// the type safety and contract for the emitted-code/runtime communication. + +// Blocks until the next infeed buffer is ready to be dequeued, then +// returns it. Fails catastrophically if the next enqueued buffer is +// not of the correct length in bytes. Checking the shape rather than +// the length would be more exact, but the length check is chosen as a +// tradeoff between error checking and speed/simplicity. +extern void* __xla_cpu_runtime_AcquireInfeedBufferForDequeue( + const xla::ExecutableRunOptions* run_options, int32_t buffer_length, + const void* shape, int32_t shape_length); + +// Relinquishes the next infeed buffer that was returned by +// __xla_cpu_runtime_AcquireInfeedBufferForDequeue. Once this call +// completes the data at buffer_ptr may no longer be +// accessed. buffer_length must match the length passed to the call to +// __xla_cpu_runtime_AcquireInfeedBufferForDequeue that returned +// buffer_ptr. This function must be called before the next buffer is +// acquired, i.e., there may only be one outstanding infeed buffer in +// use by the runtime. TODO(b/31340454) investigate whether or not it +// is worth supporting zero-copy infeed where the buffer is retained +// by the compiled code until it has been used. If zero-copy infeed is +// implemented we will add support for multiple outstanding buffers +// that can be returned out of order. +extern void __xla_cpu_runtime_ReleaseInfeedBufferAfterDequeue( + const xla::ExecutableRunOptions* run_options, int32_t buffer_length, + void* buffer_ptr, const void* shape_ptr, int32_t shape_length); + +// Blocks until the next outfeed buffer is available to be populated, then +// returns it. +extern void* __xla_cpu_runtime_AcquireOutfeedBufferForPopulation( + const xla::ExecutableRunOptions* run_options, int32_t buffer_length, + const void* shape_ptr, int32_t shape_length); + +// Relinquishes the outfeed buffer after it has been populated. +// buffer_ptr must have been previously returned by +// __xla_cpu_runtime_AcquireOutfeedBufferForPopulation. +// Once this call completes, buffer_ptr may no longer be accessed. +// buffer_length must match the length passed to the call to +// __xla_cpu_runtime_AcquireInfeedBufferForDequeue that returned +// buffer_ptr. This function must be called before the next buffer is +// acquired, i.e., there may only be one outstanding outfeed buffer in +// use by the runtime. +extern void __xla_cpu_runtime_ReleaseOutfeedBufferAfterPopulation( + const xla::ExecutableRunOptions* run_options, int32_t buffer_length, + void* buffer_ptr, const void* shape_ptr, int32_t shape_length); + +// Perform all reduce on a CPU. +// +// participating_replicas: array of replica IDs participating in the reduction, +// cf. GetParticipatingIDs. +// channel_id_present, op_id: whether op_id is a channel ID or a module ID. +// reduction_kind: operator used for a reduction, cf. ReductionKind. +// shape_ptr: shape of all input/output buffers. +extern void __xla_cpu_runtime_AllReduce( + const xla::ExecutableRunOptions* run_options, + const void* replica_groups_str, int32_t replica_groups_str_size, + int32_t channel_id_present, int32_t use_global_device_ids, int64_t op_id, + int32_t reduction_kind, const void* shape_ptr, int32_t shape_length, + int32_t num_buffers, void** input_buffers, void** output_buffers); + +extern void __xla_cpu_runtime_CollectivePermute( + const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, + int64_t op_id, int32_t byte_size, void* input_buffer, void* output_buffer, + const void* source_target_pairs, int32_t source_target_pairs_size); + +extern void __xla_cpu_runtime_AllToAll( + const xla::ExecutableRunOptions* run_options, int32_t channel_id_present, + int64_t op_id, const void* replica_groups_str, + int32_t replica_groups_str_size, int32_t num_buffers, int64_t buffer_size, + void** source_buffers, void** destination_buffers); + +// Write the partition ID into the output buffer. +extern void __xla_cpu_runtime_PartitionId( + const xla::ExecutableRunOptions* run_options, void* output_buffer); +// Write the replica ID into the output buffer. +extern void __xla_cpu_runtime_ReplicaId( + const xla::ExecutableRunOptions* run_options, void* output_buffer); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_CPU_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_transfer_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_transfer_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4ce26e39803186eb9f22bd7b37d3533c65196268 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_transfer_manager.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_CPU_CPU_TRANSFER_MANAGER_H_ +#define XLA_SERVICE_CPU_CPU_TRANSFER_MANAGER_H_ + +#include + +#include "absl/types/span.h" +#include "xla/literal.h" +#include "xla/service/cpu/xfeed_manager.h" +#include "xla/service/generic_transfer_manager.h" +#include "xla/service/transfer_manager.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// An implementation of the XLA GenericTransferManager that +// handles CPU-specific infeed. +class CpuTransferManager : public GenericTransferManager { + public: + CpuTransferManager(); + ~CpuTransferManager() override {} + + Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal) override; + Status TransferLiteralFromOutfeed(se::StreamExecutor* executor, + MutableBorrowingLiteral literal) override; + + bool CanShapedBufferBeAccessedNow( + se::StreamExecutor* executor, + const ShapedBuffer& device_buffer) const override { + return true; + } + + bool CanBufferBeAccessedNow( + se::StreamExecutor* executor, + const se::DeviceMemoryBase& device_buffer) const override { + return true; + } + + Status ReadDynamicShapes(se::Stream* stream, + const ShapedBuffer* device_buffer, + Shape* device_shape) override; + + private: + CpuTransferManager(const CpuTransferManager&) = delete; + CpuTransferManager& operator=(const CpuTransferManager&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_TRANSFER_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_xfeed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_xfeed.h new file mode 100644 index 0000000000000000000000000000000000000000..418768f6c9e3a642b5abe2bdef73f69d5b731665 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/cpu_xfeed.h @@ -0,0 +1,46 @@ +/* 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_SERVICE_CPU_CPU_XFEED_H_ +#define XLA_SERVICE_CPU_CPU_XFEED_H_ + +#include + +#include "xla/literal.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/shaped_buffer.h" +#include "xla/status.h" + +// This provides a lower level API than TransferManager that does not depend on +// StreamExecutor. It is intended to be used by callers that do not want to use +// Stream or StreamExecutor. + +namespace xla { + +// Helper function to transfers to infeed on CPU. +Status TransferLiteralToInfeedOnCpu(int device_ordinal, + const LiteralSlice& literal); + +// Helper function to transfers from outfeed on CPU. +Status TransferLiteralFromOutfeedOnCpu(int device_ordinal, + MutableBorrowingLiteral literal); + +// Helper function to retrieve dynamic shape on CPU. +Status ReadDynamicShapesOnCpu(const ShapedBuffer* device_buffer, + Shape* device_shape, + HloCostAnalysis::ShapeSizeFunction shape_size_fn); +} // namespace xla + +#endif // XLA_SERVICE_CPU_CPU_XFEED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/dot_op_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/dot_op_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..df59c5410264c4cb0fdb21f13cd67890991e0305 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/dot_op_emitter.h @@ -0,0 +1,72 @@ +/* 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_SERVICE_CPU_DOT_OP_EMITTER_H_ +#define XLA_SERVICE_CPU_DOT_OP_EMITTER_H_ + +#include "absl/strings/string_view.h" +#include "llvm/IR/IRBuilder.h" +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/cpu/cpu_options.h" +#include "xla/service/cpu/target_machine_features.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/llvm_loop.h" +#include "xla/types.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace cpu { +// Returns true if the two operands and the output of `dot_instr` must have row +// major layout. +bool DotOperandsAndResultMustHaveRowMajorLayout( + const HloInstruction& dot_instr, + const TargetMachineFeatures& target_machine_features); + +// Returns true our lowering strategy for `dot_instr` can fold in transposes to +// the either of the inputs. +bool DotImplementationCanHandleTranspose( + const HloInstruction& dot_instr, + const TargetMachineFeatures& target_machine_features); + +// Returns the index for an operand to `hlo` that should ideally be column +// major. Returns nullopt if there is no such operand or if `hlo` is not a dot +// or a fusion containing a dot. +std::optional ProfitableToMakeDotOperandColumnMajor( + const HloInstruction& hlo); + +// Emit LLVM IR to perform the dot operation on lhs_array and rhs_array and +// place the result in target_array. IR is emitted at current insert point of +// the builder. Upon completion of the method, the insert point is set to the +// end of all instructions emitted for this operation. +// +// If `addend_array` is not nullptr then it must be an array of the same +// dimensions as the result, and the result is computed as `addend_array` + +// dot(`lhs_array`, `rhs_array`). A non-null `addend_array` is only supported +// for Matrix-vector products. +Status EmitDotOperation(const HloInstruction& dot, + const llvm_ir::IrArray& target_array, + const llvm_ir::IrArray& lhs_array, + const llvm_ir::IrArray& rhs_array, + const llvm_ir::IrArray* addend_array, + llvm::Value* executable_run_options_value, + llvm::IRBuilder<>* b, mlir::MLIRContext* mlir_context, + const HloModuleConfig& hlo_module_config, + const TargetMachineFeatures& target_machine_features); +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_DOT_OP_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/elemental_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/elemental_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..8d2efb0fce4a54a3bf59cae43a685ad3b0352553 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/elemental_ir_emitter.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_SERVICE_CPU_ELEMENTAL_IR_EMITTER_H_ +#define XLA_SERVICE_CPU_ELEMENTAL_IR_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/cpu/ir_emitter.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/statusor.h" + +namespace xla { +namespace cpu { + +class CpuElementalIrEmitter : public ElementalIrEmitter { + public: + CpuElementalIrEmitter(const HloModuleConfig& module_config, + IrEmitter* ir_emitter, llvm::Module* module) + : ElementalIrEmitter(module, ir_emitter->b()), + hlo_module_config_(module_config), + ir_emitter_(ir_emitter) {} + + protected: + StatusOr EmitAtan2(PrimitiveType prim_type, llvm::Value* lhs, + llvm::Value* rhs, + absl::string_view name) override; + StatusOr EmitTanh(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr> EmitThreadLocalCall( + const HloComputation& callee, absl::Span parameters, + absl::string_view name, bool is_reducer) override { + return ir_emitter_->EmitThreadLocalCall(callee, parameters, name, + is_reducer); + } + + bool fast_min_max() override { + return hlo_module_config_.debug_options().xla_cpu_enable_fast_min_max(); + } + + const HloModuleConfig& hlo_module_config_; + IrEmitter* ir_emitter_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_ELEMENTAL_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/executable.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/executable.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..5079fa76b01702f4711cf73da16b22508f5cf6b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/executable.pb.h @@ -0,0 +1,444 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/cpu/executable.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fexecutable_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fexecutable_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/service/cpu/xla_framework.pb.h" +#include "xla/service/hlo.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fcpu_2fexecutable_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fcpu_2fexecutable_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fcpu_2fexecutable_2eproto; +namespace xla { +namespace cpu { +class XlaRuntimeCpuExecutableProto; +struct XlaRuntimeCpuExecutableProtoDefaultTypeInternal; +extern XlaRuntimeCpuExecutableProtoDefaultTypeInternal _XlaRuntimeCpuExecutableProto_default_instance_; +} // namespace cpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::cpu::XlaRuntimeCpuExecutableProto* Arena::CreateMaybeMessage<::xla::cpu::XlaRuntimeCpuExecutableProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace cpu { + +// =================================================================== + +class XlaRuntimeCpuExecutableProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.cpu.XlaRuntimeCpuExecutableProto) */ { + public: + inline XlaRuntimeCpuExecutableProto() : XlaRuntimeCpuExecutableProto(nullptr) {} + ~XlaRuntimeCpuExecutableProto() override; + explicit PROTOBUF_CONSTEXPR XlaRuntimeCpuExecutableProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaRuntimeCpuExecutableProto(const XlaRuntimeCpuExecutableProto& from); + XlaRuntimeCpuExecutableProto(XlaRuntimeCpuExecutableProto&& from) noexcept + : XlaRuntimeCpuExecutableProto() { + *this = ::std::move(from); + } + + inline XlaRuntimeCpuExecutableProto& operator=(const XlaRuntimeCpuExecutableProto& from) { + CopyFrom(from); + return *this; + } + inline XlaRuntimeCpuExecutableProto& operator=(XlaRuntimeCpuExecutableProto&& 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; + } + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { + return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); + } + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { + return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); + } + + 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 XlaRuntimeCpuExecutableProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaRuntimeCpuExecutableProto* internal_default_instance() { + return reinterpret_cast( + &_XlaRuntimeCpuExecutableProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(XlaRuntimeCpuExecutableProto& a, XlaRuntimeCpuExecutableProto& b) { + a.Swap(&b); + } + inline void Swap(XlaRuntimeCpuExecutableProto* 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(XlaRuntimeCpuExecutableProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaRuntimeCpuExecutableProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaRuntimeCpuExecutableProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaRuntimeCpuExecutableProto& from) { + XlaRuntimeCpuExecutableProto::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(XlaRuntimeCpuExecutableProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.cpu.XlaRuntimeCpuExecutableProto"; + } + protected: + explicit XlaRuntimeCpuExecutableProto(::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 { + kXlaRuntimeExecutableFieldNumber = 1, + kXlaFrameworkMappingFieldNumber = 2, + }; + // optional .xla.XlaRuntimeExecutableProto xla_runtime_executable = 1; + bool has_xla_runtime_executable() const; + private: + bool _internal_has_xla_runtime_executable() const; + public: + void clear_xla_runtime_executable(); + const ::xla::XlaRuntimeExecutableProto& xla_runtime_executable() const; + PROTOBUF_NODISCARD ::xla::XlaRuntimeExecutableProto* release_xla_runtime_executable(); + ::xla::XlaRuntimeExecutableProto* mutable_xla_runtime_executable(); + void set_allocated_xla_runtime_executable(::xla::XlaRuntimeExecutableProto* xla_runtime_executable); + private: + const ::xla::XlaRuntimeExecutableProto& _internal_xla_runtime_executable() const; + ::xla::XlaRuntimeExecutableProto* _internal_mutable_xla_runtime_executable(); + public: + void unsafe_arena_set_allocated_xla_runtime_executable( + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable); + ::xla::XlaRuntimeExecutableProto* unsafe_arena_release_xla_runtime_executable(); + + // optional .xla.cpu.XlaFrameworkMappingProto xla_framework_mapping = 2; + bool has_xla_framework_mapping() const; + private: + bool _internal_has_xla_framework_mapping() const; + public: + void clear_xla_framework_mapping(); + const ::xla::cpu::XlaFrameworkMappingProto& xla_framework_mapping() const; + PROTOBUF_NODISCARD ::xla::cpu::XlaFrameworkMappingProto* release_xla_framework_mapping(); + ::xla::cpu::XlaFrameworkMappingProto* mutable_xla_framework_mapping(); + void set_allocated_xla_framework_mapping(::xla::cpu::XlaFrameworkMappingProto* xla_framework_mapping); + private: + const ::xla::cpu::XlaFrameworkMappingProto& _internal_xla_framework_mapping() const; + ::xla::cpu::XlaFrameworkMappingProto* _internal_mutable_xla_framework_mapping(); + public: + void unsafe_arena_set_allocated_xla_framework_mapping( + ::xla::cpu::XlaFrameworkMappingProto* xla_framework_mapping); + ::xla::cpu::XlaFrameworkMappingProto* unsafe_arena_release_xla_framework_mapping(); + + // @@protoc_insertion_point(class_scope:xla.cpu.XlaRuntimeCpuExecutableProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable_; + ::xla::cpu::XlaFrameworkMappingProto* xla_framework_mapping_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fcpu_2fexecutable_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// XlaRuntimeCpuExecutableProto + +// optional .xla.XlaRuntimeExecutableProto xla_runtime_executable = 1; +inline bool XlaRuntimeCpuExecutableProto::_internal_has_xla_runtime_executable() const { + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; + PROTOBUF_ASSUME(!value || _impl_.xla_runtime_executable_ != nullptr); + return value; +} +inline bool XlaRuntimeCpuExecutableProto::has_xla_runtime_executable() const { + return _internal_has_xla_runtime_executable(); +} +inline const ::xla::XlaRuntimeExecutableProto& XlaRuntimeCpuExecutableProto::_internal_xla_runtime_executable() const { + const ::xla::XlaRuntimeExecutableProto* p = _impl_.xla_runtime_executable_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_XlaRuntimeExecutableProto_default_instance_); +} +inline const ::xla::XlaRuntimeExecutableProto& XlaRuntimeCpuExecutableProto::xla_runtime_executable() const { + // @@protoc_insertion_point(field_get:xla.cpu.XlaRuntimeCpuExecutableProto.xla_runtime_executable) + return _internal_xla_runtime_executable(); +} +inline void XlaRuntimeCpuExecutableProto::unsafe_arena_set_allocated_xla_runtime_executable( + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_runtime_executable_); + } + _impl_.xla_runtime_executable_ = xla_runtime_executable; + if (xla_runtime_executable) { + _impl_._has_bits_[0] |= 0x00000001u; + } else { + _impl_._has_bits_[0] &= ~0x00000001u; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.cpu.XlaRuntimeCpuExecutableProto.xla_runtime_executable) +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeCpuExecutableProto::release_xla_runtime_executable() { + _impl_._has_bits_[0] &= ~0x00000001u; + ::xla::XlaRuntimeExecutableProto* temp = _impl_.xla_runtime_executable_; + _impl_.xla_runtime_executable_ = 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::XlaRuntimeExecutableProto* XlaRuntimeCpuExecutableProto::unsafe_arena_release_xla_runtime_executable() { + // @@protoc_insertion_point(field_release:xla.cpu.XlaRuntimeCpuExecutableProto.xla_runtime_executable) + _impl_._has_bits_[0] &= ~0x00000001u; + ::xla::XlaRuntimeExecutableProto* temp = _impl_.xla_runtime_executable_; + _impl_.xla_runtime_executable_ = nullptr; + return temp; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeCpuExecutableProto::_internal_mutable_xla_runtime_executable() { + _impl_._has_bits_[0] |= 0x00000001u; + if (_impl_.xla_runtime_executable_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::XlaRuntimeExecutableProto>(GetArenaForAllocation()); + _impl_.xla_runtime_executable_ = p; + } + return _impl_.xla_runtime_executable_; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeCpuExecutableProto::mutable_xla_runtime_executable() { + ::xla::XlaRuntimeExecutableProto* _msg = _internal_mutable_xla_runtime_executable(); + // @@protoc_insertion_point(field_mutable:xla.cpu.XlaRuntimeCpuExecutableProto.xla_runtime_executable) + return _msg; +} +inline void XlaRuntimeCpuExecutableProto::set_allocated_xla_runtime_executable(::xla::XlaRuntimeExecutableProto* xla_runtime_executable) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_runtime_executable_); + } + if (xla_runtime_executable) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(xla_runtime_executable)); + if (message_arena != submessage_arena) { + xla_runtime_executable = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, xla_runtime_executable, submessage_arena); + } + _impl_._has_bits_[0] |= 0x00000001u; + } else { + _impl_._has_bits_[0] &= ~0x00000001u; + } + _impl_.xla_runtime_executable_ = xla_runtime_executable; + // @@protoc_insertion_point(field_set_allocated:xla.cpu.XlaRuntimeCpuExecutableProto.xla_runtime_executable) +} + +// optional .xla.cpu.XlaFrameworkMappingProto xla_framework_mapping = 2; +inline bool XlaRuntimeCpuExecutableProto::_internal_has_xla_framework_mapping() const { + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.xla_framework_mapping_ != nullptr); + return value; +} +inline bool XlaRuntimeCpuExecutableProto::has_xla_framework_mapping() const { + return _internal_has_xla_framework_mapping(); +} +inline const ::xla::cpu::XlaFrameworkMappingProto& XlaRuntimeCpuExecutableProto::_internal_xla_framework_mapping() const { + const ::xla::cpu::XlaFrameworkMappingProto* p = _impl_.xla_framework_mapping_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::cpu::_XlaFrameworkMappingProto_default_instance_); +} +inline const ::xla::cpu::XlaFrameworkMappingProto& XlaRuntimeCpuExecutableProto::xla_framework_mapping() const { + // @@protoc_insertion_point(field_get:xla.cpu.XlaRuntimeCpuExecutableProto.xla_framework_mapping) + return _internal_xla_framework_mapping(); +} +inline void XlaRuntimeCpuExecutableProto::unsafe_arena_set_allocated_xla_framework_mapping( + ::xla::cpu::XlaFrameworkMappingProto* xla_framework_mapping) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_framework_mapping_); + } + _impl_.xla_framework_mapping_ = xla_framework_mapping; + if (xla_framework_mapping) { + _impl_._has_bits_[0] |= 0x00000002u; + } else { + _impl_._has_bits_[0] &= ~0x00000002u; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.cpu.XlaRuntimeCpuExecutableProto.xla_framework_mapping) +} +inline ::xla::cpu::XlaFrameworkMappingProto* XlaRuntimeCpuExecutableProto::release_xla_framework_mapping() { + _impl_._has_bits_[0] &= ~0x00000002u; + ::xla::cpu::XlaFrameworkMappingProto* temp = _impl_.xla_framework_mapping_; + _impl_.xla_framework_mapping_ = 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::cpu::XlaFrameworkMappingProto* XlaRuntimeCpuExecutableProto::unsafe_arena_release_xla_framework_mapping() { + // @@protoc_insertion_point(field_release:xla.cpu.XlaRuntimeCpuExecutableProto.xla_framework_mapping) + _impl_._has_bits_[0] &= ~0x00000002u; + ::xla::cpu::XlaFrameworkMappingProto* temp = _impl_.xla_framework_mapping_; + _impl_.xla_framework_mapping_ = nullptr; + return temp; +} +inline ::xla::cpu::XlaFrameworkMappingProto* XlaRuntimeCpuExecutableProto::_internal_mutable_xla_framework_mapping() { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.xla_framework_mapping_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::cpu::XlaFrameworkMappingProto>(GetArenaForAllocation()); + _impl_.xla_framework_mapping_ = p; + } + return _impl_.xla_framework_mapping_; +} +inline ::xla::cpu::XlaFrameworkMappingProto* XlaRuntimeCpuExecutableProto::mutable_xla_framework_mapping() { + ::xla::cpu::XlaFrameworkMappingProto* _msg = _internal_mutable_xla_framework_mapping(); + // @@protoc_insertion_point(field_mutable:xla.cpu.XlaRuntimeCpuExecutableProto.xla_framework_mapping) + return _msg; +} +inline void XlaRuntimeCpuExecutableProto::set_allocated_xla_framework_mapping(::xla::cpu::XlaFrameworkMappingProto* xla_framework_mapping) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_framework_mapping_); + } + if (xla_framework_mapping) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(xla_framework_mapping)); + if (message_arena != submessage_arena) { + xla_framework_mapping = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, xla_framework_mapping, submessage_arena); + } + _impl_._has_bits_[0] |= 0x00000002u; + } else { + _impl_._has_bits_[0] &= ~0x00000002u; + } + _impl_.xla_framework_mapping_ = xla_framework_mapping; + // @@protoc_insertion_point(field_set_allocated:xla.cpu.XlaRuntimeCpuExecutableProto.xla_framework_mapping) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace cpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fexecutable_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/hlo_xla_runtime_pipeline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/hlo_xla_runtime_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..b77436c16565d2853da066e2aee53a7746cd0331 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/hlo_xla_runtime_pipeline.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_CPU_HLO_XLA_RUNTIME_PIPELINE_H_ +#define XLA_SERVICE_CPU_HLO_XLA_RUNTIME_PIPELINE_H_ + +#include +#include + +#include "xla/runtime/compiler.h" +#include "xla/status.h" + +namespace mlir { +class DialectRegistry; +} // namespace mlir + +namespace xla { +namespace cpu { + +struct HloXlaRuntimePipelineOptions { + bool enable_tiling_and_fusion = false; + bool enable_fusion_outlining = true; + bool remove_copies_to_outparams = true; + bool sparse_bufferization = true; + bool experimental_deallocation = false; + bool enable_avx2 = true; + // Accelerate sparse computations with CUDA threading. + // This is an experimental feature, so off by default. + int32_t xla_cpu_sparse_cuda_threads = 0; + // Optional CPU name, similar to llc's -mcpu flag. + std::string cpu_name = ""; + std::vector matmul_tile_sizes = {}; +}; + +// Creates a pipeline that lowers modules from HLO to Linalg on buffers. +Status CreateHloXlaRuntimePipeline(xla::runtime::PassManager& passes, + const HloXlaRuntimePipelineOptions& options); +Status CreateDefaultHloXlaRuntimePipeline(xla::runtime::PassManager& passes); + +void RegisterHloXlaRuntimePipelineDialects(mlir::DialectRegistry& dialects); +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_HLO_XLA_RUNTIME_PIPELINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_emission_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_emission_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..74687c6fca0e4c43bdfb406bbc98f2dfe1a36460 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_emission_utils.h @@ -0,0 +1,50 @@ +/* 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_SERVICE_CPU_IR_EMISSION_UTILS_H_ +#define XLA_SERVICE_CPU_IR_EMISSION_UTILS_H_ + +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/cpu/target_machine_features.h" + +namespace xla { +namespace cpu { + +bool PotentiallyImplementedAsEigenConvolution( + const HloInstruction& convolution, + const TargetMachineFeatures& target_machine_features); + +// Computes the minimum alignment guaranteed for a tensor of shape `shape` on +// the target machine. +int64_t GetMinimumAlignmentForArray( + const Shape& shape, const TargetMachineFeatures& target_machine_features); + +// Dynamic loop bounds are specified as an array of dimension index +// [start, limit) pairs of ir values (one for each partitioned outer dimension). +// +// EX: Let 'shape' = [8, 16, 32], with the loop bounds of the two-most major +// dimensions dynamic. Then 'dynamic_loop_bounds' will contain the +// following ir values for the two most-major dimensions: +// [dim0_index_start_ir_value, dim0_index_limit_ir_value] +// [dim1_index_start_ir_value, dim1_index_limit_ir_value] +// +// See IrFunction and ParallelLoopEmitter for details. +using DynamicLoopBounds = std::vector>; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_IR_EMISSION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..c4534fa619d650d66570c2b553af37afdb780b0e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_emitter.h @@ -0,0 +1,685 @@ +/* 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_SERVICE_CPU_IR_EMITTER_H_ +#define XLA_SERVICE_CPU_IR_EMITTER_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "llvm/TargetParser/Triple.h" +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/cpu/ir_function.h" +#include "xla/service/cpu/target_machine_features.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/llvm_ir/alias_analysis.h" +#include "xla/service/llvm_ir/fused_ir_emitter.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/ir_builder_mixin.h" +#include "xla/service/llvm_ir/loop_emitter.h" +#include "xla/service/name_uniquer.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace cpu { +// This class is the top-level API for the XLA HLO --> LLVM IR compiler. It +// implements the DfsHloVisitor interface and emits HLO computations as LLVM IR +// functions. +class IrEmitter : public DfsHloVisitorWithDefault, + public IrBuilderMixin { + friend class CpuElementalIrEmitter; + + public: + using GeneratorForOperandIrArrays = + std::function()>; + + // Create a new LLVM IR emitter. + // + // hlo_module: the HLO module we are emitting IR for. + // assignment: a BufferAssignment from which we know which buffers are used by + // the HLO nodes. + // mlir_context: the MLIR context used for IR emission. + // llvm_module: the LLVM module to emit IR into. It's built using the LLVM + // context inside of mlir_context. + // instruction_to_profile_idx: the mapping from HLO instructions to their + // index in the profiling array. + // computation_to_profile_idx: the mapping from HLO computations to their + // index in the profiling array. + // computation_transitively_contains_custom_call: the mapping from HLO + // computations to whether or not they transitively contain a custom-call + // instruction. All computations in the module must have a key in this + // map. + // emit_code_for_msan: whether emitted code should be compatible with msan. + IrEmitter(mlir::MLIRContext* mlir_context, const HloModule& hlo_module, + const BufferAssignment& assignment, llvm::Module* llvm_module, + absl::flat_hash_map + instruction_to_profile_idx, + absl::flat_hash_map + computation_to_profile_idx, + absl::flat_hash_map + computation_transitively_contains_custom_call, + const TargetMachineFeatures* target_machine, + bool emit_code_for_msan); + ~IrEmitter() override = default; + + // Emit and return the given HLO computation as an LLVM IR + // function. + // + // function_name_prefix is the desired name of the function. If the name is + // not unique among already emitted functions then a suffix is appended to + // make the name unique. + // + // 'is_top_level_computation' has the following meanings for each CPU backend: + // *) sequential: indicates that this is the entry computation of the HLO + // module. + // *) parallel: indices that this is the callee of a kCall HLO in the entry + // computation of the HLO module. + // + // If 'instruction_order' is not NULL, then the HLO instructions are emitted + // in the given order. In this case, 'instruction_order' must be a + // topological sort of the set of nodes accessible from the root of the + // computation. + // + // If 'allow_reassociation' is true, the fast-math reassociation flag will + // be enabled in the function's body. This is used when emitting reducers. + StatusOr EmitComputation( + HloComputation* computation, absl::string_view function_name_prefix, + bool is_top_level_computation, + absl::Span instruction_order, + bool allow_reassociation); + + llvm::IRBuilder<>* b() { return &b_; } + + // builder() is for IrBuilderMixin. + llvm::IRBuilder<>* builder() { return &b_; } + + // Emit an LLVM global variable for every constant buffer allocation. + Status EmitConstantGlobals(); + + protected: + // + // The following methods implement the DfsHloVisitor interface. + // + // Default action which emits code for most operations. Operations which are + // special in some way are handled explicitly in HandleFoo methods. + Status DefaultAction(HloInstruction* hlo) override; + + Status HandleAllToAll(HloInstruction* instruction) override; + Status HandleBitcast(HloInstruction* bitcast) override; + Status HandleConstant(HloInstruction* constant) override; + Status HandleCopy(HloInstruction* copy) override; + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + Status HandleSelect(HloInstruction* select) override; + Status HandleDot(HloInstruction* dot) override; + Status HandleConvolution(HloInstruction* convolution) override; + Status HandleFft(HloInstruction* fft) override; + Status HandleAllReduce(HloInstruction* crs) override; + Status HandleCollectivePermute(HloInstruction* crs) override; + Status HandleInfeed(HloInstruction* instruction) override; + Status HandleOutfeed(HloInstruction* outfeed) override; + Status HandleSort(HloInstruction* hlo) override; + Status HandleParameter(HloInstruction* parameter) override; + Status HandleReduce(HloInstruction* reduce) override; + Status HandleReduceWindow(HloInstruction* reduce_window) override; + Status HandleSelectAndScatter(HloInstruction* select_and_scatter) override; + Status HandleSend(HloInstruction* send) override; + Status HandleSendDone(HloInstruction* send_done) override; + Status HandleSlice(HloInstruction* slice) override; + Status HandleDynamicSlice(HloInstruction* dynamic_slice) override; + Status HandleDynamicUpdateSlice( + HloInstruction* dynamic_update_slice) override; + Status HandleRecv(HloInstruction* recv) override; + Status HandleRecvDone(HloInstruction* recv_done) override; + Status HandlePad(HloInstruction* pad) override; + Status HandleTuple(HloInstruction* tuple) override; + Status HandleFusion(HloInstruction* fusion) override; + Status HandleCall(HloInstruction* call) override; + Status HandleCustomCall(HloInstruction* custom_call) override; + Status HandleWhile(HloInstruction* xla_while) override; + Status HandleConcatenate(HloInstruction* concatenate) override; + Status HandleConditional(HloInstruction* conditional) override; + Status HandleScatter(HloInstruction* scatter) override; + Status HandleAfterAll(HloInstruction* after_all) override; + Status HandleAddDependency(HloInstruction* add_dependency) override; + Status HandlePartitionId(HloInstruction* hlo) override; + Status HandleReplicaId(HloInstruction* hlo) override; + Status HandleRng(HloInstruction* rng) override; + Status HandleRngGetAndUpdateState(HloInstruction* rng_state) override; + Status FinishVisit(HloInstruction* root) override; + + Status Preprocess(HloInstruction* hlo) override; + Status Postprocess(HloInstruction* hlo) override; + + // A convenient helper for calling BufferAssignment::GetUniqueSlice. + BufferAllocation::Slice GetAllocationSlice( + const HloInstruction& hlo, const ShapeIndex& index = {}) const { + return assignment_.GetUniqueSlice(&hlo, index).value(); + } + + private: + Status HandleSliceToDynamic(HloInstruction* hlo); + Status HandlePadToStatic(HloInstruction* hlo); + Status HandleTopK(HloInstruction* hlo); + Status HandleAllReduceSingleReplica(HloInstruction* crs); + Status HandleAllReduceMultipleReplica(HloInstruction* crs); +#if defined(INTEL_MKL) && defined(ENABLE_ONEDNN_V3) + Status HandleOneDnnMatMul(HloInstruction* hlo); +#endif // INTEL_MKL && ENABLE_ONEDNN_V3 + // Private helper to initialize an IR function for the computation. + void InitializeIrFunction(const std::string& function_name); + + // Emits the copying epilogue for the function, + // where it copies the returned value to the reserved alloca. + // This is only necessary for thread-local functions. + // Note that since the call graph is flattened, if the same function is + // called in both thread-local and non-thread-local it would be codegen'd + // twice, and we would know whether it's thread-local at codegen time. + void EmitThreadLocalFunctionEpilogue(HloComputation* computation); + + // Convenience functions to generate a GEP into the profile counter parameter + // which would correspond to the index for a given HLO instruction or + // computation. + llvm::Value* GetProfileCounterFor(const HloInstruction& instruction); + llvm::Value* GetProfileCounterFor(const HloComputation& computation); + + // Helper function template for the implementation of the above two functions. + template + llvm::Value* GetProfileCounterCommon( + const T& hlo, + const absl::flat_hash_map& profile_index_map); + + // Gets the IR Value emitted previously for the given hlo. + // + // Prefer calling GetIrArrayFor if the value you're reading is a buffer, + // because GetIrArrayFor annotates buffer's loads/stores with noalias + // metadata. + // + // Make sure to call this only when you're certain a value *was* emitted - if + // not found, this will log a fatal error. + llvm::Value* GetEmittedValueFor(const HloInstruction* hlo); + + // Gets an IrArray representing the given hlo. + llvm_ir::IrArray GetIrArrayFor(const HloInstruction* hlo); + + // Gets a list of IrArrays, one for each of hlo's operands. + std::vector GetIrArraysForOperandsOf( + const HloInstruction* hlo); + + // Bind all argument IrArrays of `fusion` to `fused_emitter`. + void BindFusionArguments(const HloInstruction* fusion, + FusedIrEmitter* fused_emitter); + + // Augments IrArray with aliasing information. + void AddAliasingInformationToIrArray(const HloInstruction& hlo, + llvm_ir::IrArray* array) { + alias_analysis_.AddAliasingInformationToIrArray(hlo, array); + } + + // Convenience function to get the IR type matching the given shape. + llvm::Type* IrShapeType(const Shape& shape); + + // Get the llvm::Value* that represents the "prof_counters" argument of the + // computation function being emitted by this emitter. + llvm::Value* GetProfileCountersArgument(); + + // Get the llvm::Value* that represents the "status" argument of the + // computation function being emitted by this emitter. + llvm::Value* GetStatusArgument(); + + // Get the xla::ExecutableRunOptions that represents the "run_options" + // argument of the computation function being emitted by this emitter. + llvm::Value* GetExecutableRunOptionsArgument(); + + // Get the llvm::Value* that represents the "buffer_table" argument of the + // computation function being emitted by this emitter. + llvm::Value* GetBufferTableArgument(); + + // Get the llvm::BasicBlock that contains the return instruction. + llvm::BasicBlock* GetReturnBlock(); + + // Emits code to check the state of the status object being threaded through + // each computation and return early if it's in an error state. + void EmitEarlyReturnIfErrorStatus(); + + // Helper for EmitBufferPointer. + llvm::Value* EmitGlobalBufferPointer(const BufferAllocation::Slice& slice, + const Shape& target_shape); + + // Helper for EmitBufferPointer. + llvm::Value* EmitThreadLocalBufferPointer( + const BufferAllocation::Slice& slice, const Shape& target_shape); + + // Emits code that computes the address of the given buffer allocation slice. + llvm::Value* EmitBufferPointer(const BufferAllocation::Slice& slice, + const Shape& target_shape); + + // Emits a call to a thread local function (e.g. to the computation nested + // within a reduce or a map). Thread local callees (by definition) only write + // to and read from thread local allocations. + // Supports only functions returning scalars or tuples of scalars. + // + // `parameters` holds the *scalar values* that need to be passed to the + // callee. The return value is the scalar returned by the callee. + std::vector EmitThreadLocalCall( + const HloComputation& callee, absl::Span parameters, + absl::string_view name, bool is_reducer); + + // Similar to EmitThreadLocal, yet assumes that the function returns a scalar. + llvm::Value* EmitScalarReturningThreadLocalCall( + const HloComputation& callee, absl::Span parameters, + absl::string_view name); + + // Emits a call to a "global" function (e.g. to the computation nested within + // a kWhile or a kCall). Buffer assignment unabiguously assigns buffers to + // the parameters and return values for these computations so there is no need + // to explicitly pass parameters or return results. + void EmitGlobalCall(const HloComputation& callee, absl::string_view name); + + // Returns the buffer to which a global call to `callee` would have written + // its result. + llvm::Value* GetBufferForGlobalCallReturnValue(const HloComputation& callee); + + // Verifies that the element types of all of the given operand instructions + // match and are of one of the given supported types. + Status ElementTypesSameAndSupported( + const HloInstruction& instruction, + absl::Span operands, + absl::Span supported_types); + + // Emit IR to perform a computation for every element in the given target op. + // This produces a series of nested loops (one for each dimension of the op's + // shape). The body of the inner-most loop is provided by the body_emitter + // function. + // + // desc is an optional human-readable string that's added to the loop name in + // IR. Regardless of whether desc is provided, target_op->name() is included + // in the loop name. + // + // TODO(jingyue): target_op should be a `const HloInstruction*`. + Status EmitTargetElementLoop( + HloInstruction* target_op, + const llvm_ir::ElementGenerator& element_generator); + Status EmitTargetElementLoop( + HloInstruction* target_op, absl::string_view desc, + const llvm_ir::ElementGenerator& element_generator); + + // Emits a memcpy from the source instruction's result value to the + // destination's. Both source and destination must have an entry in the + // emitted_value_ table. + Status EmitMemcpy(const HloInstruction& source, + const HloInstruction& destination); + + // Emits IR to compute the target address of the buffer for the given op. + // After calling this function, you can get a pointer to this buffer by + // calling GetIrArrayForOp or GetEmittedValueFor. + Status EmitTargetAddressForOp(const HloInstruction* op); + + // Structurizes "array_elements" into an MD array that represents "shape". + // This is a recursive function, and "dimension_index" indicates the index of + // the current dimension that the function is considering (0 means the + // most-minor dimension). + llvm::Constant* CreateInitializerForConstantArray( + const std::vector& array_elements, const Shape& shape, + int64_t dimension_index); + + // Tries to codegen a reduction operation using vectorized instructions. + // Returns true if successful, and false on failure. On failure, sets + // "failure_reason" to a string describing why it could not vectorize the + // reduction. + // + // TODO(sanjoy): Some of the things we do here can be abstracted out into + // concepts that generalize over other vectorizable operations. We should + // consider pulling out these abstractions into a VectorizingIrEmitter or + // something similar. + StatusOr EmitVectorizedReduce(HloInstruction* reduce, + HloInstruction* arg, + HloInstruction* init_value, + absl::Span dimensions, + HloComputation* function, + std::string* failure_reason); + + // We'd like to keep one or two one cache-line's worth of data in registers + // without generating IR with illegal (e.g. excessively large or + // non-power-of-two) vector types. We do this by introducing a layer of + // abstraction: we introduce a high level vector-like concept called a + // "sharded vector" that models data parallelism, and is mapped to a sequence + // scalar and vector llvm::Value s. + // + // For example, we can represent 29 f32 elements by a sharded vector mapped to + // a sequence of LLVM values of types [<16 x f32>, <8 x f32>, <4 x f32>, f32]. + // Note that the last element is scalar. + // + // There is no requirement on the ordering or the uniqueness of the elements + // mapped to sharded vectors -- we allow repeated elements, and we allow + // elements to appear in any order. + using ShardedVector = std::vector; + + // A sharded vector type is the element-wise llvm::Type's of some + // ShardedVector. + using ShardedVectorType = std::vector; + + // Create a sharded vector type corresponding to a "element_count" long + // sequence of "element_type" values. + ShardedVectorType CreateShardedVectorType(PrimitiveType element_type, + unsigned element_count); + + // Emit LLVM IR to store the sharded vector "value_to_store" to + // "store_address". + void EmitShardedVectorStore(llvm::Value* store_address, + const ShardedVector& value_to_store, + llvm::Align alignment, + const llvm_ir::IrArray& containing_array); + + using ReductionGenerator = std ::function*, llvm::Value*, llvm::Value*)>; + + // Tries to match the reduction function "function" to a known reduction + // pattern. Returns a non-null ReductionGenerator on a successful match, + // which can be used to generate the LLVM IR corresponding to said reduction. + // On failure, this stores a reason string into "failure_reason". + ReductionGenerator MatchReductionGenerator(HloComputation* function, + std::string* failure_reason) const; + + // Emits the inner loop nest that runs the reduction. Helper function for + // EmitVectorizedReduce. + StatusOr EmitInnerLoopForVectorizedReduction( + const ReductionGenerator& reduction_generator, + const llvm_ir::IrArray::Index& output_index, + const ShardedVectorType& accumulator_type, HloInstruction* init_value, + HloInstruction* arg, absl::Span dimensions, + llvm::Align element_alignment); + + // Tries to emit a fast concatenate operation using memcpy. Returns true if + // successful, and false on failure. On failure, sets "failure_reason" to a + // string describing why it could not emit a fast concatenate. + StatusOr EmitFastConcatenate(HloInstruction* concatenate, + absl::Span operands, + std::string* failure_reason); + + // Emits LLVM IR to transfer "element_count" elements of type "primitive_type" + // from the address "source" to the address "target". + void EmitTransferElements(llvm::Value* target, llvm::Value* source, + int64_t element_count, PrimitiveType primitive_type, + const llvm_ir::IrArray& target_array, + const llvm_ir::IrArray& source_array); + + // Emits printing during the execution. + llvm::Value* EmitPrintf(absl::string_view fmt, + absl::Span arguments); + llvm::Value* EmitPrintfToStderr(absl::string_view fmt, + absl::Span arguments); + + // Emits a call to a non-variadic function `func_name` with arguments + // `arguments` assuming C calling convention. + llvm::Value* EmitCallToFunc( + std::string func_name, const std::vector& arguments, + llvm::Type* return_type, bool does_not_throw = true, + bool only_accesses_arg_memory = false, + bool only_accesses_inaccessible_mem_or_arg_mem = false); + + // Assignment of the buffers needed by the computation and their shape + // information. + const BufferAssignment& assignment_; + + // The LLVM module into which IR will be emitted. + llvm::Module* module_; + + // The target architecture. + llvm::Triple::ArchType arch_type_; + + // Used to produce unique names for generated functions. + NameUniquer name_uniquer_; + + struct ComputationToEmit { + const HloComputation* computation; + bool allow_reassociation; + + bool operator==(const ComputationToEmit& other) const { + return computation == other.computation && + allow_reassociation == other.allow_reassociation; + } + + template + friend H AbslHashValue(H h, const ComputationToEmit& c) { + return H::combine(std::move(h), c.computation, c.allow_reassociation); + } + friend std::ostream& operator<<(std::ostream& os, + const ComputationToEmit& c) { + return os << c.computation->name() << ", " << c.allow_reassociation; + } + }; + + // Map containing all previously emitted computations. + absl::flat_hash_map emitted_functions_; + + // Map containing all previously emitted thread-local temporary buffers. + std::map, llvm::Value*> + thread_local_buffers_; + + // The following fields track the IR emission state. According to LLVM memory + // management rules, their memory is owned by the module (Note that IrFunction + // creates the encapsulated llvm::Function s.t. it is added to the llvm + // module's function list). + // N.B. `b_` must be ordered before `compute_function_` as + // `IrFunction::~IrFunction` references `b_`. This will ensure that the + // destructor for `compute_function_` will run before the destructor for `b_`. + llvm::IRBuilder<> b_; + std::unique_ptr compute_function_; + mlir::MLIRContext* mlir_context_; + bool allow_reassociation_; + + // The buffer allocation slice for the root of the computation being compiled. + // Only relevant for thread local computations. + BufferAllocation::Slice computation_root_allocation_; + + // Maps the buffer allocation slices for the parameters to the computation + // being compiled to their parameter numbers. Only relevant for thread local + // computations. + absl::flat_hash_map + computation_parameter_allocations_; + + // Maps HLO instructions to their index into the profile counter array. + const absl::flat_hash_map + instruction_to_profile_idx_; + + // Maps HLO computations to their index into the profile counter array. + const absl::flat_hash_map + computation_to_profile_idx_; + + // Maps HLO computations to whether they contain a custom-call instruction + // (either directly, or transitively by e.g. calling another computation that + // does). + const absl::flat_hash_map + computation_transitively_contains_custom_call_; + + // Accessor for the custom-call mapping that enforces the precondition that + // all computations must have a key in the map. + bool ComputationTransitivelyContainsCustomCall( + const HloComputation* computation) const { + auto it = computation_transitively_contains_custom_call_.find(computation); + CHECK(it != computation_transitively_contains_custom_call_.cend()) + << "Must provide 'contains CustomCall' annotation for all computations " + "in the module"; + return it->second; + } + + // Maps HLOs to Values emitted for them. + absl::flat_hash_map emitted_value_; + + llvm_ir::AliasAnalysis alias_analysis_; + + // The number of outer dimensions of the root instruction's shape that + // will be partitioned when emitting parallel loops. (See + // ParallelLoopEmitter). + int64_t num_dynamic_loop_bounds_ = 0; + + // Returns whether the given instruction should be emitted as a parallel loop. + bool ShouldEmitParallelLoopFor(const HloInstruction& op) const { + // Emit parallel loop for root instruction if dynamic outer-dimension loop + // bounds were specified. + return num_dynamic_loop_bounds_ > 0 && + op.parent()->root_instruction() == &op; + } + + // This struct contains all the state needed to emit instructions for + // profiling a computation. + class ProfilingState { + public: + ProfilingState() : use_rdtscp_(false) {} + explicit ProfilingState(bool use_rdtscp) : use_rdtscp_(use_rdtscp) {} + + // Record the cycle counter before an HLO executes. + void RecordCycleStart(llvm::IRBuilder<>* b, HloInstruction* hlo); + // Record the number of cycles it took for an HLO to execute. + void RecordCycleDelta(llvm::IRBuilder<>* b, HloInstruction* hlo, + llvm::Value* prof_counter); + // Record the number of cycles it took for the entire computation to + // execute. + void RecordCompleteComputation(llvm::IRBuilder<>* b, + llvm::Value* prof_counter); + + // Convenience function to generate a call to an intrinsic which reads the + // CPU cycle counter. + llvm::Value* ReadCycleCounter(llvm::IRBuilder<>* b); + + // Store the cycle counter delta to the per-HLO profile counter. + void UpdateProfileCounter(llvm::IRBuilder<>* b, llvm::Value* prof_counter, + llvm::Value* cycle_end, llvm::Value* cycle_start); + + private: + // Should we use the x86-specific rdtscp or the generic readcyclecounter + // intrinsic? + bool use_rdtscp_; + + // The first read cycle counter in the program. + llvm::Value* first_read_cycle_start_ = nullptr; + + // The last read cycle counter in the program. + llvm::Value* last_read_cycle_end_ = nullptr; + + // Maps HLOs to the value the cycle counter contained right before the HLO + // began to execute. + absl::flat_hash_map cycle_starts_; + }; + + ProfilingState profiling_state_; + + class TracingState { + public: + TracingState() : enabled_(false) {} + void set_enabled(bool value) { enabled_ = value; } + void EmitTracingStart(llvm::IRBuilder<>* b, HloInstruction* hlo, + llvm::Value* run_options); + void EmitTracingEnd(llvm::IRBuilder<>* b, HloInstruction* hlo, + llvm::Value* run_options); + + private: + bool enabled_; + // Maps from HLO to the activity id returned by xprof::TraceMe. + absl::flat_hash_map activity_ids_; + }; + TracingState tracing_state_; + + // Given a load instruction and a shape or buffer size, annotate the load's + // result with the alignment required by the shape or size. + void AttachAlignmentMetadataForLoad(llvm::LoadInst* load, const Shape& shape); + void AttachAlignmentMetadataForLoad(llvm::LoadInst* load, + int64_t buffer_size); + + // Given a load instruction and a shape or buffer size, annotate the load's + // result with the dereferenceable bytes required by the shape / buffer size. + void AttachDereferenceableMetadataForLoad(llvm::LoadInst* load, + const Shape& shape); + void AttachDereferenceableMetadataForLoad(llvm::LoadInst* load, + int64_t buffer_size); + + // Calculate the alignment of a buffer allocated for a given shape. + int MinimumAlignmentForShape(const Shape& shape); + + // Calculate the alignment of a buffer allocated for a given primitive type. + int MinimumAlignmentForPrimitiveType(PrimitiveType primitive_type); + + // Returns the number of bytes within the shape. + int64_t ByteSizeOf(const Shape& shape) const; + + enum class XfeedKind { + kInfeed, + kOutfeed, + }; + + // Emit IR to transfer between a {infeed,outfeed} buffer and an in-program + // address. + Status EmitXfeedTransfer(XfeedKind kind, const Shape& shape, + llvm::Value* program_buffer_address); + + // Returns a ConstExpr bitcast. + llvm::Constant* EmitGlobalForLiteral(const Literal& literal); + + const HloModuleConfig& hlo_module_config_; + + bool is_top_level_computation_; + + const TargetMachineFeatures& target_machine_features_; + + struct LiteralPtrHashFunctor { + size_t operator()(const Literal* literal) const { + return absl::HashOf(*literal); + } + }; + + struct LiteralPtrEqualityFunctor { + bool operator()(const Literal* lhs, const Literal* rhs) const { + return *lhs == *rhs; + } + }; + + absl::flat_hash_map + emitted_literals_; + + absl::flat_hash_map + constant_buffer_to_global_; + + std::vector thread_local_computations_; + std::vector global_computations_; + + bool emit_code_for_msan_; + + IrEmitter(const IrEmitter&) = delete; + IrEmitter& operator=(const IrEmitter&) = delete; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_function.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_function.h new file mode 100644 index 0000000000000000000000000000000000000000..c1841c13dfa8f5b79ba599c61ddd895d210e8833 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/ir_function.h @@ -0,0 +1,156 @@ +/* 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_SERVICE_CPU_IR_FUNCTION_H_ +#define XLA_SERVICE_CPU_IR_FUNCTION_H_ + +#include "absl/types/span.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "xla/service/cpu/ir_emission_utils.h" +#include "xla/service/hlo_module_config.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { +namespace cpu { + +// IrFunction creates and encapsulates an llvm::Function, exposing methods to +// emitters for function and function argument access. +// The llvm::Function is created with the standard function signature +// used in the XLA CPU backend (see ir_function.cc for argument details). +// In addition IrFunction saves the callers IR insert point during construction, +// and restores it after destruction. +// +// Example usage: +// +// // Create and initialize new IrFunction. +// std::unique_ptr compute_function(new IrFunction(...)); +// // Emit IR for function body using IrFunction helper methods. +// ... +// // Store reference to llvm::Function for future invocation. +// ir_functions.push_back(compute_function.function()); +// // Delete IrFunction (finalizes IR function and restores caller insertion +// // point). +// compute_function.reset(); +// + +class IrFunction { + public: + IrFunction(const std::string& function_name, + llvm::Function::LinkageTypes linkage, + const HloModuleConfig& module_config, llvm::Module* llvm_module, + llvm::IRBuilder<>* b, int64_t num_dynamic_loop_bounds); + ~IrFunction(); + + // Emit IR to read and return the set of IR values representing the dynamic + // loop bounds argument of this function. These bounds delimit the subset + // of the output that will be written by the computation's root instruction at + // runtime. This is used for parallel computations, where a single computation + // is partitioned into N calls to a function with parallel loop bounds, and + // then called N times in parallel with loop bounds limiting each call to + // producing 1/N of the output. + // + // Each element in returned vector is a pair of ir values representing the + // loop bounds for a specific dimension, where the first element of the pair + // is the dimension start index, and the second element of the pair is the + // dimension limit. + // + // EX: [dimension_i_index_start_ir_value, // dimension_i_index_limit_ir_value] + DynamicLoopBounds GetDynamicLoopBounds(); + + // Returns the encapculated llvm::Function. + llvm::Function* function() { return function_; } + + // Get the llvm::Value* that represents this functions "retval" argument. + llvm::Argument* result_arg() { return result_arg_; } + + // Get the xla::ExecutableRunOptions that represents this functions + // "run_options" argument. + llvm::Value* exec_run_options_arg() { return exec_run_options_arg_; } + + // Get the llvm::Value* that represents this functions parameters argument. + llvm::Value* parameters_arg() { return parameters_arg_; } + + // Get the llvm::Value* that represents this functions "buffer_table" + // argument. + llvm::Value* buffer_table_arg() { return buffer_table_arg_; } + + // Get the llvm::Value* that represents this functions "prof_counters" + // argument. + llvm::Value* profile_counters_arg() { return profile_counters_arg_; } + + // Get the llvm::BasicBlock* that contains this function's "ret" instruction. + llvm::BasicBlock* return_block() { return return_block_; } + + // Get the llvm::Value* that represents this function's "status" argument. + llvm::Value* status_arg() { return status_arg_; } + + private: + // Initialize an llvm::Function with standard signature based on arguments. + void Initialize(const std::string& function_name, + llvm::Function::LinkageTypes linkage, + const HloModuleConfig& module_config); + + // Emit ir to read and return the ir value for the dynamic loop bound at + // 'offset' from the "dynamic_loop_bounds" argument of this function. + llvm::Value* GetDynamicLoopBound(int64_t offset); + + llvm::IRBuilder<>* b_; + llvm::Module* llvm_module_; + llvm::IRBuilder<>::InsertPointGuard caller_insert_point_guard_; + + int64_t num_dynamic_loop_bounds_ = 0; + // Encapsulated llvm::Function. + llvm::Function* function_; + // Function argument IR values. + llvm::Argument* result_arg_; + llvm::Value* exec_run_options_arg_; + llvm::Value* parameters_arg_; + llvm::Value* buffer_table_arg_; + llvm::Value* dynamic_loop_bounds_arg_ = nullptr; + llvm::Value* profile_counters_arg_; + llvm::Value* status_arg_; + // Basic block containing return. + llvm::BasicBlock* return_block_; +}; + +// Returns arguments in `arguments` encoded as a single buffer, suitable for a +// function call. +llvm::Value* EncodeArrayFunctionArguments( + absl::Span arguments, absl::string_view name, + llvm::IRBuilder<>* b); + +// Returns an array of compute function call argument ir values. +std::vector GetArrayFunctionCallArguments( + absl::Span parameter_addresses, llvm::IRBuilder<>* b, + absl::string_view name, llvm::Value* return_value_buffer, + llvm::Value* exec_run_options_arg, llvm::Value* buffer_table_arg, + llvm::Value* status_arg, llvm::Value* profile_counters_arg); + +// Emits a call to a runtime fork/join function which dispatches parallel +// calls to 'parallel_function' (and joins threads before returning). +Status EmitCallToParallelForkJoin( + const std::vector& arguments, const Shape& shape, + absl::Span dimension_partition_counts, llvm::IRBuilder<>* b, + llvm::Function* parallel_function, absl::string_view name); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_IR_FUNCTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/llvm_ir_runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/llvm_ir_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..a45b83f7937d27527458bace4bab9810085137b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/llvm_ir_runtime.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_SERVICE_CPU_LLVM_IR_RUNTIME_H_ +#define XLA_SERVICE_CPU_LLVM_IR_RUNTIME_H_ + +#include "llvm/IR/Module.h" +#include "llvm/IR/Operator.h" +#include "xla/service/llvm_ir/llvm_util.h" + +namespace xla { +namespace cpu { +namespace runtime { + +extern const char* const kTanhV4F32SymbolName; +extern const char* const kTanhV8F32SymbolName; +extern const char* const kTanhV16F32SymbolName; +extern const char* const kExpV4F32SymbolName; +extern const char* const kExpV8F32SymbolName; +extern const char* const kExpV16F32SymbolName; +extern const char* const kLogV4F32SymbolName; +extern const char* const kLogV8F32SymbolName; +extern const char* const kLogV16F32SymbolName; + +// The following CPU runtime functions have LLVM-IR only implementations: +// +// - __xla_cpu_runtime_TanhV4F32 +// - __xla_cpu_runtime_TanhV8F32 +// +// |LinkIRRuntimeFunctions| rewrites calls to these functions into generic LLVM +// IR. + +void RewriteIRRuntimeFunctions(llvm::Module* module, + llvm::FastMathFlags fast_math_flags); + +} // namespace runtime +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_LLVM_IR_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/mlir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/mlir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..3787e2d7531068daa7c9185b8e1b138c70fb8b8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/mlir_emitter.h @@ -0,0 +1,44 @@ +/* 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_SERVICE_CPU_MLIR_EMITTER_H_ +#define XLA_SERVICE_CPU_MLIR_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/shape.h" +#include "xla/status.h" + +namespace xla { +namespace cpu { + +// Create a new MLIR function with the name `func_name`, populate it with +// `emitter` and create a call, passing it the buffers defined by +// resultShape/resultPtr and operandShapes/operandPtrs. The function is added to +// the LLVM module at `b`s insertion point. +Status EmitMlirFuncAndCall( + mlir::MLIRContext *context, llvm::IRBuilder<> *b, const Shape &result_shape, + llvm::ArrayRef operand_shapes, llvm::Value *result_ptr, + llvm::ArrayRef operand_ptrs, llvm::StringRef func_name, + llvm::function_ref emitter); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_MLIR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_matmul.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..ac43d26a2f05f200edabfbb411fa29706c9b5cbd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_matmul.h @@ -0,0 +1,43 @@ +/* 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_SERVICE_CPU_ONEDNN_MATMUL_H_ +#define XLA_SERVICE_CPU_ONEDNN_MATMUL_H_ +#if defined(INTEL_MKL) && defined(ENABLE_ONEDNN_V3) + +namespace xla { +namespace cpu { + +extern "C" { +// TODO(intel-tf): Change the function signature as +// void onednn_matmul(void* result, void** args) +// where +// args[0]: num_args (>=3, including itself) +// args[1]: ExecutableRunOption +// args[2]: OneDnnMatMulConfig +// args[3...]: Actual Operands +// so that it can take variable number of arguments. +// +// For now, we are using a fixed number of arguments. +extern void __xla_cpu_runtime_OneDnnMatMul(const void* run_options_ptr, + void* lhs, void* rhs, void* result, + void* config); +} // extern "C" + +} // namespace cpu +} // namespace xla + +#endif // INTEL_MKL && ENABLE_ONEDNN_V3 +#endif // XLA_SERVICE_CPU_ONEDNN_MATMUL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_memory_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_memory_util.h new file mode 100644 index 0000000000000000000000000000000000000000..5373d71fcd2846c557c735e89116305a9b9adc8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_memory_util.h @@ -0,0 +1,116 @@ +/* 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_SERVICE_CPU_ONEDNN_MEMORY_UTIL_H_ +#define XLA_SERVICE_CPU_ONEDNN_MEMORY_UTIL_H_ +#if defined(INTEL_MKL) && defined(ENABLE_ONEDNN_V3) + +#include "dnnl.hpp" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace cpu { + +static const int kOneDnnMaxNDims = DNNL_MAX_NDIMS; + +struct StackAlloca { + llvm::IRBuilder<>* builder; + llvm::Value* value; + void EmitLifetimeEnd() { + builder->CreateLifetimeEnd(value, builder->getInt64(-1)); + } +}; + +// Declare as opaque to put structure definition together with dependant code. +struct MemrefInfoPOD; + +StackAlloca GetAllocaAndEmitMemrefInfo(llvm::IRBuilder<>& builder, + const llvm_ir::IrArray& ir_array); + +inline dnnl::memory::data_type ToOneDnnDataType(PrimitiveType ptype) { + using dt = dnnl::memory::data_type; + switch (ptype) { + case S32: + return dt::s32; + case U8: + return dt::u8; + case S8: + return dt::s8; + case F16: + return dt::f16; + case BF16: + return dt::bf16; + case F32: + return dt::f32; + case F64: + return dt::f64; + + // TODO(intel-tf): properly handle not supported types: + // S16, S64, U16, U32, U64, C64, C128, F8E5M2, F8E4M3FN, S4, U4, + // F8E4M3B11FNUZ + default: + return dt::undef; + } +} + +inline PrimitiveType ToXlaPrimitiveType(dnnl::memory::data_type dtype) { + using dt = dnnl::memory::data_type; + switch (dtype) { + case dt::s32: + return PrimitiveType::S32; + case dt::u8: + return PrimitiveType::U8; + case dt::s8: + return PrimitiveType::S8; + case dt::f16: + return PrimitiveType::F16; + case dt::bf16: + return PrimitiveType::BF16; + case dt::f32: + return PrimitiveType::F32; + case dt::f64: + return PrimitiveType::F64; + // TODO(intel-tf): properly handle not supported type: + default: + return PRIMITIVE_TYPE_INVALID; + } +} + +class MemrefInfo { + public: + MemrefInfo(void* data); + + dnnl::memory::dims GetOneDnnDims() const; + dnnl::memory::dims GetOneDnnStrides() const; + dnnl::memory::data_type GetOneDnnDataType() const; + dnnl::memory::desc GetOneDnnMemDesc() const; + void* Data(); + + void Print(); + + private: + MemrefInfoPOD* pod_; +}; + +} // namespace cpu +} // namespace xla + +#endif // INTEL_MKL && ENABLE_ONEDNN_V3 +#endif // XLA_SERVICE_CPU_ONEDNN_MEMORY_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..c0e5013ad80f57509468252a7cd080fca60a0731 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/onednn_rewriter.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_CPU_ONEDNN_REWRITER_H_ +#define XLA_SERVICE_CPU_ONEDNN_REWRITER_H_ +#if defined(INTEL_MKL) && defined(ENABLE_ONEDNN_V3) + +#include + +#include "absl/algorithm/container.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace cpu { + +// This pass pattern-matches hlo instructions and rewrites into custom calls. +class OneDnnRewriter : public HloModulePass { + public: + absl::string_view name() const override { return "onednn-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace cpu +} // namespace xla + +#endif // INTEL_MKL && ENABLE_ONEDNN_V3 +#endif // XLA_SERVICE_CPU_ONEDNN_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/orc_jit_memory_mapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/orc_jit_memory_mapper.h new file mode 100644 index 0000000000000000000000000000000000000000..2dbfc9ec8a01a2cb4b7e21799ba110aa471e7390 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/orc_jit_memory_mapper.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_CPU_ORC_JIT_MEMORY_MAPPER_H_ +#define XLA_SERVICE_CPU_ORC_JIT_MEMORY_MAPPER_H_ + +#include + +#include "llvm/ExecutionEngine/SectionMemoryManager.h" + +namespace xla { +namespace cpu { + +namespace orc_jit_memory_mapper { +// Returns the registered memory mapper if there is one. Returns nullptr if no +// memory mapper is registered. +llvm::SectionMemoryManager::MemoryMapper* GetInstance(); + +class Registrar { + public: + // Registers the `mapper` as a memory mapper. This is a no-op if `mapper` is + // null. Precondition: no other memory mapper has been registered yet. + explicit Registrar( + std::unique_ptr mapper); +}; +} // namespace orc_jit_memory_mapper + +#define XLA_INTERNAL_REGISTER_ORC_JIT_MEMORY_MAPPER(mapper_instance, ctr) \ + static ::xla::cpu::orc_jit_memory_mapper::Registrar \ + XLA_INTERNAL_REGISTER_ORC_JIT_MEMORY_MAPPER_NAME(ctr)(mapper_instance) + +// __COUNTER__ must go through another macro to be properly expanded +#define XLA_INTERNAL_REGISTER_ORC_JIT_MEMORY_MAPPER_NAME(ctr) \ + __orc_jit_memory_mapper_registrar_##ctr + +// Registers the std::unique_ptr +// returned by the `factory` expression. `factory` is allowed to evaluate to +// a null unique_ptr in which case this macro does nothing. +#define XLA_REGISTER_ORC_JIT_MEMORY_MAPPER(factory) \ + XLA_INTERNAL_REGISTER_ORC_JIT_MEMORY_MAPPER(factory, __COUNTER__) +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_ORC_JIT_MEMORY_MAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/parallel_loop_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/parallel_loop_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..3f338851ddbaf31c3a09caac84a96d389e754b81 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/parallel_loop_emitter.h @@ -0,0 +1,74 @@ +/* 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_SERVICE_CPU_PARALLEL_LOOP_EMITTER_H_ +#define XLA_SERVICE_CPU_PARALLEL_LOOP_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/cpu/ir_emission_utils.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/loop_emitter.h" + +namespace xla { +namespace cpu { + +// ParallelLoopEmitter emits a loop nest for the target array shape. +// The outer loop bounds of the loop nest are passed as ir values at runtime +// (specified in 'dynamic_loop_bounds'), and the inner loop bounds are static. +// Dynamic loop bounds are specified as an array of dimension index +// [start, limit) pairs of ir values (one for each partitioned outer dimension). +// +// EX: Let 'shape' = [8, 16, 32], with the loop bounds of the two-most major +// dimensions dynamic. Then 'dynamic_loop_bounds' will contain the +// following ir values for the two most-major dimensions: +// [dim0_index_start_ir_value, dim0_index_limit_ir_value] +// [dim1_index_start_ir_value, dim1_index_limit_ir_value] +// +// Code emitted by ParallelLoopEmitter will be called in a multi-threaded +// context where each thread will be assigned a different set of outer dimension +// partitions, and where all threads will collectively iterate over the +// entire target array shape. +// +// Outer dimension partitions can be generated using the ShapePartitionAssigner +// and ShapePartitionIterator utility classes from shape_partition.cc. +// +class ParallelLoopEmitter : public llvm_ir::LoopEmitter { + public: + // Constructs a ParallelLoopEmitter which uses 'target_element_generator' to + // generate elements, 'dynamic_loop_bounds' to set the loop bounds of the + // most-major dimensions, and 'target_array.' shape to set the static loop + // bounds for the most-minor dimensions. + ParallelLoopEmitter(const llvm_ir::ElementGenerator& target_element_generator, + const llvm_ir::IrArray& target_array, + const DynamicLoopBounds* dynamic_loop_bounds, + llvm::IRBuilder<>* b); + + ParallelLoopEmitter(const ParallelLoopEmitter&) = delete; + ParallelLoopEmitter& operator=(const ParallelLoopEmitter&) = delete; + ~ParallelLoopEmitter() override = default; + + std::vector EmitIndexAndSetExitBasicBlock( + absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_index) override; + + private: + const DynamicLoopBounds* dynamic_loop_bounds_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_PARALLEL_LOOP_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/parallel_task_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/parallel_task_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..c48fcab8bf4e329828e38d197e4b90fd9365862e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/parallel_task_assignment.h @@ -0,0 +1,124 @@ +/* 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_SERVICE_CPU_PARALLEL_TASK_ASSIGNMENT_H_ +#define XLA_SERVICE_CPU_PARALLEL_TASK_ASSIGNMENT_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/cpu/target_machine_features.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/util.h" + +namespace xla { +namespace cpu { + +// Simple interface for different parallel cost model implementations. +class ParallelCostModel { + public: + virtual ~ParallelCostModel() = default; + virtual int64_t GetParallelTaskCount(HloInstruction* instruction) = 0; +}; + +// ParallelTaskAssignment computes parallel task counts for HLOs in 'module'. +class ParallelTaskAssignment { + public: + // 'max_parallelism': the maximum parallel task count per instruction. + // 'shape_size': shape size function used by HloCostAnalysis during parallel + // task assignment. + // 'module': the containing HloModule. + ParallelTaskAssignment(int64_t max_parallelism, + const HloCostAnalysis::ShapeSizeFunction& shape_size, + HloModule* module, + const TargetMachineFeatures* target_machine_features); + ~ParallelTaskAssignment() {} + + // Computes and returns the target parallel task count for 'instruction'. + int64_t GetTargetParallelTaskCount(HloInstruction* instruction); + + private: + std::unique_ptr cost_model_; + const TargetMachineFeatures& target_machine_features_; +}; + +// ParallelTaskAssigner computes target parallel task counts for all HLOs +// in the module, then assigns parallel task counts to HLOs in the entry +// computation, or to HLOs in embedded computations invoked by (potentially +// nested) kWhile or kCall instructions. +// Each HLO which is assigned parallel task counts is outlined into its +// own embedded computation, which is compiled as a parallel compute function, +// and which is invoked from a kCall instruction that is lowered in codegen to +// a runtime parallel fork/join call. +class ParallelTaskAssigner : public HloModulePass { + public: + // 'max_parallelism': the maximum parallel task count per instruction. + // 'shape_size': shape size function used by HloCostAnalysis during parallel + // task assignment. + ParallelTaskAssigner(const int64_t max_parallelism, + const HloCostAnalysis::ShapeSizeFunction& shape_size, + const TargetMachineFeatures* target_machine_features) + : max_parallelism_(max_parallelism), + shape_size_function_(shape_size), + target_machine_features_(*target_machine_features) {} + ~ParallelTaskAssigner() override {} + + absl::string_view name() const override { + return "cpu-parallel-task-assigner"; + } + + // Run parallel task assigner on computations with specified + // `execution_threads` in 'module'. By default, all `execution_threads` are + // included. Returns true if the computation was changed, false otherwise. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + using HloToParallelTasks = + absl::flat_hash_map; + + // Assigns target parallel tasks from 'hlo_to_parallel_tasks' to HLOs in + // 'module'. + // Returns true if the computation was changed, false otherwise. + bool AssignParallelTasks(HloModule* module, + const HloToParallelTasks& hlo_to_parallel_tasks); + bool AssignParallelTasksHelper( + HloModule* module, HloComputation* computation, + const HloToParallelTasks& hlo_to_parallel_tasks); + + // Computes target parallel task counts (returned in 'parallel_task_counts') + // for parallelizable instructions in 'module'. + void ComputeTargetParallelTasks(HloModule* module, + HloToParallelTasks* hlo_to_parallel_tasks); + + int64_t max_parallelism_; + HloCostAnalysis::ShapeSizeFunction shape_size_function_; + const TargetMachineFeatures& target_machine_features_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_PARALLEL_TASK_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/collectives.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/collectives.h new file mode 100644 index 0000000000000000000000000000000000000000..de277e67608e707a4269eb2cfc30b0b9696b1c62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/collectives.h @@ -0,0 +1,29 @@ +// Copyright 2022 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_COLLECTIVES_H_ +#define XLA_SERVICE_CPU_RUNTIME_COLLECTIVES_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace cpu { + +// Populate custom call implementing XLA CPU collectives +void PopulateXlaCpuCollectivesCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_COLLECTIVES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/convolution.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/convolution.h new file mode 100644 index 0000000000000000000000000000000000000000..dfabfc8ededaf81fc48793a3c951b1bc2f7a9c0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/convolution.h @@ -0,0 +1,46 @@ +// Copyright 2023 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_CONVOLUTION_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONVOLUTION_H_ + +#include + +#include "absl/types/span.h" +#include "xla/executable_run_options.h" +#include "xla/runtime/memref_view.h" + +namespace xla { +namespace cpu { + +struct XlaConvolution { + absl::Status operator()( + const ExecutableRunOptions* run_options, xla::runtime::MemrefView input, + xla::runtime::MemrefView kernel, xla::runtime::MemrefView output, + int64_t inputBatchDimension, + absl::Span inputSpatialDimensions, + int64_t inputFeatureDimension, + absl::Span kernelSpatialDimensions, + int64_t kernelInputFeatureDimension, int64_t kernelOutputFeatureDimension, + absl::Span outputSpatialDimensions, + absl::Span window_strides, + absl::Span padding, absl::Span lhs_dilation, + absl::Span rhs_dilation, + int64_t feature_group_count) const; + static XlaConvolution Handler() { return XlaConvolution(); } +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_CONVOLUTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/convolution_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/convolution_call.h new file mode 100644 index 0000000000000000000000000000000000000000..eea35e4b852d52d405bfe2703cd4c84b9da2d2c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/convolution_call.h @@ -0,0 +1,28 @@ +// Copyright 2023 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_CONVOLUTION_CALL_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONVOLUTION_CALL_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace cpu { + +// Populate custom call implementing XLA CPU Convolution. +void PopulateXlaCpuConvolutionCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_CONVOLUTION_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/custom_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/custom_call.h new file mode 100644 index 0000000000000000000000000000000000000000..ee8c0d8726bfbc6f9eb05b922df52c758a686961 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/custom_call.h @@ -0,0 +1,29 @@ +// Copyright 2022 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_CUSTOM_CALL_H_ +#define XLA_SERVICE_CPU_RUNTIME_CUSTOM_CALL_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace cpu { + +// Populate custom call implementing XLA CPU runtime API for the legacy ABI. +void PopulateXlaCpuCustomCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_CUSTOM_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/fft_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/fft_call.h new file mode 100644 index 0000000000000000000000000000000000000000..4865511d8dc26cbe8c89b23ef03d8f2aef6e2446 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/fft_call.h @@ -0,0 +1,28 @@ +// Copyright 2022 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_FFT_CALL_H_ +#define XLA_SERVICE_CPU_RUNTIME_FFT_CALL_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace cpu { + +// Populate custom call implementing XLA CPU FFT. +void PopulateXlaCpuFftCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_FFT_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/rng.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/rng.h new file mode 100644 index 0000000000000000000000000000000000000000..ff36b6fd1dd3bba4d6b0a02e9ec3bc7ba9de3023 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/rng.h @@ -0,0 +1,46 @@ +// Copyright 2023 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_RNG_H_ +#define XLA_SERVICE_CPU_RUNTIME_RNG_H_ + +#include + +#include "absl/status/status.h" +#include "xla/executable_run_options.h" +#include "xla/runtime/memref_view.h" + +namespace xla { +namespace cpu { + +struct XlaThreeFry { + absl::Status operator()(const ExecutableRunOptions*, + xla::runtime::FlatMemrefView state_buffer, + xla::runtime::FlatMemrefView state_out_buffer, + xla::runtime::FlatMemrefView values_buffer) const; + static XlaThreeFry Handler() { return XlaThreeFry(); } +}; + +struct XlaPhilox { + absl::Status operator()(const ExecutableRunOptions*, + xla::runtime::FlatMemrefView state_buffer, + xla::runtime::FlatMemrefView state_out_buffer, + xla::runtime::FlatMemrefView values_buffer) const; + static XlaPhilox Handler() { return XlaPhilox(); } +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_RNG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/rng_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/rng_call.h new file mode 100644 index 0000000000000000000000000000000000000000..ba95a1bbd1ef0cabe933480512554e4e5ae4eb95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/rng_call.h @@ -0,0 +1,29 @@ +// Copyright 2023 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_RNG_CALL_H_ +#define XLA_SERVICE_CPU_RUNTIME_RNG_CALL_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace cpu { + +// Populate custom call implementing XLA CPU RNGs. +void PopulateXlaCpuRngCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_RNG_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/xfeed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/xfeed.h new file mode 100644 index 0000000000000000000000000000000000000000..d4d5c9dca98ce43592f28cb944db16dd7b8578a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime/xfeed.h @@ -0,0 +1,29 @@ +// Copyright 2022 The TensorFlow Authors +// +// 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_SERVICE_CPU_RUNTIME_XFEED_H_ +#define XLA_SERVICE_CPU_RUNTIME_XFEED_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace cpu { + +// Populate custom call implementing XLA CPU infeed and outfeed. +void PopulateXlaXfeedCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_XFEED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d.h new file mode 100644 index 0000000000000000000000000000000000000000..42726f2d21a2153bd834442a70d7546e79697a3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d.h @@ -0,0 +1,50 @@ +/* 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_SERVICE_CPU_RUNTIME_CONV2D_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONV2D_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive + +extern "C" { + +extern void __xla_cpu_runtime_EigenConv2DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation, int64_t feature_group_count); + +extern void __xla_cpu_runtime_EigenConv2DF16( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + Eigen::half* out, Eigen::half* lhs, Eigen::half* rhs, int64_t input_batch, + int64_t input_rows, int64_t input_cols, int64_t input_channels, + int64_t kernel_rows, int64_t kernel_cols, int64_t kernel_channels, + int64_t kernel_filters, int64_t output_rows, int64_t output_cols, + int64_t row_stride, int64_t col_stride, int64_t padding_top, + int64_t padding_bottom, int64_t padding_left, int64_t padding_right, + int64_t lhs_row_dilation, int64_t lhs_col_dilation, + int64_t rhs_row_dilation, int64_t rhs_col_dilation, + int64_t feature_group_count); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_CONV2D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d_acl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d_acl.h new file mode 100644 index 0000000000000000000000000000000000000000..756642e0da81997e3483c3be467937eed3961ae4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d_acl.h @@ -0,0 +1,96 @@ +/* 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_SERVICE_CPU_RUNTIME_CONV2D_ACL_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONV2D_ACL_H_ + +#include "tsl/platform/types.h" + +#ifdef XLA_CPU_USE_ACL +#include "arm_compute/runtime/NEON/NEFunctions.h" +#include "arm_compute/runtime/NEON/NEScheduler.h" +#include "utils/Utils.h" + +extern "C" { +struct acl_depthwise_conv_obj_t { + arm_compute::NEDepthwiseConvolutionLayer depthwise_conv; + arm_compute::NEArithmeticAddition add; + arm_compute::NEActivationLayer act; + arm_compute::Tensor input_tensor; + arm_compute::Tensor kernel_tensor; + arm_compute::Tensor bia_tensor; + arm_compute::Tensor output_tensor; + arm_compute::Tensor output_acc_tensor; +}; + +struct acl_gemm_conv_obj_t { + arm_compute::NEGEMMConvolutionLayer gemm_conv; + arm_compute::NEArithmeticAddition add; + arm_compute::NEActivationLayer act; + arm_compute::Tensor input_tensor; + arm_compute::Tensor kernel_tensor; + arm_compute::Tensor bia_tensor; + arm_compute::Tensor output_tensor; + arm_compute::Tensor output_acc_tensor; +}; + +struct acl_conv_conf_t { + bool with_bias; + bool is_int8; + bool sum_with_eltwise; + bool fast_math; + arm_compute::TensorInfo input_info; + arm_compute::TensorInfo kernel_info; + arm_compute::TensorInfo bia_info; + arm_compute::TensorInfo output_info; + arm_compute::PadStrideInfo padstride_info; + arm_compute::Size2D dilation_info; + arm_compute::WeightsInfo kernel_wei_info; + arm_compute::ActivationLayerInfo act_info; +}; + +extern void __xla_cpu_runtime_ACLConv2DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation, int64_t feature_group_count); +} +#else +#include + +extern "C" { +inline extern void __xla_cpu_runtime_ACLConv2DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation, int64_t feature_group_count) { + std::cerr + << "Attempt to call ACL Conv2D runtime library without defining " + "XLA_CPU_USE_ACL. Add --define=build_with_acl=true to build with ACL."; + exit(1); +} +} +#endif // XLA_CPU_USE_ACL +#endif // XLA_SERVICE_CPU_RUNTIME_CONV2D_ACL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d_mkl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d_mkl.h new file mode 100644 index 0000000000000000000000000000000000000000..6bb1312bc7c8a1abcc8d206dc5d433a30d9e9d76 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv2d_mkl.h @@ -0,0 +1,35 @@ +/* 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_SERVICE_CPU_RUNTIME_CONV2D_MKL_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONV2D_MKL_H_ + +#include + +extern "C" { + +extern void __xla_cpu_runtime_MKLConv2DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation); +} + +#endif // XLA_SERVICE_CPU_RUNTIME_CONV2D_MKL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv3d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv3d.h new file mode 100644 index 0000000000000000000000000000000000000000..27976085437756437d93d0fd65dc34c2707f5d5e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv3d.h @@ -0,0 +1,53 @@ +/* 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_SERVICE_CPU_RUNTIME_CONV3D_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONV3D_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive + +extern "C" { + +extern void __xla_cpu_runtime_EigenConv3DF16( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + Eigen::half* out, Eigen::half* lhs, Eigen::half* rhs, int64_t input_batch, + int64_t input_x, int64_t input_y, int64_t input_z, int64_t input_channels, + int64_t kernel_x, int64_t kernel_y, int64_t kernel_z, + int64_t kernel_channels, int64_t kernel_filters, int64_t output_x, + int64_t output_y, int64_t output_z, int64_t x_stride, int64_t y_stride, + int64_t z_stride, int64_t padding_x_before, int64_t padding_x_after, + int64_t padding_y_before, int64_t padding_y_after, int64_t padding_z_before, + int64_t padding_z_after, int64_t lhs_x_dilation, int64_t lhs_y_dilation, + int64_t lhs_z_dilation, int64_t rhs_x_dilation, int64_t rhs_y_dilation, + int64_t rhs_z_dilation, int64_t feature_group_count); + +extern void __xla_cpu_runtime_EigenConv3DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_x, + int64_t input_y, int64_t input_z, int64_t input_channels, int64_t kernel_x, + int64_t kernel_y, int64_t kernel_z, int64_t kernel_channels, + int64_t kernel_filters, int64_t output_x, int64_t output_y, + int64_t output_z, int64_t x_stride, int64_t y_stride, int64_t z_stride, + int64_t padding_x_before, int64_t padding_x_after, int64_t padding_y_before, + int64_t padding_y_after, int64_t padding_z_before, int64_t padding_z_after, + int64_t lhs_x_dilation, int64_t lhs_y_dilation, int64_t lhs_z_dilation, + int64_t rhs_x_dilation, int64_t rhs_y_dilation, int64_t rhs_z_dilation, + int64_t feature_group_count); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_CONV3D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..613c14b1a5c6a572c22ccaa6decd02007f9bb7d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_conv_impl.h @@ -0,0 +1,197 @@ +/* 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_SERVICE_CPU_RUNTIME_CONV_IMPL_H_ +#define XLA_SERVICE_CPU_RUNTIME_CONV_IMPL_H_ + +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "tsl/framework/convolution/eigen_spatial_convolutions.h" + +#if defined(TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL) +#include "tsl/framework/contraction/eigen_contraction_kernel.h" +#endif + +// 'tensorflow' namespace is used so that types don't require qualification. +namespace tensorflow { +namespace xla { + +template +void EigenConv2DImpl( + const EigenDevice& device, ScalarType* out, ScalarType* lhs, + ScalarType* rhs, Eigen::Index input_batch, Eigen::Index input_x, + Eigen::Index input_y, Eigen::Index input_channels, Eigen::Index kernel_x, + Eigen::Index kernel_y, Eigen::Index kernel_channels, + Eigen::Index kernel_filters, Eigen::Index output_x, Eigen::Index output_y, + Eigen::Index x_stride, Eigen::Index y_stride, Eigen::Index padding_x_before, + Eigen::Index padding_x_after, Eigen::Index padding_y_before, + Eigen::Index padding_y_after, Eigen::Index lhs_x_dilation, + Eigen::Index lhs_y_dilation, Eigen::Index rhs_x_dilation, + Eigen::Index rhs_y_dilation, Eigen::Index feature_group_count) { + const Eigen::TensorMap, + Eigen::Aligned> + input(lhs, input_batch, input_x, input_y, input_channels); + + const Eigen::TensorMap, + Eigen::Aligned> + kernel(rhs, kernel_x, kernel_y, kernel_channels, kernel_filters); + + Eigen::TensorMap, + Eigen::Aligned> + output(out, input_batch, output_x, output_y, kernel_filters); + + Eigen::array, 1> contract_dims; + contract_dims[0] = Eigen::IndexPair(1, 0); + + Eigen::DSizes input_reshaped_dims; + input_reshaped_dims[0] = input_batch; + input_reshaped_dims[1] = input_x; + input_reshaped_dims[2] = input_y; + input_reshaped_dims[3] = feature_group_count; + input_reshaped_dims[4] = input_channels / feature_group_count; + + Eigen::DSizes output_reshaped_dims; + output_reshaped_dims[0] = input_batch; + output_reshaped_dims[1] = output_x; + output_reshaped_dims[2] = output_y; + output_reshaped_dims[3] = feature_group_count; + output_reshaped_dims[4] = kernel_filters / feature_group_count; + + // Molds the output of the patch extraction code into a 2d tensor: + // - the first dimension (dims[0]): the patch values to be multiplied with the + // kernels + // - the second dimension (dims[1]): everything else + Eigen::DSizes pre_contract_dims; + pre_contract_dims[0] = output_y * output_x * input_batch; + pre_contract_dims[1] = kernel_channels * kernel_y * kernel_x; + + // Molds the output of the contraction into the shape expected by the user: + Eigen::DSizes post_contract_dims; + post_contract_dims[0] = input_batch; + post_contract_dims[1] = output_x; + post_contract_dims[2] = output_y; + post_contract_dims[3] = kernel_filters / feature_group_count; + + Eigen::DSizes kernel_dims; + kernel_dims[0] = kernel_channels * kernel_y * kernel_x; + kernel_dims[1] = feature_group_count; + kernel_dims[2] = kernel_filters / feature_group_count; + + for (Eigen::Index i = 0; i < feature_group_count; ++i) { + // The row and column dimensions must be flipped when passed to Eigen. + output.reshape(output_reshaped_dims).chip(i, 3).device(device) = + input.reshape(input_reshaped_dims) + .chip(i, 3) + .extract_image_patches( + kernel_y, kernel_x, y_stride, x_stride, rhs_y_dilation, + rhs_x_dilation, lhs_y_dilation, lhs_x_dilation, + padding_y_before, padding_y_after, padding_x_before, + padding_x_after, static_cast(0.0f)) + .reshape(pre_contract_dims) + .contract(kernel.reshape(kernel_dims).chip(i, 1), contract_dims) + .reshape(post_contract_dims); + } +} + +template +void EigenConv3DImpl( + const EigenDevice& device, ScalarType* out, ScalarType* lhs, + ScalarType* rhs, Eigen::Index input_batch, Eigen::Index input_x, + Eigen::Index input_y, Eigen::Index input_z, Eigen::Index input_channels, + Eigen::Index kernel_x, Eigen::Index kernel_y, Eigen::Index kernel_z, + Eigen::Index kernel_channels, Eigen::Index kernel_filters, + Eigen::Index output_x, Eigen::Index output_y, Eigen::Index output_z, + Eigen::Index x_stride, Eigen::Index y_stride, Eigen::Index z_stride, + Eigen::Index padding_x_before, Eigen::Index padding_x_after, + Eigen::Index padding_y_before, Eigen::Index padding_y_after, + Eigen::Index padding_z_before, Eigen::Index padding_z_after, + Eigen::Index lhs_x_dilation, Eigen::Index lhs_y_dilation, + Eigen::Index lhs_z_dilation, Eigen::Index rhs_x_dilation, + Eigen::Index rhs_y_dilation, Eigen::Index rhs_z_dilation, + Eigen::Index feature_group_count) { + using ConstTType = + Eigen::TensorMap, + Eigen::Aligned>; + const ConstTType input(lhs, input_batch, input_x, input_y, input_z, + input_channels); + + const ConstTType kernel(rhs, kernel_x, kernel_y, kernel_z, kernel_channels, + kernel_filters); + + Eigen::TensorMap, + Eigen::Aligned> + output(out, input_batch, output_x, output_y, output_z, kernel_filters); + + Eigen::DSizes input_reshaped_dims; + input_reshaped_dims[0] = input_batch; + input_reshaped_dims[1] = input_x; + input_reshaped_dims[2] = input_y; + input_reshaped_dims[3] = input_z; + input_reshaped_dims[4] = feature_group_count; + input_reshaped_dims[5] = input_channels / feature_group_count; + + Eigen::DSizes output_reshaped_dims; + output_reshaped_dims[0] = input_batch; + output_reshaped_dims[1] = output_x; + output_reshaped_dims[2] = output_y; + output_reshaped_dims[3] = output_z; + output_reshaped_dims[4] = feature_group_count; + output_reshaped_dims[5] = kernel_filters / feature_group_count; + + Eigen::array, 1> contract_dims; + contract_dims[0] = Eigen::IndexPair(1, 0); + + // Molds the output of the patch extraction code into a 2d tensor: + // - the first dimension (dims[0]): the patch values to be multiplied with the + // kernels + // - the second dimension (dims[1]): everything else + Eigen::DSizes pre_contract_dims; + pre_contract_dims[0] = output_x * output_y * output_z * input_batch; + pre_contract_dims[1] = kernel_channels * kernel_x * kernel_y * kernel_z; + + // Molds the output of the contraction into the shape expected by the user: + Eigen::DSizes post_contract_dims; + post_contract_dims[0] = input_batch; + post_contract_dims[1] = output_x; + post_contract_dims[2] = output_y; + post_contract_dims[3] = output_z; + post_contract_dims[4] = kernel_filters / feature_group_count; + + Eigen::DSizes kernel_dims; + kernel_dims[0] = kernel_channels * kernel_x * kernel_y * kernel_z; + kernel_dims[1] = feature_group_count; + kernel_dims[2] = kernel_filters / feature_group_count; + + for (Eigen::Index i = 0; i < feature_group_count; ++i) { + // The dimension order must be flipped when passed to Eigen. + auto input_chip = input.reshape(input_reshaped_dims).chip(i, 4); + auto patches = + Eigen::TensorVolumePatchOp( + input_chip, kernel_z, kernel_y, kernel_x, z_stride, y_stride, + x_stride, rhs_z_dilation, rhs_y_dilation, rhs_x_dilation, + lhs_z_dilation, lhs_y_dilation, lhs_x_dilation, padding_z_before, + padding_z_after, padding_y_before, padding_y_after, + padding_x_before, padding_x_after, static_cast(0.0f)); + + output.reshape(output_reshaped_dims).chip(i, 4).device(device) = + patches.reshape(pre_contract_dims) + .contract(kernel.reshape(kernel_dims).chip(i, 1), contract_dims) + .reshape(post_contract_dims); + } +} + +} // namespace xla +} // namespace tensorflow + +#endif // XLA_SERVICE_CPU_RUNTIME_CONV_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_custom_call_status.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_custom_call_status.h new file mode 100644 index 0000000000000000000000000000000000000000..5300b4daecc3778d0fb76e01a732e4ff522564f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_custom_call_status.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_SERVICE_CPU_RUNTIME_CUSTOM_CALL_STATUS_H_ +#define XLA_SERVICE_CPU_RUNTIME_CUSTOM_CALL_STATUS_H_ + +extern "C" { + +// Returns true iff the given 'XlaCustomCallStatus' is in a success state, so +// that generated code can return early if a CustomCall fails. +extern bool __xla_cpu_runtime_StatusIsSuccess( + const void* /* XlaCustomCallStatus* */ status_ptr); +} + +#endif // XLA_SERVICE_CPU_RUNTIME_CUSTOM_CALL_STATUS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fft.h new file mode 100644 index 0000000000000000000000000000000000000000..a4c108892aba255fbd8aac3a74c892930434d851 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fft.h @@ -0,0 +1,31 @@ +/* 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_SERVICE_CPU_RUNTIME_FFT_H_ +#define XLA_SERVICE_CPU_RUNTIME_FFT_H_ + +#include + +extern "C" { + +extern void __xla_cpu_runtime_EigenFft( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, void* out, + void* operand, int32_t fft_type, int32_t double_precision, int32_t fft_rank, + int64_t input_batch, int64_t fft_length0, int64_t fft_length1, + int64_t fft_length2); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fft_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fft_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..682625e4fd9b1103bfee806d4533328120226310 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fft_impl.h @@ -0,0 +1,268 @@ +/* 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_SERVICE_CPU_RUNTIME_FFT_IMPL_H_ +#define XLA_SERVICE_CPU_RUNTIME_FFT_IMPL_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "xla/types.h" + +namespace xla { + +namespace internal { + +enum class FftType : int32_t { + FFT = 0, // Forward FFT; complex in, complex out. + IFFT = 1, // Inverse FFT; complex in, complex out. + RFFT = 2, // Forward real FFT; real in, fft_length / 2 + 1 complex out + IRFFT = 3, // Inverse real FFT; fft_length / 2 + 1 complex in, + // fft_length real out +}; +inline constexpr int FftTypeArraySize() { return 4; } + +// Computes either a forward or reverse complex-to-complex FFT. +template +void EigenFftC2C(const EigenDevice& device, Complex* out, Complex* operand, + int64_t input_batch, int64_t fft_length0, int64_t fft_length1, + int64_t fft_length2) { + // Create the axes (which are always trailing). + const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank); + constexpr auto direction = Forward ? Eigen::FFT_FORWARD : Eigen::FFT_REVERSE; + + const std::array fft_shape = { + {fft_length0, fft_length1, fft_length2}}; + + Eigen::DSizes dims; + dims[0] = input_batch; + for (int i = 0; i < FFTRank; i++) { + dims[i + 1] = fft_shape[i]; + } + const Eigen::TensorMap, + Eigen::Aligned> + input(operand, dims); + Eigen::TensorMap, + Eigen::Aligned> + output(out, dims); + output.device(device) = input.template fft(axes); +} + +// Computes a forward real->complex FFT, slicing out redundant negative +// frequencies from the innermost dimension. +template +void EigenFftR2C(const EigenDevice& device, Complex* out, Real* operand, + int64_t input_batch, int64_t fft_length0, int64_t fft_length1, + int64_t fft_length2) { + const std::array fft_shape = { + {fft_length0, fft_length1, fft_length2}}; + + Eigen::DSizes in_dims; + in_dims[0] = input_batch; + Eigen::DSizes out_dims; + out_dims[0] = input_batch; + for (int i = 0; i < FFTRank; i++) { + in_dims[i + 1] = fft_shape[i]; + out_dims[i + 1] = i == FFTRank - 1 ? fft_shape[i] / 2 + 1 : fft_shape[i]; + } + const Eigen::TensorMap, + Eigen::Aligned> + input(operand, in_dims); + Eigen::TensorMap, + Eigen::Aligned> + output(out, out_dims); + + // Create the axes (which are always trailing). + const auto axes = Eigen::ArrayXi::LinSpaced(FFTRank, 1, FFTRank); + + // Compute the full FFT using a temporary tensor. + Eigen::Tensor full_fft(in_dims); + + const Eigen::DSizes zero_start_indices; + full_fft.device(device) = + input.template fft(axes); + + // Slice away the negative frequency components. + output.device(device) = full_fft.slice(zero_start_indices, out_dims); +} + +// Computes a reverse complex->real FFT, reconstructing redundant negative +// frequencies using reverse conjugate on innermost dimension after doing IFFT +// on outer dimensions. +template +void EigenFftC2R(const EigenDevice& device, Real* out, Complex* operand, + int64_t input_batch, int64_t fft_length0, int64_t fft_length1, + int64_t fft_length2) { + const std::array fft_shape = { + {fft_length0, fft_length1, fft_length2}}; + + Eigen::DSizes in_dims; + in_dims[0] = input_batch; + Eigen::DSizes out_dims; + out_dims[0] = input_batch; + for (int i = 0; i < FFTRank; i++) { + in_dims[i + 1] = i == FFTRank - 1 ? fft_shape[i] / 2 + 1 : fft_shape[i]; + out_dims[i + 1] = fft_shape[i]; + } + const Eigen::TensorMap, + Eigen::Aligned> + input(operand, in_dims); + Eigen::TensorMap, + Eigen::Aligned> + output(out, out_dims); + + // Calculate the shape of the temporary tensor for the full FFT and the + // region we will slice from input given fft_shape. We slice input to + // fft_shape on its inner-most dimensions, except the last (which we + // slice to fft_shape[-1] / 2 + 1). + Eigen::Tensor full_fft(out_dims); + + // Calculate the starting point and range of the source of + // negative frequency part. + auto neg_sizes = in_dims; + neg_sizes[FFTRank] = fft_shape[FFTRank - 1] - in_dims[FFTRank]; + Eigen::DSizes neg_target_indices; + neg_target_indices[FFTRank] = in_dims[FFTRank]; + + const Eigen::DSizes zero_start_indices; + Eigen::DSizes neg_start_indices; + neg_start_indices[FFTRank] = 1; + + full_fft.slice(zero_start_indices, in_dims).device(device) = input; + + // First, conduct IFFTs on outer dimensions. We save computation (and + // avoid touching uninitialized memory) by slicing full_fft to the + // subregion we wrote input to. + if (FFTRank > 1) { + const auto outer_axes = + Eigen::ArrayXi::LinSpaced(FFTRank - 1, 1, FFTRank - 1); + full_fft.slice(zero_start_indices, in_dims).device(device) = + full_fft.slice(zero_start_indices, in_dims) + .template fft(outer_axes); + } + + // Reconstruct the full FFT by appending reversed and conjugated + // spectrum as the negative frequency part. + Eigen::array reverse_last_axis; + for (auto i = 0; i <= FFTRank; i++) { + reverse_last_axis[i] = i == FFTRank; + } + + if (neg_sizes[FFTRank] != 0) { + full_fft.slice(neg_target_indices, neg_sizes).device(device) = + full_fft.slice(neg_start_indices, neg_sizes) + .reverse(reverse_last_axis) + .conjugate(); + } + + auto inner_axis = Eigen::array{FFTRank}; + output.device(device) = + full_fft.template fft(inner_axis); +} + +template +void EigenFftWithRank(const EigenDevice& device, void* out, void* operand, + FftType fft_type, bool double_precision, + int64_t input_batch, int64_t fft_length0, + int64_t fft_length1, int64_t fft_length2) { + switch (fft_type) { + case FftType::FFT: + if (double_precision) { + EigenFftC2C( + device, static_cast(out), + static_cast(operand), input_batch, fft_length0, + fft_length1, fft_length2); + } else { + EigenFftC2C( + device, static_cast(out), + static_cast(operand), input_batch, fft_length0, + fft_length1, fft_length2); + } + break; + case FftType::IFFT: + if (double_precision) { + EigenFftC2C( + device, static_cast(out), + static_cast(operand), input_batch, fft_length0, + fft_length1, fft_length2); + } else { + EigenFftC2C( + device, static_cast(out), + static_cast(operand), input_batch, fft_length0, + fft_length1, fft_length2); + } + break; + case FftType::RFFT: + if (double_precision) { + EigenFftR2C( + device, static_cast(out), + static_cast(operand), input_batch, fft_length0, + fft_length1, fft_length2); + } else { + EigenFftR2C( + device, static_cast(out), static_cast(operand), + input_batch, fft_length0, fft_length1, fft_length2); + } + break; + case FftType::IRFFT: + if (double_precision) { + EigenFftC2R( + device, static_cast(out), + static_cast(operand), input_batch, fft_length0, + fft_length1, fft_length2); + } else { + EigenFftC2R( + device, static_cast(out), static_cast(operand), + input_batch, fft_length0, fft_length1, fft_length2); + } + break; + default: + // Unsupported FFT type + abort(); + } +} + +} // namespace internal + +template +void EigenFftImpl(const EigenDevice& device, void* out, void* operand, + internal::FftType fft_type, bool double_precision, + int32_t fft_rank, int64_t input_batch, int64_t fft_length0, + int64_t fft_length1, int64_t fft_length2) { + switch (fft_rank) { + case 1: + internal::EigenFftWithRank<1, EigenDevice>(device, out, operand, fft_type, + double_precision, input_batch, + fft_length0, 0, 0); + break; + case 2: + internal::EigenFftWithRank<2, EigenDevice>(device, out, operand, fft_type, + double_precision, input_batch, + fft_length0, fft_length1, 0); + break; + case 3: + internal::EigenFftWithRank<3, EigenDevice>( + device, out, operand, fft_type, double_precision, input_batch, + fft_length0, fft_length1, fft_length2); + break; + default: + // Unsupported FFT rank + abort(); + } +} + +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_FFT_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fork_join.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fork_join.h new file mode 100644 index 0000000000000000000000000000000000000000..4ecf4f07617d81e539290dfca163444277606c45 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fork_join.h @@ -0,0 +1,33 @@ +/* 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_SERVICE_CPU_RUNTIME_FORK_JOIN_H_ +#define XLA_SERVICE_CPU_RUNTIME_FORK_JOIN_H_ + +#include + +extern "C" { + +// Dispatches 'num_partitions' parallel calls to 'function_ptr' and joins +// threads before returning. See comments in runtime_fork_join.cc for details. +extern void __xla_cpu_runtime_ParallelForkJoin( + void* result_ptr, const void* run_options_ptr, const void** params, + void** buffer_table, void* status, uint64_t* prof_counters, + int32_t num_partitions, int64_t* partitions, int32_t num_partitioned_dims, + void* function_ptr); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_FORK_JOIN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fp16.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fp16.h new file mode 100644 index 0000000000000000000000000000000000000000..3f7af5197766a7707c782c66b2a2c931af546bd6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_fp16.h @@ -0,0 +1,46 @@ +/* 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_SERVICE_CPU_RUNTIME_FP16_H_ +#define XLA_SERVICE_CPU_RUNTIME_FP16_H_ + +#include + +// _Float16 always gets us the correct ABI type, so use that if available. +// AArch64 GCC defines __FLT16_MANT_DIG__ even when _Float16 is not available. +#if defined(__FLT16_MANT_DIG__) && \ + (defined(__clang__) || !(defined(__GNUC__) && defined(__aarch64__))) +using XlaF16ABIType = _Float16; +#elif defined(__x86_64__) +// Older versions of Clang don't have _Float16. Since both float and _Float16 +// are passed in the same register we can use the wider type and careful casting +// to conform to x86_64 psABI. This only works with the assumption that we're +// dealing with little-endian values passed in wider registers. +using XlaF16ABIType = float; +#else +// Default to uint16_t if we have nothing else. +using XlaF16ABIType = uint16_t; +#endif + +// Converts an F32 value to a F16. +extern "C" XlaF16ABIType __gnu_f2h_ieee(float); + +// Converts an F16 value to a F32. +extern "C" float __gnu_h2f_ieee(XlaF16ABIType); + +// Converts an F64 value to a F16. +extern "C" XlaF16ABIType __truncdfhf2(double); + +#endif // XLA_SERVICE_CPU_RUNTIME_FP16_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_key_value_sort.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_key_value_sort.h new file mode 100644 index 0000000000000000000000000000000000000000..2b450288770901827736855916da0276e89db76e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_key_value_sort.h @@ -0,0 +1,46 @@ +/* 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_SERVICE_CPU_RUNTIME_KEY_VALUE_SORT_H_ +#define XLA_SERVICE_CPU_RUNTIME_KEY_VALUE_SORT_H_ + +#include + +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive + +extern "C" { + +// Each entry in 'values' represents a 3-dimensional shape with dimensions +// [a, b, c]. The 'b' dimension of each shape is sorted into ascending order +// according to the results of comparisons using the provided 'less_than' +// function. 'values_count' must be > 0 and specifies the number of entries in +// 'values' and 'values_primitive_type_size_in_bytes'. The size of the primitive +// type of the i-th shape has exactly 'values_primitive_type_size_in_bytes[i]' +// bytes. 'is_stable' specifies whether the sorting should be stable. +// 'run_options' and 'prof_counters' are passed through to the less-than +// function, which expects the following arguments: +// - pointer to the return value buffer (char*) +// - xla::ExecutableRunOptions = 'run_options' (char*) +// - pointers to the parameter buffers (char**) +// - pointers to the buffer tables = nullptr for thread local functions (char**) +// - profile counters = 'prof_counters' (int64_t*) +extern void __xla_cpu_runtime_KeyValueSort( + int64_t a, int64_t b, int64_t c, char** values, int32_t values_count, + int32_t* values_primitive_type_size_in_bytes, bool is_stable, + char* run_options, int64_t* prof_counters, + void (*less_than)(char*, char*, char**, char**, int64_t*)); +} + +#endif // XLA_SERVICE_CPU_RUNTIME_KEY_VALUE_SORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_lightweight_check.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_lightweight_check.h new file mode 100644 index 0000000000000000000000000000000000000000..a882bd56f20879275305ea58f7e594a6b99e3d95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_lightweight_check.h @@ -0,0 +1,36 @@ +/* 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_SERVICE_CPU_RUNTIME_LIGHTWEIGHT_CHECK_H_ +#define XLA_SERVICE_CPU_RUNTIME_LIGHTWEIGHT_CHECK_H_ + +#include +#include + +// Aborts the program if the condition is false. +// +// This is like QCHECK, except it doesn't pull in the TF/XLA logging framework. +// This makes it suitable for use from within the XLA:CPU runtime files, which +// need to be lightweight. +#define XLA_LIGHTWEIGHT_CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::cerr << __FILE__ << ":" << __LINE__ \ + << " Failed XLA_LIGHTWEIGHT_QCHECK " << #cond << std::endl; \ + std::abort(); \ + } \ + } while (0) + +#endif // XLA_SERVICE_CPU_RUNTIME_LIGHTWEIGHT_CHECK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..ec6e9bf09682b655be2753348df8304bda736002 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_CPU_RUNTIME_MATMUL_H_ +#define XLA_SERVICE_CPU_RUNTIME_MATMUL_H_ + +#include + +#include + +#include "Eigen/Core" // from @eigen_archive + +extern "C" { + +// Performs a multi-threaded matrix multiplication using Eigen. 'lhs' and 'rhs' +// are pointers to buffers containing input matrices in column-major +// order. 'out' is a pointer to a buffer sufficiently large to hold the result +// of the operation. Following standard nomenclature: lhs is m x k, +// rhs is k x n, and out is m x n. +extern void __xla_cpu_runtime_EigenMatMulF16( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + Eigen::half* out, Eigen::half* lhs, Eigen::half* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenMatMulF64( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, double* out, + double* lhs, double* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenMatMulC64( + const void* run_options_ptr, std::complex* out, + std::complex* lhs, std::complex* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenMatMulC128( + const void* run_options_ptr, std::complex* out, + std::complex* lhs, std::complex* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenMatMulS32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, int32_t* out, + int32_t* lhs, int32_t* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenBatchMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, int64_t batch_size, + int32_t transpose_lhs, int32_t transpose_rhs); +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_MATMUL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul_acl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul_acl.h new file mode 100644 index 0000000000000000000000000000000000000000..57d522c3d04f27c4d4babbf175b0f7d8653994ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul_acl.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_SERVICE_CPU_RUNTIME_MATMUL_ACL_H_ +#define XLA_SERVICE_CPU_RUNTIME_MATMUL_ACL_H_ + +#include + +#include "tsl/platform/types.h" + +#ifdef XLA_CPU_USE_ACL +#include "arm_compute/runtime/NEON/NEFunctions.h" +#include "arm_compute/runtime/NEON/NEScheduler.h" +#include "utils/Utils.h" + +extern "C" { +struct acl_matmul_obj_t { + arm_compute::NEGEMM gemm; + arm_compute::NETranspose trans_lhs; + arm_compute::NETranspose trans_rhs; + arm_compute::Tensor rhs_tensor; + arm_compute::Tensor rhs_acc_tensor; + arm_compute::Tensor lhs_tensor; + arm_compute::Tensor lhs_acc_tensor; + arm_compute::Tensor out_tensor; +}; + +struct acl_matmul_conf_t { + bool with_bias; + bool is_trans_lhs; + bool is_trans_rhs; + arm_compute::TensorInfo lhs_info; + arm_compute::TensorInfo lhs_acc_info; + arm_compute::TensorInfo rhs_info; + arm_compute::TensorInfo rhs_acc_info; + arm_compute::TensorInfo out_info; + arm_compute::GEMMInfo gemm_info; + float alpha; +}; + +extern void __xla_cpu_runtime_ACLMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_ACLBatchMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, int64_t batch_size, + int32_t transpose_lhs, int32_t transpose_rhs); + +} // extern "C" +#else +extern "C" { +inline extern void __xla_cpu_runtime_ACLMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs) { + std::cerr + << "Attempt to call ACL MatMul runtime library without defining " + "XLA_CPU_USE_ACL. Add --define=build_with_acl=true to build with ACL."; + exit(1); +} + +inline extern void __xla_cpu_runtime_ACLBatchMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, int64_t batch_size, + int32_t transpose_lhs, int32_t transpose_rhs) { + std::cerr + << "Attempt to call ACL MatMul runtime library without defining " + "XLA_CPU_USE_ACL. Add --define=build_with_acl=true to build with ACL."; + exit(1); +} +} // extern "C" +#endif // XLA_CPU_USE_ACL +#endif // XLA_SERVICE_CPU_RUNTIME_MATMUL_ACL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul_common.h new file mode 100644 index 0000000000000000000000000000000000000000..a08be9d36680ebea3a812997d91de71bcf754b6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_matmul_common.h @@ -0,0 +1,154 @@ +/* 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_SERVICE_CPU_RUNTIME_MATMUL_COMMON_H_ +#define XLA_SERVICE_CPU_RUNTIME_MATMUL_COMMON_H_ + +#include + +#define EIGEN_USE_THREADS + +#include "absl/base/dynamic_annotations.h" +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "xla/executable_run_options.h" +#include "xla/service/cpu/runtime_lightweight_check.h" + +#if defined(TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL) +#include "tsl/framework/contraction/eigen_contraction_kernel.h" +#endif + +namespace xla { + +static inline bool Is16BytesAligned(void* ptr) { + return reinterpret_cast(ptr) % 16 == 0; +} + +template +void MatMul(const void* run_options_ptr, T* out, T* lhs, T* rhs, int64_t m, + int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + + int64_t lhs_rows = m; + int64_t lhs_cols = k; + if (transpose_lhs) { + std::swap(lhs_rows, lhs_cols); + } + + int64_t rhs_rows = k; + int64_t rhs_cols = n; + if (transpose_rhs) { + std::swap(rhs_rows, rhs_cols); + } + + const Eigen::TensorMap, Alignment> A(lhs, lhs_rows, + lhs_cols); + const Eigen::TensorMap, Alignment> B(rhs, rhs_rows, + rhs_cols); + Eigen::TensorMap, Alignment> C(out, m, n); + + typedef typename Eigen::Tensor::DimensionPair DimPair; + int lhs_contract_dim = transpose_lhs ? 0 : 1; + int rhs_contract_dim = transpose_rhs ? 1 : 0; + const Eigen::array dims( + {DimPair(lhs_contract_dim, rhs_contract_dim)}); + + // Matrix multiply is a special case of the "contract" operation where + // the contraction is performed along dimension 1 of the lhs and dimension + // 0 of the rhs. + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + C.device(*run_options->intra_op_thread_pool()) = A.contract(B, dims); +} + +template +void MatMul_Batch(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, Eigen::Index batch_size, + int32_t transpose_lhs, int32_t transpose_rhs) { + const xla::ExecutableRunOptions* run_options = + static_cast(run_options_ptr); + + int64_t lhs_rows = m; + int64_t lhs_cols = k; + if (transpose_lhs) { + std::swap(lhs_rows, lhs_cols); + } + + int64_t rhs_rows = k; + int64_t rhs_cols = n; + if (transpose_rhs) { + std::swap(rhs_rows, rhs_cols); + } + + const Eigen::TensorMap, Alignment> A( + lhs, lhs_rows, lhs_cols, batch_size); + const Eigen::TensorMap, Alignment> B( + rhs, rhs_rows, rhs_cols, batch_size); + Eigen::TensorMap, Alignment> C(out, m, n, batch_size); + + typedef typename Eigen::Tensor::DimensionPair DimPair; + int lhs_contract_dim = transpose_lhs ? 0 : 1; + int rhs_contract_dim = transpose_rhs ? 1 : 0; + + const Eigen::array dims( + {DimPair(lhs_contract_dim, rhs_contract_dim)}); + + // Matrix multiply is a special case of the "contract" operation where + // the contraction is performed along dimension 1 of the lhs and dimension + // 0 of the rhs. + XLA_LIGHTWEIGHT_CHECK(run_options->intra_op_thread_pool() != nullptr); + + for (int64_t i = 0; i < batch_size; ++i) { + C.chip(i, 2).device(*run_options->intra_op_thread_pool()) = + A.chip(i, 2).contract(B.chip(i, 2), dims); + } +} + +template +void MatMulDispatch(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, int32_t transpose_lhs, + int32_t transpose_rhs) { + bool all_buffers_16b_aligned = + Is16BytesAligned(out) && Is16BytesAligned(lhs) && Is16BytesAligned(rhs); + + if (!all_buffers_16b_aligned) { + MatMul(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); + return; + } + + MatMul(run_options_ptr, out, lhs, rhs, m, n, k, + transpose_lhs, transpose_rhs); +} + +template +void BatchMatMulDispatch(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, int64_t batch_size, + int32_t transpose_lhs, int32_t transpose_rhs) { + bool all_buffers_16b_aligned = + Is16BytesAligned(out) && Is16BytesAligned(lhs) && Is16BytesAligned(rhs); + + if (!all_buffers_16b_aligned) { + MatMul_Batch(run_options_ptr, out, lhs, rhs, m, n, k, + batch_size, transpose_lhs, transpose_rhs); + return; + } + MatMul_Batch(run_options_ptr, out, lhs, rhs, m, n, k, + batch_size, transpose_lhs, transpose_rhs); +} + +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_MATMUL_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_pow.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_pow.h new file mode 100644 index 0000000000000000000000000000000000000000..0dee0c607900e7006ee97337902e0042eacbf558 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_pow.h @@ -0,0 +1,27 @@ +/* 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_SERVICE_CPU_RUNTIME_POW_H_ +#define XLA_SERVICE_CPU_RUNTIME_POW_H_ + +#include + +// Raises F32 value a to the power of b. +extern "C" float __powisf2(float a, int32_t b); + +// Raises F64 value a to the power of b. +extern "C" double __powidf2(double a, int32_t b); + +#endif // XLA_SERVICE_CPU_RUNTIME_POW_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_conv2d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_conv2d.h new file mode 100644 index 0000000000000000000000000000000000000000..76c1bbb221e884a1082bbd7a028143b9f7ac6c60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_conv2d.h @@ -0,0 +1,50 @@ +/* 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_SERVICE_CPU_RUNTIME_SINGLE_THREADED_CONV2D_H_ +#define XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_CONV2D_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive + +extern "C" { + +extern void __xla_cpu_runtime_EigenSingleThreadedConv2DF16( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + Eigen::half* out, Eigen::half* lhs, Eigen::half* rhs, int64_t input_batch, + int64_t input_rows, int64_t input_cols, int64_t input_channels, + int64_t kernel_rows, int64_t kernel_cols, int64_t kernel_channels, + int64_t kernel_filters, int64_t output_rows, int64_t output_cols, + int64_t row_stride, int64_t col_stride, int64_t padding_top, + int64_t padding_bottom, int64_t padding_left, int64_t padding_right, + int64_t lhs_row_dilation, int64_t lhs_col_dilation, + int64_t rhs_row_dilation, int64_t rhs_col_dilation, + int64_t feature_group_count); + +extern void __xla_cpu_runtime_EigenSingleThreadedConv2DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_rows, + int64_t input_cols, int64_t input_channels, int64_t kernel_rows, + int64_t kernel_cols, int64_t kernel_channels, int64_t kernel_filters, + int64_t output_rows, int64_t output_cols, int64_t row_stride, + int64_t col_stride, int64_t padding_top, int64_t padding_bottom, + int64_t padding_left, int64_t padding_right, int64_t lhs_row_dilation, + int64_t lhs_col_dilation, int64_t rhs_row_dilation, + int64_t rhs_col_dilation, int64_t feature_group_count); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_CONV2D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_conv3d.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_conv3d.h new file mode 100644 index 0000000000000000000000000000000000000000..b9f3e3558a8f6be65b10d705be6d1bf70243c220 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_conv3d.h @@ -0,0 +1,53 @@ +/* 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_SERVICE_CPU_RUNTIME_SINGLE_THREADED_CONV3D_H_ +#define XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_CONV3D_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive + +extern "C" { + +extern void __xla_cpu_runtime_EigenSingleThreadedConv3DF16( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + Eigen::half* out, Eigen::half* lhs, Eigen::half* rhs, int64_t input_batch, + int64_t input_x, int64_t input_y, int64_t input_z, int64_t input_channels, + int64_t kernel_x, int64_t kernel_y, int64_t kernel_z, + int64_t kernel_channels, int64_t kernel_filters, int64_t output_x, + int64_t output_y, int64_t output_z, int64_t x_stride, int64_t y_stride, + int64_t z_stride, int64_t padding_x_before, int64_t padding_x_after, + int64_t padding_y_before, int64_t padding_y_after, int64_t padding_z_before, + int64_t padding_z_after, int64_t lhs_x_dilation, int64_t lhs_y_dilation, + int64_t lhs_z_dilation, int64_t rhs_x_dilation, int64_t rhs_y_dilation, + int64_t rhs_z_dilation, int64_t feature_group_count); + +extern void __xla_cpu_runtime_EigenSingleThreadedConv3DF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t input_batch, int64_t input_x, + int64_t input_y, int64_t input_z, int64_t input_channels, int64_t kernel_x, + int64_t kernel_y, int64_t kernel_z, int64_t kernel_channels, + int64_t kernel_filters, int64_t output_x, int64_t output_y, + int64_t output_z, int64_t x_stride, int64_t y_stride, int64_t z_stride, + int64_t padding_x_before, int64_t padding_x_after, int64_t padding_y_before, + int64_t padding_y_after, int64_t padding_z_before, int64_t padding_z_after, + int64_t lhs_x_dilation, int64_t lhs_y_dilation, int64_t lhs_z_dilation, + int64_t rhs_x_dilation, int64_t rhs_y_dilation, int64_t rhs_z_dilation, + int64_t feature_group_count); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_CONV3D_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_fft.h new file mode 100644 index 0000000000000000000000000000000000000000..ee899d91f409f488641f89029e89847e76d6ec4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_fft.h @@ -0,0 +1,31 @@ +/* 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_SERVICE_CPU_RUNTIME_SINGLE_THREADED_FFT_H_ +#define XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_FFT_H_ + +#include + +extern "C" { + +extern void __xla_cpu_runtime_EigenSingleThreadedFft( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, void* out, + void* operand, int32_t fft_type, int32_t double_precision, int32_t fft_rank, + int64_t input_batch, int64_t fft_length0, int64_t fft_length1, + int64_t fft_length2); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..da336bc0ec6a73b414e53df533ee084027e9d241 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul.h @@ -0,0 +1,65 @@ +/* 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_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_H_ +#define XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_H_ + +#include +#include + +#include "Eigen/Core" // from @eigen_archive + +extern "C" { + +// Performs a single-threaded matrix multiplication using Eigen. 'lhs' and 'rhs' +// are pointers to buffers containing input matrices in column-major order. +// 'out' is a pointer to a buffer sufficiently large to hold the result of the +// operation. Following standard nomenclature: lhs is m x k, rhs is k x n, and +// out is m x n. +extern void __xla_cpu_runtime_EigenSingleThreadedMatMulF16( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + Eigen::half* out, Eigen::half* lhs, Eigen::half* rhs, int64_t m, int64_t n, + int64_t k, int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenSingleThreadedMatMulF32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, float* out, + float* lhs, float* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenSingleThreadedMatMulF64( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, double* out, + double* lhs, double* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenSingleThreadedMatMulC64( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + std::complex* out, std::complex* lhs, + std::complex* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenSingleThreadedMatMulC128( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, + std::complex* out, std::complex* lhs, + std::complex* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +extern void __xla_cpu_runtime_EigenSingleThreadedMatMulS32( + const void* /* xla::ExecutableRunOptions* */ run_options_ptr, int32_t* out, + int32_t* lhs, int32_t* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs); + +} // extern "C" + +#endif // XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul_common.h new file mode 100644 index 0000000000000000000000000000000000000000..f6e3cd5c34209bfdbcf8978dfc64deb9fabc498f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_single_threaded_matmul_common.h @@ -0,0 +1,88 @@ +/* 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_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_COMMON_H_ +#define XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_COMMON_H_ + +#include + +#include "absl/base/attributes.h" +#include "Eigen/Core" // from @eigen_archive +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive + +#if defined(TENSORFLOW_USE_CUSTOM_CONTRACTION_KERNEL) +#include "tsl/framework/contraction/eigen_contraction_kernel.h" +#endif + +namespace xla { + +static inline bool Is16BytesAligned(void* ptr) { + return reinterpret_cast(ptr) % 16 == 0; +} + +template +void SingleThreadedMatMul(const void* run_options_ptr, T* out, T* lhs, T* rhs, + int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, int32_t transpose_rhs) { + int64_t lhs_rows = m; + int64_t lhs_cols = k; + if (transpose_lhs) { + std::swap(lhs_rows, lhs_cols); + } + + int64_t rhs_rows = k; + int64_t rhs_cols = n; + if (transpose_rhs) { + std::swap(rhs_rows, rhs_cols); + } + + const Eigen::TensorMap, Alignment> A(lhs, lhs_rows, + lhs_cols); + const Eigen::TensorMap, Alignment> B(rhs, rhs_rows, + rhs_cols); + Eigen::TensorMap, Alignment> C(out, m, n); + + typedef typename Eigen::Tensor::DimensionPair DimPair; + int lhs_contract_dim = transpose_lhs ? 0 : 1; + int rhs_contract_dim = transpose_rhs ? 1 : 0; + const Eigen::array dims( + {DimPair(lhs_contract_dim, rhs_contract_dim)}); + + // Matrix multiply is a special case of the "contract" operation where + // the contraction is performed along dimension 1 of the lhs and dimension + // 0 of the rhs. + C = A.contract(B, dims); +} + +template +void SingleThreadedMatMulDispatch(const void* run_options_ptr, T* out, T* lhs, + T* rhs, int64_t m, int64_t n, int64_t k, + int32_t transpose_lhs, + int32_t transpose_rhs) { + bool all_buffers_16b_aligned = + Is16BytesAligned(out) && Is16BytesAligned(lhs) && Is16BytesAligned(rhs); + + if (!all_buffers_16b_aligned) { + SingleThreadedMatMul( + run_options_ptr, out, lhs, rhs, m, n, k, transpose_lhs, transpose_rhs); + } + + SingleThreadedMatMul(run_options_ptr, out, lhs, rhs, m, + n, k, transpose_lhs, transpose_rhs); +} + +} // namespace xla + +#endif // XLA_SERVICE_CPU_RUNTIME_SINGLE_THREADED_MATMUL_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_topk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_topk.h new file mode 100644 index 0000000000000000000000000000000000000000..e33766c7a83cf759a753b6e746a72ba1bcca0751 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/runtime_topk.h @@ -0,0 +1,30 @@ +/* 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_SERVICE_CPU_RUNTIME_TOPK_H_ +#define XLA_SERVICE_CPU_RUNTIME_TOPK_H_ + +#include + +extern "C" { + +// Calculates `batch_size` topk operations with `input_size` inputs each. The +// outputs are written to `out_values` and `out_indices`. +extern void __xla_cpu_runtime_TopKF32(int64_t batch_size, int64_t input_size, + int64_t k, const float* values, + float* out_values, int32_t* out_indices); +} + +#endif // XLA_SERVICE_CPU_RUNTIME_TOPK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/shape_partition.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/shape_partition.h new file mode 100644 index 0000000000000000000000000000000000000000..ac6667ae532642b6a8996baf26aed721d1857fd9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/shape_partition.h @@ -0,0 +1,105 @@ +/* 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_SERVICE_CPU_SHAPE_PARTITION_H_ +#define XLA_SERVICE_CPU_SHAPE_PARTITION_H_ + +#include + +#include "xla/shape_util.h" + +namespace xla { +namespace cpu { + +// ShapePartitionAssigner partitions the most-major dimensions of 'shape' such +// that the total partition count <= 'target_partition_count'. +// +// Example 1: +// +// Let 'shape' = [8, 16, 32] and 'target_partition_count' = 6. +// +// Because the most-major dimension size is <= 'target_partition_count', we +// can generate our target number of partitions by partition the most-major +// dimensions. +// +// This will result in the following partitions of the most-major dimension: +// +// [0, 1), [1, 2), [2, 3), [3, 4), [4, 5) [5, 8) +// +// Note that the last partition has residual because the dimension size is +// not a multiple of the partition count. +// +// +// Example 2: +// +// Let 'shape' = [8, 16, 32] and 'target_partition_count' = 16. +// +// Because the most-major dimension only has size 8, we must also partition +// the next most-major dimension to generate the target of 16 partitions. +// We factor 'target_partition_count' by the number of most-major dimensions +// we need to partition, to get a per-dimension target partition count: +// +// target_dimension_partition_count = 16 ^ (1 / 2) == 4 +// +// This will result in the following partitions of the most-major dimension: +// +// [0, 2), [2, 4), [4, 6), [6, 8) +// +// This will result in the following partitions of the second most-major +// dimension: +// +// [0, 4), [4, 8), [8, 12), [12, 16) +// +class ShapePartitionAssigner { + public: + ShapePartitionAssigner(const Shape& shape) : shape_(shape) {} + + // Returns dimension partition counts (starting at outer-most dimension). + std::vector Run(int64_t target_partition_count); + + // Returns the total partition count based on 'dimension_partition_counts'. + static int64_t GetTotalPartitionCount( + const std::vector& dimension_partition_counts); + + private: + const Shape& shape_; +}; + +// ShapePartitionIterator iterates through outer-dimension partitions of +// 'shape' as specified by 'dimension_partition_counts'. +class ShapePartitionIterator { + public: + ShapePartitionIterator(const Shape& shape, + absl::Span dimension_partition_counts); + + // Returns a partition [start, size] for each dimension. + // Partitions are listed starting from outer-most dimension first. + std::vector> GetPartition(int64_t index) const; + + int64_t GetTotalPartitionCount() const; + + private: + const Shape& shape_; + const std::vector dimension_partition_counts_; + + std::vector dimensions_; + std::vector dimension_partition_sizes_; + std::vector dimension_partition_strides_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_SHAPE_PARTITION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/simple_orc_jit.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/simple_orc_jit.h new file mode 100644 index 0000000000000000000000000000000000000000..a6fa7f896a28a6da1963ed453cc2520cd9212779 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/simple_orc_jit.h @@ -0,0 +1,138 @@ +/* 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_SERVICE_CPU_SIMPLE_ORC_JIT_H_ +#define XLA_SERVICE_CPU_SIMPLE_ORC_JIT_H_ + +#include +#include +#include + +#include "llvm/ExecutionEngine/JITEventListener.h" +#include "llvm/ExecutionEngine/Orc/Core.h" +#include "llvm/ExecutionEngine/Orc/ExecutorProcessControl.h" +#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" +#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" +#include "llvm/ExecutionEngine/Orc/SymbolStringPool.h" +#include "llvm/IR/Module.h" +#include "llvm/Target/TargetMachine.h" +#include "llvm/TargetParser/Triple.h" +#include "xla/service/cpu/compiler_functor.h" +#include "xla/types.h" + +namespace xla { +namespace cpu { + +// Simplified LLVM JIT based on the new Orc API. +// +// This class wraps Orc's functionality into a single interface that only +// exposes what we need for XLA. +// +// Supports JIT-ing multiple modules but without cross-module linking. +// Implements eager compilation - the module is lowered to binary as soon as +// it's added to the JIT. +class SimpleOrcJIT : public llvm::JITEventListener { + public: + using ObjLayerT = llvm::orc::RTDyldObjectLinkingLayer; + using CompileLayerT = llvm::orc::IRCompileLayer; + + // Create a new JIT, targeting the host architecture. + // + // {pre,post}_optimization_hook is invoked on the module before/after all + // LLVM IR-level optimizations. post_codegen_hook is invoked after + // compiling to machine code. + SimpleOrcJIT( + std::unique_ptr target_process_control, + std::unique_ptr execution_session, + const llvm::TargetOptions& target_options, + llvm::CodeGenOptLevel opt_level, bool optimize_for_size, + bool disable_expensive_passes, bool disable_slp_vectorizer, + llvm::FastMathFlags fast_math_flags, + LLVMCompiler::ModuleHook pre_optimization_hook, + LLVMCompiler::ModuleHook post_optimization_hook, + std::function post_codegen_hook); + + static llvm::Expected> Create( + const llvm::TargetOptions& target_options, + llvm::CodeGenOptLevel opt_level, bool optimize_for_size, + bool disable_expensive_passes, bool disable_slp_vectorizer, + llvm::FastMathFlags fast_math_flags, + LLVMCompiler::ModuleHook pre_optimization_hook, + LLVMCompiler::ModuleHook post_optimization_hook, + std::function post_codegen_hook); + + ~SimpleOrcJIT() override; + + const llvm::DataLayout& data_layout() const { return data_layout_; } + + const llvm::Triple& target_triple() const { return target_triple_; } + + llvm::Error AddModule(llvm::orc::ThreadSafeModule module); + + // Discards objects we no longer need once we are done compiling. + void DoneCompiling(); + + // Get the runtime address of the compiled symbol whose name is given. Returns + // nullptr if the symbol cannot be found. + llvm::Expected FindCompiledSymbol( + const std::string& name); + + llvm::TargetMachine* target_machine() const { return target_machine_.get(); } + + // Creates an llvm::TargetMachine suitable for JITting code that will run on + // the current machine. + static std::unique_ptr InferTargetMachineForJIT( + const llvm::TargetOptions& target_options, + llvm::CodeGenOptLevel opt_level); + + int64_t SizeOfGeneratedCodeInBytes() const { + return size_of_generated_code_in_bytes_; + } + + private: + llvm::orc::ExecutorSymbolDef ResolveRuntimeSymbol(llvm::StringRef name); + + void notifyObjectLoaded( + llvm::JITEventListener::ObjectKey key, + const llvm::object::ObjectFile& object, + const llvm::RuntimeDyld::LoadedObjectInfo& object_info) override; + void notifyFreeingObject(llvm::JITEventListener::ObjectKey key) override; + + std::unique_ptr target_machine_; + llvm::Triple target_triple_; + const llvm::DataLayout data_layout_; + std::unique_ptr target_process_control_; + std::unique_ptr execution_session_; + ObjLayerT object_layer_; + CompileLayerT compile_layer_; + llvm::orc::JITDylib* main_jit_dylib_; + int64_t size_of_generated_code_in_bytes_ = 0; + + // Non owning pointer to a JIT event listener that registers the JIT events + // with an attached GDB. + // + // Note: we get a pointer to this event listener using + // `createGDBRegistrationListener` which makes it look like we're supposed to + // free this, but the function is poorly named and really just returns a + // pointer to a static object. + llvm::JITEventListener* gdb_jit_event_listener_; + + llvm::JITEventListener* perf_jit_event_listener_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_SIMPLE_ORC_JIT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/target_machine_features.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/target_machine_features.h new file mode 100644 index 0000000000000000000000000000000000000000..65b7621a80ded6d5366d57ad6596e2c8f855ac21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/target_machine_features.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_SERVICE_CPU_TARGET_MACHINE_FEATURES_H_ +#define XLA_SERVICE_CPU_TARGET_MACHINE_FEATURES_H_ + +#include "absl/container/flat_hash_map.h" +#include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/Target/TargetMachine.h" +#include "xla/primitive_util.h" + +namespace xla { +namespace cpu { + +// Abstract interface for classes providing information about the target we're +// compiling for. +class TargetMachineFeatures { + public: + static constexpr int kX86AvxVectorByteSize = 32; + + // Input and output tensor buffers must be aligned to this many bytes if we + // want to call an Eigen backed GEMM or Convolution. + static constexpr int kEigenExpectedTensorAlignment = 16; + + // Return the vectorization factor, which is the number of bytes of data + // explicitly vectorized routines will try to process at once. + virtual int vectorization_factor_in_bytes() const = 0; + + // Return the size of the largest vector size in bytes. We need to pass in + // "function" since llvm functions can contain annotations for specializing + // them to specific micro-architectures (though currently XLA does not use + // this functionality). + virtual int vector_register_byte_size( + const llvm::Function& function) const = 0; + + // Return the number of elements of type `type` that can fit into the largest + // vector register available. We need to pass in "function" since llvm + // functions can contain annotations for specializing them to specific + // micro-architectures (though currently XLA does not use this functionality). + virtual int vector_register_num_elements(const llvm::Function& function, + PrimitiveType type) const = 0; + + // Return the number of vector registers. We need to pass in + // "function" since llvm functions can contain annotations for specializing + // them to specific micro-architectures (though currently XLA does not use + // this functionality). + virtual int vector_register_count(const llvm::Function& function) const = 0; + + // Returns the minimum alignment for a buffer of size size_bytes. + virtual int64_t minimum_alignment_for_allocation( + int64_t size_bytes) const = 0; + + virtual ~TargetMachineFeatures() = default; +}; + +// Implements the TargetMachineFeatures interface using an llvm::TargetMachine. +class LLVMTargetMachineFeatures : public TargetMachineFeatures { + public: + static constexpr int kX86AvxVectorByteSize = 32; + + LLVMTargetMachineFeatures(llvm::TargetMachine* target_machine) + : target_machine_(target_machine) {} + + int vectorization_factor_in_bytes() const override { + // Ideally this should be a function of the cache line size (which we can + // get from llvm::TargetTransformInfo::getCacheLineSize) of the target + // machine. Guess a value of 128 bytes for now. + return 128; + } + + int vector_register_byte_size(const llvm::Function& function) const override { + llvm::TargetTransformInfo* tti = GetTargetTransformInfoFor(function); + return tti->getRegisterBitWidth( + llvm::TargetTransformInfo::RGK_FixedWidthVector) / + 8; + } + + int vector_register_num_elements(const llvm::Function& function, + PrimitiveType type) const override { + return vector_register_byte_size(function) / + (primitive_util::BitWidth(type) / 8); + } + + int vector_register_count(const llvm::Function& function) const override { + llvm::TargetTransformInfo* tti = GetTargetTransformInfoFor(function); + return static_cast(tti->getNumberOfRegisters( + tti->getRegisterClassForType(/*Vector=*/true))); + } + + int64_t minimum_alignment_for_allocation(int64_t size_bytes) const override; + + private: + llvm::TargetTransformInfo* GetTargetTransformInfoFor( + const llvm::Function& function) const; + + // This cache saves us from having to create a llvm::TargetTransformInfo for + // every call to GetTargetTransformInfoFor (creating a TargetTransformInfo + // costs one heap allocation on X86). + // + // This is mutated from within `GetTargetTransformInfoFor` which is + // semantically a getter (and thus `const`); and is therefore declared + // mutable. Making this mutable is okay because it has cache semantics. + mutable absl::flat_hash_map + target_transform_info_cache_; + llvm::TargetMachine* target_machine_; +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_TARGET_MACHINE_FEATURES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/tiled_dot_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/tiled_dot_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..e5060453a51556b013497441855d2ea818b6f735 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/tiled_dot_emitter.h @@ -0,0 +1,51 @@ +/* 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_SERVICE_CPU_TILED_DOT_EMITTER_H_ +#define XLA_SERVICE_CPU_TILED_DOT_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "xla/service/hlo_module_config.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace cpu { + +// These routines emit LLVM IR implementing tiled GEMM and GEMV routines. + +void EmitRowMajorGemv(PrimitiveType scalar_type, int64_t tile_rows, + int64_t tile_cols, int64_t m, int64_t k, llvm::Value* lhs, + llvm::Value* rhs, llvm::Value* addend, + llvm::Value* result, llvm::IRBuilder<>* b, + const HloModuleConfig& module_config); + +void EmitColumnMajorGemv(PrimitiveType scalar_type, int64_t tile_rows, + int64_t tile_cols, int64_t m, int64_t k, + llvm::Value* lhs, llvm::Value* rhs, + llvm::Value* addend, llvm::Value* result, + llvm::IRBuilder<>* b, + const HloModuleConfig& module_config); + +void EmitSmallGemm(PrimitiveType scalar_type, int64_t m, int64_t k, int64_t n, + int64_t max_vectorization_width, int64_t max_vector_count, + int64_t min_vectorization_width, int64_t tile_size_m, + int64_t tile_size_k, llvm::Value* lhs, llvm::Value* rhs, + llvm::Value* result, llvm::IRBuilder<>* b, + const HloModuleConfig& module_config); + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_TILED_DOT_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/vector_support_library.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/vector_support_library.h new file mode 100644 index 0000000000000000000000000000000000000000..7250cf2d8bad46d9dba648376bd2508a5c585d85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/vector_support_library.h @@ -0,0 +1,345 @@ +/* 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_SERVICE_CPU_VECTOR_SUPPORT_LIBRARY_H_ +#define XLA_SERVICE_CPU_VECTOR_SUPPORT_LIBRARY_H_ + +#include + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/primitive_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace cpu { + +// Simple wrappers around llvm::APFloat::APFloat to make the calling code more +// obvious. + +inline llvm::APFloat GetIeeeF32(float f) { return llvm::APFloat(f); } +inline llvm::APFloat GetIeeeF32FromBitwiseRep(int32_t bitwise_value) { + return llvm::APFloat(llvm::APFloat::IEEEsingle(), + llvm::APInt(/*numBits=*/32, /*val=*/bitwise_value)); +} + +// A thin wrapper around llvm_util.h to make code generating vector math flow +// more readable. +class VectorSupportLibrary { + public: + // This VectorSupportLibrary instance remembers `primitive_type` and + // `vector_size`, and these are implicitly used by the methods on this + // instance (i.e. LoadVector will load a vector of type <`vector_size` x + // `primitive_type`>). + VectorSupportLibrary(PrimitiveType primitive_type, int64_t vector_size, + llvm::IRBuilder<>* b, std::string name); + + llvm::Value* Mul(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* Mul(int64_t lhs, llvm::Value* rhs) { + return Mul(b()->getInt64(lhs), rhs); + } + llvm::Value* Mul(const llvm::APFloat& lhs, llvm::Value* rhs) { + return Mul(GetConstantFloat(rhs->getType(), lhs), rhs); + } + + // If your call resolved to these then you probably wanted the versions taking + // APFloat. + llvm::Value* Mul(double lhs, llvm::Value* rhs) = delete; + llvm::Value* Mul(float lhs, llvm::Value* rhs) = delete; + + llvm::Value* Add(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* Add(int64_t lhs, llvm::Value* rhs) { + return Add(b()->getInt64(lhs), rhs); + } + llvm::Value* Add(const llvm::APFloat& lhs, llvm::Value* rhs) { + return Add(GetConstantFloat(rhs->getType(), lhs), rhs); + } + + // If your call resolved to these then you probably wanted the versions taking + // APFloat. + llvm::Value* Add(double lhs, llvm::Value* rhs) = delete; + llvm::Value* Add(float lhs, llvm::Value* rhs) = delete; + + llvm::Value* Sub(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* Sub(llvm::Value* lhs, const llvm::APFloat& rhs) { + return Sub(lhs, GetConstantFloat(lhs->getType(), rhs)); + } + llvm::Value* Max(llvm::Value* lhs, llvm::Value* rhs, + bool enable_fast_min_max); + llvm::Value* Max(const llvm::APFloat& lhs, llvm::Value* rhs, + bool enable_fast_min_max) { + return Max(GetConstantFloat(rhs->getType(), lhs), rhs, enable_fast_min_max); + } + llvm::Value* Div(llvm::Value* lhs, llvm::Value* rhs); + + llvm::Value* MulAdd(llvm::Value* a, llvm::Value* b, llvm::Value* c) { + return Add(c, Mul(a, b)); + } + + llvm::Value* MulAdd(llvm::Value* a, llvm::Value* b, const llvm::APFloat& c) { + return Add(GetConstantFloat(vector_type(), c), Mul(a, b)); + } + + llvm::Value* MulAdd(llvm::Value* a, const llvm::APFloat& b, + const llvm::APFloat& c) { + return Add(GetConstantFloat(a->getType(), c), + Mul(a, GetConstantFloat(a->getType(), b))); + } + + llvm::Value* Floor(llvm::Value* a); + + // Precondition: Neither `low` nor `high` is nan. + llvm::Value* Clamp(llvm::Value* a, const llvm::APFloat& low, + const llvm::APFloat& high); + + llvm::Value* SplatFloat(const llvm::APFloat& d) { + return GetConstantFloat(vector_type(), d); + } + + // These compare instructions return a floating point typed mask instead of an + // i1. For instance, on a vector typed input, lanes where the predicate is + // true get a float with all ones and other lanes get a float with all zeros. + // This is slightly odd from the perspective of LLVM's type system, but it + // makes kernel IR generation code written using VectorSupportLibrary (its + // raison d'etre) less cluttered. + + llvm::Value* FCmpEQMask(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* FCmpEQMask(llvm::Value* lhs, const llvm::APFloat& rhs) { + return FCmpEQMask(lhs, GetConstantFloat(lhs->getType(), rhs)); + } + llvm::Value* FCmpULEMask(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* FCmpOLTMask(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* FCmpOLTMask(llvm::Value* lhs, const llvm::APFloat& rhs) { + return FCmpOLTMask(lhs, GetConstantFloat(lhs->getType(), rhs)); + } + + // These boolean operations operate on the bitwise values of the floating + // point inputs. They return a (vector of) float(s) but like in the mask + // generating predicates above this type system oddity makes the kernel IR + // generation code less cluttered. + llvm::Value* FloatAnd(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* FloatAnd(llvm::Value* lhs, const llvm::APFloat& rhs) { + return FloatAnd(lhs, GetConstantFloat(lhs->getType(), rhs)); + } + llvm::Value* FloatOr(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* FloatOr(llvm::Value* lhs, const llvm::APFloat& rhs) { + return FloatOr(lhs, GetConstantFloat(lhs->getType(), rhs)); + } + llvm::Value* FloatNot(llvm::Value* lhs); + llvm::Value* FloatAndNot(llvm::Value* lhs, llvm::Value* rhs) { + return FloatAnd(FloatNot(lhs), rhs); + } + + llvm::Value* BroadcastScalar(llvm::Value* x); + llvm::Value* BroadcastScalar(const llvm::APFloat& d) { + return BroadcastScalar(GetConstantFloat(scalar_type(), d)); + } + + llvm::Value* ComputeOffsetPointer(llvm::Value* base_pointer, + llvm::Value* offset_elements); + llvm::Value* ComputeOffsetPointer(llvm::Value* base_pointer, + llvm::Value* offset_elements, + int64_t scale) { + return ComputeOffsetPointer( + base_pointer, b_->CreateMul(b_->getInt64(scale), offset_elements)); + } + llvm::Value* ComputeOffsetPointer(llvm::Value* base_pointer, + int64_t offset_elements) { + return ComputeOffsetPointer(base_pointer, b()->getInt64(offset_elements)); + } + + llvm::Value* LoadVector(llvm::Value* pointer); + + llvm::Value* LoadVector(llvm::Value* base_pointer, + llvm::Value* offset_elements) { + return LoadVector(ComputeOffsetPointer(base_pointer, offset_elements)); + } + + llvm::Value* LoadVector(llvm::Value* base_pointer, int64_t offset_elements) { + return LoadVector(base_pointer, b()->getInt64(offset_elements)); + } + + llvm::Value* LoadScalar(llvm::Value* pointer); + + llvm::Value* LoadScalar(llvm::Value* base_pointer, + llvm::Value* offset_elements) { + return LoadScalar(ComputeOffsetPointer(base_pointer, offset_elements)); + } + + llvm::Value* LoadScalar(llvm::Value* base_pointer, int64_t offset_elements) { + return LoadScalar(base_pointer, b()->getInt64(offset_elements)); + } + + void StoreVector(llvm::Value* value, llvm::Value* pointer); + + void StoreVector(llvm::Value* value, llvm::Value* base_pointer, + llvm::Value* offset_elements) { + StoreVector(value, ComputeOffsetPointer(base_pointer, offset_elements)); + } + + void StoreVector(llvm::Value* value, llvm::Value* base_pointer, + int64_t offset_elements) { + StoreVector(value, base_pointer, b()->getInt64(offset_elements)); + } + + void StoreScalar(llvm::Value* value, llvm::Value* pointer); + void StoreScalar(llvm::Value* value, llvm::Value* base_pointer, + llvm::Value* offset_elements) { + StoreScalar(value, ComputeOffsetPointer(base_pointer, offset_elements)); + } + + void StoreScalar(llvm::Value* value, llvm::Value* base_pointer, + int64_t offset_elements) { + StoreScalar(base_pointer, b()->getInt64(offset_elements)); + } + + llvm::Value* LoadBroadcast(llvm::Value* pointer); + llvm::Value* LoadBroadcast(llvm::Value* base_pointer, + llvm::Value* offset_elements) { + return LoadBroadcast(ComputeOffsetPointer(base_pointer, offset_elements)); + } + llvm::Value* LoadBroadcast(llvm::Value* base_pointer, + int64_t offset_elements) { + return LoadBroadcast(base_pointer, b()->getInt64(offset_elements)); + } + + // Compute the horizontal sum of each vector in `vectors`. The i'th element + // in the result vector is the (scalar) horizontal sum of the i'th vector in + // `vectors`. If `init_values` is not nullptr then the value in the i'th lane + // in `init_values` is added to the i'th horizontal sum. + std::vector ComputeHorizontalSums( + std::vector vectors, llvm::Value* init_values = nullptr); + + llvm::Value* GetZeroVector(); + llvm::Value* GetZeroScalar(); + + llvm::IRBuilder<>* b() const { return b_; } + int64_t vector_size() const { return vector_size_; } + llvm::Type* vector_type() const { return vector_type_; } + llvm::Type* vector_pointer_type() const { return vector_pointer_type_; } + llvm::Type* scalar_type() const { return scalar_type_; } + llvm::Type* scalar_pointer_type() const { return scalar_pointer_type_; } + int64_t scalar_byte_size() const { + return primitive_util::BitWidth(primitive_type_) / 8; + } + + const std::string& name() const { return name_; } + + private: + llvm::Value* ExtractLowHalf(llvm::Value*); + llvm::Value* ExtractHighHalf(llvm::Value*); + + llvm::Value* MulInternal(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* AddInternal(llvm::Value* lhs, llvm::Value* rhs); + + llvm::Value* AddReduce(llvm::Value* vector); + + // Checks that each value in `values` is either of type scalar_type() or + // vector_type(). This LOG(FATAL)'s so it should only be called in cases + // where a mismatching type is a programmer bug. + void AssertCorrectTypes(std::initializer_list values); + + // Perform an X86 AVX style horizontal add between `lhs` and `rhs`. The + // resulting IR for an 8-float wide vector is expected to lower to a single + // vhaddps instruction on a CPU that supports vhaddps, and not be too bad in + // other cases. + // + // For a vector width of 8, the result vector is computed as: + // Result[0] = Lhs[0] + Lhs[1] + // Result[1] = Lhs[2] + Lhs[3] + // Result[2] = Rhs[0] + Rhs[1] + // Result[3] = Rhs[2] + Rhs[3] + // Result[4] = Lhs[4] + Lhs[5] + // Result[5] = Lhs[6] + Lhs[7] + // Result[6] = Rhs[4] + Rhs[5] + // Result[7] = Rhs[6] + Rhs[7] + llvm::Value* AvxStyleHorizontalAdd(llvm::Value* lhs, llvm::Value* rhs); + + std::vector ComputeAvxOptimizedHorizontalSums( + std::vector vectors, llvm::Value* init_values); + + llvm::Type* IntegerTypeForFloatSize(bool vector); + llvm::Value* I1ToFloat(llvm::Value* i1); + llvm::Value* GetConstantFloat(llvm::Type* type, const llvm::APFloat& f) { + llvm::Constant* scalar_value = llvm::ConstantFP::get(type->getContext(), f); + if (llvm::isa(type)) { + return llvm::ConstantVector::getSplat( + llvm::ElementCount::getFixed(vector_size()), scalar_value); + } + return scalar_value; + } + + int64_t vector_size_; + PrimitiveType primitive_type_; + llvm::IRBuilder<>* b_; + llvm::Type* vector_type_; + llvm::Type* vector_pointer_type_; + llvm::Type* scalar_type_; + llvm::Type* scalar_pointer_type_; + std::string name_; +}; + +// This wraps an alloca-backed stack variable which LLVM's SSA construction pass +// can later convert to a SSA value. +class LlvmVariable { + public: + LlvmVariable(llvm::Type*, llvm::IRBuilder<>* b); + + llvm::Value* Get() const; + void Set(llvm::Value* new_value); + + private: + llvm::AllocaInst* alloca_; + llvm::IRBuilder<>* b_; +}; + +class VectorVariable : public LlvmVariable { + public: + VectorVariable(VectorSupportLibrary* vector_support, + llvm::Value* initial_value) + : LlvmVariable(vector_support->vector_type(), vector_support->b()) { + Set(initial_value); + } +}; + +class ScalarVariable : public LlvmVariable { + public: + ScalarVariable(VectorSupportLibrary* vector_support, + llvm::Value* initial_value) + : LlvmVariable(vector_support->scalar_type(), vector_support->b()) { + Set(initial_value); + } +}; + +// This wraps a set of alloca-backed stack variables that can, as a whole, store +// a tile. A "tile" is a sequence of vectors that is typically used as a 2D +// grid of scalar values (e.g. for tiled GEMMs). +class TileVariable { + public: + TileVariable(VectorSupportLibrary* vector_support, + std::vector initial_value); + + std::vector Get() const; + void Set(absl::Span value); + + private: + std::vector storage_; +}; +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_VECTOR_SUPPORT_LIBRARY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/windows_compatibility.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/windows_compatibility.h new file mode 100644 index 0000000000000000000000000000000000000000..ce213977eb2e3a871754e78f6d3983eee05efd0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/windows_compatibility.h @@ -0,0 +1,31 @@ +/* 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_SERVICE_CPU_WINDOWS_COMPATIBILITY_H_ +#define XLA_SERVICE_CPU_WINDOWS_COMPATIBILITY_H_ + +#ifdef _MSC_VER + +extern "C" { + +// MSVC does not have sincos[f]. +void sincos(double x, double *sinv, double *cosv); +void sincosf(float x, float *sinv, float *cosv); + +} + +#endif // _MSC_VER + +#endif // XLA_SERVICE_CPU_WINDOWS_COMPATIBILITY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xfeed_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xfeed_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..0d5d5ee34707cd04fbb6a0ff8d9963d42ac9bab1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xfeed_manager.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. +==============================================================================*/ + +// This header declares the abstract class for the infeed manager that +// is used by the CPU runtime to transfer buffers into an executing +// CPU computation, e.g., to feed data into a while loop. + +#ifndef XLA_SERVICE_CPU_XFEED_MANAGER_H_ +#define XLA_SERVICE_CPU_XFEED_MANAGER_H_ + +#include + +#include "absl/types/span.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace cpu { +namespace runtime { + +// Abstract class defining an infeed buffer that is passed to the +// runtime by a client. The client manages the storage of the buffer. +class XfeedBuffer { + public: + virtual ~XfeedBuffer() = default; + + virtual int32_t length() = 0; + virtual void* data() = 0; + + // The 'shape' parameter reflects what shape the embedded program was + // expecting / producing with respect to this XfeedBuffer. E.g. this will + // contain information about the layout of an outfed buffer. + virtual void Done(StatusOr shape) = 0; +}; + +// Reusable component for managing the infeed and outfeed queue state. +class XfeedQueueManager { + public: + XfeedQueueManager(std::string queue_name) : queue_name_(queue_name) {} + + // Calls the completion callback for any enqueued buffers that have + // not been dequeued by the runtime, and empties the + // queue. Reset may not be called while a runtime computation is + // processing a dequeued buffer. The only safe way to ensure this + // condition is to call Reset when no computation is taking place. + void Reset(); + + // Adds a sequence of buffers to the queue atomically. buffer->Done will be + // called when the buffer will no longer be accessed by the XfeedManager, + // either as a result of a call to Reset or because the runtime has dequeued + // and used the buffer. + void EnqueueBuffersAtomically(absl::Span buffers); + + // Blocks until the queue is non-empty, then returns the buffer at the head of + // the queue. Sets the current buffer to be the returned buffer. It is an + // error to call BlockingDequeueBuffer if there is an unreleased current + // buffer, i.e., ReleaseCurrentBuffer must be called between calls to + // BlockingDequeueBuffer. + XfeedBuffer* BlockingDequeueBuffer(); + + // Releases the current buffer, which is the last buffer returned by + // BlockingDequeuBuffer and not yet released. length and data must + // match the buffer->length() and buffer->data() for the current + // buffer. + // + // 'shape' communicates the shape of the buffer being released. If the program + // passed a value that could not be decoded as a shape, 'shape' will be an + // error status. In the case of outfeed, this indicates the layout of the + // shape that has been outfed. In the case of infeed, this can be used for + // sanity checking purposes. + void ReleaseCurrentBuffer(int32_t length, void* data, StatusOr shape); + + private: + const std::string queue_name_; + + absl::Mutex mu_; + + // Condition variable that is signaled every time a buffer is + // enqueued to an empty queue. + absl::CondVar cv_; + + // XfeedBuffer* queue contents are not owned, but buffer->Done must + // be called when the buffer is no longer needed by the runtime. + std::deque enqueued_buffers_; + + // If non-NULL, the buffer that is currently being processed by the + // runtime. Not owned. + XfeedBuffer* current_buffer_ = nullptr; +}; + +// Client-side class used to enqueue infeed buffers. +class XfeedManager { + public: + XfeedManager() = default; + + void Reset(); + + XfeedQueueManager* infeed() { return &infeed_; } + XfeedQueueManager* outfeed() { return &outfeed_; } + + private: + XfeedQueueManager infeed_ = {"infeed"}; + XfeedQueueManager outfeed_ = {"outfeed"}; +}; + +int64_t GetByteSizeRequirement(const Shape& shape, int64_t pointer_size); + +} // namespace runtime +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_XFEED_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xla_framework.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xla_framework.h new file mode 100644 index 0000000000000000000000000000000000000000..bd7d572fc3c6ecdc6d775cb788aa828dcbfbd7b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xla_framework.h @@ -0,0 +1,65 @@ +/* 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_SERVICE_CPU_XLA_FRAMEWORK_H_ +#define XLA_SERVICE_CPU_XLA_FRAMEWORK_H_ + +#include +#include + +#include "xla/service/cpu/xla_framework.pb.h" + +namespace xla { +namespace cpu { + +// Maps the descriptor table with inputs/outputs. Note that flattened_outputs +// and result are mutually exclusive -- see below. +// +// Contains the same info as "xla_framework" MLIR annotations. That is: +// - inputs: indices in the descriptor table of the input arguments. +// - output_is_tuple: if set, the output is a tuple. +// - flattened_outputs: if the output is a tuple, this contains the indices +// (if any) in the descriptor table that correspond to the expanded tuple. +// - result: if the output is NOT a tuple, contains the index in the descriptor +// table of the result. +struct XlaFrameworkMapping { + std::vector inputs; + std::vector flattened_outputs; + int64_t result = -1; + bool output_is_tuple = false; + + XlaFrameworkMappingProto ToProto() const { + XlaFrameworkMappingProto proto; + *proto.mutable_inputs() = {inputs.begin(), inputs.end()}; + *proto.mutable_flattened_outputs() = {flattened_outputs.begin(), + flattened_outputs.end()}; + proto.set_result(result); + proto.set_output_is_tuple(output_is_tuple); + return proto; + } + + void FromProto(const XlaFrameworkMappingProto& proto) { + inputs = {proto.inputs().begin(), proto.inputs().end()}; + flattened_outputs = {proto.flattened_outputs().begin(), + proto.flattened_outputs().end()}; + result = proto.result(); + output_is_tuple = proto.output_is_tuple(); + } +}; + +} // namespace cpu +} // namespace xla + +#endif // XLA_SERVICE_CPU_XLA_FRAMEWORK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xla_framework.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xla_framework.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..d8ba0c7b2f99fd4d4fd361984e62145c647f2eaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu/xla_framework.pb.h @@ -0,0 +1,458 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/cpu/xla_framework.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fxla_5fframework_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fxla_5fframework_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_xla_2fservice_2fcpu_2fxla_5fframework_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fcpu_2fxla_5fframework_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fcpu_2fxla_5fframework_2eproto; +namespace xla { +namespace cpu { +class XlaFrameworkMappingProto; +struct XlaFrameworkMappingProtoDefaultTypeInternal; +extern XlaFrameworkMappingProtoDefaultTypeInternal _XlaFrameworkMappingProto_default_instance_; +} // namespace cpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::cpu::XlaFrameworkMappingProto* Arena::CreateMaybeMessage<::xla::cpu::XlaFrameworkMappingProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace cpu { + +// =================================================================== + +class XlaFrameworkMappingProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.cpu.XlaFrameworkMappingProto) */ { + public: + inline XlaFrameworkMappingProto() : XlaFrameworkMappingProto(nullptr) {} + ~XlaFrameworkMappingProto() override; + explicit PROTOBUF_CONSTEXPR XlaFrameworkMappingProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaFrameworkMappingProto(const XlaFrameworkMappingProto& from); + XlaFrameworkMappingProto(XlaFrameworkMappingProto&& from) noexcept + : XlaFrameworkMappingProto() { + *this = ::std::move(from); + } + + inline XlaFrameworkMappingProto& operator=(const XlaFrameworkMappingProto& from) { + CopyFrom(from); + return *this; + } + inline XlaFrameworkMappingProto& operator=(XlaFrameworkMappingProto&& 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; + } + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { + return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); + } + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { + return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); + } + + 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 XlaFrameworkMappingProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaFrameworkMappingProto* internal_default_instance() { + return reinterpret_cast( + &_XlaFrameworkMappingProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(XlaFrameworkMappingProto& a, XlaFrameworkMappingProto& b) { + a.Swap(&b); + } + inline void Swap(XlaFrameworkMappingProto* 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(XlaFrameworkMappingProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaFrameworkMappingProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaFrameworkMappingProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaFrameworkMappingProto& from) { + XlaFrameworkMappingProto::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(XlaFrameworkMappingProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.cpu.XlaFrameworkMappingProto"; + } + protected: + explicit XlaFrameworkMappingProto(::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 { + kInputsFieldNumber = 1, + kFlattenedOutputsFieldNumber = 2, + kOutputIsTupleFieldNumber = 4, + kResultFieldNumber = 3, + }; + // repeated int64 inputs = 1 [packed = true]; + int inputs_size() const; + private: + int _internal_inputs_size() const; + public: + void clear_inputs(); + private: + int64_t _internal_inputs(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_inputs() const; + void _internal_add_inputs(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_inputs(); + public: + int64_t inputs(int index) const; + void set_inputs(int index, int64_t value); + void add_inputs(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + inputs() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_inputs(); + + // repeated int64 flattened_outputs = 2 [packed = true]; + int flattened_outputs_size() const; + private: + int _internal_flattened_outputs_size() const; + public: + void clear_flattened_outputs(); + private: + int64_t _internal_flattened_outputs(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_flattened_outputs() const; + void _internal_add_flattened_outputs(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_flattened_outputs(); + public: + int64_t flattened_outputs(int index) const; + void set_flattened_outputs(int index, int64_t value); + void add_flattened_outputs(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + flattened_outputs() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_flattened_outputs(); + + // optional bool output_is_tuple = 4; + bool has_output_is_tuple() const; + private: + bool _internal_has_output_is_tuple() const; + public: + void clear_output_is_tuple(); + bool output_is_tuple() const; + void set_output_is_tuple(bool value); + private: + bool _internal_output_is_tuple() const; + void _internal_set_output_is_tuple(bool value); + public: + + // optional int64 result = 3 [default = -1]; + bool has_result() const; + private: + bool _internal_has_result() const; + public: + void clear_result(); + int64_t result() const; + void set_result(int64_t value); + private: + int64_t _internal_result() const; + void _internal_set_result(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.cpu.XlaFrameworkMappingProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > inputs_; + mutable std::atomic _inputs_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > flattened_outputs_; + mutable std::atomic _flattened_outputs_cached_byte_size_; + bool output_is_tuple_; + int64_t result_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fcpu_2fxla_5fframework_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// XlaFrameworkMappingProto + +// repeated int64 inputs = 1 [packed = true]; +inline int XlaFrameworkMappingProto::_internal_inputs_size() const { + return _impl_.inputs_.size(); +} +inline int XlaFrameworkMappingProto::inputs_size() const { + return _internal_inputs_size(); +} +inline void XlaFrameworkMappingProto::clear_inputs() { + _impl_.inputs_.Clear(); +} +inline int64_t XlaFrameworkMappingProto::_internal_inputs(int index) const { + return _impl_.inputs_.Get(index); +} +inline int64_t XlaFrameworkMappingProto::inputs(int index) const { + // @@protoc_insertion_point(field_get:xla.cpu.XlaFrameworkMappingProto.inputs) + return _internal_inputs(index); +} +inline void XlaFrameworkMappingProto::set_inputs(int index, int64_t value) { + _impl_.inputs_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.cpu.XlaFrameworkMappingProto.inputs) +} +inline void XlaFrameworkMappingProto::_internal_add_inputs(int64_t value) { + _impl_.inputs_.Add(value); +} +inline void XlaFrameworkMappingProto::add_inputs(int64_t value) { + _internal_add_inputs(value); + // @@protoc_insertion_point(field_add:xla.cpu.XlaFrameworkMappingProto.inputs) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +XlaFrameworkMappingProto::_internal_inputs() const { + return _impl_.inputs_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +XlaFrameworkMappingProto::inputs() const { + // @@protoc_insertion_point(field_list:xla.cpu.XlaFrameworkMappingProto.inputs) + return _internal_inputs(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +XlaFrameworkMappingProto::_internal_mutable_inputs() { + return &_impl_.inputs_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +XlaFrameworkMappingProto::mutable_inputs() { + // @@protoc_insertion_point(field_mutable_list:xla.cpu.XlaFrameworkMappingProto.inputs) + return _internal_mutable_inputs(); +} + +// repeated int64 flattened_outputs = 2 [packed = true]; +inline int XlaFrameworkMappingProto::_internal_flattened_outputs_size() const { + return _impl_.flattened_outputs_.size(); +} +inline int XlaFrameworkMappingProto::flattened_outputs_size() const { + return _internal_flattened_outputs_size(); +} +inline void XlaFrameworkMappingProto::clear_flattened_outputs() { + _impl_.flattened_outputs_.Clear(); +} +inline int64_t XlaFrameworkMappingProto::_internal_flattened_outputs(int index) const { + return _impl_.flattened_outputs_.Get(index); +} +inline int64_t XlaFrameworkMappingProto::flattened_outputs(int index) const { + // @@protoc_insertion_point(field_get:xla.cpu.XlaFrameworkMappingProto.flattened_outputs) + return _internal_flattened_outputs(index); +} +inline void XlaFrameworkMappingProto::set_flattened_outputs(int index, int64_t value) { + _impl_.flattened_outputs_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.cpu.XlaFrameworkMappingProto.flattened_outputs) +} +inline void XlaFrameworkMappingProto::_internal_add_flattened_outputs(int64_t value) { + _impl_.flattened_outputs_.Add(value); +} +inline void XlaFrameworkMappingProto::add_flattened_outputs(int64_t value) { + _internal_add_flattened_outputs(value); + // @@protoc_insertion_point(field_add:xla.cpu.XlaFrameworkMappingProto.flattened_outputs) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +XlaFrameworkMappingProto::_internal_flattened_outputs() const { + return _impl_.flattened_outputs_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +XlaFrameworkMappingProto::flattened_outputs() const { + // @@protoc_insertion_point(field_list:xla.cpu.XlaFrameworkMappingProto.flattened_outputs) + return _internal_flattened_outputs(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +XlaFrameworkMappingProto::_internal_mutable_flattened_outputs() { + return &_impl_.flattened_outputs_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +XlaFrameworkMappingProto::mutable_flattened_outputs() { + // @@protoc_insertion_point(field_mutable_list:xla.cpu.XlaFrameworkMappingProto.flattened_outputs) + return _internal_mutable_flattened_outputs(); +} + +// optional int64 result = 3 [default = -1]; +inline bool XlaFrameworkMappingProto::_internal_has_result() const { + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + return value; +} +inline bool XlaFrameworkMappingProto::has_result() const { + return _internal_has_result(); +} +inline void XlaFrameworkMappingProto::clear_result() { + _impl_.result_ = int64_t{-1}; + _impl_._has_bits_[0] &= ~0x00000002u; +} +inline int64_t XlaFrameworkMappingProto::_internal_result() const { + return _impl_.result_; +} +inline int64_t XlaFrameworkMappingProto::result() const { + // @@protoc_insertion_point(field_get:xla.cpu.XlaFrameworkMappingProto.result) + return _internal_result(); +} +inline void XlaFrameworkMappingProto::_internal_set_result(int64_t value) { + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.result_ = value; +} +inline void XlaFrameworkMappingProto::set_result(int64_t value) { + _internal_set_result(value); + // @@protoc_insertion_point(field_set:xla.cpu.XlaFrameworkMappingProto.result) +} + +// optional bool output_is_tuple = 4; +inline bool XlaFrameworkMappingProto::_internal_has_output_is_tuple() const { + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; + return value; +} +inline bool XlaFrameworkMappingProto::has_output_is_tuple() const { + return _internal_has_output_is_tuple(); +} +inline void XlaFrameworkMappingProto::clear_output_is_tuple() { + _impl_.output_is_tuple_ = false; + _impl_._has_bits_[0] &= ~0x00000001u; +} +inline bool XlaFrameworkMappingProto::_internal_output_is_tuple() const { + return _impl_.output_is_tuple_; +} +inline bool XlaFrameworkMappingProto::output_is_tuple() const { + // @@protoc_insertion_point(field_get:xla.cpu.XlaFrameworkMappingProto.output_is_tuple) + return _internal_output_is_tuple(); +} +inline void XlaFrameworkMappingProto::_internal_set_output_is_tuple(bool value) { + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.output_is_tuple_ = value; +} +inline void XlaFrameworkMappingProto::set_output_is_tuple(bool value) { + _internal_set_output_is_tuple(value); + // @@protoc_insertion_point(field_set:xla.cpu.XlaFrameworkMappingProto.output_is_tuple) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace cpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fcpu_2fxla_5fframework_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu_gpu_shape_verifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu_gpu_shape_verifier.h new file mode 100644 index 0000000000000000000000000000000000000000..ef43fcc59670e2ee5048edba47457f1aece6d06c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/cpu_gpu_shape_verifier.h @@ -0,0 +1,48 @@ +/* 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_SERVICE_CPU_GPU_SHAPE_VERIFIER_H_ +#define XLA_SERVICE_CPU_GPU_SHAPE_VERIFIER_H_ + +#include +#include + +#include "xla/service/hlo_verifier.h" + +namespace xla { + +// Verifies that HLO Shapes are supported by the XLA-CPU and XLA-GPU compilers. +class CpuGpuShapeVerifier : public ShapeVerifier { + public: + explicit CpuGpuShapeVerifier(const HloVerifierOpts& opts) + : ShapeVerifier(opts) {} + + Status Preprocess(HloInstruction* hlo) override; +}; + +// A verifier metadata class that uses the CpuGpuShapeVerifier. +class CpuGpuVerifierMetadata : public TargetVerifierMetadata { + public: + explicit CpuGpuVerifierMetadata(HloVerifierOpts&& opts) + : TargetVerifierMetadata(std::move(opts)) {} + + std::unique_ptr GetVerifier() const override { + return std::make_unique(GetVerifierOpts()); + } +}; + +} // namespace xla + +#endif // XLA_SERVICE_CPU_GPU_SHAPE_VERIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_sharding_helper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_sharding_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..e3432342b8ae70d7ff376bbd35940dc3c37dae0a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_sharding_helper.h @@ -0,0 +1,79 @@ +/* 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. +==============================================================================*/ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_sharding.h" + +#ifndef XLA_SERVICE_CUSTOM_CALL_SHARDING_HELPER_H_ +#define XLA_SERVICE_CUSTOM_CALL_SHARDING_HELPER_H_ + +namespace xla { + +// Helper class that helps implement sharding propagation policies for +// CustomCalls. It is called and used by the ShardingPropagation pass. Meant to +// be overridden by targets. +class CustomCallShardingHelper { + public: + // Function that manipulates an instruction sharding based on a user wanting + // to update the sharding of an instruction. + virtual HloSharding PropagateUserSharding(const HloInstruction* instruction, + const HloInstruction* user, + const HloSharding& sharding) const; + // Infer sharding from the operands of an instruction. + virtual std::optional InferShardingFromOperands( + const HloInstruction* instruction) const; + // Returns if the instruction passed as parameter is a supported custom-call + // for which the functions of this class are implemented. + virtual bool IsCustomCallShardable(const HloInstruction* instruction) const; + // Returns the list of instructions in sub-computations that must be sharded + // in the same way as `instruction`. + virtual std::vector GetRelatedInstructions( + HloInstruction* instruction) const { + return {}; + } + virtual ~CustomCallShardingHelper() = default; +}; + +namespace spmd { +class SpmdPartitioningVisitor; +} // namespace spmd + +// Helper class that provides a partitioning function in addition to sharding +// policies. +class CustomCallPartitioner : public CustomCallShardingHelper { + public: + virtual xla::Status Partition(spmd::SpmdPartitioningVisitor* partitioner, + HloInstruction* hlo) const; + + // Returns if the given side-effecting custom-call is allowed to have + // replicated sharding. + virtual bool CanSideEffectingHaveReplicatedSharding() const { return false; } +}; + +// Fetch partitioning overrides on a per-custom_call_target basis. +const CustomCallPartitioner* GetCustomCallPartitioner( + const std::string& custom_call_target); +// Register partitioning overrides on a per-custom_call_target basis. +void RegisterCustomCallPartitioner( + const std::string& custom_call_target, + std::unique_ptr partitioner); + +} // namespace xla + +#endif // XLA_SERVICE_CUSTOM_CALL_SHARDING_HELPER_H__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_status.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_status.h new file mode 100644 index 0000000000000000000000000000000000000000..db6da7e36c338df2302e4b6213f6b6759c9e70c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_status.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_CUSTOM_CALL_STATUS_H_ +#define XLA_SERVICE_CUSTOM_CALL_STATUS_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// ABI-stable public interfaces for XlaCustomCallStatus. + +// Represents the result of a CustomCall: success or failure, with an associated +// error message in the failure case. +typedef struct XlaCustomCallStatus_ XlaCustomCallStatus; + +// Set the XlaCustomCallStatus to a success state. This is the default state. +void XlaCustomCallStatusSetSuccess(XlaCustomCallStatus* status); + +// Set the XlaCustomCallStatus to a failure state with the given error message. +// Does not take ownership of the supplied message string; instead copies the +// first 'message_len' bytes, or up to the null terminator, whichever comes +// first. +void XlaCustomCallStatusSetFailure(XlaCustomCallStatus* status, + const char* message, size_t message_len); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // XLA_SERVICE_CUSTOM_CALL_STATUS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_status_internal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_status_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..4758a19986653092850fdb8338a696dbe5f51543 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_status_internal.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_CUSTOM_CALL_STATUS_INTERNAL_H_ +#define XLA_SERVICE_CUSTOM_CALL_STATUS_INTERNAL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/service/custom_call_status.h" + +struct XlaCustomCallStatus_ { + // The message being present means "failure". Otherwise means "success". + std::optional message; +}; + +namespace xla { + +// Get a view of the internal error message of the XlaCustomCallStatus. Only +// lives as long as the XlaCustomCallStatus. Returns an empty optional if the +// result was "success". +std::optional CustomCallStatusGetMessage( + const XlaCustomCallStatus* status); + +} // namespace xla + +#endif // XLA_SERVICE_CUSTOM_CALL_INTERNAL_STATUS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_target_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_target_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..51ca96033d163fd1762e5445c5dd4184d5be249d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/custom_call_target_registry.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_SERVICE_CUSTOM_CALL_TARGET_REGISTRY_H_ +#define XLA_SERVICE_CUSTOM_CALL_TARGET_REGISTRY_H_ + +// This file is depended on by kernels that have to build for mobile devices. +// For this reason, we avoid relying on TensorFlow and instead only use the +// standard C++ library. + +#include +#include +#include // NOLINT +#include +#include +#include + +namespace xla { + +// XLA JIT compilers use this registry to resolve symbolic CustomCall targets; +// so when using XLA as a JIT, CustomCall targets need to be registered here +// with the symbol name used in the CustomCall. +// +// The XLA:CPU ahead-of-time (AOT) compiler links using a standard offline +// linker; so when compiling in CPU AOT mode, you *also* need to make sure the +// name of the callee (presumably implemented in C++) matches up with the +// symbolic name used in the CustomCall. +// +// We maintain the registry in both the JIT and the AOT cases for simplicity, +// but we only use it when running in JIT mode. +class CustomCallTargetRegistry { + public: + static CustomCallTargetRegistry* Global(); + + void Register(const std::string& symbol, void* address, + const std::string& platform); + void* Lookup(const std::string& symbol, const std::string& platform) const; + + private: + // hash> is surprisingly not provided by default in stl. It would + // be better to use absl's hash function, but we're avoiding an absl + // dependency here because this library is pulled in by all XLA:CPU AoT + // binaries. + struct HashPairOfStrings { + size_t operator()(const std::pair& k) const { + std::hash hasher; + size_t h1 = hasher(k.first); + size_t h2 = hasher(k.second); + // This is a bad hash function, but it's good enough for our purposes + // here. Nobody is going to try to DoS this hashtable. :) + return h1 ^ 31 * h2; + } + }; + + // Maps the pair (symbol, platform) to a C function implementing a custom call + // named `symbol` for StreamExecutor platform `platform`. + // + // Different platforms have different ABIs. TODO(jlebar): Describe them! + // + // (We use std::unordered_map and std::mutex rather than absl::flat_hash_map + // and absl::mutex because we want to avoid an absl dependency, because this + // library is pulled in by all XLA:CPU AoT binaries.) + std::unordered_map, void*, + HashPairOfStrings> + registered_symbols_; + mutable std::mutex mu_; +}; + +class RegisterCustomCallTarget { + public: + explicit RegisterCustomCallTarget(const std::string& name, void* address, + const std::string& platform) { + CustomCallTargetRegistry::Global()->Register(name, address, platform); + } +}; + +#define XLA_REGISTER_CUSTOM_CALL_CONCAT(a, b) a##b + +#define XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM_HELPER(symbol, address, \ + platform, counter) \ + static ::xla::RegisterCustomCallTarget XLA_REGISTER_CUSTOM_CALL_CONCAT( \ + custom_call_target_register, counter)( \ + symbol, reinterpret_cast(address), platform) + +#define XLA_REGISTER_CUSTOM_CALL_TARGET(function, platform) \ + XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(#function, function, platform) + +#define XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(symbol, address, platform) \ + XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM_HELPER(symbol, address, platform, \ + __COUNTER__) + +// Convenience overloads for registering custom-call targets on the CPU. +#define XLA_CPU_REGISTER_CUSTOM_CALL_TARGET(function) \ + XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(#function, function, "Host") + +#define XLA_CPU_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(symbol, address) \ + XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(symbol, address, "Host") + +} // namespace xla + +#endif // XLA_SERVICE_CUSTOM_CALL_TARGET_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_as_convolution_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_as_convolution_util.h new file mode 100644 index 0000000000000000000000000000000000000000..c84ea3c9a2dda4928c47e92102628449901169c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_as_convolution_util.h @@ -0,0 +1,102 @@ +/* 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_SERVICE_DOT_AS_CONVOLUTION_UTIL_H_ +#define XLA_SERVICE_DOT_AS_CONVOLUTION_UTIL_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { +namespace dot_as_convolution_util { + +// Type of Batch representation for a convolution that has a spatial dimension +// that is effectively a batch dimension. We currently have two +// representations that we detect as "batch equivalent" and this enum allows +// differentiating between the two. +enum class SpatialBatchRepresentation { + kNone, + kUnpaddedVersion, + kPaddedVersion, +}; + +// Describes the dimensions of a convolution that can be interpreted as a dot +// or a normal convolution. +struct DotConvolutionDimsInfo { + // The dimension numbers for the operands and output corresponding to a + // logical dimension (e.g., batch, contracting, non-contracting). If an + // operand or the output doesn't have the logical dimension, it is set to + // -1. + struct DimNums { + int64_t lhs; + int64_t rhs; + int64_t output; + // The corresponding spatial dimension in the convolution's config. Set to + // -1 if it's not mapped to a spatial dimension. + int64_t spatial_dim; + }; + std::vector batch_dims; + std::vector contracting_dims; + std::vector lhs_non_contracting_dims; + std::vector rhs_non_contracting_dims; + std::vector conv_spatial_dims; +}; + +// Parses a convolution and returns a DotGeneralAsConvolutionDimsInfo. If it can +// be interpreted as a dot, there is no conv_spatial_dims. +DotConvolutionDimsInfo ParseConvolutionDimsInfo(const HloInstruction* conv); + +// Creates sharded convolution instruction that can be interpreted as a dot. +// This is a utility for per-op partitioners. +// - 'conv' is the original convolution instruction. +// - 'dot_dnums' is the result of ParseDotConvolutionDimsInfo() for 'conv'. +// - 'sharded_lhs_hlo' and 'sharded_rhs_hlo' are sharded inputs for the result +// convolution instruction. +StatusOr> +CreateShardedConvForDotGeneralConvolution( + const HloInstruction& conv, const DotConvolutionDimsInfo& dot_dnums, + HloInstruction* sharded_lhs_hlo, HloInstruction* sharded_rhs_hlo); + +// Check if a spatial dim is parallel batch dimension. +// A parallel batch dimension in DotGeneral is represented as a spatial +// dimension with window size B (batch dimension size), stride B - 1, and base +// dilation B or an alternative representation of window size B, stride B, +// padding low/high B - 1, base dilation B - 1 and window reversal +SpatialBatchRepresentation SpatialIsBatch(int64_t lhs_spatial_size, + const WindowDimension& spatial_wd); +// Returns if the spatial dimension represented by 'spatial_wd' is an LHS non +// contracting dimension. +bool SpatialIsLhsNonContracting(int64_t rhs_spatial_size, + const WindowDimension& spatial_wd); +// Returns if the spatial dimension represented by 'spatial_wd' is an RHS non +// contracting dimension. +bool SpatialIsRhsNonContracting(int64_t lhs_spatial_size, + int64_t rhs_spatial_size, + const WindowDimension& spatial_wd); +// Returns if the spatial dimension represented by 'spatial_wd' endsup being +// equivalent to a contracting dimension. +bool SpatialIsContracting(int64_t lhs_spatial_size, int64_t rhs_spatial_size, + const WindowDimension& spatial_wd); +// Returns a DotConvolutionDimsInfo from a kDot instruction, where all +// the spatial_dim values are set to -1. +DotConvolutionDimsInfo ParseDotGeneralFromDot(const HloInstruction* dot); + +} // namespace dot_as_convolution_util +} // namespace xla + +#endif // XLA_SERVICE_DOT_AS_CONVOLUTION_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..af826ed8c7ad283586f7df5bccf3518ca47bc091 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_decomposer.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_DOT_DECOMPOSER_H_ +#define XLA_SERVICE_DOT_DECOMPOSER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// DotDecomposer is a pass which converts dots into a canonical form where +// non-contracting and contracting dimensions are reshaped together and batch +// dimensions are the most major dimensions. +class DotDecomposer : public HloModulePass { + public: + absl::string_view name() const override { return "dot_decomposer"; } + + // Run DotDecomposer pass on computations in 'module'. + // Returns whether the 'module' was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_DOT_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_dimension_merger.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_dimension_merger.h new file mode 100644 index 0000000000000000000000000000000000000000..9bb969732797cad416a46b4b6d2002dc4299b7ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_dimension_merger.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_DOT_DIMENSION_MERGER_H_ +#define XLA_SERVICE_DOT_DIMENSION_MERGER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Merge consecutive batch dimensions of a dot() by inserting reshapes. +class DotDimensionMerger : public HloModulePass { + public: + absl::string_view name() const override { return "dot_dimension_merger"; } + + // Run the pass on computations in 'module'. + // Return whether the 'module' was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_DOT_DIMENSION_MERGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_merger.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_merger.h new file mode 100644 index 0000000000000000000000000000000000000000..7bc0e80e6281a665ef51c40b4eb7fb7d96495f70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dot_merger.h @@ -0,0 +1,71 @@ +/* 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_SERVICE_DOT_MERGER_H_ +#define XLA_SERVICE_DOT_MERGER_H_ + +#include +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Merges dots that share an operand. Transforms +// +// x = dot(a, b) +// y = dot(a, c) +// +// into +// +// z = dot(a, concat(b, c)) +// x = slice(z) +// y = slice(z). +// +// This requires that x and y are independent -- that is, x does not +// transitively depend on y, and y does not transitively depend on x. +// +// This is a good transformation if the merged dot runs faster than the original +// dots. On the other hand, merging the dots results in a single result buffer +// z whose live range is the union of x and y's live ranges, so can lead to +// increased memory pressure. You probably only want to do this optimization on +// "small" dots which cannot saturate your device when run alone. +// +// We thus allow backends to set a max size above which an op will not be +// merged. The input+output bytes of at least one dot must be below the +// threshold otherwise we won't merge. (We don't require that both dots be +// below the threshold because backends likely want to allow merging a "small" +// dot into a "large" dot while preventing two large dots from being merged.) +// +// Will skip gemms with more than one non-contracting dimension in the dot +// operands to be concatenated. +class DotMerger : public HloModulePass { + public: + explicit DotMerger(int64_t max_size_to_merge) + : max_size_to_merge_(max_size_to_merge) {} + + absl::string_view name() const override { return "dot-merger"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + int64_t max_size_to_merge_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_DOT_MERGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dump.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dump.h new file mode 100644 index 0000000000000000000000000000000000000000..6e1cab91716086869f49394c29c6f10f482b46e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dump.h @@ -0,0 +1,153 @@ +/* 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_SERVICE_DUMP_H_ +#define XLA_SERVICE_DUMP_H_ + +#include "absl/strings/string_view.h" +#include "mlir/IR/Operation.h" // from @llvm-project +#include "xla/hlo/ir/hlo_module.h" +#include "xla/status.h" +#include "xla/xla.pb.h" + +// Consolidated utilities for logging information during compilation, usually +// based on the options specified in the DebugOptions proto. +// +// Most functions here take an HloModule and read the DebugOptions from the +// module's config. + +namespace xla { + +// Argument used when calling DumpHloModuleIfEnabled before optimizations are +// performed on an HloModule. +constexpr char kBeforeOptimizationsDumpName[] = "before_optimizations"; +constexpr char kAfterOptimizationsDumpName[] = "after_optimizations"; + +class BufferAssignment; +class HloSnapshot; + +// Get a timestamp which we can use as a filename prefix specific to this +// module. +std::string TimestampFor(const HloModule& module); + +// Create the filename we will use to dump in DumpToFileInDir. +std::string FilenameFor(int unique_id, absl::string_view module_name, + absl::string_view prefix, absl::string_view suffix); +std::string FilenameFor(const HloModule& module, absl::string_view prefix, + absl::string_view suffix); + +// Writes the given string to a file in the xla_dump_to directory specified by +// module's DebugOptions. +// +// If module doesn't have an xla_dump_to directory, does nothing. +void DumpToFileInDir(const HloModule& module, absl::string_view file_prefix, + absl::string_view file_suffix, absl::string_view contents); +void DumpToFileInDir(const DebugOptions& debug_options, + absl::string_view filename, absl::string_view contents); + +// Like DumpToFileInDir, except if module doesn't have an xla_dump_to directory +// specified, or if that directory is equal to "-", writes to stdout instead. +void DumpToFileInDirOrStdout(const HloModule& module, + absl::string_view file_prefix, + absl::string_view file_suffix, + absl::string_view contents); + +// Like DumpToFileInDir, except if debug_options doesn't have an xla_dump_to +// directory specified, or if that directory is equal to "-", writes to stdout +// instead. +void DumpToFileInDirOrStdout(const DebugOptions& debug_options, int unique_id, + absl::string_view module_name, + absl::string_view file_prefix, + absl::string_view file_suffix, + absl::string_view contents); + +// Writes the given op to a file in the xla_dump_to directory specified by +// module's DebugOptions. Sets the op's source locations to that file. +// +// If module doesn't have an xla_dump_to directory, does nothing. +void DumpToFileInDirOrStdout(const HloModule& module, + absl::string_view file_prefix, + mlir::Operation* op); + +// Dumps the given protobuf to the given filename if dumping is enabled. +// Exactly where and in what formats it's dumped is determined by the debug +// options. +void DumpProtobufToFile(const tsl::protobuf::Message& proto, + const DebugOptions& debug_options, + absl::string_view filename); + +// Similar to above, but the filename depends on module's information and the +// given name. +void DumpPerModuleProtobufToFile(const HloModule& module, + const tsl::protobuf::Message& proto, + const DebugOptions& debug_options, + absl::string_view name); + +// Dumps the given HLO module if dumping is enabled for the module. Exactly +// where and in what formats it's dumped is determined by the module's config. +void DumpHloModuleIfEnabled(const HloModule& module, absl::string_view name); +void DumpHloModuleIfEnabled(const HloModule& module, + const BufferAssignment& buffer_assn, + absl::string_view name); + +// Dumps the given HLO module after running one HLO pass and before running +// another, if that's enabled. Returns the full file paths of all dumps of the +// module, or an empty vector if nothing was dumped. +std::vector DumpHloModuleBetweenPassesIfEnabled( + absl::string_view pipeline_name, absl::string_view before_pass_name, + absl::string_view after_pass_name, const HloModule& module); + +// Dumps the given HLO module during the given HLO pass, if that's enabled. +// +// "step" is a human-readable description of where we are in the middle of this +// pass. For example, "before-assigning-layouts". +void DumpHloModuleDuringPassIfEnabled(absl::string_view pass_name, + absl::string_view step, + const HloModule& module); + +// Dumps the given HloSnapshot to the module's xla_dump_dir, if this is enabled. +// +// Prefer the first overload below, as this will give filenames that are +// consistent with the other methods here. The second overload (which doesn't +// take an HloModule) is useful in the cases when you're dumping an HloSnapshot +// and simply don't have an HloModule. +void DumpHloSnapshotIfEnabled(const HloModule& module, + const HloSnapshot& snapshot); +void DumpHloSnapshotIfEnabled(const HloSnapshot& snapshot, + const DebugOptions& opts); + +void DumpHloModuleMetadataIfEnabled(const std::vector& modules); + +// Returns true if we should dump data for an HloModule. This is useful if you +// want to check if DumpToFileInDir{,OrStdout} will do anything before +// generating an expensive string. +bool DumpingEnabledForHloModule(absl::string_view hlo_module_name, + const DebugOptions& opts); +inline bool DumpingEnabledForHloModule(const HloModule& module) { + return DumpingEnabledForHloModule(module.name(), + module.config().debug_options()); +} + +// Returns true if DumpToFileInDirOrStdout and DumpHloModuleIfEnabled will write +// to stdout, rather than to a file on disk. +// +// This is useful if you want to do something different when writing to stdout. +// For example, maybe you have (almost-)duplicate data that you wouldn't mind +// writing to two files, but you don't want to print twice. +bool DumpingToStdout(const DebugOptions& opts); + +} // namespace xla + +#endif // XLA_SERVICE_DUMP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_dimension_inference.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_dimension_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..0631936d4958dcdb9706754e5f2801b3bf0e8e6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_dimension_inference.h @@ -0,0 +1,188 @@ +/* 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_SERVICE_DYNAMIC_DIMENSION_INFERENCE_H_ +#define XLA_SERVICE_DYNAMIC_DIMENSION_INFERENCE_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/shape_util.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { + +// DynamicDimensionInference analyzes each HLO instruction in a graph and +// inferences which dimensions are dynamic and which scalar instructions +// represent the runtime real size of those dynamic dimensions. +class DynamicDimensionInference { + public: + enum ShapeCheckMode { + kInvalid = 0, + // At compile time, pessimisticly assumes runtime shape checks may fail and + // returns a compile-time error. + kCompileTime, + // Insert runtime checks as Hlo ops. + kRuntime, + // Ignore shape check. + kIgnore, + }; + using CustomCallInferenceHandler = + std::function; + + // Generate an assertion which fails the execution if the instruction value is + // false. + using AssertionGenerator = std::function; + + static StatusOr Run( + HloModule* module, + CustomCallInferenceHandler custom_call_handler = nullptr, + ShapeCheckMode shape_check_mode = ShapeCheckMode::kIgnore, + const AssertionGenerator& assertion_generator = nullptr, + const absl::flat_hash_set& execution_threads_ = {}); + + std::string ToString() const; + + // If the dimension `dim` of instruction `inst` at `index` has a dynamic size, + // returns a scalar HloInstruction that represents the runtime size of that + // dimension. Otherwise returns nullptr. + HloInstruction* GetDynamicSize(HloInstruction* inst, const ShapeIndex& index, + int64_t dim) const; + + const HloInstruction* GetDynamicSize(const HloInstruction* inst, + const ShapeIndex& index, + int64_t dim) const; + + // Returns dynamic sizes of all dimensions of `inst`'s leaf node at `index`. + // Static sizes are represented by nullptr. + std::vector GetDynamicSizes(HloInstruction* inst, + const ShapeIndex& index) const; + + // Returns if `index` at `inst` contains any dynamic dimension. + // Recursively go into tuples. + bool HasDynamicDimension(HloInstruction* inst, + ShapeIndexView index = {}) const; + + // Forward dynamic dimension size at `dim` from `inst` to `new_inst`. + Status ForwardDynamicSize(HloInstruction* inst, HloInstruction* new_inst, + const ShapeIndex& index); + + // Update the dynamic mapping so that we know dimension `dim` of instruction + // `inst` at `index` has a dynamic size, and its runtime size is represented + // by a scalar instruction `size`. + void SetDynamicSize(HloInstruction* inst, const ShapeIndex& index, + int64_t dim, HloInstruction* size); + + // For all tensors whose dynamic dimension is `replace`, replace them with + // `with`. + void ReplaceAllDynamicDimensionUsesWith(HloInstruction* replace, + HloInstruction* with); + + // Update dynamic dimension inference to analyze `inst`. Useful to + // incrementally track new instructions added after initial run. + Status Update(HloInstruction* inst); + + friend class DynamicDimensionInferenceVisitor; + + private: + explicit DynamicDimensionInference( + HloModule* module, CustomCallInferenceHandler custom_call_handler, + ShapeCheckMode shape_check_mode, AssertionGenerator assertion_generator, + const absl::flat_hash_set& execution_threads_); + + // DynamicDimension is used as a key in the dynamic key-value mapping. It + // unambiguously represents a dynamic dimension of a instruction at a given + // index. + struct DynamicDimension { + // HloInstruction that holds the dimension. + HloInstruction* inst; + // Subshape of the instruction that holds the dimension. + ShapeIndex index; + // The dimension number of the dynamic dimension at given index of a given + // instruction. + int64_t dim; + + // Artifacts needed to make this struct able to be used as a `key` in absl + // maps. "friend" keywords are added so these functions can be found through + // ADL. + template + friend H AbslHashValue(H h, const DynamicDimension& m) { + return H::combine(std::move(h), m.inst, m.index, m.dim); + } + + friend bool operator==(const DynamicDimension& lhs, + const DynamicDimension& rhs) { + return lhs.inst == rhs.inst && lhs.index == rhs.index && + lhs.dim == rhs.dim; + } + + std::tuple ToTuple() const { + return std::make_tuple( + inst && inst->GetModule() ? inst->GetModule()->unique_id() : -1, + inst ? inst->unique_id() : -1, index.ToString(), dim); + } + + friend bool operator<(const DynamicDimension& lhs, + const DynamicDimension& rhs) { + return lhs.ToTuple() < rhs.ToTuple(); + } + }; + + // Copies the internal mapping from instruction `from` to instruction `to`. + // This is useful when an instruction is replaced by the other during the + // inferencing process. + void CopyMapping(HloInstruction* from, HloInstruction* to); + + // AnalyzeDynamicDimensions starts the analysis of the dynamic dimensions in + // module_. + Status AnalyzeDynamicDimensions(); + + // HloModule being analyzed. + HloModule* module_; + + // dynamic_mapping_ holds the result of the analysis. It maps a dynamic + // dimension to a scalar HloInstruction that represents the real dynamic size + // of the dynamic dimension. + using DynamicMapping = std::map; + DynamicMapping dynamic_mapping_; + + // A convenient mapping from an hlo to the set of dynamic dimensions that it + // holds. + using PerHloDynamicDimensions = + ConstHloInstructionMap>; + PerHloDynamicDimensions per_hlo_dynamic_dimensions_; + + // A handler for custom calls. + CustomCallInferenceHandler custom_call_handler_; + + // Indicates what to do at places where shape check is needed. + ShapeCheckMode shape_check_mode_; + + AssertionGenerator assertion_generator_; + + const absl::flat_hash_set& execution_threads_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_DYNAMIC_DIMENSION_INFERENCE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_dimension_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_dimension_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..aae92ddd59a23f2782a529d173abf20cb54a2094 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_dimension_simplifier.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_DYNAMIC_DIMENSION_SIMPLIFIER_H_ +#define XLA_SERVICE_DYNAMIC_DIMENSION_SIMPLIFIER_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This pass simplifies operations on dynamic dimension sizes so that it can be +// easily analyzed by later passes. +class DynamicDimensionSimplifier : public HloModulePass { + public: + absl::string_view name() const override { + return "dynamic dimension simplifier"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; +} // namespace xla + +#endif // XLA_SERVICE_DYNAMIC_DIMENSION_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_index_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_index_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..723c686239de9a4e2354bbca16dac0a6120b9d17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_index_splitter.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_DYNAMIC_INDEX_SPLITTER_H_ +#define XLA_SERVICE_DYNAMIC_INDEX_SPLITTER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Convert R1 index operands to DynamicSlice and DynamicUpdateSlice ops into +// separate scalars. +class DynamicIndexSplitter : public HloModulePass { + public: + DynamicIndexSplitter() = default; + absl::string_view name() const override { return "dynamic-index-splitter"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_DYNAMIC_INDEX_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_padder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_padder.h new file mode 100644 index 0000000000000000000000000000000000000000..b35d6678a377cc70e1fe91feccf36ee73d57c631 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_padder.h @@ -0,0 +1,100 @@ +/* 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_SERVICE_DYNAMIC_PADDER_H_ +#define XLA_SERVICE_DYNAMIC_PADDER_H_ + +#include + +#include "xla/service/dynamic_dimension_inference.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// With bounded shapes, only part of the shape contains effective data and the +// rest contains padded data, whose value can be anything depending on the +// source of the data. When a bounded shape is directly consumed by an +// instruction that collapses dimensions (reduce for example), the padding data +// would affect result of the instruction. +// +// DynamicPadder uses DynamicDimensionInference to detect bounded shapes in a +// hlo module, it then inserts certain instructions to reset the padding into an +// identity value so that in doesn't affect the result of subsequent +// instruction. For example, it'd reset the padding to 0 before a bounded shape +// is consumed by a reduce-sum. +// +// Dynamic_padder removes dynamic shapes from the entry computation, and inserts +// custom calls (with dynamic shapes), which are lowered by specialized +// emitters: PadToStatic and SliceToDynamic. + +// Each instruction can have one of the three modes in supporting dynamic +// lowering. +enum OpDynamismSupport { + // There is no support for dynamic lowering -- dynamic padder will make sure + // the input to that op has static bound by rewriting the op (e.g, extra space + // in reduce_sum will be padded with 0). + kNoSupport = 0, + // The op can take either dynamic input or static input. + kOptional, + // The op only has a dynamic lowering, dynamic padder will make sure the input + // to this op is in dynamic form. + kRequired, +}; + +struct DynamicPadderOptions { + // Returns true if given instruction supports native dynamic lowering. If + // so, dynamic padder will not attempt to pad it. + using OpSupportsDynamismHandler = + std::function; + + OpSupportsDynamismHandler op_supports_dynamism_handler = nullptr; + + // Instruct how to inference output dynamic dimensions of custom calls. + DynamicDimensionInference::CustomCallInferenceHandler custom_call_handler = + nullptr; + + // If `slice_dynamic_output` is true, insert 'slice_to_dynamic' ops to all + // outputs that are inferred to be dynamic. + bool slice_dynamic_output = true; + + // Assertion generator for shape checks, only used if shape check mode is + // "runtime". + DynamicDimensionInference::AssertionGenerator assertion_generator; + + // If set to true, pessimisticly assumes runtime shape checks may fail and + // returns a compile-time error. + DynamicDimensionInference::ShapeCheckMode shape_check_mode = + DynamicDimensionInference::ShapeCheckMode::kIgnore; +}; + +class DynamicPadder : public HloModulePass { + public: + explicit DynamicPadder(DynamicPadderOptions options = DynamicPadderOptions()) + : options_(options) {} + + absl::string_view name() const override { return "dynamic_padder"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + DynamicPadderOptions options_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_DYNAMIC_PADDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_window_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_window_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..01f3445f9ba19d1f74ab59dca5f6ece905182190 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/dynamic_window_utils.h @@ -0,0 +1,50 @@ +/* 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_SERVICE_DYNAMIC_WINDOW_UTILS_H_ +#define XLA_SERVICE_DYNAMIC_WINDOW_UTILS_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/types.h" +namespace xla { +struct DynamicWindowDims { + HloInstruction* padding_before; + HloInstruction* output_size; +}; + +// This mirrors the logic in GetWindowedOutputSizeVerbose but with HLOs as +// inputs and outputs. +DynamicWindowDims GetWindowedOutputSize(HloInstruction* input_size, + int64_t window_size, + int64_t window_dilation, + int64_t window_stride, + PaddingType padding_type); + +DynamicWindowDims GetWindowedInputGradSize(HloInstruction* input_size, + int64_t window_size, + int64_t window_dilation, + int64_t window_stride, + PaddingType padding_type); + +} // namespace xla + +#endif // XLA_SERVICE_DYNAMIC_WINDOW_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/eigh_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/eigh_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..db86358aaae0cac64ab7b4cd9cbb871490133c99 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/eigh_expander.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_EIGH_EXPANDER_H_ +#define XLA_SERVICE_EIGH_EXPANDER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/client/xla_builder.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +class EighExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "eigh_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; + + virtual XlaOp BuildEigh(XlaOp a, bool lower, int64_t max_iter, float tol, + bool sort_eigenvalues); + + Status SortByEigenvalues(XlaOp& v, XlaOp& w); + + private: + // Mapping from op signatures to existing computations. + absl::flat_hash_map computation_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_EIGH_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/elemental_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/elemental_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..5dccb034e66e9607453ba978e49db1b527b65846 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/elemental_ir_emitter.h @@ -0,0 +1,322 @@ +/* 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_SERVICE_ELEMENTAL_IR_EMITTER_H_ +#define XLA_SERVICE_ELEMENTAL_IR_EMITTER_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/ir_builder_mixin.h" +#include "xla/service/llvm_ir/loop_emitter.h" +#include "xla/statusor.h" + +namespace xla { + +class ElementalIrEmitter : public IrBuilderMixin { + public: + using HloToElementGeneratorMap = + absl::flat_hash_map; + + ElementalIrEmitter(llvm::Module* module, llvm::IRBuilder<>* b) + : b_(b), module_(module) {} + + virtual ~ElementalIrEmitter() = default; + + // Returns a function to generate an element of the output of `hlo`, given a + // map of functions to generate elements of its operands. + llvm_ir::ElementGenerator MakeElementGenerator( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator); + + llvm::IRBuilder<>* b() { return b_; } + + // builder() is for IrBuilderMixin. + llvm::IRBuilder<>* builder() { return b_; } + + llvm::Module* module() { return module_; } + + // Returns which ops invalidate the cache of emitted instructions by creating + // a new BasicBlock and setting the insertion point to the newly created + // BasicBlock. We can only reuse cached values if they were emitted in the + // same BasicBlock as the current BasicBlock. + static bool OpInvalidatesCache(const HloInstruction* hlo); + + protected: + virtual llvm_ir::IrArray::Index GetSourceIndexOfBitcast( + const llvm_ir::IrArray::Index& index, const HloInstruction* hlo) { + return index.SourceIndexOfBitcast(hlo->shape(), hlo->operand(0)->shape(), + b_); + } + + virtual StatusOr EmitFloatBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual llvm::Value* EmitExtractReal(llvm::Value* value); + virtual llvm::Value* EmitExtractImag(llvm::Value* value); + + virtual StatusOr EmitF32ToBF16(llvm::Value* f32_value); + + private: + virtual StatusOr EmitUnaryOp(const HloInstruction* op, + llvm::Value* operand_value); + + virtual StatusOr EmitBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual StatusOr EmitIntegerUnaryOp(const HloInstruction* op, + llvm::Value* operand_value); + + virtual StatusOr EmitFloatUnaryOp(const HloInstruction* op, + llvm::Value* operand_value); + + virtual StatusOr EmitComplexUnaryOp(const HloInstruction* op, + llvm::Value* operand_value); + + llvm::Value* IsZero(llvm::Value* v); + llvm::Value* IsIntMinDivisionOverflow(llvm::Value* lhs, llvm::Value* rhs); + llvm::Value* GetZero(llvm::Type* type); + llvm::Value* GetOne(llvm::Type* type); + llvm::Value* GetIntSMin(llvm::Type* type); + llvm::Value* GetMinusOne(llvm::Type* type); + + llvm::Value* EmitIntegerDivide(llvm::Value* lhs, llvm::Value* rhs, + bool is_signed); + llvm::Value* EmitIntegerRemainder(llvm::Value* lhs, llvm::Value* rhs, + bool is_signed); + llvm::Value* EmitIntegerPow(llvm::Value* lhs, llvm::Value* rhs, + bool is_signed); + + virtual StatusOr EmitPredBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual StatusOr EmitIntegerBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value, + bool is_signed); + + virtual StatusOr EmitComplexBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual llvm::Value* EmitFloatMax(llvm::Value* lhs_value, + llvm::Value* rhs_value, + absl::string_view name); + + virtual llvm::Value* EmitFloatMin(llvm::Value* lhs_value, + llvm::Value* rhs_value, + absl::string_view name); + + llvm::Value* EmitIntegralMax(llvm::Value* lhs_value, llvm::Value* rhs_value, + bool is_signed); + + llvm::Value* EmitIntegralMin(llvm::Value* lhs_value, llvm::Value* rhs_value, + bool is_signed); + + virtual StatusOr EmitAtan2(PrimitiveType prim_type, + llvm::Value* lhs, llvm::Value* rhs, + absl::string_view name); + + virtual StatusOr EmitLog(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitSqrt(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitCbrt(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitRsqrt(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitLog1p(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitSin(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitCos(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitTan(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitExp(PrimitiveType prim_type, + llvm::Value* value, + absl::string_view name); + + virtual StatusOr EmitExpm1(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitPow(PrimitiveType prim_type, + llvm::Value* lhs, llvm::Value* rhs, + absl::string_view name); + + virtual StatusOr EmitTanh(PrimitiveType prim_type, + llvm::Value* value); + + virtual StatusOr EmitReducePrecision(const HloInstruction* hlo, + llvm::Value* x); + + virtual StatusOr> + EmitComplexAbsHelper(PrimitiveType prim_type, llvm::Value* operand_value, + bool return_sqrt); + + virtual StatusOr EmitComplexAbs(PrimitiveType prim_type, + llvm::Value* operand_value); + + virtual StatusOr EmitSqrtComplexAbs(PrimitiveType prim_type, + llvm::Value* operand_value); + virtual StatusOr EmitRsqrtComplexAbs( + PrimitiveType prim_type, llvm::Value* operand_value); + + virtual StatusOr EmitComplexAdd(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual StatusOr EmitComplexSubtract(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual StatusOr EmitComplexMultiply(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual StatusOr EmitComplexDivide(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + virtual StatusOr EmitComplexLog(const HloInstruction* op, + llvm::Value* operand_value); + + virtual StatusOr EmitComplexSqrt(const HloInstruction* op, + PrimitiveType prim_type, + llvm::Value* operand_value); + + virtual StatusOr EmitComplexRsqrt(const HloInstruction* op, + PrimitiveType prim_type, + llvm::Value* operand_value); + + StatusOr EmitAccumResult( + absl::Span accumulator_addrs, + llvm::ArrayRef accumulator_types, bool is_variadic); + + // Composes a complex struct. imag may be nullptr for simple cast operations. + llvm::Value* EmitComposeComplex(const HloInstruction* op, llvm::Value* real, + llvm::Value* imag); + + // Emit `accumulator + lhs * rhs` for the given primitive type. + llvm::Value* EmitMulAdd(llvm::Value* lhs, llvm::Value* rhs, + llvm::Value* accumulator, + xla::PrimitiveType primitive_type); + + // Identifier of the thread unique among all threads on the device + virtual llvm::Value* EmitThreadId() { return b_->getIntN(128, 0); } + + StatusOr EmitElementalSelect( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& index); + + StatusOr EmitElementalClamp( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& index); + + StatusOr EmitElementalConcatenate( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& target_index); + + StatusOr EmitElementalDynamicSlice( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& index); + + StatusOr EmitElementalGather( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& index); + + StatusOr EmitElementalDynamicUpdateSlice( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& index); + + StatusOr EmitElementalPad( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& padded_index); + + StatusOr EmitElementalDot( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& dot_result_index); + + virtual StatusOr> EmitThreadLocalCall( + const HloComputation& callee, absl::Span parameters, + absl::string_view name, bool is_reducer) = 0; + + StatusOr EmitElementalMap( + const HloMapInstruction* map_instr, + absl::Span elemental_operands); + + StatusOr EmitElementalReduceWindow( + const HloReduceWindowInstruction* reduce_window, + std::vector input_generators, + std::vector initial_value_generators, + const llvm_ir::IrArray::Index& index); + + StatusOr EmitElementalReduce( + const HloReduceInstruction* reduce, + std::vector input_generators, + std::vector initial_value_generators, + const llvm_ir::IrArray::Index& index); + + virtual StatusOr EmitConvolution( + const HloInstruction* hlo, + const HloToElementGeneratorMap& operand_to_generator, + const llvm_ir::IrArray::Index& index); + + // Computes the complex power function, returns (a + i*b)^(c + i*d). + StatusOr EmitComplexPower(const HloInstruction* op, + llvm::Value* a, llvm::Value* b, + llvm::Value* c, llvm::Value* d); + + // Evaluates a polynomial using Horner's method. + StatusOr EvaluatePolynomial( + llvm::Type* type, llvm::Value* x, absl::Span coefficients); + + virtual bool fast_min_max() = 0; + + llvm::IRBuilder<>* const b_; + + llvm::Module* module_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_ELEMENTAL_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/executable.h new file mode 100644 index 0000000000000000000000000000000000000000..dc52a64bb81465b6a0166b8c87a49febbe079dab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/executable.h @@ -0,0 +1,422 @@ +/* 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_SERVICE_EXECUTABLE_H_ +#define XLA_SERVICE_EXECUTABLE_H_ + +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/types/span.h" +#include "absl/types/variant.h" +#include "xla/debug_options_flags.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/computation_layout.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_execution_profile.h" +#include "xla/service/hlo_graph_dumper.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/maybe_owning_device_memory.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/service/shaped_buffer.h" +#include "xla/shape.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/util.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// TODO(b/150633678): Both the ExecutionInput and ExecutionOutput need to be +// revisited, with the execute APIs taking data structure which can better model +// shareable buffers. +// +// ExecutionInput buffers are in one of three states: +// +// 1) Owned by the caller and immutable. +// 2) Donated by the caller but returned on error. +// 3) Donated by the caller and freed on error. +// +// Case (1) buffers are stored as MaybeOwningDeviceMemory(DeviceMemoryBase). +// Case (2) buffers are stored as MaybeOwningDeviceMemory(OwningDeviceMemory), +// with their indices present in unowned_indices_. +// Case (3) buffers are stored as MaybeOwningDeviceMemory(OwningDeviceMemory), +// with their indices absent from unowned_indices_. +class ExecutionInput { + public: + explicit ExecutionInput(xla::Shape shape) : buffers_(std::move(shape)) { + SetHostShape(ShapeUtil::DeviceShapeToHostShape(buffers_.shape())); + } + // TODO(b/170310047): remove this overload. + ExecutionInput(xla::Shape shape, xla::Shape host_shape) + : buffers_(std::move(shape)) { + SetHostShape(ShapeUtil::DeviceShapeToHostShape(buffers_.shape())); + } + + explicit ExecutionInput(ShapeTree buffers) + : buffers_(std::move(buffers)) { + SetHostShape(ShapeUtil::DeviceShapeToHostShape(buffers_.shape())); + } + // TODO(b/170310047): remove this overload. + ExecutionInput(ShapeTree buffers, + xla::Shape host_shape) + : buffers_(std::move(buffers)) { + SetHostShape(ShapeUtil::DeviceShapeToHostShape(buffers_.shape())); + } + + ExecutionInput(ExecutionInput&&) = default; + + ~ExecutionInput(); + + ExecutionInput& operator=(ExecutionInput&&) = default; + + const Shape& shape() const { + return dynamic_shape_ != nullptr ? *dynamic_shape_ : buffers_.shape(); + } + + const Shape& host_shape() const { + return host_shape_ != nullptr ? *host_shape_ : shape(); + } + + Status SetDynamicShape(Shape dynamic_shape); + + xla::StatusOr ToShapedBuffer( + se::DeviceMemoryAllocator* allocator, int device_ordinal) const; + + void SetBuffer(const ShapeIndex& index, MaybeOwningDeviceMemory buffer) { + *buffers_.mutable_element(index) = std::move(buffer); + } + + void SetUnownedBuffer(const ShapeIndex& index, + MaybeOwningDeviceMemory buffer); + + void SetUnownedIndex(const ShapeIndex& index) { + unowned_indices_.insert(index); + } + + void ClearUnownedIndex(const ShapeIndex& index) { + unowned_indices_.erase(index); + } + + const std::set& unowned_indices() { return unowned_indices_; } + + const ShapeTree& Buffers() const { return buffers_; } + + ShapeTree* MutableBuffers() { return &buffers_; } + + MaybeOwningDeviceMemory* MutableBuffer(const ShapeIndex& index) { + return buffers_.mutable_element(index); + } + + const MaybeOwningDeviceMemory& Buffer(const ShapeIndex& index) const { + return buffers_.element(index); + } + + private: + void SetHostShape(xla::Shape host_shape) { + if (shape() != host_shape) { + host_shape_ = std::make_unique(std::move(host_shape)); + } + } + + ShapeTree buffers_; + // Set of indices of buffers that should be returned to the caller if an error + // occurs when enqueuing the computation. + std::set unowned_indices_; + std::unique_ptr dynamic_shape_; + std::unique_ptr host_shape_; +}; + +// ExecutionOutput encapsulates the output buffers of a execution and the +// leftover buffers to be released by the caller. +class ExecutionOutput { + public: + explicit ExecutionOutput(ScopedShapedBuffer result) + : result_(std::move(result)) {} + ExecutionOutput(ScopedShapedBuffer result, + std::vector to_be_released) + : result_(std::move(result)), + to_be_released_(std::move(to_be_released)) {} + // TODO(b/170310047): remove this overload. + ExecutionOutput(Shape on_host_shape, Shape on_device_shape, + se::DeviceMemoryAllocator* allocator, int device_ordinal) + : result_(std::move(on_device_shape), allocator, device_ordinal) {} + ExecutionOutput(Shape on_device_shape, se::DeviceMemoryAllocator* allocator, + int device_ordinal) + : result_(std::move(on_device_shape), allocator, device_ordinal) {} + ExecutionOutput(ExecutionOutput&&) = default; + ExecutionOutput& operator=(ExecutionOutput&&) = default; + + ~ExecutionOutput() { + // If the ExecutionOutput has not been committed, and if there are aliased + // indices, clear them off the ScopedShapedBuffer to prevent them to be + // released. + for (auto& index : aliased_indices_) { + result_.set_buffer(se::OwningDeviceMemory(), index); + } + } + + void AddAliasedIndex(ShapeIndex index) { + aliased_indices_.push_back(std::move(index)); + } + + void AddToBeReleased(se::OwningDeviceMemory mem) { + to_be_released_.push_back(std::move(mem)); + } + + // Should be called once it is known that the execute operation succeeded, + // before returning the ExecutionOutput to the caller. + ExecutionOutput& Commit() { + aliased_indices_.clear(); + return *this; + } + + const ScopedShapedBuffer& Result() const { return result_; } + + ScopedShapedBuffer* MutableResult() { return &result_; } + + ScopedShapedBuffer ConsumeResult() { + aliased_indices_.clear(); + return std::move(result_); + } + + const std::vector& ToBeReleased() const { + return to_be_released_; + } + + std::vector ConsumeToBeReleased() { + return std::move(to_be_released_); + } + + std::vector ConsumeAliasedIndices() { + auto aliased = std::move(aliased_indices_); + aliased_indices_.clear(); + return aliased; + } + + private: + ScopedShapedBuffer result_; + + // Leftover buffers for the caller to release. Elements in this list are + // donated input memory buffers that are not reused by XLA as outputs. + std::vector to_be_released_; + + // These are the indices in result_ which have been aliased from the caller. + // If the execution operation fails, the caller should maintain ownership of + // the buffer, so we track the indices here, and unless the ExecutionOutput is + // committed, we remove them from the result_ before destruction. + std::vector aliased_indices_; + + // A shape table is a continuous region in memory that is used to hold the + // runtime dimension sizes of dynamic output shapes. + se::OwningDeviceMemory output_shape_table_; +}; + +// A given platform's compiler will produce an Executable -- this is a uniform +// interface that is used for launching compiled programs across platforms. +class Executable { + public: + // The hlo_module parameter may be nullptr, if the given executable type + // doesn't need it for execution. + explicit Executable(std::shared_ptr hlo_module) + : hlo_module_(std::move(hlo_module)) {} + + // TODO(b/172012028): Remove this constructor. + // The hlo_module parameter may be nullptr, if the given executable type + // doesn't need it for execution. + explicit Executable( + std::shared_ptr hlo_module, + std::unique_ptr hlo_profile_printer_data, + std::unique_ptr hlo_profile_index_map) + : hlo_module_(std::move(hlo_module)), + hlo_profile_printer_data_(std::move(hlo_profile_printer_data)), + hlo_profile_index_map_(std::move(hlo_profile_index_map)) { + CHECK_EQ(hlo_profile_printer_data_.get() == nullptr, + hlo_profile_index_map_.get() == nullptr); + } + virtual ~Executable() {} + + // Enqueues the compilation result on the provided stream, passing the given + // arguments. This call is blocking and returns after the execution is done. + // + // If the hlo_execution_profile is provided as non-nullptr, profiling will be + // enabled. + // + // Returns a shaped buffer containing the result of the computation. + StatusOr ExecuteOnStream( + const ServiceExecutableRunOptions* run_options, + absl::Span arguments, + HloExecutionProfile* hlo_execution_profile); + + // Starts the given program executing on the given stream/executor. + // + // `arguments` are ShapeTree containing the input parameters. For each element + // in the shape tree, if the element holds the ownership of the memory, it is + // considered donated and XLA will potentially reuse it as output buffers. For + // all donated inputs, XLA is also responsible for freeing them. + // + // If an input is donated to XLA but is not reused as output, it is returned + // as an leftover buffer for the caller to release. + // + // This call should be non-blocking and may return as soon as all of the + // operations are enqueued for launch on the stream. Note that some + // implementations may in fact block or may block in some circumstances (e.g., + // when profiling); i.e., asynchronous is a "may" not a "must". + // + // If the hlo_execution_profile is provided as non-nullptr, profiling will be + // enabled. Note that profiling is tricky to use correctly, as the profiling + // objects (when they exist) must out-live the task. + virtual StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + absl::Span arguments, + HloExecutionProfile* hlo_execution_profile); + + // Same as ExecuteAsyncOnStream(), but blocks waiting for the computation to + // complete. + StatusOr ExecuteOnStream( + const ServiceExecutableRunOptions* run_options, + std::vector arguments, + HloExecutionProfile* hlo_execution_profile); + + virtual StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + std::vector arguments, + HloExecutionProfile* hlo_execution_profile) = 0; + + // Same as ExecuteOnStream(), but runs this executable on multiple + // streams. arguments[i] contains the arguments to the execution on + // run_options[i]->stream() and the returned value is at index i of the + // returned vector. + virtual StatusOr> ExecuteOnStreams( + absl::Span run_options, + absl::Span> arguments); + + // Convenience wrapper for calling Executable::ExecuteOnStream. Sets up a + // timer for the execution, sets up HLO profiling if enabled, and fills in the + // given ExecutionProfile if non-null. + StatusOr ExecuteOnStreamWrapper( + const ServiceExecutableRunOptions* run_options, + absl::Span arguments); + + StatusOr ExecuteOnStreamWrapper( + const ServiceExecutableRunOptions* run_options, + std::vector arguments); + + StatusOr ExecuteAsyncOnStreamWrapper( + const ServiceExecutableRunOptions* run_options, + absl::Span arguments); + + StatusOr ExecuteAsyncOnStreamWrapper( + const ServiceExecutableRunOptions* run_options, + std::vector arguments); + + const HloProfilePrinterData& hlo_profile_printer_data() const { + CHECK(hlo_profiling_enabled()); + return *hlo_profile_printer_data_; + } + + const HloProfileIndexMap& hlo_profile_index_map() const { + CHECK(hlo_profiling_enabled()); + return *hlo_profile_index_map_; + } + + // Returns whether this executable was compiled with HLO profilings support + // enabled. If not, the caller should not expect an hlo_execution_profile + // passed to ExecuteOnStream above to be populated during execution. + bool hlo_profiling_enabled() const { + return hlo_profile_printer_data_ != nullptr; + } + + HloModule& module() const { + CHECK(hlo_module_ != nullptr); + return *hlo_module_; + } + std::shared_ptr shared_module() const { return hlo_module_; } + + bool has_module() const { return hlo_module_ != nullptr; } + + const HloModuleConfig& module_config() const { + CHECK(hlo_module_ != nullptr); + return hlo_module_->config(); + } + + // The shape (including layout) that results from this execution. This is the + // shape of the DeviceMemoryBase result value in ExecuteOnStream above. + const Shape& result_shape() const { + CHECK(hlo_module_ != nullptr); + return hlo_module_->config().entry_computation_layout().result_shape(); + } + + // Returns the size of the executable in bytes. Returns -1 if this query is + // not supported by the executable. + // + // Does not include the size of used libraries (e.g. cuDNN, Eigen, etc.). + virtual int64_t SizeOfGeneratedCodeInBytes() const; + + // Dumping helpers. + void set_hlo_proto(std::unique_ptr hlo_proto) { + hlo_proto_ = std::move(hlo_proto); + } + bool dumping_snapshot() const { + return has_module() + ? module_config().debug_options().xla_dump_hlo_snapshots() + : false; + } + HloProto const* hlo_proto() const { return hlo_proto_.get(); } + + std::string& debug_info() { return debug_info_; } + void set_debug_info(const std::string& debug_info) { + debug_info_ = debug_info; + } + // Gather unused but donated buffers, return them to the caller of this API. + // We don't free buffers inside this function since the caller could have + // different preferences for buffer deallocation. For example, in TensorFlow, + // buffers are mostly efficiently deallocated as soon as a program has been + // launched. However, in XRT, the buffers are expected to be deallocated after + // the program has finished since XRT doesn't support async deallocation. + void MarkToBeReleasedArguments(absl::Span arguments, + ExecutionOutput& result); + + protected: + // HloModule this was compiled from. BufferAssignment keeps pointers to + // HloInstructions owned by the HloModule so we need to keep the HloModule + // around if we keep the BufferAssignment around. + // + // This member may be nullptr, if the given executable type doesn't need it + // for execution. + const std::shared_ptr hlo_module_; + + // The serialized HLO proto. Non-null only if dumping snapshots is enabled. + std::unique_ptr hlo_proto_; + + // Execution count, used to generate a unique filename for each dumped + // execution. + int64_t execution_count_ = 0; + + std::unique_ptr hlo_profile_printer_data_; + std::unique_ptr hlo_profile_index_map_; + + // Generic debug information as a string. + std::string debug_info_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/execution_tracker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/execution_tracker.h new file mode 100644 index 0000000000000000000000000000000000000000..d194e750101034d58ca8049cc9216700d3b66e12 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/execution_tracker.h @@ -0,0 +1,100 @@ +/* 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_SERVICE_EXECUTION_TRACKER_H_ +#define XLA_SERVICE_EXECUTION_TRACKER_H_ + +#include +#include +#include + +#include "xla/executable_run_options.h" +#include "xla/service/backend.h" +#include "xla/service/stream_pool.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Represents an asynchronously launched execution. Owns the stream (from the +// passed run_options->stream()) on which the execution is launched and releases +// the stream when destructed. +class AsyncExecution { + public: + AsyncExecution(Backend* backend, std::vector streams, + const ExecutionProfile& profile, GlobalDataHandle result); + + Status BlockUntilDone() const; + + const GlobalDataHandle& result() const { return result_; } + + const ExecutionProfile& profile() const { return profile_; } + + private: + // Backend to execute the computation on. + Backend* backend_; + + // Stream on which the execution is launched. + std::vector streams_; + + // Profile object of the execution to be returned to the user. + ExecutionProfile profile_; + + // Data handle to the result of the execution. Data represented by this handle + // is valid only after BlockUntilDone() is called. + GlobalDataHandle result_; +}; + +// Tracks asynchronously launched executions for the XLA service. +class ExecutionTracker { + public: + ExecutionTracker(); + + // Registers an execution with its backend, streams, and data handle to the + // execution result. Returns a handle for the registered execution. + ExecutionHandle Register(Backend* backend, + std::vector stream, + const ExecutionProfile& profile, + GlobalDataHandle data); + + // Unregisters the execution for the given handle. + Status Unregister(const ExecutionHandle& handle); + + // Resolves the given ExecutionHandle to an AsyncExecution. Returns an + // error status if the given handle is not found, which means that the + // execution is not yet registered or already unregistered. + StatusOr Resolve(const ExecutionHandle& handle); + + private: + // The next handle to assign to an execution. + int64_t next_handle_ ABSL_GUARDED_BY(execution_mutex_); + + // Mapping from ExecutionHandle handle to the corresponding registered + // AsyncExecution object. + std::map> handle_to_execution_ + ABSL_GUARDED_BY(execution_mutex_); + + absl::Mutex execution_mutex_; // Guards the execution mapping. + + ExecutionTracker(const ExecutionTracker&) = delete; + ExecutionTracker& operator=(const ExecutionTracker&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_EXECUTION_TRACKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/export_hlo.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/export_hlo.h new file mode 100644 index 0000000000000000000000000000000000000000..e14a66fca5f6bd679a81008a59808a75653cd0d8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/export_hlo.h @@ -0,0 +1,82 @@ +/* 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_SERVICE_EXPORT_HLO_H_ +#define XLA_SERVICE_EXPORT_HLO_H_ + +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/stream_executor/device_description.pb.h" + +// Functionality to enable HLO uploads from XLA to HLO repositories. Unoptimized +// HLO means the HLO given to XLA, while optimized HLO refers to HLO that has +// been successfully compiled. Errors in upload should not block compilation. + +namespace xla { + +// Uploads HLO to a repository. The only non-dummy implementation is +// Google-internal as of 2023-10. +class SymbolUploader { + public: + virtual ~SymbolUploader() = default; + + // Returns a string identifying the uploaded HLO, or empty if the upload did + // not complete. We use optional rather than StatusOr because an upload error + // is not a compiler error. + virtual std::optional MaybeUploadUnoptimizedHloModule( + HloModule* module, + const stream_executor::GpuTargetConfigProto& gpu_target_config) = 0; +}; + +// Registers a single process-wide XSymbolUploader to use. The registry is used +// to provide a hook for internal infrastructure and ensure that only one +// background thread is uploading. +class SymbolUploaderRegistry { + public: + SymbolUploaderRegistry() : xsymbol_uploader_(nullptr) {} + void Register(std::unique_ptr xsymbol_uploader) { + xsymbol_uploader_ = std::move(xsymbol_uploader); + } + + SymbolUploader* uploader() const { return xsymbol_uploader_.get(); } + + private: + std::unique_ptr xsymbol_uploader_; +}; + +inline SymbolUploaderRegistry& GetGlobalSymbolUploaderRegistry() { + static auto* const registry = new SymbolUploaderRegistry; + return *registry; +} + +// The actual entry points from XLA start here. +inline std::optional MaybeUploadUnoptimizedGpuSymbolsToXSymbol( + HloModule* module, + const stream_executor::GpuTargetConfigProto& gpu_target_config) { + if (SymbolUploader* uploader = GetGlobalSymbolUploaderRegistry().uploader(); + uploader != nullptr) { + return uploader->MaybeUploadUnoptimizedHloModule(module, gpu_target_config); + } + + return std::nullopt; +} + +} // namespace xla + +#endif // XLA_SERVICE_EXPORT_HLO_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/flatten_call_graph.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/flatten_call_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..bb3b43b4b20264a2dd6f8068d7b9e4cf44408aed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/flatten_call_graph.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. +==============================================================================*/ + +// Flatten the call graph for an HLO module into a tree. + +#ifndef XLA_SERVICE_FLATTEN_CALL_GRAPH_H_ +#define XLA_SERVICE_FLATTEN_CALL_GRAPH_H_ + +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Flattening associates each call site with a unique computation (for +// sequential calling contexts) This simplifies buffer assignment and +// points-to analysis (see b/36865746 for details). +class FlattenCallGraph : public HloModulePass { + public: + absl::string_view name() const override { return "flatten-call-graph"; } + + // Duplicates computations called from multiple call- or while-nodes to + // flatten the call graph. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_FLATTEN_CALL_GRAPH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float8_fnuz_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float8_fnuz_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..6aaad33767233aa68160ec57b8c5e1b5a7a88f35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float8_fnuz_ir_emitter.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_FLOAT8_FNUZ_IR_EMITTER_H_ +#define XLA_SERVICE_FLOAT8_FNUZ_IR_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace float8_fnuz_ir_emitter { + +// Convert the given floating point input to the output type. input_type must +// be one of BF16, F16, F32, and F64. output_type must be one of F8E4M3FNUZ and +// F8E5M2FNUZ. +StatusOr EmitFloatingToF8fnuz(PrimitiveType input_type, + llvm::Value* input_value, + PrimitiveType output_type, + llvm::IRBuilder<>* b); + +// Convert the given floating point input to the output type. input_type must +// be one of F8E4M3FNUZ and F8E5M2FNUZ. output_type must be one of BF16, F16, +// F32, and F64. +StatusOr EmitF8fnuzToFloating(PrimitiveType input_type, + llvm::Value* f8_value, + PrimitiveType output_type, + llvm::IRBuilder<>* b, + llvm::Module* module); +} // namespace float8_fnuz_ir_emitter +} // namespace xla + +#endif // XLA_SERVICE_FLOAT8_FNUZ_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float_normalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float_normalization.h new file mode 100644 index 0000000000000000000000000000000000000000..e23776315c38a0f08fe89b338713f38bb5867f97 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float_normalization.h @@ -0,0 +1,105 @@ +/* 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_SERVICE_FLOAT_NORMALIZATION_H_ +#define XLA_SERVICE_FLOAT_NORMALIZATION_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/float_support.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which adds type conversions (e.g. F32 <-> BF16) for HLO instructions +// that do not support low-precision input/output or mixed precision, according +// to the passed-in backend-specific FloatSupport instance. +class FloatNormalization : public HloModulePass { + public: + explicit FloatNormalization(const FloatSupport* float_support) + : float_support_(float_support), + name_("float-normalization-" + + primitive_util::LowercasePrimitiveTypeName( + float_support_->LowPrecisionType())) {} + + ~FloatNormalization() override = default; + absl::string_view name() const override { return name_; } + + // Run float normalization on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const FloatSupport* float_support_; + std::string name_; +}; + +// A pass that unconditionally removes the mixed F32/BF16 uses in HLO +// instructions (excluding convert) by adding F32 <-> BF16 conversions. Unlike +// FloatNormalization, this pass does not use a backend-specific +// FloatSupport, and does not change HLOs that have BF16 data if they do not +// use mixed precision; it removes mixed precision even if the backend supports +// it. This pass is used to make the HLO module valid for other HLO passes which +// do not support mixed precision. Currently, this pass is only used by the +// Despecializer, not by our normal compilation flow on TPU. +class BFloat16MixedPrecisionRemoval : public HloModulePass { + public: + BFloat16MixedPrecisionRemoval() = default; + + ~BFloat16MixedPrecisionRemoval() override = default; + + absl::string_view name() const override { + return "bf16-mixed-precision-removal"; + } + + // Run mixed precision removal on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + StatusOr Run(HloModule* module, + const absl::flat_hash_set& + execution_threads) override { + FloatNormalization normalization(&no_mixed_precision_support_); + return normalization.Run(module, execution_threads); + } + + private: + class BFloat16SupportForMixedPrecisionRemoval : public FloatSupport { + public: + BFloat16SupportForMixedPrecisionRemoval() : FloatSupport(BF16) {} + + ~BFloat16SupportForMixedPrecisionRemoval() override = default; + + bool SupportsLowPrecisionOperand(const HloInstruction& hlo, + int64_t operand_index) const override { + return true; + } + + bool SupportsLowPrecisionOutput(const HloInstruction& hlo) const override { + return true; + } + + bool SupportsMixedPrecisions(const HloInstruction& hlo) const override { + return false; + } + } no_mixed_precision_support_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_FLOAT_NORMALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float_support.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float_support.h new file mode 100644 index 0000000000000000000000000000000000000000..9a2691be1f27f628ea881b4f457e90a20f8cff43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/float_support.h @@ -0,0 +1,89 @@ +/* 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_SERVICE_FLOAT_SUPPORT_H_ +#define XLA_SERVICE_FLOAT_SUPPORT_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// This class has methods to query if a certain low-precision floating-point +// type, such as bfloat16, is supported in certain instructions on a given +// backend. +class FloatSupport { + public: + explicit FloatSupport(PrimitiveType low_precision_type) + : low_precision_type_(low_precision_type) {} + virtual ~FloatSupport() = default; + + // The low-precision type. Callers can use this class to query whether the + // backend supports this type. + PrimitiveType LowPrecisionType() const { return low_precision_type_; } + + // A high-precision type that should be used in place of the low-precision + // type if the backend does not support the low-precision type for a certain + // instruction. + PrimitiveType HighPrecisionType() const { + if (low_precision_type_ == F8E5M2 || low_precision_type_ == F8E4M3FN || + low_precision_type_ == F8E4M3B11FNUZ || + low_precision_type_ == F8E5M2FNUZ || + low_precision_type_ == F8E4M3FNUZ) { + return F16; + } + DCHECK_EQ(low_precision_type_, BF16); + return F32; + } + + // Returns whether the backend supports a low-precision operand for the HLO + // instruction at the given index. + virtual bool SupportsLowPrecisionOperand(const HloInstruction& hlo, + int64_t operand_index) const; + + // Returns whether the backend supports a low-precision output for the HLO + // instruction. + virtual bool SupportsLowPrecisionOutput(const HloInstruction& hlo) const; + + // Returns whether the backend support mixed precision: the operands, output, + // and parameters/output of the called computations can have different + // precisions (both the low-precision and the high-precision types). + virtual bool SupportsMixedPrecisions(const HloInstruction& hlo) const; + + // Returns whether the given HLO preserves its low-precision operand precision + // at the given index, so even if the output is the high-precision type, + // elements in the output that depend on the low-precision operand will still + // effectively have low precision even if they are in the high-precision + // format. Similarly, this also means if the output is low-precision then + // increasing the operand precision from the low-precision type to the + // high-precision type will not change the output. This typically includes + // HLOs that pass elements from the operand to the output without arithmetic + // operations. + static bool EffectiveOperandPrecisionIsOutputPrecision( + const HloInstruction& hlo, int64_t operand_index); + + // Returns if the backend only uses low precision for the operand at the + // specified index, even if the operand is in the high-precision type. + virtual bool EffectiveOperandPrecisionIsLowPrecision( + const HloInstruction& hlo, int64_t operand_index) const; + + private: + PrimitiveType low_precision_type_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_FLOAT_SUPPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/fusion_node_indexing_evaluation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/fusion_node_indexing_evaluation.h new file mode 100644 index 0000000000000000000000000000000000000000..80e376b991a78c6d7ff3e2517867087ed5cf2904 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/fusion_node_indexing_evaluation.h @@ -0,0 +1,99 @@ +/* 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_SERVICE_FUSION_NODE_INDEXING_EVALUATION_H_ +#define XLA_SERVICE_FUSION_NODE_INDEXING_EVALUATION_H_ + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/types.h" + +namespace xla { +class FusionNodeIndexingEvaluation { + public: + explicit FusionNodeIndexingEvaluation(const HloInstruction* fusion, + int64_t root_usage_count = 1); + + // Evaluate the number of times 'producer' would be emitted if it is fused + // into 'fusion_'. If the duplication is "too high" (some arbitrary chosen + // constant), returns true. + bool CodeDuplicationTooHigh(const HloInstruction* producer) const; + + // Evaluate the maximum code duplication inside the fusion node. If the + // maximum code duplication is "too high" (some arbitrary chosen constant), + // returns true. + bool MaxCodeDuplicationTooHigh() const; + + // Evaluate the number of times 'producer' would be emitted if it is fused + // into 'fusion_'. + int64_t EvaluateEmittedInstructions(const HloInstruction* producer) const; + + // Update the evaluation cache after having fused 'producer' into 'fusion_'. + // 'producer' is the cloned instruction which is now part of the fusion + // computation. 'indexing_users_of_producer' are the direct or indirect users + // of 'producer' which pass index values created by them. + void UpdateEvaluationCache( + const HloInstruction* producer, + absl::flat_hash_set indexing_users_of_producer); + + // Prior to fusing, we need to erase the indexing_users_ entry of the + // producer to be fused, because the HloInstruction pointer will be + // invalidated. We return the set of direct or indirect users which pass index + // values created by them to the fusion parameter corresponding to this + // producer. This will be needed for updating the evaluation cache (see + // UpdateEvaluationCache). + absl::flat_hash_set RemoveFusionOperand( + HloInstruction* fusion_operand); + + private: + // We don't want to have too much code duplication, because it slows down the + // compilation time. There is a tradeoff between compilation time and runtime. + // This constant defines the maximum amount of times that we allow to emit the + // same op (indexed with different index values). + static const int64_t kAllowedCodeDuplication; + + // Computes the 'indexing_users_' and 'index_usage_count_' maps based on the + // current instructions inside the fusion node. Also updates + // 'total_emitted_instructions_' accordingly. + void RecomputeCache(); + + // Computes the 'index_usage_count_' entry for 'instruction'. + void UpdateIndexUsageCount(const HloInstruction* instruction); + + // Updates the 'indexing_users_' entry of the operands of 'instruction'. + void UpdateIndexingUsersOfOperands(const HloInstruction* instruction); + + // Collects for each instruction in a fusion node from which direct or + // indirect users newly created index values are passed. Roughly speaking, we + // reuse index values if the shapes are equal when ignoring the element type + // (we may reuse also if the shape change is a bitcast, but we don't consider + // that here). By ignoring potential reuses our estimate of which instruction + // generates a new index value is a bit more conservative than necessary. + absl::flat_hash_map> + indexing_users_; + + // Stores the number of different index accesses for each instruction in a + // fusion node. The fusion emitter caches access with the same index, so this + // value indicates how many times a specific instruction will be emitted. + absl::flat_hash_map index_usage_count_; + + // The fusion instruction. + const HloInstruction* fusion_; +}; +} // namespace xla + +#endif // XLA_SERVICE_FUSION_NODE_INDEXING_EVALUATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/fusion_queue.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/fusion_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..fe458cc05c2871c554ce18ca3fe99d17483b0a5c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/fusion_queue.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_SERVICE_FUSION_QUEUE_H_ +#define XLA_SERVICE_FUSION_QUEUE_H_ + +#include +#include + +#include "absl/strings/str_cat.h" +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { + +// A queue interface that allows implementations to choose fusion candidates in +// custom order. +class FusionQueue { + public: + FusionQueue() = default; + virtual ~FusionQueue() = default; + + // Dequeues the next fusion candidates: a consumer and the list of producers + // as operand indices. + virtual std::pair> + DequeueNextInstructionAndOperandsToFuseInOrder() = 0; + + // A callback passed to the queue implementation right before the producer is + // fused into the consumer. + virtual void PreFusion(HloInstruction* producer, HloInstruction* consumer) {} + + // A callback passed to the queue implementation right after the fusion is + // created. Note that original_producer could have been destroyed. + virtual void OnFusingInstruction(HloInstruction* fusion, + HloInstruction* original_producer, + HloInstruction* original_consumer) {} + + // A callback passed to the queue implementation when a proposed fusion does + // not happen. + virtual void NotFusingInstruction(HloInstruction* producer, + HloInstruction* consumer) {} + + // A callback passed to the queue implementation to notify the removal of an + // instruction. + virtual void RemoveInstruction(HloInstruction* instruction) = 0; + + // Returns the fusion configuration. + virtual const std::vector* FusionConfiguration() = 0; +}; + +} // namespace xla + +#endif // XLA_SERVICE_FUSION_QUEUE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..6c76cf330adeca0143c74d71a7a1bd88bac701a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_expander.h @@ -0,0 +1,62 @@ +/* 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_SERVICE_GATHER_EXPANDER_H_ +#define XLA_SERVICE_GATHER_EXPANDER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// This pass rewrites gather operations into (roughly) while loops of dynamic +// slices. +// +// This pass can be used two ways: +// +// - kEliminateAllGathers: For backends that don't support gather, this pass +// can convert every gather to a loop. +// +// - kEliminateSimpleGathers: For backends that *do* support gather, this pass +// can strength-reduce "simple" gathers -- specifically, gathers that can be +// represented without a loop -- to dyanmic-slices. +// +// Note that even in kEliminateSimpleGathers mode, this pass may still expand a +// gather into a loop (with a trip-count of 1). It's up to other simplification +// passes to remove the loop. +// +class GatherExpander : public OpExpanderPass { + public: + enum Mode { + kEliminateAllGathers, + kEliminateSimpleGathers, + }; + + explicit GatherExpander(Mode m) : mode_(m) {} + + absl::string_view name() const override { return "gather_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* gather_inst) override; + + private: + Mode mode_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GATHER_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_scatter_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_scatter_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..fd14709327f80da390ede50be8f6993f9fd4f0d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_scatter_utils.h @@ -0,0 +1,57 @@ +/* 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_SERVICE_GATHER_SCATTER_UTILS_H_ +#define XLA_SERVICE_GATHER_SCATTER_UTILS_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { + +// Transforms the given index tensor to make it two-dimensional, with the index +// vector dimension being dimension 1. +// Example: +// input: indices = tensor<4x2x3xi32>, index_vector_dim = 1 +// output: tensor<12x2xi32> +StatusOr TransformStartIndices(HloInstruction* indices, + int64_t index_vector_dim); + +// Given a map from index vector positions to dimension numbers, returns a pair +// of permutations that when applied to the operand, let you replace the map +// with the identity permutation. +// In gather, the map is called `start_index_map`. In scatter, it's +// `scatter_dims_to_operand_dims`. +std::pair, std::vector> +MakeOperandStartIndexPermutations(absl::Span, int operand_rank); + +StatusOr MaybeTranspose(HloInstruction* operand, + absl::Span permutation); + +StatusOr> MaybeTranspose( + absl::Span operands, + const std::vector& operand_permutation); + +// Moves the given dimension to the last dimension. +// Example: MoveDimensionToEnd(tensor<1x2x3xi1>, 0): tensor<2x3x1xi1>. +StatusOr MoveDimensionToEnd(HloInstruction* operand, + size_t dimension, size_t rank); + +} // namespace xla + +#endif // XLA_SERVICE_GATHER_SCATTER_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..f4cbd25d2143bcda3ff1ddbfbbe103df4ad548f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gather_simplifier.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 XLA_SERVICE_GATHER_SIMPLIFIER_H_ +#define XLA_SERVICE_GATHER_SIMPLIFIER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// This pass rewrites gather operations into a combination of transposes, +// reshapes and a simpler gather. +// +// The output gather's attributes will have the following characteristics: +// - start_indices is a two-dimensional tensor +// - index_vector_dim is 1 +// - start_index_map is [0, 1, ...] +// - collapsed_slice_dims is [] +// - offset_dims is [1, 2, ...] +// +// The purpose of this pass is to check whether this transformation has any +// performance implications. +class GatherSimplifier : public OpExpanderPass { + public: + absl::string_view name() const override { return "gather_simplifier"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; + + StatusOr ExpandInstruction(HloInstruction* inst) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GATHER_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/generic_transfer_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/generic_transfer_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..318a9b4780388c59781d5200e78fd50c8951987a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/generic_transfer_manager.h @@ -0,0 +1,80 @@ +/* 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_SERVICE_GENERIC_TRANSFER_MANAGER_H_ +#define XLA_SERVICE_GENERIC_TRANSFER_MANAGER_H_ + +#include + +#include "xla/service/transfer_manager.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// A generic implementation of the XLA TransferManager interface +// that is the base class for both CPU and GPU. For GPU, it transfers +// data between host and device (GPU). For CPU, since the "device" +// here is the host itself, there's not much for this transfer manager +// to do except memcpy the result. There is a CpuTransferManager that +// inherits from GenericTransferManager and handles CPU-specific +// infeed. +class GenericTransferManager : public TransferManager { + public: + struct LiteralFromDeviceMetadata : public TransferManager::TransferMetadata { + bool callback_is_host_callback_safe = false; + }; + + GenericTransferManager(se::Platform::Id platform_id, size_t pointer_size); + + se::Platform::Id PlatformId() const override; + + void TransferLiteralFromDevice( + se::Stream* stream, const ShapedBuffer& device_buffer, + MutableBorrowingLiteral literal, std::function done, + const TransferMetadata* transfer_metadata) override; + + Status TransferLiteralToDeviceAsync( + se::Stream* stream, const LiteralSlice& literal, + const ShapedBuffer& device_buffer, + const TransferMetadata* transfer_metadata) override; + + Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal) override; + Status TransferLiteralFromOutfeed(se::StreamExecutor* executor, + MutableBorrowingLiteral literal) override; + + Status ResetDevices(absl::Span executors) override; + + int64_t GetByteSizeRequirement(const Shape& shape) const override; + + Status WriteSingleTupleIndexTable( + se::Stream* stream, absl::Span elements, + const Shape& shape, se::DeviceMemoryBase* region) override; + + private: + // The platform this transfer manager targets. + const se::Platform::Id platform_id_; + + // The size in bytes of pointers on this platform. + const size_t pointer_size_; + + GenericTransferManager(const GenericTransferManager&) = delete; + GenericTransferManager& operator=(const GenericTransferManager&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GENERIC_TRANSFER_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/global_device_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/global_device_id.h new file mode 100644 index 0000000000000000000000000000000000000000..cc843a5aee327788a1f32ffcb5eff32476de6bd2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/global_device_id.h @@ -0,0 +1,38 @@ +/* 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_SERVICE_GLOBAL_DEVICE_ID_H_ +#define XLA_SERVICE_GLOBAL_DEVICE_ID_H_ + +#include + +#include "absl/types/span.h" +#include "xla/types.h" +#include "tsl/lib/gtl/int_type.h" + +namespace xla { + +// Strongly-typed integer type for naming a device globally within a distributed +// system. XLA doesn't have a strong opinion about what global numbering scheme +// is applied to GPUs; the user must provide a local -> global mapping via +// GpuExecutableRunOptions for the local GPUs. +TSL_LIB_GTL_DEFINE_INT_TYPE(GlobalDeviceId, int64_t); + +// Returns a comma-separated string of global device IDs. +std::string GlobalDeviceIdsToString(absl::Span ids); + +} // namespace xla + +#endif // XLA_SERVICE_GLOBAL_DEVICE_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/alias_passthrough_params.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/alias_passthrough_params.h new file mode 100644 index 0000000000000000000000000000000000000000..4483691dfe1b6df76a5def47a1113818fa2f393c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/alias_passthrough_params.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_SERVICE_GPU_ALIAS_PASSTHROUGH_PARAMS_H_ +#define XLA_SERVICE_GPU_ALIAS_PASSTHROUGH_PARAMS_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// This pass aliases input and output buffers that are associated with a +// parameter that is passed through to the module root unmodified. +// +// This pass assumes that parameters and the root use unnested shapes, which is +// the case for XLA:GPU. +// +// This pass must run prior to copy insertion. +class AliasPassthroughParams : public HloModulePass { + public: + AliasPassthroughParams() = default; + ~AliasPassthroughParams() override = default; + absl::string_view name() const override { return "alias_passthrough_params"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_ALIAS_PASSTHROUGH_PARAMS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/all_reduce_blueconnect.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/all_reduce_blueconnect.h new file mode 100644 index 0000000000000000000000000000000000000000..72faa7b5b7e1387abf7b90b00a140316d21816ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/all_reduce_blueconnect.h @@ -0,0 +1,52 @@ +/* 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_SERVICE_GPU_ALL_REDUCE_BLUECONNECT_H_ +#define XLA_SERVICE_GPU_ALL_REDUCE_BLUECONNECT_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Decomposes all-reduce operations using the BlueConnect algorithm. +// +// Paper: "BLUECONNECT: DECOMPOSING ALL-REDUCE FOR DEEP LEARNING ON +// HETEROGENEOUS NETWORK HIERARCHY" +// https://mlsys.org/Conferences/2019/doc/2019/130.pdf +// +// This algorithm attempts to minimize the number of levels of network hierarchy +// traversed for as much data transfer as possible. This implementation assumes +// that host IDs are ordered corresponding to network hierarchy. +class AllReduceBlueConnect : public HloModulePass { + public: + explicit AllReduceBlueConnect(size_t num_devices_per_host) + : num_devices_per_host_(num_devices_per_host) {} + + absl::string_view name() const override { return "all-reduce-blueconnect"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + size_t num_devices_per_host_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_ALL_REDUCE_BLUECONNECT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/analytical_latency_estimator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/analytical_latency_estimator.h new file mode 100644 index 0000000000000000000000000000000000000000..8086ba55a5df6b169e14f089d5ca223f341ca4df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/analytical_latency_estimator.h @@ -0,0 +1,62 @@ +/* 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_SERVICE_GPU_ANALYTICAL_LATENCY_ESTIMATOR_H_ +#define XLA_SERVICE_GPU_ANALYTICAL_LATENCY_ESTIMATOR_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/latency_hiding_scheduler.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { +// Implementation of AnalyticalLatencyEstimator using HloAnalysis and +// GPUPerformanceModel to estimate latencies for instructions. +class AnalyticalLatencyEstimator : public LatencyEstimator { + public: + AnalyticalLatencyEstimator( + const SchedulerConfig& config, + std::unique_ptr latency_estimator, + const se::DeviceDescription& gpu_info, + HloCostAnalysis::ShapeSizeFunction shape_size_function, + HloComputation* computation); + + TimeCost GetLatencyBetween(const HloGraphNode& from, + const HloGraphNode& target) const override; + TimeCost NodeCost(const HloInstruction* instr) const override; + int CyclesPerMicrosecond() const override { + return latency_estimator_->CyclesPerMicrosecond(); + } + + static constexpr TimeCost kLowCost = 1.0; + static constexpr TimeCost kLowLatency = 1.0; + + private: + const SchedulerConfig config_; + const se::DeviceDescription& gpu_info_; + std::optional cost_analysis_; + std::unique_ptr latency_estimator_; + HloCostAnalysis::ShapeSizeFunction shape_size_function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_ANALYTICAL_LATENCY_ESTIMATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/autotuner_compile_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/autotuner_compile_util.h new file mode 100644 index 0000000000000000000000000000000000000000..b5f5a763f4ed8be7ea8922024c021fe7565171a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/autotuner_compile_util.h @@ -0,0 +1,115 @@ +/* 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_SERVICE_GPU_AUTOTUNER_COMPILE_UTIL_H_ +#define XLA_SERVICE_GPU_AUTOTUNER_COMPILE_UTIL_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_clone_context.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/compiler.h" +#include "xla/service/executable.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream.h" +#include "xla/util.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Autotuning utils which require compiling fusions separately. Requires a +// separate target, as runtime autotuning cannot perform compilation. +class AutotunerCompileUtil { + public: + // The GenerateModuleFn must generate/extract a module using the provided + // debug options. Typically it should set the debug options of the extracted + // module before it would transform it, to ensure that the transforms can use + // the debug options. In justified cases, it may override some of the provided + // debug options. + using GenerateModuleFn = + absl::AnyInvocable>( + const DebugOptions&)>; + + // Generates a compile util for a platform associated with the `stream`. + // + // Returns an empty optional if the AutotuneConfig is deviceless, as + // autotuning is impossible in that case. + static StatusOr> Create( + const AutotuneConfig& config, const DebugOptions& opts); + + struct ProfilingOutput { + ProfilingOutput(absl::Duration duration, ScopedShapedBuffer&& buffer) + : duration(duration), output(std::move(buffer)) {} + + absl::Duration duration; + ScopedShapedBuffer output; + }; + + // Generates an executable first, given the module generator function in + // `extractor`. + // + // Runs the resulting executable with the given extractor, cached with + // `(cache_key, config)`. Returns `std::nullopt` on expected failure, bad + // `Status` otherwise. + StatusOr> ProfileExecutable( + Executable* executable, se::Stream* stream, + absl::Span input_buffers, + absl::Span input_shapes); + + // Generic method to compile a generated module from `extractor` in isolation. + // + // Returns: + // - `nullptr` on *expected* failure + // - `Executable` if everything goes fine. + // - `Status` on *unexpected* failure. + StatusOr> Compile(GenerateModuleFn extractor); + + // Generic method to extract an HLO using the debug options of the + // AutotunerCompileUtil. + // + // Typically we can use Compile directly. + StatusOr> ExtractModule( + GenerateModuleFn extractor); + + private: + AutotunerCompileUtil(const AutotuneConfig& config, Compiler* compiler, + se::StreamExecutor& stream_executor, se::Stream& stream, + se::DeviceMemoryAllocator& allocator, + const DebugOptions& opts); + + StatusOr Execute(Executable& executable, + std::vector arguments); + + AutotuneConfig config_; + Compiler* compiler_; + se::StreamExecutor& stream_executor_; + se::Stream& stream_; + se::DeviceMemoryAllocator& allocator_; + DebugOptions opts_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_AUTOTUNER_COMPILE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/autotuner_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/autotuner_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d25f881274389d7f42d0ed0d58c6fcfb072e39c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/autotuner_util.h @@ -0,0 +1,269 @@ +/* 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_SERVICE_GPU_AUTOTUNER_UTIL_H_ +#define XLA_SERVICE_GPU_AUTOTUNER_UTIL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "xla/autotune_results.pb.h" +#include "xla/autotuning.pb.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/stream_executor/gpu/redzone_allocator.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +struct DeviceConfig { + se::StreamExecutor* stream_exec; // never null + + // If the `allocator` parameter is not null, we will use it to allocate temp + // memory while timing the various convolution algorithms. If it's null, + // we'll use the default allocator on the StreamExecutor. + se::DeviceMemoryAllocator* allocator = nullptr; // may be null +}; + +struct DevicelessConfig { + // The human-readable description of the device. It can be found by using + // stream_exec->GetDeviceDescription().model_str() when the stream executor + // is available. + std::string model_str; + + // A field to determine the architecture of the device. We only pick an + // algorithm for non-Ampere architectures. + se::CudaComputeCapability cuda_compute_capability{0, 0}; +}; + +class AutotuneCacheKey { + public: + AutotuneCacheKey(absl::string_view model_str, + const HloInstruction& instruction); + + explicit AutotuneCacheKey(absl::string_view model_str, + absl::string_view hlo_canonical) + : model_str_(model_str), hlo_canonical_(hlo_canonical) {} + + absl::string_view GetModelStr() const { return model_str_; } + + absl::string_view GetHlo() const { return hlo_canonical_; } + + template + friend H AbslHashValue(H h, const AutotuneCacheKey& w) { + return H::combine(std::move(h), w.model_str_, w.hlo_canonical_); + } + + bool operator==(const AutotuneCacheKey& w) const { + return model_str_ == w.model_str_ && hlo_canonical_ == w.hlo_canonical_; + } + + std::string ToString() const { + return absl::StrFormat("", model_str_, + hlo_canonical_); + } + + private: + std::string model_str_; + std::string hlo_canonical_; +}; + +class AutotuneConfig { + public: + bool should_init_buffers() const { return autotune_level_ >= 2; } + bool should_reinit_output_buffer() const { return autotune_level_ >= 3; } + bool should_check_correctness() const { return autotune_level_ >= 4; } + bool should_crash_on_check_failure() const { + return should_crash_on_check_failure_; + } + + AutotuneConfig(const std::variant& config, + const DebugOptions& debug_options) + : config_(config), + autotune_level_(debug_options.xla_gpu_autotune_level()), + should_crash_on_check_failure_( + debug_options.xla_gpu_crash_on_verification_failures()), + exhaustive_tiling_search_( + debug_options.xla_gpu_exhaustive_tiling_search()) {} + + absl::string_view GetModelStr() const { + if (auto deviceless_config = std::get_if(&config_)) { + return deviceless_config->model_str; + } + + const auto& device_config = std::get(config_); + return device_config.stream_exec->GetDeviceDescription().model_str(); + } + + se::StreamExecutor* GetExecutor() const { + CHECK(std::holds_alternative(config_)); + return std::get(config_).stream_exec; + } + + se::DeviceMemoryAllocator* GetAllocator() const { + CHECK(std::holds_alternative(config_)); + auto& cf = std::get(config_); + return cf.allocator ? cf.allocator : GetExecutor()->GetAllocator(); + } + + StatusOr GetStream() const { + CHECK(std::holds_alternative(config_)); + return GetAllocator()->GetStream(GetExecutor()->device_ordinal()); + } + + se::CudaComputeCapability GetCudaComputeCapability() const { + if (auto c = std::get_if(&config_)) { + return c->stream_exec->GetDeviceDescription().cuda_compute_capability(); + } + return std::get(config_).cuda_compute_capability; + } + + bool IsDeviceless() const { + return std::holds_alternative(config_); + } + + bool ExhaustiveTilingSearch() const { return exhaustive_tiling_search_; } + + private: + std::variant config_; + int32_t autotune_level_; + bool should_crash_on_check_failure_; + bool exhaustive_tiling_search_; +}; + +using AutotuneNoCacheFn = std::function()>; + +struct AutotunerUtil { + // Create a buffer for a given operation using redzone checker, initialize + // based on a given rng state. + static StatusOr CreateBuffer( + se::RedzoneAllocator& allocator, const Shape& shape, + const AutotuneConfig& config, int64_t& rng_state); + + static StatusOr Autotune( + const HloInstruction* instr, const AutotuneConfig& config, + const AutotuneNoCacheFn& autotune_fn); + + // Returns the same cache key that would be used inside Autotune(). + // + // Normally, we don't have to use this low level method. + static AutotuneCacheKey GetKey(const HloInstruction* instr, + const AutotuneConfig& config); + + // Checks if the key is in the autotune cache. + // + // Normally, we don't have to use this low level method. + static bool IsInCache(const AutotuneCacheKey& key); + + // Adds the result to the autotune cache. + // + // Returns true if the entry is inserted. + // + // Normally, we don't have to use this low level method. + static bool AddResult(const AutotuneCacheKey& key, AutotuneResult result); + + // Creates a RedzoneAllocator from a given config. If `force_stream` is + // provided, than it is used for checking redzones. + static StatusOr CreateRedzoneAllocator( + const AutotuneConfig& config, const DebugOptions& opts, + se::Stream* force_stream = nullptr); + + // Functions to save/load XLA's autotuning results. + // + // This is used for ahead-of-time autotuning. Specifically: + // + // When XLA calls cublas (for matmuls, aka "gemm" or "dot") or cudnn (for + // convolutions), it usually has to choose an "algorithm" for the particular + // dot/conv. XLA queries cublas/cudnn for a list of candidate algorithms. + // Then it runs all of them and picks the fastest one. This is what we call + // "autotuning". It happens in GemmAlgorithmPicker and GpuConvAlgorithmPicker. + // + // Autotuning is necessary to get good performance for dot/conv. But it also + // has some disadvantages. + // + // - Because it relies on timing data, it is fundamentally nondeterministic. + // But even if two algorithms have similar runtimes, our choice of + // algorithm may be visible to the user: Different algorithms can have + // different numerics, and sometimes they can even have different bugs! + // + // - Trying all the candidate algorithms can be slow, especially if when some + // of the candidates are "very bad" and run especially slowly compared to + // the optimal candidate. This slows down compilation. + // + // To address the disadvantages above, we allow users to save/restore the + // autotuning choices that XLA has made, using the functions below. + // + // Loading autotuning results does not erase existing autotuning choices, but + // in the event of a disagreement between the existing data and the new data, + // the new algorithm is chosen. + // + // Note that even if you call LoadAutotuneResults(), if XLA encounters a + // dot/conv that is *not* covered by the loaded data, it will go ahead and + // autotune it like normal. In other words, the behavior of XLA should be + // identical with or without ahead-of-time autotuning, modulo nondeterminism. + // + // This is important if you want to be able to use the same autotuning file + // with different versions of XLA, because as XLA changes, exactly which + // dots/convs it wants to run can also change. For example, XLA might change + // the conv padding heuristics it uses, and we don't want that to mean that + // all users of ahead-of-time autotuning are broken. + static StatusOr SerializeAutotuneResults( + bool as_textproto = false); + + static Status SerializeAutotuneResults(AutotuneResults* results); + static Status LoadAutotuneResults(absl::string_view data, + bool as_textproto = false); + + static Status LoadAutotuneResults(const AutotuneResults& results); + + // Serializes autotune results into a file. + // + // If `file_path` ends with ".txt" or ".textproto", then the textproto format + // is used, otherwise the binary protobuf format. + static Status SerializeAutotuneResultsToFile(absl::string_view file_path); + + // Loads autotune results from a file. + // + // If `file_path` ends with ".txt" or ".textproto", then the file is + // considered to be in the textproto format, otherwise the binary protobuf + // format. + static Status LoadAutotuneResultsFromFile(absl::string_view file_path); + + static void ClearAutotuneResults(); + + // Extracts an HLO instruction into a new HLO module replacing its operands + // with parameter instructions. + static std::unique_ptr ExtractInstructionIntoNewModule( + const HloInstruction& hlo); + + // Extracts an HLO computation into a new HLO module, using its clone as the + // root computation. + static std::unique_ptr ExtractComputationIntoNewModule( + const HloComputation& computation); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_AUTOTUNER_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/backend_configs.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/backend_configs.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..21ce398467438f815d2dbcf66cdb1e121238e92d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/backend_configs.pb.h @@ -0,0 +1,3485 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/backend_configs.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fbackend_5fconfigs_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 "xla/autotuning.pb.h" +#include "xla/xla_data.pb.h" +#include "tsl/protobuf/dnn.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +namespace xla { +namespace gpu { +class BitcastBackendConfig; +struct BitcastBackendConfigDefaultTypeInternal; +extern BitcastBackendConfigDefaultTypeInternal _BitcastBackendConfig_default_instance_; +class CollectiveBackendConfig; +struct CollectiveBackendConfigDefaultTypeInternal; +extern CollectiveBackendConfigDefaultTypeInternal _CollectiveBackendConfig_default_instance_; +class CudnnConvBackendConfig; +struct CudnnConvBackendConfigDefaultTypeInternal; +extern CudnnConvBackendConfigDefaultTypeInternal _CudnnConvBackendConfig_default_instance_; +class CudnnfMHABackendConfig; +struct CudnnfMHABackendConfigDefaultTypeInternal; +extern CudnnfMHABackendConfigDefaultTypeInternal _CudnnfMHABackendConfig_default_instance_; +class FusionBackendConfig; +struct FusionBackendConfigDefaultTypeInternal; +extern FusionBackendConfigDefaultTypeInternal _FusionBackendConfig_default_instance_; +class GemmBackendConfig; +struct GemmBackendConfigDefaultTypeInternal; +extern GemmBackendConfigDefaultTypeInternal _GemmBackendConfig_default_instance_; +class ReificationCost; +struct ReificationCostDefaultTypeInternal; +extern ReificationCostDefaultTypeInternal _ReificationCost_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::BitcastBackendConfig* Arena::CreateMaybeMessage<::xla::gpu::BitcastBackendConfig>(Arena*); +template<> ::xla::gpu::CollectiveBackendConfig* Arena::CreateMaybeMessage<::xla::gpu::CollectiveBackendConfig>(Arena*); +template<> ::xla::gpu::CudnnConvBackendConfig* Arena::CreateMaybeMessage<::xla::gpu::CudnnConvBackendConfig>(Arena*); +template<> ::xla::gpu::CudnnfMHABackendConfig* Arena::CreateMaybeMessage<::xla::gpu::CudnnfMHABackendConfig>(Arena*); +template<> ::xla::gpu::FusionBackendConfig* Arena::CreateMaybeMessage<::xla::gpu::FusionBackendConfig>(Arena*); +template<> ::xla::gpu::GemmBackendConfig* Arena::CreateMaybeMessage<::xla::gpu::GemmBackendConfig>(Arena*); +template<> ::xla::gpu::ReificationCost* Arena::CreateMaybeMessage<::xla::gpu::ReificationCost>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +enum GemmBackendConfig_Epilogue : int { + GemmBackendConfig_Epilogue_DEFAULT = 0, + GemmBackendConfig_Epilogue_BIAS = 1, + GemmBackendConfig_Epilogue_RELU = 2, + GemmBackendConfig_Epilogue_BIAS_RELU = 3, + GemmBackendConfig_Epilogue_GELU = 4, + GemmBackendConfig_Epilogue_GELU_AUX = 5, + GemmBackendConfig_Epilogue_BIAS_GELU = 6, + GemmBackendConfig_Epilogue_BIAS_GELU_AUX = 7, + GemmBackendConfig_Epilogue_GemmBackendConfig_Epilogue_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + GemmBackendConfig_Epilogue_GemmBackendConfig_Epilogue_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool GemmBackendConfig_Epilogue_IsValid(int value); +constexpr GemmBackendConfig_Epilogue GemmBackendConfig_Epilogue_Epilogue_MIN = GemmBackendConfig_Epilogue_DEFAULT; +constexpr GemmBackendConfig_Epilogue GemmBackendConfig_Epilogue_Epilogue_MAX = GemmBackendConfig_Epilogue_BIAS_GELU_AUX; +constexpr int GemmBackendConfig_Epilogue_Epilogue_ARRAYSIZE = GemmBackendConfig_Epilogue_Epilogue_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* GemmBackendConfig_Epilogue_descriptor(); +template +inline const std::string& GemmBackendConfig_Epilogue_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function GemmBackendConfig_Epilogue_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + GemmBackendConfig_Epilogue_descriptor(), enum_t_value); +} +inline bool GemmBackendConfig_Epilogue_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, GemmBackendConfig_Epilogue* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + GemmBackendConfig_Epilogue_descriptor(), name, value); +} +// =================================================================== + +class CudnnConvBackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.CudnnConvBackendConfig) */ { + public: + inline CudnnConvBackendConfig() : CudnnConvBackendConfig(nullptr) {} + ~CudnnConvBackendConfig() override; + explicit PROTOBUF_CONSTEXPR CudnnConvBackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CudnnConvBackendConfig(const CudnnConvBackendConfig& from); + CudnnConvBackendConfig(CudnnConvBackendConfig&& from) noexcept + : CudnnConvBackendConfig() { + *this = ::std::move(from); + } + + inline CudnnConvBackendConfig& operator=(const CudnnConvBackendConfig& from) { + CopyFrom(from); + return *this; + } + inline CudnnConvBackendConfig& operator=(CudnnConvBackendConfig&& 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 CudnnConvBackendConfig& default_instance() { + return *internal_default_instance(); + } + enum FilterAndBiasReorderingOneofCase { + kReorderedInt8NchwVect = 7, + FILTER_AND_BIAS_REORDERING_ONEOF_NOT_SET = 0, + }; + + static inline const CudnnConvBackendConfig* internal_default_instance() { + return reinterpret_cast( + &_CudnnConvBackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CudnnConvBackendConfig& a, CudnnConvBackendConfig& b) { + a.Swap(&b); + } + inline void Swap(CudnnConvBackendConfig* 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(CudnnConvBackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CudnnConvBackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CudnnConvBackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CudnnConvBackendConfig& from) { + CudnnConvBackendConfig::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(CudnnConvBackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.CudnnConvBackendConfig"; + } + protected: + explicit CudnnConvBackendConfig(::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 { + kSerializedGraphFieldNumber = 9, + kAlgorithmFieldNumber = 6, + kConvResultScaleFieldNumber = 4, + kSideInputScaleFieldNumber = 5, + kLeakyreluAlphaFieldNumber = 8, + kActivationModeFieldNumber = 3, + kReorderedInt8NchwVectFieldNumber = 7, + }; + // optional string serialized_graph = 9; + bool has_serialized_graph() const; + private: + bool _internal_has_serialized_graph() const; + public: + void clear_serialized_graph(); + const std::string& serialized_graph() const; + template + void set_serialized_graph(ArgT0&& arg0, ArgT... args); + std::string* mutable_serialized_graph(); + PROTOBUF_NODISCARD std::string* release_serialized_graph(); + void set_allocated_serialized_graph(std::string* serialized_graph); + private: + const std::string& _internal_serialized_graph() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_serialized_graph(const std::string& value); + std::string* _internal_mutable_serialized_graph(); + public: + + // .stream_executor.dnn.AlgorithmProto algorithm = 6; + 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(); + + // double conv_result_scale = 4; + void clear_conv_result_scale(); + double conv_result_scale() const; + void set_conv_result_scale(double value); + private: + double _internal_conv_result_scale() const; + void _internal_set_conv_result_scale(double value); + public: + + // double side_input_scale = 5; + void clear_side_input_scale(); + double side_input_scale() const; + void set_side_input_scale(double value); + private: + double _internal_side_input_scale() const; + void _internal_set_side_input_scale(double value); + public: + + // double leakyrelu_alpha = 8; + void clear_leakyrelu_alpha(); + double leakyrelu_alpha() const; + void set_leakyrelu_alpha(double value); + private: + double _internal_leakyrelu_alpha() const; + void _internal_set_leakyrelu_alpha(double value); + public: + + // .stream_executor.dnn.ActivationMode activation_mode = 3; + void clear_activation_mode(); + ::stream_executor::dnn::ActivationMode activation_mode() const; + void set_activation_mode(::stream_executor::dnn::ActivationMode value); + private: + ::stream_executor::dnn::ActivationMode _internal_activation_mode() const; + void _internal_set_activation_mode(::stream_executor::dnn::ActivationMode value); + public: + + // bool reordered_int8_nchw_vect = 7; + bool has_reordered_int8_nchw_vect() const; + private: + bool _internal_has_reordered_int8_nchw_vect() const; + public: + void clear_reordered_int8_nchw_vect(); + bool reordered_int8_nchw_vect() const; + void set_reordered_int8_nchw_vect(bool value); + private: + bool _internal_reordered_int8_nchw_vect() const; + void _internal_set_reordered_int8_nchw_vect(bool value); + public: + + void clear_filter_and_bias_reordering_oneof(); + FilterAndBiasReorderingOneofCase filter_and_bias_reordering_oneof_case() const; + // @@protoc_insertion_point(class_scope:xla.gpu.CudnnConvBackendConfig) + private: + class _Internal; + void set_has_reordered_int8_nchw_vect(); + + inline bool has_filter_and_bias_reordering_oneof() const; + inline void clear_has_filter_and_bias_reordering_oneof(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr serialized_graph_; + ::stream_executor::dnn::AlgorithmProto* algorithm_; + double conv_result_scale_; + double side_input_scale_; + double leakyrelu_alpha_; + int activation_mode_; + union FilterAndBiasReorderingOneofUnion { + constexpr FilterAndBiasReorderingOneofUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool reordered_int8_nchw_vect_; + } filter_and_bias_reordering_oneof_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// ------------------------------------------------------------------- + +class GemmBackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.GemmBackendConfig) */ { + public: + inline GemmBackendConfig() : GemmBackendConfig(nullptr) {} + ~GemmBackendConfig() override; + explicit PROTOBUF_CONSTEXPR GemmBackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + GemmBackendConfig(const GemmBackendConfig& from); + GemmBackendConfig(GemmBackendConfig&& from) noexcept + : GemmBackendConfig() { + *this = ::std::move(from); + } + + inline GemmBackendConfig& operator=(const GemmBackendConfig& from) { + CopyFrom(from); + return *this; + } + inline GemmBackendConfig& operator=(GemmBackendConfig&& 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 GemmBackendConfig& default_instance() { + return *internal_default_instance(); + } + enum AlgorithmCase { + kSelectedAlgorithm = 1, + ALGORITHM_NOT_SET = 0, + }; + + static inline const GemmBackendConfig* internal_default_instance() { + return reinterpret_cast( + &_GemmBackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(GemmBackendConfig& a, GemmBackendConfig& b) { + a.Swap(&b); + } + inline void Swap(GemmBackendConfig* 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(GemmBackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + GemmBackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const GemmBackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const GemmBackendConfig& from) { + GemmBackendConfig::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(GemmBackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.GemmBackendConfig"; + } + protected: + explicit GemmBackendConfig(::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 GemmBackendConfig_Epilogue Epilogue; + static constexpr Epilogue DEFAULT = + GemmBackendConfig_Epilogue_DEFAULT; + static constexpr Epilogue BIAS = + GemmBackendConfig_Epilogue_BIAS; + static constexpr Epilogue RELU = + GemmBackendConfig_Epilogue_RELU; + static constexpr Epilogue BIAS_RELU = + GemmBackendConfig_Epilogue_BIAS_RELU; + static constexpr Epilogue GELU = + GemmBackendConfig_Epilogue_GELU; + static constexpr Epilogue GELU_AUX = + GemmBackendConfig_Epilogue_GELU_AUX; + static constexpr Epilogue BIAS_GELU = + GemmBackendConfig_Epilogue_BIAS_GELU; + static constexpr Epilogue BIAS_GELU_AUX = + GemmBackendConfig_Epilogue_BIAS_GELU_AUX; + static inline bool Epilogue_IsValid(int value) { + return GemmBackendConfig_Epilogue_IsValid(value); + } + static constexpr Epilogue Epilogue_MIN = + GemmBackendConfig_Epilogue_Epilogue_MIN; + static constexpr Epilogue Epilogue_MAX = + GemmBackendConfig_Epilogue_Epilogue_MAX; + static constexpr int Epilogue_ARRAYSIZE = + GemmBackendConfig_Epilogue_Epilogue_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + Epilogue_descriptor() { + return GemmBackendConfig_Epilogue_descriptor(); + } + template + static inline const std::string& Epilogue_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Epilogue_Name."); + return GemmBackendConfig_Epilogue_Name(enum_t_value); + } + static inline bool Epilogue_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + Epilogue* value) { + return GemmBackendConfig_Epilogue_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kDotDimensionNumbersFieldNumber = 7, + kPrecisionConfigFieldNumber = 12, + kAlphaRealFieldNumber = 2, + kBetaFieldNumber = 3, + kAlphaImagFieldNumber = 9, + kEpilogueFieldNumber = 13, + kSelectedAlgorithmFieldNumber = 1, + }; + // .xla.DotDimensionNumbers dot_dimension_numbers = 7; + bool has_dot_dimension_numbers() const; + private: + bool _internal_has_dot_dimension_numbers() const; + public: + void clear_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_dot_dimension_numbers(); + void set_allocated_dot_dimension_numbers(::xla::DotDimensionNumbers* dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_dot_dimension_numbers( + ::xla::DotDimensionNumbers* dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_dot_dimension_numbers(); + + // .xla.PrecisionConfig precision_config = 12; + bool has_precision_config() const; + private: + bool _internal_has_precision_config() const; + public: + void clear_precision_config(); + const ::xla::PrecisionConfig& precision_config() const; + PROTOBUF_NODISCARD ::xla::PrecisionConfig* release_precision_config(); + ::xla::PrecisionConfig* mutable_precision_config(); + void set_allocated_precision_config(::xla::PrecisionConfig* precision_config); + private: + const ::xla::PrecisionConfig& _internal_precision_config() const; + ::xla::PrecisionConfig* _internal_mutable_precision_config(); + public: + void unsafe_arena_set_allocated_precision_config( + ::xla::PrecisionConfig* precision_config); + ::xla::PrecisionConfig* unsafe_arena_release_precision_config(); + + // double alpha_real = 2; + void clear_alpha_real(); + double alpha_real() const; + void set_alpha_real(double value); + private: + double _internal_alpha_real() const; + void _internal_set_alpha_real(double value); + public: + + // double beta = 3; + void clear_beta(); + double beta() const; + void set_beta(double value); + private: + double _internal_beta() const; + void _internal_set_beta(double value); + public: + + // double alpha_imag = 9; + void clear_alpha_imag(); + double alpha_imag() const; + void set_alpha_imag(double value); + private: + double _internal_alpha_imag() const; + void _internal_set_alpha_imag(double value); + public: + + // .xla.gpu.GemmBackendConfig.Epilogue epilogue = 13; + void clear_epilogue(); + ::xla::gpu::GemmBackendConfig_Epilogue epilogue() const; + void set_epilogue(::xla::gpu::GemmBackendConfig_Epilogue value); + private: + ::xla::gpu::GemmBackendConfig_Epilogue _internal_epilogue() const; + void _internal_set_epilogue(::xla::gpu::GemmBackendConfig_Epilogue value); + public: + + // int64 selected_algorithm = 1; + bool has_selected_algorithm() const; + private: + bool _internal_has_selected_algorithm() const; + public: + void clear_selected_algorithm(); + int64_t selected_algorithm() const; + void set_selected_algorithm(int64_t value); + private: + int64_t _internal_selected_algorithm() const; + void _internal_set_selected_algorithm(int64_t value); + public: + + void clear_algorithm(); + AlgorithmCase algorithm_case() const; + // @@protoc_insertion_point(class_scope:xla.gpu.GemmBackendConfig) + private: + class _Internal; + void set_has_selected_algorithm(); + + inline bool has_algorithm() const; + inline void clear_has_algorithm(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::DotDimensionNumbers* dot_dimension_numbers_; + ::xla::PrecisionConfig* precision_config_; + double alpha_real_; + double beta_; + double alpha_imag_; + int epilogue_; + union AlgorithmUnion { + constexpr AlgorithmUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int64_t selected_algorithm_; + } algorithm_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// ------------------------------------------------------------------- + +class BitcastBackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.BitcastBackendConfig) */ { + public: + inline BitcastBackendConfig() : BitcastBackendConfig(nullptr) {} + ~BitcastBackendConfig() override; + explicit PROTOBUF_CONSTEXPR BitcastBackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BitcastBackendConfig(const BitcastBackendConfig& from); + BitcastBackendConfig(BitcastBackendConfig&& from) noexcept + : BitcastBackendConfig() { + *this = ::std::move(from); + } + + inline BitcastBackendConfig& operator=(const BitcastBackendConfig& from) { + CopyFrom(from); + return *this; + } + inline BitcastBackendConfig& operator=(BitcastBackendConfig&& 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 BitcastBackendConfig& default_instance() { + return *internal_default_instance(); + } + static inline const BitcastBackendConfig* internal_default_instance() { + return reinterpret_cast( + &_BitcastBackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(BitcastBackendConfig& a, BitcastBackendConfig& b) { + a.Swap(&b); + } + inline void Swap(BitcastBackendConfig* 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(BitcastBackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BitcastBackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BitcastBackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BitcastBackendConfig& from) { + BitcastBackendConfig::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(BitcastBackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.BitcastBackendConfig"; + } + protected: + explicit BitcastBackendConfig(::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 { + kSourceLayoutFieldNumber = 1, + kResultLayoutFieldNumber = 2, + }; + // .xla.LayoutProto source_layout = 1; + bool has_source_layout() const; + private: + bool _internal_has_source_layout() const; + public: + void clear_source_layout(); + const ::xla::LayoutProto& source_layout() const; + PROTOBUF_NODISCARD ::xla::LayoutProto* release_source_layout(); + ::xla::LayoutProto* mutable_source_layout(); + void set_allocated_source_layout(::xla::LayoutProto* source_layout); + private: + const ::xla::LayoutProto& _internal_source_layout() const; + ::xla::LayoutProto* _internal_mutable_source_layout(); + public: + void unsafe_arena_set_allocated_source_layout( + ::xla::LayoutProto* source_layout); + ::xla::LayoutProto* unsafe_arena_release_source_layout(); + + // .xla.LayoutProto result_layout = 2; + bool has_result_layout() const; + private: + bool _internal_has_result_layout() const; + public: + void clear_result_layout(); + const ::xla::LayoutProto& result_layout() const; + PROTOBUF_NODISCARD ::xla::LayoutProto* release_result_layout(); + ::xla::LayoutProto* mutable_result_layout(); + void set_allocated_result_layout(::xla::LayoutProto* result_layout); + private: + const ::xla::LayoutProto& _internal_result_layout() const; + ::xla::LayoutProto* _internal_mutable_result_layout(); + public: + void unsafe_arena_set_allocated_result_layout( + ::xla::LayoutProto* result_layout); + ::xla::LayoutProto* unsafe_arena_release_result_layout(); + + // @@protoc_insertion_point(class_scope:xla.gpu.BitcastBackendConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::LayoutProto* source_layout_; + ::xla::LayoutProto* result_layout_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// ------------------------------------------------------------------- + +class CollectiveBackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.CollectiveBackendConfig) */ { + public: + inline CollectiveBackendConfig() : CollectiveBackendConfig(nullptr) {} + ~CollectiveBackendConfig() override; + explicit PROTOBUF_CONSTEXPR CollectiveBackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CollectiveBackendConfig(const CollectiveBackendConfig& from); + CollectiveBackendConfig(CollectiveBackendConfig&& from) noexcept + : CollectiveBackendConfig() { + *this = ::std::move(from); + } + + inline CollectiveBackendConfig& operator=(const CollectiveBackendConfig& from) { + CopyFrom(from); + return *this; + } + inline CollectiveBackendConfig& operator=(CollectiveBackendConfig&& 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 CollectiveBackendConfig& default_instance() { + return *internal_default_instance(); + } + static inline const CollectiveBackendConfig* internal_default_instance() { + return reinterpret_cast( + &_CollectiveBackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(CollectiveBackendConfig& a, CollectiveBackendConfig& b) { + a.Swap(&b); + } + inline void Swap(CollectiveBackendConfig* 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(CollectiveBackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CollectiveBackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CollectiveBackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CollectiveBackendConfig& from) { + CollectiveBackendConfig::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(CollectiveBackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.CollectiveBackendConfig"; + } + protected: + explicit CollectiveBackendConfig(::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 { + kIsSyncFieldNumber = 1, + }; + // bool is_sync = 1; + void clear_is_sync(); + bool is_sync() const; + void set_is_sync(bool value); + private: + bool _internal_is_sync() const; + void _internal_set_is_sync(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.CollectiveBackendConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + bool is_sync_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// ------------------------------------------------------------------- + +class ReificationCost final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.ReificationCost) */ { + public: + inline ReificationCost() : ReificationCost(nullptr) {} + ~ReificationCost() override; + explicit PROTOBUF_CONSTEXPR ReificationCost(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ReificationCost(const ReificationCost& from); + ReificationCost(ReificationCost&& from) noexcept + : ReificationCost() { + *this = ::std::move(from); + } + + inline ReificationCost& operator=(const ReificationCost& from) { + CopyFrom(from); + return *this; + } + inline ReificationCost& operator=(ReificationCost&& 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 ReificationCost& default_instance() { + return *internal_default_instance(); + } + static inline const ReificationCost* internal_default_instance() { + return reinterpret_cast( + &_ReificationCost_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(ReificationCost& a, ReificationCost& b) { + a.Swap(&b); + } + inline void Swap(ReificationCost* 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(ReificationCost* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ReificationCost* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ReificationCost& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ReificationCost& from) { + ReificationCost::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(ReificationCost* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.ReificationCost"; + } + protected: + explicit ReificationCost(::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 { + kEndToEndCyclesFieldNumber = 1, + }; + // double end_to_end_cycles = 1; + void clear_end_to_end_cycles(); + double end_to_end_cycles() const; + void set_end_to_end_cycles(double value); + private: + double _internal_end_to_end_cycles() const; + void _internal_set_end_to_end_cycles(double value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.ReificationCost) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + double end_to_end_cycles_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// ------------------------------------------------------------------- + +class FusionBackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.FusionBackendConfig) */ { + public: + inline FusionBackendConfig() : FusionBackendConfig(nullptr) {} + ~FusionBackendConfig() override; + explicit PROTOBUF_CONSTEXPR FusionBackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FusionBackendConfig(const FusionBackendConfig& from); + FusionBackendConfig(FusionBackendConfig&& from) noexcept + : FusionBackendConfig() { + *this = ::std::move(from); + } + + inline FusionBackendConfig& operator=(const FusionBackendConfig& from) { + CopyFrom(from); + return *this; + } + inline FusionBackendConfig& operator=(FusionBackendConfig&& 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 FusionBackendConfig& default_instance() { + return *internal_default_instance(); + } + static inline const FusionBackendConfig* internal_default_instance() { + return reinterpret_cast( + &_FusionBackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 5; + + friend void swap(FusionBackendConfig& a, FusionBackendConfig& b) { + a.Swap(&b); + } + inline void Swap(FusionBackendConfig* 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(FusionBackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FusionBackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FusionBackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FusionBackendConfig& from) { + FusionBackendConfig::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(FusionBackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.FusionBackendConfig"; + } + protected: + explicit FusionBackendConfig(::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 { + kKindFieldNumber = 1, + kTritonGemmConfigFieldNumber = 2, + kReificationCostFieldNumber = 3, + }; + // string kind = 1; + void clear_kind(); + const std::string& kind() const; + template + void set_kind(ArgT0&& arg0, ArgT... args); + std::string* mutable_kind(); + PROTOBUF_NODISCARD std::string* release_kind(); + void set_allocated_kind(std::string* kind); + private: + const std::string& _internal_kind() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_kind(const std::string& value); + std::string* _internal_mutable_kind(); + public: + + // .xla.AutotuneResult.TritonGemmKey triton_gemm_config = 2; + bool has_triton_gemm_config() const; + private: + bool _internal_has_triton_gemm_config() const; + public: + void clear_triton_gemm_config(); + const ::xla::AutotuneResult_TritonGemmKey& triton_gemm_config() const; + PROTOBUF_NODISCARD ::xla::AutotuneResult_TritonGemmKey* release_triton_gemm_config(); + ::xla::AutotuneResult_TritonGemmKey* mutable_triton_gemm_config(); + void set_allocated_triton_gemm_config(::xla::AutotuneResult_TritonGemmKey* triton_gemm_config); + private: + const ::xla::AutotuneResult_TritonGemmKey& _internal_triton_gemm_config() const; + ::xla::AutotuneResult_TritonGemmKey* _internal_mutable_triton_gemm_config(); + public: + void unsafe_arena_set_allocated_triton_gemm_config( + ::xla::AutotuneResult_TritonGemmKey* triton_gemm_config); + ::xla::AutotuneResult_TritonGemmKey* unsafe_arena_release_triton_gemm_config(); + + // .xla.gpu.ReificationCost reification_cost = 3; + bool has_reification_cost() const; + private: + bool _internal_has_reification_cost() const; + public: + void clear_reification_cost(); + const ::xla::gpu::ReificationCost& reification_cost() const; + PROTOBUF_NODISCARD ::xla::gpu::ReificationCost* release_reification_cost(); + ::xla::gpu::ReificationCost* mutable_reification_cost(); + void set_allocated_reification_cost(::xla::gpu::ReificationCost* reification_cost); + private: + const ::xla::gpu::ReificationCost& _internal_reification_cost() const; + ::xla::gpu::ReificationCost* _internal_mutable_reification_cost(); + public: + void unsafe_arena_set_allocated_reification_cost( + ::xla::gpu::ReificationCost* reification_cost); + ::xla::gpu::ReificationCost* unsafe_arena_release_reification_cost(); + + // @@protoc_insertion_point(class_scope:xla.gpu.FusionBackendConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr kind_; + ::xla::AutotuneResult_TritonGemmKey* triton_gemm_config_; + ::xla::gpu::ReificationCost* reification_cost_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// ------------------------------------------------------------------- + +class CudnnfMHABackendConfig final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.CudnnfMHABackendConfig) */ { + public: + inline CudnnfMHABackendConfig() : CudnnfMHABackendConfig(nullptr) {} + ~CudnnfMHABackendConfig() override; + explicit PROTOBUF_CONSTEXPR CudnnfMHABackendConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CudnnfMHABackendConfig(const CudnnfMHABackendConfig& from); + CudnnfMHABackendConfig(CudnnfMHABackendConfig&& from) noexcept + : CudnnfMHABackendConfig() { + *this = ::std::move(from); + } + + inline CudnnfMHABackendConfig& operator=(const CudnnfMHABackendConfig& from) { + CopyFrom(from); + return *this; + } + inline CudnnfMHABackendConfig& operator=(CudnnfMHABackendConfig&& 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 CudnnfMHABackendConfig& default_instance() { + return *internal_default_instance(); + } + static inline const CudnnfMHABackendConfig* internal_default_instance() { + return reinterpret_cast( + &_CudnnfMHABackendConfig_default_instance_); + } + static constexpr int kIndexInFileMessages = + 6; + + friend void swap(CudnnfMHABackendConfig& a, CudnnfMHABackendConfig& b) { + a.Swap(&b); + } + inline void Swap(CudnnfMHABackendConfig* 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(CudnnfMHABackendConfig* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CudnnfMHABackendConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CudnnfMHABackendConfig& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CudnnfMHABackendConfig& from) { + CudnnfMHABackendConfig::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(CudnnfMHABackendConfig* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.CudnnfMHABackendConfig"; + } + protected: + explicit CudnnfMHABackendConfig(::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 = 8, + kBmm1DotDimensionNumbersFieldNumber = 11, + kBmm2DotDimensionNumbersFieldNumber = 12, + kIntermediateTensorShapeFieldNumber = 14, + kBmm1GradGemm1DotDimensionNumbersFieldNumber = 16, + kBmm1GradGemm2DotDimensionNumbersFieldNumber = 17, + kBmm2GradGemm1DotDimensionNumbersFieldNumber = 18, + kBmm2GradGemm2DotDimensionNumbersFieldNumber = 19, + kFmhaScaleFieldNumber = 10, + kDropoutRateFieldNumber = 13, + kSeedFieldNumber = 15, + }; + // .stream_executor.dnn.AlgorithmProto algorithm = 8; + 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(); + + // .xla.DotDimensionNumbers bmm1_dot_dimension_numbers = 11; + bool has_bmm1_dot_dimension_numbers() const; + private: + bool _internal_has_bmm1_dot_dimension_numbers() const; + public: + void clear_bmm1_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& bmm1_dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_bmm1_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_bmm1_dot_dimension_numbers(); + void set_allocated_bmm1_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm1_dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_bmm1_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_bmm1_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_bmm1_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm1_dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_bmm1_dot_dimension_numbers(); + + // .xla.DotDimensionNumbers bmm2_dot_dimension_numbers = 12; + bool has_bmm2_dot_dimension_numbers() const; + private: + bool _internal_has_bmm2_dot_dimension_numbers() const; + public: + void clear_bmm2_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& bmm2_dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_bmm2_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_bmm2_dot_dimension_numbers(); + void set_allocated_bmm2_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm2_dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_bmm2_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_bmm2_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_bmm2_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm2_dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_bmm2_dot_dimension_numbers(); + + // .xla.ShapeProto intermediate_tensor_shape = 14; + bool has_intermediate_tensor_shape() const; + private: + bool _internal_has_intermediate_tensor_shape() const; + public: + void clear_intermediate_tensor_shape(); + const ::xla::ShapeProto& intermediate_tensor_shape() const; + PROTOBUF_NODISCARD ::xla::ShapeProto* release_intermediate_tensor_shape(); + ::xla::ShapeProto* mutable_intermediate_tensor_shape(); + void set_allocated_intermediate_tensor_shape(::xla::ShapeProto* intermediate_tensor_shape); + private: + const ::xla::ShapeProto& _internal_intermediate_tensor_shape() const; + ::xla::ShapeProto* _internal_mutable_intermediate_tensor_shape(); + public: + void unsafe_arena_set_allocated_intermediate_tensor_shape( + ::xla::ShapeProto* intermediate_tensor_shape); + ::xla::ShapeProto* unsafe_arena_release_intermediate_tensor_shape(); + + // .xla.DotDimensionNumbers bmm1_grad_gemm1_dot_dimension_numbers = 16; + bool has_bmm1_grad_gemm1_dot_dimension_numbers() const; + private: + bool _internal_has_bmm1_grad_gemm1_dot_dimension_numbers() const; + public: + void clear_bmm1_grad_gemm1_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& bmm1_grad_gemm1_dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_bmm1_grad_gemm1_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_bmm1_grad_gemm1_dot_dimension_numbers(); + void set_allocated_bmm1_grad_gemm1_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm1_grad_gemm1_dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_bmm1_grad_gemm1_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_bmm1_grad_gemm1_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_bmm1_grad_gemm1_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm1_grad_gemm1_dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_bmm1_grad_gemm1_dot_dimension_numbers(); + + // .xla.DotDimensionNumbers bmm1_grad_gemm2_dot_dimension_numbers = 17; + bool has_bmm1_grad_gemm2_dot_dimension_numbers() const; + private: + bool _internal_has_bmm1_grad_gemm2_dot_dimension_numbers() const; + public: + void clear_bmm1_grad_gemm2_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& bmm1_grad_gemm2_dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_bmm1_grad_gemm2_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_bmm1_grad_gemm2_dot_dimension_numbers(); + void set_allocated_bmm1_grad_gemm2_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm1_grad_gemm2_dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_bmm1_grad_gemm2_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_bmm1_grad_gemm2_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_bmm1_grad_gemm2_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm1_grad_gemm2_dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_bmm1_grad_gemm2_dot_dimension_numbers(); + + // .xla.DotDimensionNumbers bmm2_grad_gemm1_dot_dimension_numbers = 18; + bool has_bmm2_grad_gemm1_dot_dimension_numbers() const; + private: + bool _internal_has_bmm2_grad_gemm1_dot_dimension_numbers() const; + public: + void clear_bmm2_grad_gemm1_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& bmm2_grad_gemm1_dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_bmm2_grad_gemm1_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_bmm2_grad_gemm1_dot_dimension_numbers(); + void set_allocated_bmm2_grad_gemm1_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm2_grad_gemm1_dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_bmm2_grad_gemm1_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_bmm2_grad_gemm1_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_bmm2_grad_gemm1_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm2_grad_gemm1_dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_bmm2_grad_gemm1_dot_dimension_numbers(); + + // .xla.DotDimensionNumbers bmm2_grad_gemm2_dot_dimension_numbers = 19; + bool has_bmm2_grad_gemm2_dot_dimension_numbers() const; + private: + bool _internal_has_bmm2_grad_gemm2_dot_dimension_numbers() const; + public: + void clear_bmm2_grad_gemm2_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& bmm2_grad_gemm2_dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_bmm2_grad_gemm2_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_bmm2_grad_gemm2_dot_dimension_numbers(); + void set_allocated_bmm2_grad_gemm2_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm2_grad_gemm2_dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_bmm2_grad_gemm2_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_bmm2_grad_gemm2_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_bmm2_grad_gemm2_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm2_grad_gemm2_dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_bmm2_grad_gemm2_dot_dimension_numbers(); + + // double fmha_scale = 10; + void clear_fmha_scale(); + double fmha_scale() const; + void set_fmha_scale(double value); + private: + double _internal_fmha_scale() const; + void _internal_set_fmha_scale(double value); + public: + + // double dropout_rate = 13; + void clear_dropout_rate(); + double dropout_rate() const; + void set_dropout_rate(double value); + private: + double _internal_dropout_rate() const; + void _internal_set_dropout_rate(double value); + public: + + // int64 seed = 15; + void clear_seed(); + int64_t seed() const; + void set_seed(int64_t value); + private: + int64_t _internal_seed() const; + void _internal_set_seed(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.CudnnfMHABackendConfig) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::stream_executor::dnn::AlgorithmProto* algorithm_; + ::xla::DotDimensionNumbers* bmm1_dot_dimension_numbers_; + ::xla::DotDimensionNumbers* bmm2_dot_dimension_numbers_; + ::xla::ShapeProto* intermediate_tensor_shape_; + ::xla::DotDimensionNumbers* bmm1_grad_gemm1_dot_dimension_numbers_; + ::xla::DotDimensionNumbers* bmm1_grad_gemm2_dot_dimension_numbers_; + ::xla::DotDimensionNumbers* bmm2_grad_gemm1_dot_dimension_numbers_; + ::xla::DotDimensionNumbers* bmm2_grad_gemm2_dot_dimension_numbers_; + double fmha_scale_; + double dropout_rate_; + int64_t seed_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CudnnConvBackendConfig + +// .stream_executor.dnn.AlgorithmProto algorithm = 6; +inline bool CudnnConvBackendConfig::_internal_has_algorithm() const { + return this != internal_default_instance() && _impl_.algorithm_ != nullptr; +} +inline bool CudnnConvBackendConfig::has_algorithm() const { + return _internal_has_algorithm(); +} +inline const ::stream_executor::dnn::AlgorithmProto& CudnnConvBackendConfig::_internal_algorithm() const { + const ::stream_executor::dnn::AlgorithmProto* p = _impl_.algorithm_; + return p != nullptr ? *p : reinterpret_cast( + ::stream_executor::dnn::_AlgorithmProto_default_instance_); +} +inline const ::stream_executor::dnn::AlgorithmProto& CudnnConvBackendConfig::algorithm() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.algorithm) + return _internal_algorithm(); +} +inline void CudnnConvBackendConfig::unsafe_arena_set_allocated_algorithm( + ::stream_executor::dnn::AlgorithmProto* algorithm) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.algorithm_); + } + _impl_.algorithm_ = algorithm; + if (algorithm) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnConvBackendConfig.algorithm) +} +inline ::stream_executor::dnn::AlgorithmProto* CudnnConvBackendConfig::release_algorithm() { + + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.algorithm_; + _impl_.algorithm_ = 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 ::stream_executor::dnn::AlgorithmProto* CudnnConvBackendConfig::unsafe_arena_release_algorithm() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnConvBackendConfig.algorithm) + + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.algorithm_; + _impl_.algorithm_ = nullptr; + return temp; +} +inline ::stream_executor::dnn::AlgorithmProto* CudnnConvBackendConfig::_internal_mutable_algorithm() { + + if (_impl_.algorithm_ == nullptr) { + auto* p = CreateMaybeMessage<::stream_executor::dnn::AlgorithmProto>(GetArenaForAllocation()); + _impl_.algorithm_ = p; + } + return _impl_.algorithm_; +} +inline ::stream_executor::dnn::AlgorithmProto* CudnnConvBackendConfig::mutable_algorithm() { + ::stream_executor::dnn::AlgorithmProto* _msg = _internal_mutable_algorithm(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnConvBackendConfig.algorithm) + return _msg; +} +inline void CudnnConvBackendConfig::set_allocated_algorithm(::stream_executor::dnn::AlgorithmProto* algorithm) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.algorithm_); + } + if (algorithm) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(algorithm)); + if (message_arena != submessage_arena) { + algorithm = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, algorithm, submessage_arena); + } + + } else { + + } + _impl_.algorithm_ = algorithm; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnConvBackendConfig.algorithm) +} + +// double conv_result_scale = 4; +inline void CudnnConvBackendConfig::clear_conv_result_scale() { + _impl_.conv_result_scale_ = 0; +} +inline double CudnnConvBackendConfig::_internal_conv_result_scale() const { + return _impl_.conv_result_scale_; +} +inline double CudnnConvBackendConfig::conv_result_scale() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.conv_result_scale) + return _internal_conv_result_scale(); +} +inline void CudnnConvBackendConfig::_internal_set_conv_result_scale(double value) { + + _impl_.conv_result_scale_ = value; +} +inline void CudnnConvBackendConfig::set_conv_result_scale(double value) { + _internal_set_conv_result_scale(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnConvBackendConfig.conv_result_scale) +} + +// .stream_executor.dnn.ActivationMode activation_mode = 3; +inline void CudnnConvBackendConfig::clear_activation_mode() { + _impl_.activation_mode_ = 0; +} +inline ::stream_executor::dnn::ActivationMode CudnnConvBackendConfig::_internal_activation_mode() const { + return static_cast< ::stream_executor::dnn::ActivationMode >(_impl_.activation_mode_); +} +inline ::stream_executor::dnn::ActivationMode CudnnConvBackendConfig::activation_mode() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.activation_mode) + return _internal_activation_mode(); +} +inline void CudnnConvBackendConfig::_internal_set_activation_mode(::stream_executor::dnn::ActivationMode value) { + + _impl_.activation_mode_ = value; +} +inline void CudnnConvBackendConfig::set_activation_mode(::stream_executor::dnn::ActivationMode value) { + _internal_set_activation_mode(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnConvBackendConfig.activation_mode) +} + +// double side_input_scale = 5; +inline void CudnnConvBackendConfig::clear_side_input_scale() { + _impl_.side_input_scale_ = 0; +} +inline double CudnnConvBackendConfig::_internal_side_input_scale() const { + return _impl_.side_input_scale_; +} +inline double CudnnConvBackendConfig::side_input_scale() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.side_input_scale) + return _internal_side_input_scale(); +} +inline void CudnnConvBackendConfig::_internal_set_side_input_scale(double value) { + + _impl_.side_input_scale_ = value; +} +inline void CudnnConvBackendConfig::set_side_input_scale(double value) { + _internal_set_side_input_scale(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnConvBackendConfig.side_input_scale) +} + +// double leakyrelu_alpha = 8; +inline void CudnnConvBackendConfig::clear_leakyrelu_alpha() { + _impl_.leakyrelu_alpha_ = 0; +} +inline double CudnnConvBackendConfig::_internal_leakyrelu_alpha() const { + return _impl_.leakyrelu_alpha_; +} +inline double CudnnConvBackendConfig::leakyrelu_alpha() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.leakyrelu_alpha) + return _internal_leakyrelu_alpha(); +} +inline void CudnnConvBackendConfig::_internal_set_leakyrelu_alpha(double value) { + + _impl_.leakyrelu_alpha_ = value; +} +inline void CudnnConvBackendConfig::set_leakyrelu_alpha(double value) { + _internal_set_leakyrelu_alpha(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnConvBackendConfig.leakyrelu_alpha) +} + +// bool reordered_int8_nchw_vect = 7; +inline bool CudnnConvBackendConfig::_internal_has_reordered_int8_nchw_vect() const { + return filter_and_bias_reordering_oneof_case() == kReorderedInt8NchwVect; +} +inline bool CudnnConvBackendConfig::has_reordered_int8_nchw_vect() const { + return _internal_has_reordered_int8_nchw_vect(); +} +inline void CudnnConvBackendConfig::set_has_reordered_int8_nchw_vect() { + _impl_._oneof_case_[0] = kReorderedInt8NchwVect; +} +inline void CudnnConvBackendConfig::clear_reordered_int8_nchw_vect() { + if (_internal_has_reordered_int8_nchw_vect()) { + _impl_.filter_and_bias_reordering_oneof_.reordered_int8_nchw_vect_ = false; + clear_has_filter_and_bias_reordering_oneof(); + } +} +inline bool CudnnConvBackendConfig::_internal_reordered_int8_nchw_vect() const { + if (_internal_has_reordered_int8_nchw_vect()) { + return _impl_.filter_and_bias_reordering_oneof_.reordered_int8_nchw_vect_; + } + return false; +} +inline void CudnnConvBackendConfig::_internal_set_reordered_int8_nchw_vect(bool value) { + if (!_internal_has_reordered_int8_nchw_vect()) { + clear_filter_and_bias_reordering_oneof(); + set_has_reordered_int8_nchw_vect(); + } + _impl_.filter_and_bias_reordering_oneof_.reordered_int8_nchw_vect_ = value; +} +inline bool CudnnConvBackendConfig::reordered_int8_nchw_vect() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.reordered_int8_nchw_vect) + return _internal_reordered_int8_nchw_vect(); +} +inline void CudnnConvBackendConfig::set_reordered_int8_nchw_vect(bool value) { + _internal_set_reordered_int8_nchw_vect(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnConvBackendConfig.reordered_int8_nchw_vect) +} + +// optional string serialized_graph = 9; +inline bool CudnnConvBackendConfig::_internal_has_serialized_graph() const { + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; + return value; +} +inline bool CudnnConvBackendConfig::has_serialized_graph() const { + return _internal_has_serialized_graph(); +} +inline void CudnnConvBackendConfig::clear_serialized_graph() { + _impl_.serialized_graph_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; +} +inline const std::string& CudnnConvBackendConfig::serialized_graph() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnConvBackendConfig.serialized_graph) + return _internal_serialized_graph(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CudnnConvBackendConfig::set_serialized_graph(ArgT0&& arg0, ArgT... args) { + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.serialized_graph_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnConvBackendConfig.serialized_graph) +} +inline std::string* CudnnConvBackendConfig::mutable_serialized_graph() { + std::string* _s = _internal_mutable_serialized_graph(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnConvBackendConfig.serialized_graph) + return _s; +} +inline const std::string& CudnnConvBackendConfig::_internal_serialized_graph() const { + return _impl_.serialized_graph_.Get(); +} +inline void CudnnConvBackendConfig::_internal_set_serialized_graph(const std::string& value) { + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.serialized_graph_.Set(value, GetArenaForAllocation()); +} +inline std::string* CudnnConvBackendConfig::_internal_mutable_serialized_graph() { + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.serialized_graph_.Mutable(GetArenaForAllocation()); +} +inline std::string* CudnnConvBackendConfig::release_serialized_graph() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnConvBackendConfig.serialized_graph) + if (!_internal_has_serialized_graph()) { + return nullptr; + } + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.serialized_graph_.Release(); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.serialized_graph_.IsDefault()) { + _impl_.serialized_graph_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; +} +inline void CudnnConvBackendConfig::set_allocated_serialized_graph(std::string* serialized_graph) { + if (serialized_graph != nullptr) { + _impl_._has_bits_[0] |= 0x00000001u; + } else { + _impl_._has_bits_[0] &= ~0x00000001u; + } + _impl_.serialized_graph_.SetAllocated(serialized_graph, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.serialized_graph_.IsDefault()) { + _impl_.serialized_graph_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnConvBackendConfig.serialized_graph) +} + +inline bool CudnnConvBackendConfig::has_filter_and_bias_reordering_oneof() const { + return filter_and_bias_reordering_oneof_case() != FILTER_AND_BIAS_REORDERING_ONEOF_NOT_SET; +} +inline void CudnnConvBackendConfig::clear_has_filter_and_bias_reordering_oneof() { + _impl_._oneof_case_[0] = FILTER_AND_BIAS_REORDERING_ONEOF_NOT_SET; +} +inline CudnnConvBackendConfig::FilterAndBiasReorderingOneofCase CudnnConvBackendConfig::filter_and_bias_reordering_oneof_case() const { + return CudnnConvBackendConfig::FilterAndBiasReorderingOneofCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// GemmBackendConfig + +// int64 selected_algorithm = 1; +inline bool GemmBackendConfig::_internal_has_selected_algorithm() const { + return algorithm_case() == kSelectedAlgorithm; +} +inline bool GemmBackendConfig::has_selected_algorithm() const { + return _internal_has_selected_algorithm(); +} +inline void GemmBackendConfig::set_has_selected_algorithm() { + _impl_._oneof_case_[0] = kSelectedAlgorithm; +} +inline void GemmBackendConfig::clear_selected_algorithm() { + if (_internal_has_selected_algorithm()) { + _impl_.algorithm_.selected_algorithm_ = int64_t{0}; + clear_has_algorithm(); + } +} +inline int64_t GemmBackendConfig::_internal_selected_algorithm() const { + if (_internal_has_selected_algorithm()) { + return _impl_.algorithm_.selected_algorithm_; + } + return int64_t{0}; +} +inline void GemmBackendConfig::_internal_set_selected_algorithm(int64_t value) { + if (!_internal_has_selected_algorithm()) { + clear_algorithm(); + set_has_selected_algorithm(); + } + _impl_.algorithm_.selected_algorithm_ = value; +} +inline int64_t GemmBackendConfig::selected_algorithm() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.selected_algorithm) + return _internal_selected_algorithm(); +} +inline void GemmBackendConfig::set_selected_algorithm(int64_t value) { + _internal_set_selected_algorithm(value); + // @@protoc_insertion_point(field_set:xla.gpu.GemmBackendConfig.selected_algorithm) +} + +// double alpha_real = 2; +inline void GemmBackendConfig::clear_alpha_real() { + _impl_.alpha_real_ = 0; +} +inline double GemmBackendConfig::_internal_alpha_real() const { + return _impl_.alpha_real_; +} +inline double GemmBackendConfig::alpha_real() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.alpha_real) + return _internal_alpha_real(); +} +inline void GemmBackendConfig::_internal_set_alpha_real(double value) { + + _impl_.alpha_real_ = value; +} +inline void GemmBackendConfig::set_alpha_real(double value) { + _internal_set_alpha_real(value); + // @@protoc_insertion_point(field_set:xla.gpu.GemmBackendConfig.alpha_real) +} + +// double alpha_imag = 9; +inline void GemmBackendConfig::clear_alpha_imag() { + _impl_.alpha_imag_ = 0; +} +inline double GemmBackendConfig::_internal_alpha_imag() const { + return _impl_.alpha_imag_; +} +inline double GemmBackendConfig::alpha_imag() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.alpha_imag) + return _internal_alpha_imag(); +} +inline void GemmBackendConfig::_internal_set_alpha_imag(double value) { + + _impl_.alpha_imag_ = value; +} +inline void GemmBackendConfig::set_alpha_imag(double value) { + _internal_set_alpha_imag(value); + // @@protoc_insertion_point(field_set:xla.gpu.GemmBackendConfig.alpha_imag) +} + +// double beta = 3; +inline void GemmBackendConfig::clear_beta() { + _impl_.beta_ = 0; +} +inline double GemmBackendConfig::_internal_beta() const { + return _impl_.beta_; +} +inline double GemmBackendConfig::beta() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.beta) + return _internal_beta(); +} +inline void GemmBackendConfig::_internal_set_beta(double value) { + + _impl_.beta_ = value; +} +inline void GemmBackendConfig::set_beta(double value) { + _internal_set_beta(value); + // @@protoc_insertion_point(field_set:xla.gpu.GemmBackendConfig.beta) +} + +// .xla.DotDimensionNumbers dot_dimension_numbers = 7; +inline bool GemmBackendConfig::_internal_has_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.dot_dimension_numbers_ != nullptr; +} +inline bool GemmBackendConfig::has_dot_dimension_numbers() const { + return _internal_has_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& GemmBackendConfig::_internal_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& GemmBackendConfig::dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.dot_dimension_numbers) + return _internal_dot_dimension_numbers(); +} +inline void GemmBackendConfig::unsafe_arena_set_allocated_dot_dimension_numbers( + ::xla::DotDimensionNumbers* dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dot_dimension_numbers_); + } + _impl_.dot_dimension_numbers_ = dot_dimension_numbers; + if (dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.GemmBackendConfig.dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* GemmBackendConfig::release_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.dot_dimension_numbers_; + _impl_.dot_dimension_numbers_ = 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::DotDimensionNumbers* GemmBackendConfig::unsafe_arena_release_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.GemmBackendConfig.dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.dot_dimension_numbers_; + _impl_.dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* GemmBackendConfig::_internal_mutable_dot_dimension_numbers() { + + if (_impl_.dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.dot_dimension_numbers_ = p; + } + return _impl_.dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* GemmBackendConfig::mutable_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.GemmBackendConfig.dot_dimension_numbers) + return _msg; +} +inline void GemmBackendConfig::set_allocated_dot_dimension_numbers(::xla::DotDimensionNumbers* dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dot_dimension_numbers_); + } + if (dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(dot_dimension_numbers)); + if (message_arena != submessage_arena) { + dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.dot_dimension_numbers_ = dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.GemmBackendConfig.dot_dimension_numbers) +} + +// .xla.PrecisionConfig precision_config = 12; +inline bool GemmBackendConfig::_internal_has_precision_config() const { + return this != internal_default_instance() && _impl_.precision_config_ != nullptr; +} +inline bool GemmBackendConfig::has_precision_config() const { + return _internal_has_precision_config(); +} +inline const ::xla::PrecisionConfig& GemmBackendConfig::_internal_precision_config() const { + const ::xla::PrecisionConfig* p = _impl_.precision_config_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_PrecisionConfig_default_instance_); +} +inline const ::xla::PrecisionConfig& GemmBackendConfig::precision_config() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.precision_config) + return _internal_precision_config(); +} +inline void GemmBackendConfig::unsafe_arena_set_allocated_precision_config( + ::xla::PrecisionConfig* precision_config) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.precision_config_); + } + _impl_.precision_config_ = precision_config; + if (precision_config) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.GemmBackendConfig.precision_config) +} +inline ::xla::PrecisionConfig* GemmBackendConfig::release_precision_config() { + + ::xla::PrecisionConfig* temp = _impl_.precision_config_; + _impl_.precision_config_ = 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::PrecisionConfig* GemmBackendConfig::unsafe_arena_release_precision_config() { + // @@protoc_insertion_point(field_release:xla.gpu.GemmBackendConfig.precision_config) + + ::xla::PrecisionConfig* temp = _impl_.precision_config_; + _impl_.precision_config_ = nullptr; + return temp; +} +inline ::xla::PrecisionConfig* GemmBackendConfig::_internal_mutable_precision_config() { + + if (_impl_.precision_config_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::PrecisionConfig>(GetArenaForAllocation()); + _impl_.precision_config_ = p; + } + return _impl_.precision_config_; +} +inline ::xla::PrecisionConfig* GemmBackendConfig::mutable_precision_config() { + ::xla::PrecisionConfig* _msg = _internal_mutable_precision_config(); + // @@protoc_insertion_point(field_mutable:xla.gpu.GemmBackendConfig.precision_config) + return _msg; +} +inline void GemmBackendConfig::set_allocated_precision_config(::xla::PrecisionConfig* precision_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.precision_config_); + } + if (precision_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(precision_config)); + if (message_arena != submessage_arena) { + precision_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, precision_config, submessage_arena); + } + + } else { + + } + _impl_.precision_config_ = precision_config; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.GemmBackendConfig.precision_config) +} + +// .xla.gpu.GemmBackendConfig.Epilogue epilogue = 13; +inline void GemmBackendConfig::clear_epilogue() { + _impl_.epilogue_ = 0; +} +inline ::xla::gpu::GemmBackendConfig_Epilogue GemmBackendConfig::_internal_epilogue() const { + return static_cast< ::xla::gpu::GemmBackendConfig_Epilogue >(_impl_.epilogue_); +} +inline ::xla::gpu::GemmBackendConfig_Epilogue GemmBackendConfig::epilogue() const { + // @@protoc_insertion_point(field_get:xla.gpu.GemmBackendConfig.epilogue) + return _internal_epilogue(); +} +inline void GemmBackendConfig::_internal_set_epilogue(::xla::gpu::GemmBackendConfig_Epilogue value) { + + _impl_.epilogue_ = value; +} +inline void GemmBackendConfig::set_epilogue(::xla::gpu::GemmBackendConfig_Epilogue value) { + _internal_set_epilogue(value); + // @@protoc_insertion_point(field_set:xla.gpu.GemmBackendConfig.epilogue) +} + +inline bool GemmBackendConfig::has_algorithm() const { + return algorithm_case() != ALGORITHM_NOT_SET; +} +inline void GemmBackendConfig::clear_has_algorithm() { + _impl_._oneof_case_[0] = ALGORITHM_NOT_SET; +} +inline GemmBackendConfig::AlgorithmCase GemmBackendConfig::algorithm_case() const { + return GemmBackendConfig::AlgorithmCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// BitcastBackendConfig + +// .xla.LayoutProto source_layout = 1; +inline bool BitcastBackendConfig::_internal_has_source_layout() const { + return this != internal_default_instance() && _impl_.source_layout_ != nullptr; +} +inline bool BitcastBackendConfig::has_source_layout() const { + return _internal_has_source_layout(); +} +inline const ::xla::LayoutProto& BitcastBackendConfig::_internal_source_layout() const { + const ::xla::LayoutProto* p = _impl_.source_layout_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_LayoutProto_default_instance_); +} +inline const ::xla::LayoutProto& BitcastBackendConfig::source_layout() const { + // @@protoc_insertion_point(field_get:xla.gpu.BitcastBackendConfig.source_layout) + return _internal_source_layout(); +} +inline void BitcastBackendConfig::unsafe_arena_set_allocated_source_layout( + ::xla::LayoutProto* source_layout) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_layout_); + } + _impl_.source_layout_ = source_layout; + if (source_layout) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.BitcastBackendConfig.source_layout) +} +inline ::xla::LayoutProto* BitcastBackendConfig::release_source_layout() { + + ::xla::LayoutProto* temp = _impl_.source_layout_; + _impl_.source_layout_ = 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::LayoutProto* BitcastBackendConfig::unsafe_arena_release_source_layout() { + // @@protoc_insertion_point(field_release:xla.gpu.BitcastBackendConfig.source_layout) + + ::xla::LayoutProto* temp = _impl_.source_layout_; + _impl_.source_layout_ = nullptr; + return temp; +} +inline ::xla::LayoutProto* BitcastBackendConfig::_internal_mutable_source_layout() { + + if (_impl_.source_layout_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::LayoutProto>(GetArenaForAllocation()); + _impl_.source_layout_ = p; + } + return _impl_.source_layout_; +} +inline ::xla::LayoutProto* BitcastBackendConfig::mutable_source_layout() { + ::xla::LayoutProto* _msg = _internal_mutable_source_layout(); + // @@protoc_insertion_point(field_mutable:xla.gpu.BitcastBackendConfig.source_layout) + return _msg; +} +inline void BitcastBackendConfig::set_allocated_source_layout(::xla::LayoutProto* source_layout) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_layout_); + } + if (source_layout) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_layout)); + if (message_arena != submessage_arena) { + source_layout = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, source_layout, submessage_arena); + } + + } else { + + } + _impl_.source_layout_ = source_layout; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.BitcastBackendConfig.source_layout) +} + +// .xla.LayoutProto result_layout = 2; +inline bool BitcastBackendConfig::_internal_has_result_layout() const { + return this != internal_default_instance() && _impl_.result_layout_ != nullptr; +} +inline bool BitcastBackendConfig::has_result_layout() const { + return _internal_has_result_layout(); +} +inline const ::xla::LayoutProto& BitcastBackendConfig::_internal_result_layout() const { + const ::xla::LayoutProto* p = _impl_.result_layout_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_LayoutProto_default_instance_); +} +inline const ::xla::LayoutProto& BitcastBackendConfig::result_layout() const { + // @@protoc_insertion_point(field_get:xla.gpu.BitcastBackendConfig.result_layout) + return _internal_result_layout(); +} +inline void BitcastBackendConfig::unsafe_arena_set_allocated_result_layout( + ::xla::LayoutProto* result_layout) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.result_layout_); + } + _impl_.result_layout_ = result_layout; + if (result_layout) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.BitcastBackendConfig.result_layout) +} +inline ::xla::LayoutProto* BitcastBackendConfig::release_result_layout() { + + ::xla::LayoutProto* temp = _impl_.result_layout_; + _impl_.result_layout_ = 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::LayoutProto* BitcastBackendConfig::unsafe_arena_release_result_layout() { + // @@protoc_insertion_point(field_release:xla.gpu.BitcastBackendConfig.result_layout) + + ::xla::LayoutProto* temp = _impl_.result_layout_; + _impl_.result_layout_ = nullptr; + return temp; +} +inline ::xla::LayoutProto* BitcastBackendConfig::_internal_mutable_result_layout() { + + if (_impl_.result_layout_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::LayoutProto>(GetArenaForAllocation()); + _impl_.result_layout_ = p; + } + return _impl_.result_layout_; +} +inline ::xla::LayoutProto* BitcastBackendConfig::mutable_result_layout() { + ::xla::LayoutProto* _msg = _internal_mutable_result_layout(); + // @@protoc_insertion_point(field_mutable:xla.gpu.BitcastBackendConfig.result_layout) + return _msg; +} +inline void BitcastBackendConfig::set_allocated_result_layout(::xla::LayoutProto* result_layout) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.result_layout_); + } + if (result_layout) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(result_layout)); + if (message_arena != submessage_arena) { + result_layout = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, result_layout, submessage_arena); + } + + } else { + + } + _impl_.result_layout_ = result_layout; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.BitcastBackendConfig.result_layout) +} + +// ------------------------------------------------------------------- + +// CollectiveBackendConfig + +// bool is_sync = 1; +inline void CollectiveBackendConfig::clear_is_sync() { + _impl_.is_sync_ = false; +} +inline bool CollectiveBackendConfig::_internal_is_sync() const { + return _impl_.is_sync_; +} +inline bool CollectiveBackendConfig::is_sync() const { + // @@protoc_insertion_point(field_get:xla.gpu.CollectiveBackendConfig.is_sync) + return _internal_is_sync(); +} +inline void CollectiveBackendConfig::_internal_set_is_sync(bool value) { + + _impl_.is_sync_ = value; +} +inline void CollectiveBackendConfig::set_is_sync(bool value) { + _internal_set_is_sync(value); + // @@protoc_insertion_point(field_set:xla.gpu.CollectiveBackendConfig.is_sync) +} + +// ------------------------------------------------------------------- + +// ReificationCost + +// double end_to_end_cycles = 1; +inline void ReificationCost::clear_end_to_end_cycles() { + _impl_.end_to_end_cycles_ = 0; +} +inline double ReificationCost::_internal_end_to_end_cycles() const { + return _impl_.end_to_end_cycles_; +} +inline double ReificationCost::end_to_end_cycles() const { + // @@protoc_insertion_point(field_get:xla.gpu.ReificationCost.end_to_end_cycles) + return _internal_end_to_end_cycles(); +} +inline void ReificationCost::_internal_set_end_to_end_cycles(double value) { + + _impl_.end_to_end_cycles_ = value; +} +inline void ReificationCost::set_end_to_end_cycles(double value) { + _internal_set_end_to_end_cycles(value); + // @@protoc_insertion_point(field_set:xla.gpu.ReificationCost.end_to_end_cycles) +} + +// ------------------------------------------------------------------- + +// FusionBackendConfig + +// string kind = 1; +inline void FusionBackendConfig::clear_kind() { + _impl_.kind_.ClearToEmpty(); +} +inline const std::string& FusionBackendConfig::kind() const { + // @@protoc_insertion_point(field_get:xla.gpu.FusionBackendConfig.kind) + return _internal_kind(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void FusionBackendConfig::set_kind(ArgT0&& arg0, ArgT... args) { + + _impl_.kind_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.FusionBackendConfig.kind) +} +inline std::string* FusionBackendConfig::mutable_kind() { + std::string* _s = _internal_mutable_kind(); + // @@protoc_insertion_point(field_mutable:xla.gpu.FusionBackendConfig.kind) + return _s; +} +inline const std::string& FusionBackendConfig::_internal_kind() const { + return _impl_.kind_.Get(); +} +inline void FusionBackendConfig::_internal_set_kind(const std::string& value) { + + _impl_.kind_.Set(value, GetArenaForAllocation()); +} +inline std::string* FusionBackendConfig::_internal_mutable_kind() { + + return _impl_.kind_.Mutable(GetArenaForAllocation()); +} +inline std::string* FusionBackendConfig::release_kind() { + // @@protoc_insertion_point(field_release:xla.gpu.FusionBackendConfig.kind) + return _impl_.kind_.Release(); +} +inline void FusionBackendConfig::set_allocated_kind(std::string* kind) { + if (kind != nullptr) { + + } else { + + } + _impl_.kind_.SetAllocated(kind, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.kind_.IsDefault()) { + _impl_.kind_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.FusionBackendConfig.kind) +} + +// .xla.AutotuneResult.TritonGemmKey triton_gemm_config = 2; +inline bool FusionBackendConfig::_internal_has_triton_gemm_config() const { + return this != internal_default_instance() && _impl_.triton_gemm_config_ != nullptr; +} +inline bool FusionBackendConfig::has_triton_gemm_config() const { + return _internal_has_triton_gemm_config(); +} +inline const ::xla::AutotuneResult_TritonGemmKey& FusionBackendConfig::_internal_triton_gemm_config() const { + const ::xla::AutotuneResult_TritonGemmKey* p = _impl_.triton_gemm_config_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_AutotuneResult_TritonGemmKey_default_instance_); +} +inline const ::xla::AutotuneResult_TritonGemmKey& FusionBackendConfig::triton_gemm_config() const { + // @@protoc_insertion_point(field_get:xla.gpu.FusionBackendConfig.triton_gemm_config) + return _internal_triton_gemm_config(); +} +inline void FusionBackendConfig::unsafe_arena_set_allocated_triton_gemm_config( + ::xla::AutotuneResult_TritonGemmKey* triton_gemm_config) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.triton_gemm_config_); + } + _impl_.triton_gemm_config_ = triton_gemm_config; + if (triton_gemm_config) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.FusionBackendConfig.triton_gemm_config) +} +inline ::xla::AutotuneResult_TritonGemmKey* FusionBackendConfig::release_triton_gemm_config() { + + ::xla::AutotuneResult_TritonGemmKey* temp = _impl_.triton_gemm_config_; + _impl_.triton_gemm_config_ = 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_TritonGemmKey* FusionBackendConfig::unsafe_arena_release_triton_gemm_config() { + // @@protoc_insertion_point(field_release:xla.gpu.FusionBackendConfig.triton_gemm_config) + + ::xla::AutotuneResult_TritonGemmKey* temp = _impl_.triton_gemm_config_; + _impl_.triton_gemm_config_ = nullptr; + return temp; +} +inline ::xla::AutotuneResult_TritonGemmKey* FusionBackendConfig::_internal_mutable_triton_gemm_config() { + + if (_impl_.triton_gemm_config_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::AutotuneResult_TritonGemmKey>(GetArenaForAllocation()); + _impl_.triton_gemm_config_ = p; + } + return _impl_.triton_gemm_config_; +} +inline ::xla::AutotuneResult_TritonGemmKey* FusionBackendConfig::mutable_triton_gemm_config() { + ::xla::AutotuneResult_TritonGemmKey* _msg = _internal_mutable_triton_gemm_config(); + // @@protoc_insertion_point(field_mutable:xla.gpu.FusionBackendConfig.triton_gemm_config) + return _msg; +} +inline void FusionBackendConfig::set_allocated_triton_gemm_config(::xla::AutotuneResult_TritonGemmKey* triton_gemm_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.triton_gemm_config_); + } + if (triton_gemm_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(triton_gemm_config)); + if (message_arena != submessage_arena) { + triton_gemm_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, triton_gemm_config, submessage_arena); + } + + } else { + + } + _impl_.triton_gemm_config_ = triton_gemm_config; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.FusionBackendConfig.triton_gemm_config) +} + +// .xla.gpu.ReificationCost reification_cost = 3; +inline bool FusionBackendConfig::_internal_has_reification_cost() const { + return this != internal_default_instance() && _impl_.reification_cost_ != nullptr; +} +inline bool FusionBackendConfig::has_reification_cost() const { + return _internal_has_reification_cost(); +} +inline void FusionBackendConfig::clear_reification_cost() { + if (GetArenaForAllocation() == nullptr && _impl_.reification_cost_ != nullptr) { + delete _impl_.reification_cost_; + } + _impl_.reification_cost_ = nullptr; +} +inline const ::xla::gpu::ReificationCost& FusionBackendConfig::_internal_reification_cost() const { + const ::xla::gpu::ReificationCost* p = _impl_.reification_cost_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::gpu::_ReificationCost_default_instance_); +} +inline const ::xla::gpu::ReificationCost& FusionBackendConfig::reification_cost() const { + // @@protoc_insertion_point(field_get:xla.gpu.FusionBackendConfig.reification_cost) + return _internal_reification_cost(); +} +inline void FusionBackendConfig::unsafe_arena_set_allocated_reification_cost( + ::xla::gpu::ReificationCost* reification_cost) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.reification_cost_); + } + _impl_.reification_cost_ = reification_cost; + if (reification_cost) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.FusionBackendConfig.reification_cost) +} +inline ::xla::gpu::ReificationCost* FusionBackendConfig::release_reification_cost() { + + ::xla::gpu::ReificationCost* temp = _impl_.reification_cost_; + _impl_.reification_cost_ = 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::gpu::ReificationCost* FusionBackendConfig::unsafe_arena_release_reification_cost() { + // @@protoc_insertion_point(field_release:xla.gpu.FusionBackendConfig.reification_cost) + + ::xla::gpu::ReificationCost* temp = _impl_.reification_cost_; + _impl_.reification_cost_ = nullptr; + return temp; +} +inline ::xla::gpu::ReificationCost* FusionBackendConfig::_internal_mutable_reification_cost() { + + if (_impl_.reification_cost_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::gpu::ReificationCost>(GetArenaForAllocation()); + _impl_.reification_cost_ = p; + } + return _impl_.reification_cost_; +} +inline ::xla::gpu::ReificationCost* FusionBackendConfig::mutable_reification_cost() { + ::xla::gpu::ReificationCost* _msg = _internal_mutable_reification_cost(); + // @@protoc_insertion_point(field_mutable:xla.gpu.FusionBackendConfig.reification_cost) + return _msg; +} +inline void FusionBackendConfig::set_allocated_reification_cost(::xla::gpu::ReificationCost* reification_cost) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.reification_cost_; + } + if (reification_cost) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(reification_cost); + if (message_arena != submessage_arena) { + reification_cost = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, reification_cost, submessage_arena); + } + + } else { + + } + _impl_.reification_cost_ = reification_cost; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.FusionBackendConfig.reification_cost) +} + +// ------------------------------------------------------------------- + +// CudnnfMHABackendConfig + +// .stream_executor.dnn.AlgorithmProto algorithm = 8; +inline bool CudnnfMHABackendConfig::_internal_has_algorithm() const { + return this != internal_default_instance() && _impl_.algorithm_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_algorithm() const { + return _internal_has_algorithm(); +} +inline const ::stream_executor::dnn::AlgorithmProto& CudnnfMHABackendConfig::_internal_algorithm() const { + const ::stream_executor::dnn::AlgorithmProto* p = _impl_.algorithm_; + return p != nullptr ? *p : reinterpret_cast( + ::stream_executor::dnn::_AlgorithmProto_default_instance_); +} +inline const ::stream_executor::dnn::AlgorithmProto& CudnnfMHABackendConfig::algorithm() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.algorithm) + return _internal_algorithm(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_algorithm( + ::stream_executor::dnn::AlgorithmProto* algorithm) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.algorithm_); + } + _impl_.algorithm_ = algorithm; + if (algorithm) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.algorithm) +} +inline ::stream_executor::dnn::AlgorithmProto* CudnnfMHABackendConfig::release_algorithm() { + + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.algorithm_; + _impl_.algorithm_ = 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 ::stream_executor::dnn::AlgorithmProto* CudnnfMHABackendConfig::unsafe_arena_release_algorithm() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.algorithm) + + ::stream_executor::dnn::AlgorithmProto* temp = _impl_.algorithm_; + _impl_.algorithm_ = nullptr; + return temp; +} +inline ::stream_executor::dnn::AlgorithmProto* CudnnfMHABackendConfig::_internal_mutable_algorithm() { + + if (_impl_.algorithm_ == nullptr) { + auto* p = CreateMaybeMessage<::stream_executor::dnn::AlgorithmProto>(GetArenaForAllocation()); + _impl_.algorithm_ = p; + } + return _impl_.algorithm_; +} +inline ::stream_executor::dnn::AlgorithmProto* CudnnfMHABackendConfig::mutable_algorithm() { + ::stream_executor::dnn::AlgorithmProto* _msg = _internal_mutable_algorithm(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.algorithm) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_algorithm(::stream_executor::dnn::AlgorithmProto* algorithm) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.algorithm_); + } + if (algorithm) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(algorithm)); + if (message_arena != submessage_arena) { + algorithm = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, algorithm, submessage_arena); + } + + } else { + + } + _impl_.algorithm_ = algorithm; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.algorithm) +} + +// double fmha_scale = 10; +inline void CudnnfMHABackendConfig::clear_fmha_scale() { + _impl_.fmha_scale_ = 0; +} +inline double CudnnfMHABackendConfig::_internal_fmha_scale() const { + return _impl_.fmha_scale_; +} +inline double CudnnfMHABackendConfig::fmha_scale() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.fmha_scale) + return _internal_fmha_scale(); +} +inline void CudnnfMHABackendConfig::_internal_set_fmha_scale(double value) { + + _impl_.fmha_scale_ = value; +} +inline void CudnnfMHABackendConfig::set_fmha_scale(double value) { + _internal_set_fmha_scale(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnfMHABackendConfig.fmha_scale) +} + +// double dropout_rate = 13; +inline void CudnnfMHABackendConfig::clear_dropout_rate() { + _impl_.dropout_rate_ = 0; +} +inline double CudnnfMHABackendConfig::_internal_dropout_rate() const { + return _impl_.dropout_rate_; +} +inline double CudnnfMHABackendConfig::dropout_rate() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.dropout_rate) + return _internal_dropout_rate(); +} +inline void CudnnfMHABackendConfig::_internal_set_dropout_rate(double value) { + + _impl_.dropout_rate_ = value; +} +inline void CudnnfMHABackendConfig::set_dropout_rate(double value) { + _internal_set_dropout_rate(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnfMHABackendConfig.dropout_rate) +} + +// .xla.DotDimensionNumbers bmm1_dot_dimension_numbers = 11; +inline bool CudnnfMHABackendConfig::_internal_has_bmm1_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.bmm1_dot_dimension_numbers_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_bmm1_dot_dimension_numbers() const { + return _internal_has_bmm1_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::_internal_bmm1_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.bmm1_dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::bmm1_dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.bmm1_dot_dimension_numbers) + return _internal_bmm1_dot_dimension_numbers(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_bmm1_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm1_dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm1_dot_dimension_numbers_); + } + _impl_.bmm1_dot_dimension_numbers_ = bmm1_dot_dimension_numbers; + if (bmm1_dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm1_dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::release_bmm1_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.bmm1_dot_dimension_numbers_; + _impl_.bmm1_dot_dimension_numbers_ = 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::DotDimensionNumbers* CudnnfMHABackendConfig::unsafe_arena_release_bmm1_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.bmm1_dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.bmm1_dot_dimension_numbers_; + _impl_.bmm1_dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::_internal_mutable_bmm1_dot_dimension_numbers() { + + if (_impl_.bmm1_dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.bmm1_dot_dimension_numbers_ = p; + } + return _impl_.bmm1_dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::mutable_bmm1_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_bmm1_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.bmm1_dot_dimension_numbers) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_bmm1_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm1_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm1_dot_dimension_numbers_); + } + if (bmm1_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(bmm1_dot_dimension_numbers)); + if (message_arena != submessage_arena) { + bmm1_dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, bmm1_dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.bmm1_dot_dimension_numbers_ = bmm1_dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm1_dot_dimension_numbers) +} + +// .xla.DotDimensionNumbers bmm2_dot_dimension_numbers = 12; +inline bool CudnnfMHABackendConfig::_internal_has_bmm2_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.bmm2_dot_dimension_numbers_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_bmm2_dot_dimension_numbers() const { + return _internal_has_bmm2_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::_internal_bmm2_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.bmm2_dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::bmm2_dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.bmm2_dot_dimension_numbers) + return _internal_bmm2_dot_dimension_numbers(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_bmm2_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm2_dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm2_dot_dimension_numbers_); + } + _impl_.bmm2_dot_dimension_numbers_ = bmm2_dot_dimension_numbers; + if (bmm2_dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm2_dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::release_bmm2_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.bmm2_dot_dimension_numbers_; + _impl_.bmm2_dot_dimension_numbers_ = 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::DotDimensionNumbers* CudnnfMHABackendConfig::unsafe_arena_release_bmm2_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.bmm2_dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.bmm2_dot_dimension_numbers_; + _impl_.bmm2_dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::_internal_mutable_bmm2_dot_dimension_numbers() { + + if (_impl_.bmm2_dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.bmm2_dot_dimension_numbers_ = p; + } + return _impl_.bmm2_dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::mutable_bmm2_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_bmm2_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.bmm2_dot_dimension_numbers) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_bmm2_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm2_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm2_dot_dimension_numbers_); + } + if (bmm2_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(bmm2_dot_dimension_numbers)); + if (message_arena != submessage_arena) { + bmm2_dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, bmm2_dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.bmm2_dot_dimension_numbers_ = bmm2_dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm2_dot_dimension_numbers) +} + +// .xla.ShapeProto intermediate_tensor_shape = 14; +inline bool CudnnfMHABackendConfig::_internal_has_intermediate_tensor_shape() const { + return this != internal_default_instance() && _impl_.intermediate_tensor_shape_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_intermediate_tensor_shape() const { + return _internal_has_intermediate_tensor_shape(); +} +inline const ::xla::ShapeProto& CudnnfMHABackendConfig::_internal_intermediate_tensor_shape() const { + const ::xla::ShapeProto* p = _impl_.intermediate_tensor_shape_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ShapeProto_default_instance_); +} +inline const ::xla::ShapeProto& CudnnfMHABackendConfig::intermediate_tensor_shape() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.intermediate_tensor_shape) + return _internal_intermediate_tensor_shape(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_intermediate_tensor_shape( + ::xla::ShapeProto* intermediate_tensor_shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.intermediate_tensor_shape_); + } + _impl_.intermediate_tensor_shape_ = intermediate_tensor_shape; + if (intermediate_tensor_shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.intermediate_tensor_shape) +} +inline ::xla::ShapeProto* CudnnfMHABackendConfig::release_intermediate_tensor_shape() { + + ::xla::ShapeProto* temp = _impl_.intermediate_tensor_shape_; + _impl_.intermediate_tensor_shape_ = 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::ShapeProto* CudnnfMHABackendConfig::unsafe_arena_release_intermediate_tensor_shape() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.intermediate_tensor_shape) + + ::xla::ShapeProto* temp = _impl_.intermediate_tensor_shape_; + _impl_.intermediate_tensor_shape_ = nullptr; + return temp; +} +inline ::xla::ShapeProto* CudnnfMHABackendConfig::_internal_mutable_intermediate_tensor_shape() { + + if (_impl_.intermediate_tensor_shape_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ShapeProto>(GetArenaForAllocation()); + _impl_.intermediate_tensor_shape_ = p; + } + return _impl_.intermediate_tensor_shape_; +} +inline ::xla::ShapeProto* CudnnfMHABackendConfig::mutable_intermediate_tensor_shape() { + ::xla::ShapeProto* _msg = _internal_mutable_intermediate_tensor_shape(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.intermediate_tensor_shape) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_intermediate_tensor_shape(::xla::ShapeProto* intermediate_tensor_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.intermediate_tensor_shape_); + } + if (intermediate_tensor_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(intermediate_tensor_shape)); + if (message_arena != submessage_arena) { + intermediate_tensor_shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, intermediate_tensor_shape, submessage_arena); + } + + } else { + + } + _impl_.intermediate_tensor_shape_ = intermediate_tensor_shape; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.intermediate_tensor_shape) +} + +// .xla.DotDimensionNumbers bmm1_grad_gemm1_dot_dimension_numbers = 16; +inline bool CudnnfMHABackendConfig::_internal_has_bmm1_grad_gemm1_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.bmm1_grad_gemm1_dot_dimension_numbers_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_bmm1_grad_gemm1_dot_dimension_numbers() const { + return _internal_has_bmm1_grad_gemm1_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::_internal_bmm1_grad_gemm1_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.bmm1_grad_gemm1_dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::bmm1_grad_gemm1_dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm1_dot_dimension_numbers) + return _internal_bmm1_grad_gemm1_dot_dimension_numbers(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_bmm1_grad_gemm1_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm1_grad_gemm1_dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm1_grad_gemm1_dot_dimension_numbers_); + } + _impl_.bmm1_grad_gemm1_dot_dimension_numbers_ = bmm1_grad_gemm1_dot_dimension_numbers; + if (bmm1_grad_gemm1_dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm1_dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::release_bmm1_grad_gemm1_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.bmm1_grad_gemm1_dot_dimension_numbers_; + _impl_.bmm1_grad_gemm1_dot_dimension_numbers_ = 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::DotDimensionNumbers* CudnnfMHABackendConfig::unsafe_arena_release_bmm1_grad_gemm1_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm1_dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.bmm1_grad_gemm1_dot_dimension_numbers_; + _impl_.bmm1_grad_gemm1_dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::_internal_mutable_bmm1_grad_gemm1_dot_dimension_numbers() { + + if (_impl_.bmm1_grad_gemm1_dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.bmm1_grad_gemm1_dot_dimension_numbers_ = p; + } + return _impl_.bmm1_grad_gemm1_dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::mutable_bmm1_grad_gemm1_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_bmm1_grad_gemm1_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm1_dot_dimension_numbers) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_bmm1_grad_gemm1_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm1_grad_gemm1_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm1_grad_gemm1_dot_dimension_numbers_); + } + if (bmm1_grad_gemm1_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(bmm1_grad_gemm1_dot_dimension_numbers)); + if (message_arena != submessage_arena) { + bmm1_grad_gemm1_dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, bmm1_grad_gemm1_dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.bmm1_grad_gemm1_dot_dimension_numbers_ = bmm1_grad_gemm1_dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm1_dot_dimension_numbers) +} + +// .xla.DotDimensionNumbers bmm1_grad_gemm2_dot_dimension_numbers = 17; +inline bool CudnnfMHABackendConfig::_internal_has_bmm1_grad_gemm2_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.bmm1_grad_gemm2_dot_dimension_numbers_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_bmm1_grad_gemm2_dot_dimension_numbers() const { + return _internal_has_bmm1_grad_gemm2_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::_internal_bmm1_grad_gemm2_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.bmm1_grad_gemm2_dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::bmm1_grad_gemm2_dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm2_dot_dimension_numbers) + return _internal_bmm1_grad_gemm2_dot_dimension_numbers(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_bmm1_grad_gemm2_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm1_grad_gemm2_dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm1_grad_gemm2_dot_dimension_numbers_); + } + _impl_.bmm1_grad_gemm2_dot_dimension_numbers_ = bmm1_grad_gemm2_dot_dimension_numbers; + if (bmm1_grad_gemm2_dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm2_dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::release_bmm1_grad_gemm2_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.bmm1_grad_gemm2_dot_dimension_numbers_; + _impl_.bmm1_grad_gemm2_dot_dimension_numbers_ = 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::DotDimensionNumbers* CudnnfMHABackendConfig::unsafe_arena_release_bmm1_grad_gemm2_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm2_dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.bmm1_grad_gemm2_dot_dimension_numbers_; + _impl_.bmm1_grad_gemm2_dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::_internal_mutable_bmm1_grad_gemm2_dot_dimension_numbers() { + + if (_impl_.bmm1_grad_gemm2_dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.bmm1_grad_gemm2_dot_dimension_numbers_ = p; + } + return _impl_.bmm1_grad_gemm2_dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::mutable_bmm1_grad_gemm2_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_bmm1_grad_gemm2_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm2_dot_dimension_numbers) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_bmm1_grad_gemm2_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm1_grad_gemm2_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm1_grad_gemm2_dot_dimension_numbers_); + } + if (bmm1_grad_gemm2_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(bmm1_grad_gemm2_dot_dimension_numbers)); + if (message_arena != submessage_arena) { + bmm1_grad_gemm2_dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, bmm1_grad_gemm2_dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.bmm1_grad_gemm2_dot_dimension_numbers_ = bmm1_grad_gemm2_dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm1_grad_gemm2_dot_dimension_numbers) +} + +// .xla.DotDimensionNumbers bmm2_grad_gemm1_dot_dimension_numbers = 18; +inline bool CudnnfMHABackendConfig::_internal_has_bmm2_grad_gemm1_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.bmm2_grad_gemm1_dot_dimension_numbers_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_bmm2_grad_gemm1_dot_dimension_numbers() const { + return _internal_has_bmm2_grad_gemm1_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::_internal_bmm2_grad_gemm1_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.bmm2_grad_gemm1_dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::bmm2_grad_gemm1_dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm1_dot_dimension_numbers) + return _internal_bmm2_grad_gemm1_dot_dimension_numbers(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_bmm2_grad_gemm1_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm2_grad_gemm1_dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm2_grad_gemm1_dot_dimension_numbers_); + } + _impl_.bmm2_grad_gemm1_dot_dimension_numbers_ = bmm2_grad_gemm1_dot_dimension_numbers; + if (bmm2_grad_gemm1_dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm1_dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::release_bmm2_grad_gemm1_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.bmm2_grad_gemm1_dot_dimension_numbers_; + _impl_.bmm2_grad_gemm1_dot_dimension_numbers_ = 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::DotDimensionNumbers* CudnnfMHABackendConfig::unsafe_arena_release_bmm2_grad_gemm1_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm1_dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.bmm2_grad_gemm1_dot_dimension_numbers_; + _impl_.bmm2_grad_gemm1_dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::_internal_mutable_bmm2_grad_gemm1_dot_dimension_numbers() { + + if (_impl_.bmm2_grad_gemm1_dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.bmm2_grad_gemm1_dot_dimension_numbers_ = p; + } + return _impl_.bmm2_grad_gemm1_dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::mutable_bmm2_grad_gemm1_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_bmm2_grad_gemm1_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm1_dot_dimension_numbers) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_bmm2_grad_gemm1_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm2_grad_gemm1_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm2_grad_gemm1_dot_dimension_numbers_); + } + if (bmm2_grad_gemm1_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(bmm2_grad_gemm1_dot_dimension_numbers)); + if (message_arena != submessage_arena) { + bmm2_grad_gemm1_dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, bmm2_grad_gemm1_dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.bmm2_grad_gemm1_dot_dimension_numbers_ = bmm2_grad_gemm1_dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm1_dot_dimension_numbers) +} + +// .xla.DotDimensionNumbers bmm2_grad_gemm2_dot_dimension_numbers = 19; +inline bool CudnnfMHABackendConfig::_internal_has_bmm2_grad_gemm2_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.bmm2_grad_gemm2_dot_dimension_numbers_ != nullptr; +} +inline bool CudnnfMHABackendConfig::has_bmm2_grad_gemm2_dot_dimension_numbers() const { + return _internal_has_bmm2_grad_gemm2_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::_internal_bmm2_grad_gemm2_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.bmm2_grad_gemm2_dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& CudnnfMHABackendConfig::bmm2_grad_gemm2_dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm2_dot_dimension_numbers) + return _internal_bmm2_grad_gemm2_dot_dimension_numbers(); +} +inline void CudnnfMHABackendConfig::unsafe_arena_set_allocated_bmm2_grad_gemm2_dot_dimension_numbers( + ::xla::DotDimensionNumbers* bmm2_grad_gemm2_dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm2_grad_gemm2_dot_dimension_numbers_); + } + _impl_.bmm2_grad_gemm2_dot_dimension_numbers_ = bmm2_grad_gemm2_dot_dimension_numbers; + if (bmm2_grad_gemm2_dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm2_dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::release_bmm2_grad_gemm2_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.bmm2_grad_gemm2_dot_dimension_numbers_; + _impl_.bmm2_grad_gemm2_dot_dimension_numbers_ = 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::DotDimensionNumbers* CudnnfMHABackendConfig::unsafe_arena_release_bmm2_grad_gemm2_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm2_dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.bmm2_grad_gemm2_dot_dimension_numbers_; + _impl_.bmm2_grad_gemm2_dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::_internal_mutable_bmm2_grad_gemm2_dot_dimension_numbers() { + + if (_impl_.bmm2_grad_gemm2_dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.bmm2_grad_gemm2_dot_dimension_numbers_ = p; + } + return _impl_.bmm2_grad_gemm2_dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* CudnnfMHABackendConfig::mutable_bmm2_grad_gemm2_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_bmm2_grad_gemm2_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm2_dot_dimension_numbers) + return _msg; +} +inline void CudnnfMHABackendConfig::set_allocated_bmm2_grad_gemm2_dot_dimension_numbers(::xla::DotDimensionNumbers* bmm2_grad_gemm2_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.bmm2_grad_gemm2_dot_dimension_numbers_); + } + if (bmm2_grad_gemm2_dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(bmm2_grad_gemm2_dot_dimension_numbers)); + if (message_arena != submessage_arena) { + bmm2_grad_gemm2_dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, bmm2_grad_gemm2_dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.bmm2_grad_gemm2_dot_dimension_numbers_ = bmm2_grad_gemm2_dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.CudnnfMHABackendConfig.bmm2_grad_gemm2_dot_dimension_numbers) +} + +// int64 seed = 15; +inline void CudnnfMHABackendConfig::clear_seed() { + _impl_.seed_ = int64_t{0}; +} +inline int64_t CudnnfMHABackendConfig::_internal_seed() const { + return _impl_.seed_; +} +inline int64_t CudnnfMHABackendConfig::seed() const { + // @@protoc_insertion_point(field_get:xla.gpu.CudnnfMHABackendConfig.seed) + return _internal_seed(); +} +inline void CudnnfMHABackendConfig::_internal_set_seed(int64_t value) { + + _impl_.seed_ = value; +} +inline void CudnnfMHABackendConfig::set_seed(int64_t value) { + _internal_set_seed(value); + // @@protoc_insertion_point(field_set:xla.gpu.CudnnfMHABackendConfig.seed) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::xla::gpu::GemmBackendConfig_Epilogue> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::gpu::GemmBackendConfig_Epilogue>() { + return ::xla::gpu::GemmBackendConfig_Epilogue_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fbackend_5fconfigs_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_allocations.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_allocations.h new file mode 100644 index 0000000000000000000000000000000000000000..04e76c5157ee13ab982607d057ac76171d55f5c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_allocations.h @@ -0,0 +1,100 @@ +/* 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_SERVICE_GPU_BUFFER_ALLOCATIONS_H_ +#define XLA_SERVICE_GPU_BUFFER_ALLOCATIONS_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/str_format.h" +#include "absl/types/span.h" +#include "xla/service/buffer_assignment.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thread-compatible class that encapsulates the base addresses of the +// allocated device buffers. +class BufferAllocations { + public: + BufferAllocations(absl::Span buffers, + int device_ordinal, + se::DeviceMemoryAllocator* memory_allocator) + : buffers_(buffers.begin(), buffers.end()), + device_ordinal_(device_ordinal), + memory_allocator_(memory_allocator) {} + + BufferAllocations(BufferAllocations&& other) = default; + BufferAllocations& operator=(BufferAllocations&& other) = default; + BufferAllocations(const BufferAllocations&) = delete; + BufferAllocations& operator=(const BufferAllocations&) = delete; + + se::DeviceMemoryAllocator* memory_allocator() const { + return memory_allocator_; + } + int device_ordinal() const { return device_ordinal_; } + + // Returns the device address of buffer `buffer_index`. `buffer_index` must be + // a valid index, i.e., in [0, buffer_count). This function returns null if + // `buffer_index` is not assigned to a buffer address. + se::DeviceMemoryBase GetDeviceAddress( + BufferAllocation::Index buffer_index) const; + + // Returns a mutable value for the allocation at a given `buffer_index`. + se::DeviceMemoryBase& GetMutableDeviceAddress( + BufferAllocation::Index buffer_index); + + // Same as above, but also adjusts the returned address for the offset and + // size contained in the given slice. + se::DeviceMemoryBase GetDeviceAddress( + const BufferAllocation::Slice& buffer_slice) const; + + // Tears down all buffers allocated by this object that are not in + // `live_addresses`. + Status TearDown(const std::set& live_addresses, + absl::Span allocations); + + std::string ToString() const { + std::string out; + for (BufferAllocation::Index i = 0; i < buffers_.size(); ++i) { + const auto& buf = buffers_[i]; + absl::StrAppendFormat(&out, "Buffer %d -> %p (%d B)", i, buf.opaque(), + buf.size()); + } + return out; + } + + size_t size() const { return buffers_.size(); } + + private: + // An array of device pointers that stores the address of each buffer + // indexed by Index. Each element can point to a temporary buffer, an + // input buffer, or nullptr if no buffer is needed for that Index. + std::vector buffers_; + int device_ordinal_; + se::DeviceMemoryAllocator* memory_allocator_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_BUFFER_ALLOCATIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_comparator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_comparator.h new file mode 100644 index 0000000000000000000000000000000000000000..df4b6215aaf99bdd4161a17394ed7dced2190ba5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_comparator.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_SERVICE_GPU_BUFFER_COMPARATOR_H_ +#define XLA_SERVICE_GPU_BUFFER_COMPARATOR_H_ + +#include "xla/service/hlo_module_config.h" +#include "xla/shape.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A device-side comparator that compares buffers. +class BufferComparator { + public: + BufferComparator(const BufferComparator&) = delete; + BufferComparator(BufferComparator&&) = default; + + BufferComparator(const Shape& shape, const HloModuleConfig& config); + + // Returns true if the two buffers compare equal. The definition of "equal" + // is: + // * All NaNs equal. + // * All fp16 infs are treated as 65505 or -65505. Otherwise, + // infs and negative infs compare equal. + // * With NaNs and infs taken care of, a and b compare equal iff: + // abs(a - b) / (max(abs(a), abs(b)) + 1) < tolerance + // + // See the implementation for the tolerance value. + StatusOr CompareEqual(se::Stream* stream, se::DeviceMemoryBase current, + se::DeviceMemoryBase expected) const; + + private: + Shape shape_; + HloModuleConfig config_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_BUFFER_COMPARATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_sharing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_sharing.h new file mode 100644 index 0000000000000000000000000000000000000000..5867dd8d03193a5b95adf9ea45e3de1b61007527 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/buffer_sharing.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_SERVICE_GPU_BUFFER_SHARING_H_ +#define XLA_SERVICE_GPU_BUFFER_SHARING_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/shape_util.h" + +namespace xla { +namespace gpu { +std::optional FusionCanShareBufferHint(const HloInstruction* user, + const HloInstruction* operand, + const ShapeIndex& user_index); + +std::optional CanShareBufferHint(const HloInstruction* user, + const HloInstruction* operand, + const ShapeIndex& user_index); +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_BUFFER_SHARING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/compile_module_to_llvm_ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/compile_module_to_llvm_ir.h new file mode 100644 index 0000000000000000000000000000000000000000..64d73b81700f96b394368b39dd7f1610bd3deaed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/compile_module_to_llvm_ir.h @@ -0,0 +1,81 @@ +/* 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_SERVICE_GPU_COMPILE_MODULE_TO_LLVM_IR_H_ +#define XLA_SERVICE_GPU_COMPILE_MODULE_TO_LLVM_IR_H_ + +#include +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/buffer_value.h" +#include "xla/service/gpu/executable.pb.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +struct CompileModuleResults { + std::unique_ptr llvm_module; + std::unique_ptr buffer_assignment; + std::vector allocations; + std::variant + executable; + EntryFunctionAttributes entry_func_attrs; + std::vector constants; + absl::flat_hash_map output_info; + Shape output_shape; + std::string module_name; +}; + +// Removes all globals from the given module that are both uninitialized and +// have no uses within that module. +void RemoveUnusedAndUninitializedGlobals( + llvm::Module* llvm_module, + const std::vector& constants); + +// Compile `hlo_module` using XLA GPU and return the LLVM module thus generated. +// The GpuExecutable (and the Thunks that are part of it) are not returned. +StatusOr> CompileModuleToLlvmIr( + HloModule* hlo_module, llvm::LLVMContext* llvm_context, + const std::string& target_triple, const std::string& data_layout, + const std::string& platform_name, se::Platform::Id platform_id, + const se::DeviceDescription& gpu_device_info, + const BufferValue::SizeFunction& buffer_size_bytes_function); + +Status CompileModuleToLlvmIrImpl( + HloModule* hlo_module, llvm::LLVMContext* llvm_context, + const std::string& target_triple, const std::string& data_layout, + const std::string& platform_name, se::Platform::Id platform_id, + const se::DeviceDescription& gpu_device_info, + const HloDataflowAnalysis::CanShareBuffer& can_share_buffer_function, + const BufferValue::SizeFunction& buffer_size_bytes_function, + CompileModuleResults* results, se::StreamExecutor* stream_exec = nullptr); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_COMPILE_MODULE_TO_LLVM_IR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conditional_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conditional_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..044275b4b88848d1cf4cfaa3e2dab7a54d88fae9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conditional_thunk.h @@ -0,0 +1,72 @@ +/* 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_SERVICE_GPU_CONDITIONAL_THUNK_H_ +#define XLA_SERVICE_GPU_CONDITIONAL_THUNK_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/sequential_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +struct ConditionalThunkConfig { + bool branch_index_is_bool; + int64_t branch_count; + std::vector> branch_thunks; +}; + +// ConditionalThunk implements the conditional instruction on GPU by reading the +// predicate of the conditional and executing the true or the false computation +// depending on the value of the predicate. +// +// ConditionalThunk assumes that the buffers of the conditional result and the +// result of the true and false computations share the same allocation. Also, +// the buffers of the true operand of the conditional and that of the parameter +// instruction of the true computation share the same allocation. Similarly, the +// buffers of the false operand and that of the parameter instruction of the +// false computation share the same allocation. +class ConditionalThunk : public Thunk { + public: + ConditionalThunk(ThunkInfo thunk_info, ConditionalThunkConfig config, + const BufferAllocation::Slice& branch_index_buffer_index); + + ConditionalThunk(const ConditionalThunk&) = delete; + ConditionalThunk& operator=(const ConditionalThunk&) = delete; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + absl::Span> branch_thunks() { + return config_.branch_thunks; + } + + private: + const ConditionalThunkConfig config_; + BufferAllocation::Slice branch_index_buffer_index_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CONDITIONAL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conv_algorithm_picker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conv_algorithm_picker.h new file mode 100644 index 0000000000000000000000000000000000000000..2850c0609e70a7eeeef3444d1c577875a4cae712 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conv_algorithm_picker.h @@ -0,0 +1,164 @@ +/* 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_SERVICE_GPU_CONV_ALGORITHM_PICKER_H_ +#define XLA_SERVICE_GPU_CONV_ALGORITHM_PICKER_H_ + +#include +#include +#include +#include + +#include "xla/autotune_results.pb.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/gpu/gpu_conv_runner.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) +#include "xla/stream_executor/gpu/redzone_allocator.h" +#endif + +namespace xla { +namespace gpu { + +// Choose the fastest algorithm for each conv. +// Modifies CustomCalls to cudnn convolutions, choosing the best algorithm for +// each and adding explicit scratch space to the CustomCalls. +// +// We pick the algorithm before fusion so that we can generate better HLO. After +// GpuConvRewriter, our convolutions are CustomCalls which return a +// tuple (conv_result, scratch_memory), and the each conv uses 0 bytes of +// scratch: +// +// customcall = (f32[...], f32[0]) +// return gte(customcall, 0) +// +// The algorithm picker then chooses the best algorithm, and potentially +// increases the scratch space. It replaces customcall with new_tuple, +// giving us the following: +// +// new_customcall = (f32[...], f32[N]) +// new_tuple = tuple(gte(new_customcall, 0), constant f32[0]) +// return gte(new_tuple, 0) +// +// The new tuple and gte instructions can be simplified away, because +// nobody is expected to use the scratch value. +// +// However, if we were to run GpuConvAlgorithmPicker after fusion +// the gte(customcall, 0) would probably already be into a fusion node. We +// can't simplify across HloComputation boundaries, so in this case we +// wouldn't be able to simplify away the new_tuple bits. +// +// It supports two modes: device and deviceless. +// In device mode, we run autotuning on the device and store autotune results. +// +// In deviceless mode, we pass in some information related to the device and +// use stored autotune results to rewrite convolutions. If the required autotune +// result is not stored, then the performance of convolution will be suboptimal. +class GpuConvAlgorithmPicker : public HloModulePass { + public: + explicit GpuConvAlgorithmPicker(AutotuneConfig config) : config_(config) {} + + absl::string_view name() const override { + return "gpu-conv-algorithm-picker"; + } + + static bool IsEnabled(const HloModule* module) { + return module->config().debug_options().xla_gpu_autotune_level() != 0; + } + + static bool IsCandidate(const HloInstruction* instr) { + return IsCustomCallToDnnConvolution(*instr); + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Run autotuning on allocated buffers and pick the best algorithm. + StatusOr PickBestAlgorithmWithAllocatedBuffer( + const AutotuneConfig& config, GpuConvConfig conv_config, + const ServiceExecutableRunOptions* run_options, + const DebugOptions& debug_options, + std::vector buffers, + std::vector result_buffers); + + private: + StatusOr RunOnComputation(HloComputation* computation); + StatusOr RunOnInstruction(HloInstruction* instr); + + StatusOr PickBestAlgorithm( + const HloCustomCallInstruction* instr); + StatusOr PickBestAlgorithmNoCache( + const HloCustomCallInstruction* instr); + +#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) + // Simple bundle of an algorithm and its output, for comparing results across + // autotuned algorithms. + struct ReferenceResult { + stream_executor::dnn::AlgorithmDesc algorithm; + std::vector buffers; + }; + + // Execution environment for autotuning. Runtime autotuning requires runtime + // information such as input/output buffers in order to run. It can be + // constructed from the autotuned instruction by FromInstruction. + struct AutotuneRuntimeArguments { + const Shape result_shape; + const HloModuleConfig hlo_module_config; + std::vector operand_buffers; + std::vector result_buffers; + se::RedzoneAllocator* input_output_allocator; + const GpuConvConfig gpu_conv_config; + std::optional canonical_hlo; + + static StatusOr FromInstruction( + const HloCustomCallInstruction* instr, + se::DeviceMemoryAllocator* allocator, se::StreamExecutor* stream, + se::RedzoneAllocator* input_output_allocator); + }; + + StatusOr AutotuneOneConvRunner( + se::Stream* stream, GenericConvRunner* runner, + std::optional* reference_result, + absl::Span disabled_algos, + std::optional instruction_info, + const AutotuneRuntimeArguments& runtime_arguments); + + // Pick the best algorithm for CUDA platform. + StatusOr PickBestAlgorithmNoCacheCuda( + const HloCustomCallInstruction* instr, se::Stream* stream, + std::optional instruction_info, + const AutotuneRuntimeArguments& runtime_arguments); +#endif + + StatusOr PickBestAlgorithmNoCacheRocm( + const HloCustomCallInstruction* instr, + se::DeviceMemoryAllocator* allocator, se::Stream* stream); + + private: + AutotuneConfig config_; +}; + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_CONV_ALGORITHM_PICKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conv_layout_normalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conv_layout_normalization.h new file mode 100644 index 0000000000000000000000000000000000000000..52fd26c1fbf95b60e73f14f0646eecd03f2b726d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/conv_layout_normalization.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_SERVICE_GPU_CONV_LAYOUT_NORMALIZATION_H_ +#define XLA_SERVICE_GPU_CONV_LAYOUT_NORMALIZATION_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +StatusOr> NormalizeLayoutForGpuCustomCalls( + HloCustomCallInstruction*); + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_CONV_LAYOUT_NORMALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/convolution_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/convolution_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..d7f731302c1a949314725a837910618c109b4ff5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/convolution_thunk.h @@ -0,0 +1,95 @@ +/* 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_SERVICE_GPU_CONVOLUTION_THUNK_H_ +#define XLA_SERVICE_GPU_CONVOLUTION_THUNK_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/gpu_conv_runner.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a DNN +// convolution. It is generated by IrEmitter. +// +// This is thread-compatible. +class ConvolutionThunk : public Thunk { + public: + // Constructs a thunk for launching a DNN convolution. + // + // operand_slices should be in the same order as cudnn_call->operands(). + ConvolutionThunk(ThunkInfo thunk_info, GpuConvConfig config, + std::vector operand_slices, + std::vector result_slices, + BufferAllocation::Slice scratch_slice); + + ConvolutionThunk(const ConvolutionThunk&) = delete; + ConvolutionThunk& operator=(const ConvolutionThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + std::vector operand_buffers_; + std::vector result_buffers_; + BufferAllocation::Slice scratch_buffer_; + GenericConvRunner& GetOrCreateRunner(const stream_executor::Stream* stream); + + // Convolution config + const GpuConvConfig config_; + absl::Mutex mu_; + absl::flat_hash_map> + runner_cache_ ABSL_GUARDED_BY(mu_); +}; + +// Launches the kernel that reorders input data for int8x32 convolutions. +class ConvolutionReorderThunk : public Thunk { + public: + ConvolutionReorderThunk(ThunkInfo thunk_info, absl::Span filter_nchw, + std::vector operand_slices, + std::vector result_slices); + + ConvolutionReorderThunk(const ConvolutionReorderThunk&) = delete; + ConvolutionReorderThunk& operator=(const ConvolutionReorderThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + static se::dnn::FilterDescriptor CreateFilterDescriptor( + absl::Span filter_nchw); + + const se::dnn::FilterDescriptor filter_descriptor_; + std::vector operand_buffers_; + std::vector result_buffers_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CONVOLUTION_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/copy_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/copy_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..fa9306ce7e3fde7bc1485161e2036a6766a62b46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/copy_fusion.h @@ -0,0 +1,46 @@ +/* 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_SERVICE_GPU_COPY_FUSION_H_ +#define XLA_SERVICE_GPU_COPY_FUSION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// CopyFusion checks if a fusion is followed by multiple copies and if so, adds +// those copies to the fusion, replacing the copies with get_tuple_elements. +class CopyFusion : public HloModulePass { + public: + CopyFusion() = default; + + absl::string_view name() const override { return "copy_fusion"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr DoCopyFusion(HloComputation* computation); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_COPY_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/copy_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/copy_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..7576c81ca98ec652ed8d4c18828eadd7ee30d45b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/copy_thunk.h @@ -0,0 +1,70 @@ +/* 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_SERVICE_GPU_COPY_THUNK_H_ +#define XLA_SERVICE_GPU_COPY_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that copies data from a device buffer to another device buffer. +class DeviceToDeviceCopyThunk : public Thunk { + public: + // Constructs a CopyThunk that copies host data from `source_buffer` to the + // device buffer `destination_buffer`. `mem_size` is the size of the data in + // bytes. + DeviceToDeviceCopyThunk(ThunkInfo thunk_info, + const BufferAllocation::Slice& source_buffer, + const BufferAllocation::Slice& destination_buffer, + uint64_t mem_size, mlir::Value source_value, + mlir::Value destination_value); + + DeviceToDeviceCopyThunk(const DeviceToDeviceCopyThunk&) = delete; + DeviceToDeviceCopyThunk& operator=(const DeviceToDeviceCopyThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + source_value_ = nullptr; + destination_value_ = nullptr; + } + + const BufferAllocation::Slice& source() const { return source_buffer_; } + const BufferAllocation::Slice& destination() const { + return destination_buffer_; + } + uint64_t size_bytes() const { return mem_size_; } + mlir::Value source_value() const { return source_value_; } + mlir::Value destination_value() const { return destination_value_; } + + private: + const BufferAllocation::Slice source_buffer_; + const BufferAllocation::Slice destination_buffer_; + const uint64_t mem_size_; + mlir::Value source_value_; + mlir::Value destination_value_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_COPY_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_cudnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_cudnn.h new file mode 100644 index 0000000000000000000000000000000000000000..4feaf28bb1f51c467b413912b9b51a8ff332e02f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_cudnn.h @@ -0,0 +1,205 @@ +/* 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_SERVICE_GPU_CUBLAS_CUDNN_H_ +#define XLA_SERVICE_GPU_CUBLAS_CUDNN_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "tsl/platform/statusor.h" + +namespace xla { +namespace gpu { + +// Different types of convolutions supported by cudnn. +// +// A way to think about these is that a convolution is defined by three arrays +// -- the "input", the "filter", and the "output" -- and given any two of these, +// we can compute the third. For example, a backward-input convolution takes as +// input a filter and an "output" and produces an "input" such that if one were +// to do a forward convolution of "input" using filter, the result would be +// something with the same shape as "output". +// +// This way of thinking is not correct if you look at the values produced. For +// example, a backward-input convolution is not actually the mathematical +// inverse of a forward convolution. But it's right as far as the shapes and +// "connectivity" (i.e. which elements of the input affect which elements of +// the output) are concerned. +enum class CudnnConvKind { + kForward, // input + filter => output + kBackwardInput, // filter + output => input + kBackwardFilter, // input + output => filter + kForwardActivation, // activation(conv(input, filter) + broadcast(bias) + + // (optionally) side_input) => output + kForwardGraph, // pointwise(...pointwise(conv(input, filter))...) + // => output +}; + +enum class CudnnfMHAKind { + kBmmBmm, + kScaleBiasMaskSoftmax, + kScaleBiasMaskSoftmaxDropout, + kScaleMaskSoftmax, + kScaleMaskSoftmaxDropout, + kSoftmaxDropout, + kSoftmax, + kScaleBiasSoftmax, + kScaleBiasSoftmaxDropout, + kBackwardBmmBmm, + kBackwardScaleBiasMaskSoftmax, + kBackwardScaleBiasMaskSoftmaxDropout, + kBackwardScaleMaskSoftmax, + kBackwardScaleMaskSoftmaxDropout, + kBackwardSoftmaxDropout, + kBackwardSoftmax, + kBackwardScaleBiasSoftmax, + kBackwardScaleBiasSoftmaxDropout, +}; + +StatusOr GetCudnnConvKind(const HloCustomCallInstruction* instr); + +// Converts a CudnnConvKind value to a string. +std::string CudnnConvKindToString(CudnnConvKind kind); + +// Matrix multiplication rewritten into a GEMM custom call. +// All matrix multiplications should be rewritten as such custom calls +// after a GemmRewriter lowering pass. +bool IsCublasGemm(const HloInstruction& hlo); + +// Matrix multiplication that calls into legacy cublas. +bool IsLegacyCublasMatmul(const HloInstruction& hlo); + +// Matrix multiplication that calls into cublasLt. +bool IsCublasLtMatmul(const HloInstruction& hlo); + +// Scaled matrix multiplication in FP8. Calls into cublasLt. +bool IsCublasLtMatmulF8(const HloInstruction& hlo); + +// A call to cuBLAS general matrix multiplication API. +extern const absl::string_view kGemmCallTarget; + +// A call to cuBLAS Lt API matrix multiplication. +extern const absl::string_view kCublasLtMatmulCallTarget; + +// A call to cuBLASLt for scaled matrix multiplication in FP8. +extern const absl::string_view kCublasLtMatmulF8CallTarget; + +// A call to cuBLAS for a triangular solve. +// +// Like cudnn convolutions, this op returns a tuple (result, scratch_memory). +extern const absl::string_view kTriangularSolveCallTarget; + +// A call to cuDNN for convolution (forward, backward filter, or backward input) +// is represented as a CustomCall HLO with a call target equal to one of these +// strings. +// +// These CustomCalls have window() and convolution_dimension_numbers() set like +// regular convolution ops. They have the same LHS and RHS operands, plus two +// additional constant operands: an int64_t operand for the cudnn algorithm and +// a bool operand for whether tensor_ops is enabled. A value of -1 for the cudnn +// algorithm means that the implementation is free to choose the best algorithm +// it can. +// +// These calls output a tuple (conv_result, scratch_memory), where conv_result +// is the actual result of the convolution, and scratch_memory is temporary +// memory used by cudnn. Callers shouldn't inspect scratch_memory, as its value +// is not well-defined. +// +// GpuConvRewriter lowers kConvolution HLOs to these custom calls. +// When it does so, it chooses algorithm -1 and 0 bytes of scratch space. Later +// on in the pipeline, CudnnConvAlgorithmChooser chooses an explicit +// algorithm for each conv and sets the amount of scratch space needed. +// +// (Representing the scratch memory as an output may seem strange at first, but +// it's quite sensible, from a certain point of view. The scratch buffer is a +// location in memory that the conv can write into, but which it can't legally +// read from, at least until it's written something first. But that's exactly +// the definition of an output buffer.) +extern const absl::string_view kCudnnConvForwardCallTarget; +extern const absl::string_view kCudnnConvBackwardInputCallTarget; +extern const absl::string_view kCudnnConvBackwardFilterCallTarget; +extern const absl::string_view kCudnnConvBiasActivationForwardCallTarget; +extern const absl::string_view kCudnnConvForwardGraphCallTarget; + +// cuDNN specific convolution helper (emitted together with a int8x32 +// convolution, if reordering is required). +extern const absl::string_view kCudnnConvReorderFilterCallTarget; +extern const absl::string_view kCudnnConvReorderFilterAndBiasCallTarget; + +// Returns true if `hlo` will be implemented as a call to a cuDNN convolution +// routine. +// +// This returns true if `hlo` is a CustomCall HLO with a call target equal to +// one of the kCudnnConvFoo constants above, but returns *false* for HLOs with a +// kConvolution opcode. +bool IsCustomCallToDnnConvolution(const HloInstruction& hlo); + +// Returns true if `hlo` will be implemented as a call to cuDNN convolution +// reordering helper (required for int8x32 convolutions). +bool IsCudnnConvolutionReorder(const HloInstruction& hlo); + +// The fused_mha_rewriter phase where each of the MHA signatures are pattern +// matched and rewritten into a custom-call with specific custom-call target. +// The custom-call target specifies the MHA signature. For example, BMM1 - Bias +// - Scale - Mask - Softmax - BMM2 pattern can have the target as +// cudnn$fmhaBiasScaleMaskSoftmax. +// The fMHA signatures currently supported by cudnn are: +// 1.BMM1 - BMM2 +// 2. BMM1 - Scale - Bias - Mask - Softmax - BMM2 +// 3. BMM1 - Scale - Bias - Mask - Softmax - Dropout - BMM2 +// 4. BMM1 - Scale - Mask - Softmax - BMM2 +// 5. BMM1 - Scale - Mask - Softmax - Dropout - BMM2 +// 6. BMM1 - Softmax - Dropout - BMM2 +// 7. BMM1 - Softmax - BMM2 +// 8. BMM1 - scale - Bias - Softmax - BMM2 +// Forward calls +extern const absl::string_view kCudnnfMHABmmBmmCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasMaskSoftmaxCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasMaskSoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHAScaleMaskSoftmaxCallTarget; +extern const absl::string_view kCudnnfMHAScaleMaskSoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasSoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasSoftmaxCallTarget; +// Backward calls +extern const absl::string_view kCudnnfMHABmmBmmBackwardCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxBackwardCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasMaskSoftmaxBackwardCallTarget; +extern const absl::string_view + kCudnnfMHAScaleBiasMaskSoftmaxDropoutBackwardCallTarget; +extern const absl::string_view kCudnnfMHAScaleMaskSoftmaxBackwardCallTarget; +extern const absl::string_view + kCudnnfMHAScaleMaskSoftmaxDropoutBackwardCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxDropoutBackwardCallTarget; +extern const absl::string_view + kCudnnfMHAScaleBiasSoftmaxDropoutBackwardCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasSoftmaxBackwardCallTarget; + +bool IsFwdCustomCallTofMHA(const HloInstruction& hlo); +bool IsBwdCustomCallTofMHA(const HloInstruction& hlo); +bool IsCustomCallTofMHA(const HloInstruction& hlo); + +StatusOr GetCudnnfMHAKind(const HloCustomCallInstruction* instr); + +std::string CudnnfMHAKindToString(CudnnfMHAKind kind); +Status SetFMHAInstructionName(HloModule* module, HloInstruction* fmha); + +bool MHACallHasDropout(absl::string_view fmha_call_name); +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_CUDNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_lt_matmul_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_lt_matmul_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..3098d18687d35aec6590366480a3a3dd7d3bc27e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_lt_matmul_thunk.h @@ -0,0 +1,85 @@ +/* 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_SERVICE_GPU_CUBLAS_LT_MATMUL_THUNK_H_ +#define XLA_SERVICE_GPU_CUBLAS_LT_MATMUL_THUNK_H_ + +#include +#include +#include + +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/matmul_utils.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "tsl/platform/statusor.h" +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#else +#include "rocm/rocm_config.h" +#include "xla/stream_executor/rocm/hip_blas_lt.h" +#endif // GOOGLE_CUDA + +namespace xla { +namespace gpu { + +class CublasLtMatmulThunk : public Thunk { + public: + CublasLtMatmulThunk(ThunkInfo thunk_info, GemmConfig gemm_config, + se::gpu::BlasLt::Epilogue epilogue, int64_t algorithm_idx, + BufferAllocation::Slice a_buffer, + BufferAllocation::Slice b_buffer, + BufferAllocation::Slice c_buffer, + BufferAllocation::Slice d_buffer, + BufferAllocation::Slice bias_buffer /* may be null */, + BufferAllocation::Slice aux_buffer /* may be null */, + BufferAllocation::Slice a_scale_buffer /* may be null */, + BufferAllocation::Slice b_scale_buffer /* may be null */, + BufferAllocation::Slice c_scale_buffer /* may be null */, + BufferAllocation::Slice d_scale_buffer /* may be null */, + BufferAllocation::Slice d_amax_buffer /* may be null */); + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + StatusOr GetMatmulPlan( + const stream_executor::Stream* stream); + + absl::Mutex matmul_plans_cache_mutex_; + absl::flat_hash_map> + matmul_plans_cache_ ABSL_GUARDED_BY(matmul_plans_cache_mutex_); + + GemmConfig gemm_config_; + se::gpu::BlasLt::Epilogue epilogue_; + int64_t algorithm_idx_; + BufferAllocation::Slice a_buffer_; + BufferAllocation::Slice b_buffer_; + BufferAllocation::Slice c_buffer_; + BufferAllocation::Slice d_buffer_; + BufferAllocation::Slice bias_buffer_; + BufferAllocation::Slice aux_buffer_; + BufferAllocation::Slice a_scale_buffer_; + BufferAllocation::Slice b_scale_buffer_; + BufferAllocation::Slice c_scale_buffer_; + BufferAllocation::Slice d_scale_buffer_; + BufferAllocation::Slice d_amax_buffer_; + std::optional algorithm_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_LT_MATMUL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_pad_for_gemms.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_pad_for_gemms.h new file mode 100644 index 0000000000000000000000000000000000000000..758949c91eb9fb0bb37398bf34ee47db92b97c35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_pad_for_gemms.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_GPU_CUBLAS_PAD_FOR_GEMMS_H_ +#define XLA_SERVICE_GPU_CUBLAS_PAD_FOR_GEMMS_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Adds padding to dot operations to make them run faster on GPUs. +// +// +// This can be used to pad f16 dots on tensor cores, or s8 dots to multiples of +// four. +// +// This pass depends on xla::DotDecomposer pass, +// so it should go strictly later. +class CublasPadForGemms : public HloModulePass { + public: + CublasPadForGemms(const se::CudaComputeCapability cuda_compute_capability, + PrimitiveType datatype, int32_t pad_to_multiple_of) + : cuda_compute_capability_(cuda_compute_capability), + datatype_(datatype), + pad_to_multiple_of_(pad_to_multiple_of) {} + + absl::string_view name() const override { return "cublas-pad-for-gemms"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability cuda_compute_capability_; + PrimitiveType datatype_; + int32_t pad_to_multiple_of_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_PAD_FOR_GEMMS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_padding_requirements.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_padding_requirements.h new file mode 100644 index 0000000000000000000000000000000000000000..b0b44e61b57bbe68c29834d295a6ca5f4ddbc3c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cublas_padding_requirements.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_GPU_CUBLAS_PADDING_REQUIREMENTS_H_ +#define XLA_SERVICE_GPU_CUBLAS_PADDING_REQUIREMENTS_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +struct CublasPaddingRequirement { + int min_compute_capability; + PrimitiveType data_type; + int multiple_of; +}; + +// List of padding requirements per compute capability and data type. +constexpr std::array CublasPaddingRequirements{ + {{se::CudaComputeCapability::VOLTA, S8, 4}, + {se::CudaComputeCapability::VOLTA, F16, 8}, + {se::CudaComputeCapability::AMPERE, BF16, 8}}}; + +// Tell if either of the operands of the dot requires padding. +bool CublasRequiresPadding(const HloDotInstruction& dot, + se::CudaComputeCapability cc); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_PADDING_REQUIREMENTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_conv_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_conv_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..67c40792df08ad4527f8687afe4bace7d8fd1f23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_conv_rewriter.h @@ -0,0 +1,116 @@ +/* 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_SERVICE_GPU_CUDNN_FUSED_CONV_REWRITER_H_ +#define XLA_SERVICE_GPU_CUDNN_FUSED_CONV_REWRITER_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Rewrites custom-calls targeting cudnnConvolutionForward to +// cudnnConvolutionBiasActivationForward by fusing operations following forward +// convolution. This transform must run after cudnn_conv_rewriter. +// +// Semantics of underlying cudnn ops: +// +// https://docs.nvidia.com/deeplearning/cudnn/api/index.html#cudnnConvolutionBiasActivationForward +// https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#scaling-parameters +// +// ## Floating-point convs +// +// A "complete" fused floating-point conv has the form +// +// max(0, alpha1 * conv(x, w) + alpha2 * side_input + broadcast(bias)), +// +// which we fuse to +// +// cudnnConvolutionBiasActivationForward(x, w, bias, side_input). +// +// You can leave out side_input, bias, alpha1, alpha2, and max(x, 0) and still +// get a fused convolution. alpha1/2 must be broadcasts of scalar constants. +// +// f16 convs accumulate in f32. We represent this in HLO as an f32 convolution +// whose inputs can be converted to f16 without loss of precision and whose +// output is immediately converted to f16. A fused f16 conv must follow one of +// the following idioms. +// +// 1. convert_f16(conv_f32(x_f32, w_f32)) + +// side_input_f16 + broadcast(bias_f16) +// +// 2. convert_f16(conv_f32(x_f32, w_f32) + +// side_input_f32 + broadcast(bias_f32)) +// +// (These are not strictly mathematically equivalent, but cudnn doesn't tell us +// which one it does, and we deem them "close enough".) +// +// The foo_f32 HLOs must all be losslessly-convertible to f16. Some valid +// examples: +// +// - foo_f32 = convert_f32(foo_f16) +// - foo_f32 = an f32 constant whose values all fit within f16 +// - foo_f32 = broadcast/transpose/reshape(one of the above) +// +// If you have a relu, it can appear before or after the convert_f16. +// +// Note that here `bias` must be losslessly-convertible to f16; this is +// different than for s8 convolutions, where bias is f32. +// +// ## Integer convs +// +// In pure HLO, a "complete" integer conv is spelled as one of the following +// `result`s. +// +// base = alpha1_f32 * convert_f32(conv_s32(input_s32, filter_s32)) + +// alpha2_f32 * side_input + +// bias_f32 +// +// result_f32 = max(result_f32, 0) +// result_s8_option1 = max(convert_s8(clamp(-128, base, 127)), 0) +// result_s8_option2 = convert_s8(clamp(-128, max(base, 0), 127)) +// +// The foo_s32 HLOs must be losslessly-convertible to s8. If the `result_s8` +// case, side_input should be an f32 HLO that's losslessly-convertible to s8; +// otherwise, it should be losslessly-convertible to f32. +// +// In the `result_s8` case where there's no bias, side-input, or alpha1, you can +// skip the convert_f32 on conv. +// +// If you have an integer convolution that doesn't fit one of these idioms, this +// pass returns an error -- cudnn will not be able to run it. +class CudnnFusedConvRewriter : public HloModulePass { + public: + explicit CudnnFusedConvRewriter(se::CudaComputeCapability cc) + : compute_capability_(cc) {} + + absl::string_view name() const override { + return "cudnn-fused-convolution-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_FUSED_CONV_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_mha_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_mha_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..76704ff06ae1c4dd215dba8e6e0634df250fe654 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_mha_rewriter.h @@ -0,0 +1,54 @@ +/* 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_SERVICE_GPU_CUDNN_FUSED_MHA_REWRITER_H_ +#define XLA_SERVICE_GPU_CUDNN_FUSED_MHA_REWRITER_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/dnn.h" + +namespace xla { +namespace gpu { + +class CudnnFusedMHARewriter : public HloModulePass { + public: + explicit CudnnFusedMHARewriter(se::CudaComputeCapability cc, + se::StreamExecutor* stream_executor) + : compute_capability_(cc), stream_executor_(stream_executor) {} + + explicit CudnnFusedMHARewriter(se::CudaComputeCapability cc, + se::dnn::VersionInfo cudnn_version) + : compute_capability_(cc), cudnn_version_(cudnn_version) {} + + absl::string_view name() const override { + return "cudnn-fused-multi-headed-attention-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; + se::StreamExecutor* stream_executor_ = nullptr; + const se::dnn::VersionInfo cudnn_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_FUSED_MHA_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..2cbdc041e82a68419d7581a950f6d7d135ccfe73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_CUDNN_FUSED_MHA_TRANSPOSE_FUSION_H_ +#define XLA_SERVICE_GPU_CUDNN_FUSED_MHA_TRANSPOSE_FUSION_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +class CudnnFusedMHATransposeFusion : public HloModulePass { + public: + CudnnFusedMHATransposeFusion() = default; + + absl::string_view name() const override { + return "cudnn-fused-multi-headed-attention-transpose-fusion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_FUSED_MHA_TRANSPOSE_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_pad_for_convolutions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_pad_for_convolutions.h new file mode 100644 index 0000000000000000000000000000000000000000..dc403112632eec742e9dd1fdd36928c1d30c4961 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_pad_for_convolutions.h @@ -0,0 +1,53 @@ +/* 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_SERVICE_GPU_CUDNN_PAD_FOR_CONVOLUTIONS_H_ +#define XLA_SERVICE_GPU_CUDNN_PAD_FOR_CONVOLUTIONS_H_ + +#include "xla/hlo/ir/hlo_casting_utils.h" +#include "xla/literal_util.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/util.h" +#include "xla/window_util.h" + +namespace xla { +namespace gpu { + +// Two zero-paddings for CuDNN thunking are done in this transform: padding for +// tensor cores and padding for integer convolutions. This transform also +// add slice instruction to remove unnecessary output features. +class CudnnPadForConvolutions : public HloModulePass { + public: + explicit CudnnPadForConvolutions(se::CudaComputeCapability compute_capability) + : compute_capability_(compute_capability) {} + + absl::string_view name() const override { + return "cudnn_pad_for_convolutions"; + } + // Run PadForConvolutions on the given module and return if any change is made + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_PAD_FOR_CONVOLUTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_simplify_padding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_simplify_padding.h new file mode 100644 index 0000000000000000000000000000000000000000..67b5d37316ec72ece02622f1275dc74cd75feb0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_simplify_padding.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_SERVICE_GPU_CUDNN_SIMPLIFY_PADDING_H_ +#define XLA_SERVICE_GPU_CUDNN_SIMPLIFY_PADDING_H_ + +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla::gpu { + +// Simplifies or eliminates padding introduced by CudnnPadForConvolutions and +// CudnnVectorizeConvolutions. +// +// CudnnVectorizeConvolutions will generate code that does the following. +// - pad input and output features to a multiple of 32 (or 4), +// - reshape input from [N,C,H,W] to [N,C/32,H,W,32] and reshape kernel from +// [I,O,H,W] to [I/32,32,O,H,W], +// - run the conv, +// - reshape output from [N,C/32,H,W,32] to [N,C,H,W], and finally +// - slice off the padding on the C channel. +// +// But if this is followed by another convolution (very common), then the slice +// is immediately followed by another pad. This may be redundant; we know that +// the trailing channels sliced off from the first conv are 0. +// +// Ideally we can eliminate the whole reshape+slice+pad+reshape sequence between +// the two convolutions. +// +// Specifically, this pass tries to merge the slice at the end of the sequence +// above into the pad from the next convolution (when we can prove that the +// sliced-off elements are all 0). We then rely on algsimp to remove the pad if +// it's a nop and then to merge and eliminate the remaining reshapes. +// +// This pass should run after CudnnVectorizeConvolutions and there should be no +// simplification passes in between that modify the reshape-transpose-reshape +// introduced by int8x32 convolution filter reordering. +class CudnnSimplifyPadding : public HloModulePass { + public: + CudnnSimplifyPadding() = default; + + absl::string_view name() const override { return "cudnn_simplify_padding"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_CUDNN_SIMPLIFY_PADDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_support_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_support_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0ed4a88bdd21fc17ceeb5ef1966e61e81e19cab9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_support_utils.h @@ -0,0 +1,74 @@ +/* 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_SERVICE_GPU_CUDNN_SUPPORT_UTILS_H_ +#define XLA_SERVICE_GPU_CUDNN_SUPPORT_UTILS_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/shape.h" +#include "xla/stream_executor/device_description.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// Indicates whether the `compute_capability` supports an optimized integer +// implementation of the given `conv` operation vectorized to `vector_size`. +// +// This function does not guarantee that a convolution will be padded and/or +// vectorized. It only checks that it is a valid candiate for such optimization. +StatusOr CudnnSupportsOptimizedIntegerConvolution( + const se::CudaComputeCapability& compute_capability, + HloCustomCallInstruction& conv, int vector_size); + +// Represents configuration for the reshape-transpose-reshape operations that +// are equivalent to `cudnnReorderFilterAndBias`. This is used by int8x32 +// vectorized convolutions. +// +// For filter reordering the equivalent HLO is: +// %reshape = s8[$S] reshape(%input) +// %transpose = s8[I/32,H,W,O/8,2,8,4,4] transpose(%reshape), dimensions={$D} +// %result = s8[O,I/32,H,W,32] reshape(%transpose) +// +// For bias reordering the HLO is similar, but the op shapes are s8[O/32,4,2,4] +// for %transpose, and s8[O/32,2,4,4] for %result. +// +// The helper functions below calculate the shape $S (transpose_shape) and +// dimensions $D (permutation) from the convolution dimensions numbers config. +// The result_shape is fixed and is present for the convenience. +struct CudnnReorderTransposeConfig { + Shape transpose_shape; + Shape result_shape; + std::vector permutation; +}; + +// Create a transposition for an int8x32 convolution filter that effectively +// does the same thing as cudnnReorderFilterAndBias, but could also be constant +// folded or fused. +StatusOr CudnnInferTransposeForFilterReordering( + const Shape& shape, const ConvolutionDimensionNumbers& dimension_numbers); + +// Create a transposition for an int8x32 convolution bias that effectively +// does the same thing as cudnnReorderFilterAndBias, but could also be constant +// folded or fused. +StatusOr CudnnInferTransposeForBiasReordering( + const Shape& shape); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_SUPPORT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_vectorize_convolutions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_vectorize_convolutions.h new file mode 100644 index 0000000000000000000000000000000000000000..9721125cf23751c25eb5946a5e9a1466aed92bd4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cudnn_vectorize_convolutions.h @@ -0,0 +1,71 @@ +/* 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_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_ +#define XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_ + +#include + +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" + +namespace xla { +namespace gpu { + +// Changes the shape of cudnn convolutions to allow faster "vectorized" +// algorithms. +// +// On sm61+ will convert int8_t convolutions from +// +// - [N, C, H, W] to [N, C/4, H, W, 4], +// +// assuming C is divisible by 4. +// +// On sm75+ will convert int8_t convolutions from +// +// - [N, C, H, W] to [N, C/32, H, W, 32], +// - [N, C/4, H, W, 4] to [N, C/32, H, W, 32], and +// - [N, C, H, W] to [N, C/4, H, W, 4] (same as sm61+), +// +// assuming C is divisible by 4 or 32. +// +// This pass will not pad the channel dim to a multiple of 4 or 32, so you +// should run CudnnPadForConvolutions before this. +class CudnnVectorizeConvolutions : public HloModulePass { + public: + explicit CudnnVectorizeConvolutions( + se::CudaComputeCapability compute_capability, + se::dnn::VersionInfo cudnn_version) + : compute_capability_(compute_capability), + cudnn_version_(cudnn_version) {} + + absl::string_view name() const override { + return "cudnn_vectorize_convolutions"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; + const se::dnn::VersionInfo cudnn_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cusolver_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cusolver_context.h new file mode 100644 index 0000000000000000000000000000000000000000..63138f5fd601585f2bf116af811f8e219682b6f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cusolver_context.h @@ -0,0 +1,110 @@ +/* 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_SERVICE_GPU_CUSOLVER_CONTEXT_H_ +#define XLA_SERVICE_GPU_CUSOLVER_CONTEXT_H_ + +#include +#include + +#define TENSORFLOW_USE_HIPSOLVER \ + (TENSORFLOW_USE_ROCM && (TF_ROCM_VERSION >= 40500)) +#define TENSORFLOW_USE_ROCSOLVER \ + (TENSORFLOW_USE_ROCM && (TF_ROCM_VERSION < 40500)) +#define TENSORFLOW_USE_CUSOLVER_OR_HIPSOLVER \ + (!TENSORFLOW_USE_ROCM || TENSORFLOW_USE_HIPSOLVER) + +#if !TENSORFLOW_USE_ROCM +#include "third_party/gpus/cuda/include/cusolverDn.h" +using gpusolverHandle_t = cusolverDnHandle_t; +#else +#include "rocm/rocm_config.h" +// Macros to ease the transition from rocsolver to hipsolver. +#if TENSORFLOW_USE_HIPSOLVER +#include "xla/stream_executor/rocm/hipsolver_wrapper.h" +using gpusolverHandle_t = hipsolverHandle_t; +#else // TENSORFLOW_USE_ROCSOLVER +#include "xla/stream_executor/rocm/rocblas_wrapper.h" +#include "xla/stream_executor/rocm/rocsolver_wrapper.h" +using gpusolverHandle_t = rocblas_handle; +#endif // TF_ROCM_VERSION >= 40500 +#endif // TENSORFLOW_USE_ROCM + +#include "xla/statusor.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +namespace se = ::stream_executor; + +class GpuSolverContext { + public: + static StatusOr Create(); + + Status SetStream(se::Stream* stream); + + // Computes the Cholesky factorization of multiple matrices. See + // https://docs.nvidia.com/cuda/cusolver/index.html#cuSolverDN-lt-t-gt-batchpotrf + // + // `as` is a list of pointers to the batch_size individual n x n matricies + // that make up the input array. + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory as, int lda, + se::DeviceMemory lapack_info, int batch_size); + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory as, int lda, + se::DeviceMemory lapack_info, int batch_size); + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory*> as, int lda, + se::DeviceMemory lapack_info, int batch_size); + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory*> as, int lda, + se::DeviceMemory lapack_info, int batch_size); + + // Returns the max size of the `workspace` required by Potrf and PotrfBatched, + // in number of elements of `type`. + // + // (cusolver's PotrfBatched doesn't require a workspace per se -- it uses the + // input array as scratch. But we do need to materialize the `as` input, and + // we do this in the workspace.) + // + // This is a bit of a hack; we could instead split it up into two functions. + // But at the moment, it's an implementation detail of CholeskyThunk whether + // it calls Potrf or PotrfBatched, so we need to allocate enough scratch space + // for either. + // + // In practice, this does not result in a notable increase in scratch space + // needed, because both cases require a relatively small amount of scratch. + StatusOr PotrfBufferSize(PrimitiveType type, + se::blas::UpperLower uplo, int n, int lda, + int batch_size); + + private: + explicit GpuSolverContext(gpusolverHandle_t handle); + + struct Deleter { + void operator()(gpusolverHandle_t handle); + }; + + std::unique_ptr, Deleter> handle_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUSOLVER_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cusolver_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cusolver_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..9d68cfa15bae1424f6903cfbdd7e9206d2700290 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/cusolver_rewriter.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_GPU_CUSOLVER_REWRITER_H_ +#define XLA_SERVICE_GPU_CUSOLVER_REWRITER_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/cusolver_context.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Rewrites Cholesky calls into CustomCall HLOs that call into cuSolver. +class GpusolverRewriter : public HloModulePass { + public: + GpusolverRewriter(); + absl::string_view name() const override { return "gpusolver-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation* computation); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUSOLVER_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/custom_call_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/custom_call_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..329dbf02dfa8f09e341f75e4c7524a6a8cff4632 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/custom_call_thunk.h @@ -0,0 +1,70 @@ +/* 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_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ +#define XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ + +#include "xla/service/custom_call_status_internal.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "xla/stream_executor/gpu/gpu_types.h" +#endif + +namespace xla { +namespace gpu { + +// Thunk to run a GPU custom call. +// +// This thunk's `ExecuteOnStream` implementation executes a host function +// `call_target` which is expected to enqueue operations onto the GPU. +// +// Note that not all kCustomCall HLOs in XLA:GPU end up being run by this thunk. +// XLA itself creates kCustomCall instructions when lowering kConvolution HLOs +// into calls to cudnn. These internally-created custom-calls are run using +// ConvolutionThunk, not CustomCallThunk. There's no ambiguity because they +// have special call target names (e.g. "__cudnn$convForward") that only the +// compiler is allowed to create. +class CustomCallThunk : public Thunk { + public: + using OptionalSlice = ::std::optional; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + using Stream = stream_executor::gpu::GpuStreamHandle; +#else // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + using Stream = void*; +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + + using CustomCallTarget = std::function; + CustomCallThunk(ThunkInfo thunk_info, CustomCallTarget call_target, + std::vector operands, + std::vector results, + const std::string& opaque); + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const CustomCallTarget call_target_; + const std::vector operands_; + const std::vector results_; + const std::string opaque_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/dot_dimension_sorter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/dot_dimension_sorter.h new file mode 100644 index 0000000000000000000000000000000000000000..0a2e19542f0b7429bff4a8fa2e52216a9c468db8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/dot_dimension_sorter.h @@ -0,0 +1,49 @@ +/* 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_SERVICE_GPU_DOT_DIMENSION_SORTER_H_ +#define XLA_SERVICE_GPU_DOT_DIMENSION_SORTER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Sorts contracting dimensions of dot() operands when this reduces the +// number of transposes. Example: +// dot(p0, p1), lhs_contracting_dims={3,2}, rhs_contracting_dims={2,1} -> +// dot(p0, p1), lhs_contracting_dims={2,3}, rhs_contracting_dims={1,2} +// The first case gets transposes inserted by dot_decomposer, the second one +// does not and thus is generally more efficient. + +// TODO(b/265688934): do the same for batch dimensions? + +class DotDimensionSorter : public HloModulePass { + public: + absl::string_view name() const override { return "dot_dimension_sorter"; } + + // Run the pass on computations in 'module'. + // Returns whether the 'module' was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_DOT_DIMENSION_SORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/elemental_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/elemental_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..f97861ba2e7afc1e0064452a29726ac4c3409685 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/elemental_ir_emitter.h @@ -0,0 +1,137 @@ +/* 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_SERVICE_GPU_ELEMENTAL_IR_EMITTER_H_ +#define XLA_SERVICE_GPU_ELEMENTAL_IR_EMITTER_H_ + +#include + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/gpu/target_util.h" +#include "xla/service/hlo_module_config.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +class GpuElementalIrEmitter : public ElementalIrEmitter { + public: + GpuElementalIrEmitter(IrEmitterContext& ir_emitter_context, + llvm::IRBuilder<>* b); + + protected: + llvm_ir::IrArray::Index GetSourceIndexOfBitcast( + const llvm_ir::IrArray::Index& index, const HloInstruction* hlo) override; + + StatusOr EmitFloatBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value) override; + + StatusOr EmitLog(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitLog1p(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitSin(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitCos(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitTan(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitExp(PrimitiveType prim_type, llvm::Value* value, + absl::string_view name) override; + + StatusOr EmitExpm1(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitSqrt(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitRsqrt(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitPow(PrimitiveType prim_type, llvm::Value* lhs, + llvm::Value* rhs, + absl::string_view name) override; + + StatusOr EmitAtan2(PrimitiveType prim_type, llvm::Value* lhs, + llvm::Value* rhs, + absl::string_view name) override; + + StatusOr EmitTanh(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitComplexAbs(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitCbrt(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr> EmitThreadLocalCall( + const HloComputation& callee, absl::Span parameters, + absl::string_view, bool /*is_reducer*/) override; + + llvm::Value* EmitThreadId() override; + + bool fast_min_max() override { + return ir_emitter_context_.debug_options().xla_gpu_enable_fast_min_max(); + } + + private: + // Emits IR for op, which must have opcode kPower. + StatusOr EmitPowerOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + // Emits IR to call an LLVM intrinsic of type [T] -> T. Adjusts + // callee_name according to T. Returns the IR value that represents the + // return value of the function. + StatusOr EmitLlvmIntrinsicMathCall( + const std::string& callee_name, absl::Span operands, + absl::Span input_types, PrimitiveType output_type); + + // Emits IR to call a device function of type [T] -> T. Adjusts + // callee_name according to T. Returns the IR value that represents the + // return value of the function. + StatusOr EmitDeviceMathCall( + TargetDeviceFunctionID funcid, absl::Span operands, + absl::Span input_types, PrimitiveType output_type, + absl::string_view name = ""); + + // Emits IR to call a function of type [T] -> T. Does not munge callee_name. + // Returns the IR value that represents the return value of the function. + StatusOr EmitMathCall( + const std::string& callee_name, absl::Span operands, + absl::Span input_types, PrimitiveType output_type, + absl::string_view name = ""); + + IrEmitterContext& ir_emitter_context_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_ELEMENTAL_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/executable.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/executable.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..6840eaebe1d68afcf732afac015a58c161b6330e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/executable.pb.h @@ -0,0 +1,935 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/executable.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fexecutable_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fexecutable_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/service/hlo.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fexecutable_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fexecutable_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fexecutable_2eproto; +namespace xla { +namespace gpu { +class XlaRuntimeGpuExecutableProto; +struct XlaRuntimeGpuExecutableProtoDefaultTypeInternal; +extern XlaRuntimeGpuExecutableProtoDefaultTypeInternal _XlaRuntimeGpuExecutableProto_default_instance_; +class XlaRuntimeGpuExecutableProto_ConstantInfoProto; +struct XlaRuntimeGpuExecutableProto_ConstantInfoProtoDefaultTypeInternal; +extern XlaRuntimeGpuExecutableProto_ConstantInfoProtoDefaultTypeInternal _XlaRuntimeGpuExecutableProto_ConstantInfoProto_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::XlaRuntimeGpuExecutableProto* Arena::CreateMaybeMessage<::xla::gpu::XlaRuntimeGpuExecutableProto>(Arena*); +template<> ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* Arena::CreateMaybeMessage<::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +// =================================================================== + +class XlaRuntimeGpuExecutableProto_ConstantInfoProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto) */ { + public: + inline XlaRuntimeGpuExecutableProto_ConstantInfoProto() : XlaRuntimeGpuExecutableProto_ConstantInfoProto(nullptr) {} + ~XlaRuntimeGpuExecutableProto_ConstantInfoProto() override; + explicit PROTOBUF_CONSTEXPR XlaRuntimeGpuExecutableProto_ConstantInfoProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaRuntimeGpuExecutableProto_ConstantInfoProto(const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from); + XlaRuntimeGpuExecutableProto_ConstantInfoProto(XlaRuntimeGpuExecutableProto_ConstantInfoProto&& from) noexcept + : XlaRuntimeGpuExecutableProto_ConstantInfoProto() { + *this = ::std::move(from); + } + + inline XlaRuntimeGpuExecutableProto_ConstantInfoProto& operator=(const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from) { + CopyFrom(from); + return *this; + } + inline XlaRuntimeGpuExecutableProto_ConstantInfoProto& operator=(XlaRuntimeGpuExecutableProto_ConstantInfoProto&& 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 XlaRuntimeGpuExecutableProto_ConstantInfoProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaRuntimeGpuExecutableProto_ConstantInfoProto* internal_default_instance() { + return reinterpret_cast( + &_XlaRuntimeGpuExecutableProto_ConstantInfoProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(XlaRuntimeGpuExecutableProto_ConstantInfoProto& a, XlaRuntimeGpuExecutableProto_ConstantInfoProto& b) { + a.Swap(&b); + } + inline void Swap(XlaRuntimeGpuExecutableProto_ConstantInfoProto* 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(XlaRuntimeGpuExecutableProto_ConstantInfoProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaRuntimeGpuExecutableProto_ConstantInfoProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from) { + XlaRuntimeGpuExecutableProto_ConstantInfoProto::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(XlaRuntimeGpuExecutableProto_ConstantInfoProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto"; + } + protected: + explicit XlaRuntimeGpuExecutableProto_ConstantInfoProto(::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 { + kSymbolNameFieldNumber = 1, + kContentFieldNumber = 2, + kAllocationIndexFieldNumber = 3, + }; + // string symbol_name = 1; + void clear_symbol_name(); + const std::string& symbol_name() const; + template + void set_symbol_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_symbol_name(); + PROTOBUF_NODISCARD std::string* release_symbol_name(); + void set_allocated_symbol_name(std::string* symbol_name); + private: + const std::string& _internal_symbol_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_symbol_name(const std::string& value); + std::string* _internal_mutable_symbol_name(); + public: + + // bytes content = 2; + void clear_content(); + const std::string& content() const; + template + void set_content(ArgT0&& arg0, ArgT... args); + std::string* mutable_content(); + PROTOBUF_NODISCARD std::string* release_content(); + void set_allocated_content(std::string* content); + private: + const std::string& _internal_content() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_content(const std::string& value); + std::string* _internal_mutable_content(); + public: + + // int32 allocation_index = 3; + void clear_allocation_index(); + int32_t allocation_index() const; + void set_allocation_index(int32_t value); + private: + int32_t _internal_allocation_index() const; + void _internal_set_allocation_index(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr symbol_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_; + int32_t allocation_index_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fexecutable_2eproto; +}; +// ------------------------------------------------------------------- + +class XlaRuntimeGpuExecutableProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.XlaRuntimeGpuExecutableProto) */ { + public: + inline XlaRuntimeGpuExecutableProto() : XlaRuntimeGpuExecutableProto(nullptr) {} + ~XlaRuntimeGpuExecutableProto() override; + explicit PROTOBUF_CONSTEXPR XlaRuntimeGpuExecutableProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaRuntimeGpuExecutableProto(const XlaRuntimeGpuExecutableProto& from); + XlaRuntimeGpuExecutableProto(XlaRuntimeGpuExecutableProto&& from) noexcept + : XlaRuntimeGpuExecutableProto() { + *this = ::std::move(from); + } + + inline XlaRuntimeGpuExecutableProto& operator=(const XlaRuntimeGpuExecutableProto& from) { + CopyFrom(from); + return *this; + } + inline XlaRuntimeGpuExecutableProto& operator=(XlaRuntimeGpuExecutableProto&& 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 XlaRuntimeGpuExecutableProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaRuntimeGpuExecutableProto* internal_default_instance() { + return reinterpret_cast( + &_XlaRuntimeGpuExecutableProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(XlaRuntimeGpuExecutableProto& a, XlaRuntimeGpuExecutableProto& b) { + a.Swap(&b); + } + inline void Swap(XlaRuntimeGpuExecutableProto* 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(XlaRuntimeGpuExecutableProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaRuntimeGpuExecutableProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaRuntimeGpuExecutableProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaRuntimeGpuExecutableProto& from) { + XlaRuntimeGpuExecutableProto::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(XlaRuntimeGpuExecutableProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.XlaRuntimeGpuExecutableProto"; + } + protected: + explicit XlaRuntimeGpuExecutableProto(::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 XlaRuntimeGpuExecutableProto_ConstantInfoProto ConstantInfoProto; + + // accessors ------------------------------------------------------- + + enum : int { + kConstantsFieldNumber = 5, + kGpuAsmTextFieldNumber = 3, + kGpuBinaryFieldNumber = 4, + kXlaRuntimeExecutableFieldNumber = 1, + kEntryFuncAttrsFieldNumber = 2, + }; + // repeated .xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto constants = 5; + int constants_size() const; + private: + int _internal_constants_size() const; + public: + void clear_constants(); + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* mutable_constants(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >* + mutable_constants(); + private: + const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& _internal_constants(int index) const; + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* _internal_add_constants(); + public: + const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& constants(int index) const; + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* add_constants(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >& + constants() const; + + // string gpu_asm_text = 3; + void clear_gpu_asm_text(); + const std::string& gpu_asm_text() const; + template + void set_gpu_asm_text(ArgT0&& arg0, ArgT... args); + std::string* mutable_gpu_asm_text(); + PROTOBUF_NODISCARD std::string* release_gpu_asm_text(); + void set_allocated_gpu_asm_text(std::string* gpu_asm_text); + private: + const std::string& _internal_gpu_asm_text() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_gpu_asm_text(const std::string& value); + std::string* _internal_mutable_gpu_asm_text(); + public: + + // bytes gpu_binary = 4; + void clear_gpu_binary(); + const std::string& gpu_binary() const; + template + void set_gpu_binary(ArgT0&& arg0, ArgT... args); + std::string* mutable_gpu_binary(); + PROTOBUF_NODISCARD std::string* release_gpu_binary(); + void set_allocated_gpu_binary(std::string* gpu_binary); + private: + const std::string& _internal_gpu_binary() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_gpu_binary(const std::string& value); + std::string* _internal_mutable_gpu_binary(); + public: + + // .xla.XlaRuntimeExecutableProto xla_runtime_executable = 1; + bool has_xla_runtime_executable() const; + private: + bool _internal_has_xla_runtime_executable() const; + public: + void clear_xla_runtime_executable(); + const ::xla::XlaRuntimeExecutableProto& xla_runtime_executable() const; + PROTOBUF_NODISCARD ::xla::XlaRuntimeExecutableProto* release_xla_runtime_executable(); + ::xla::XlaRuntimeExecutableProto* mutable_xla_runtime_executable(); + void set_allocated_xla_runtime_executable(::xla::XlaRuntimeExecutableProto* xla_runtime_executable); + private: + const ::xla::XlaRuntimeExecutableProto& _internal_xla_runtime_executable() const; + ::xla::XlaRuntimeExecutableProto* _internal_mutable_xla_runtime_executable(); + public: + void unsafe_arena_set_allocated_xla_runtime_executable( + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable); + ::xla::XlaRuntimeExecutableProto* unsafe_arena_release_xla_runtime_executable(); + + // .xla.EntryFunctionAttributes entry_func_attrs = 2; + bool has_entry_func_attrs() const; + private: + bool _internal_has_entry_func_attrs() const; + public: + void clear_entry_func_attrs(); + const ::xla::EntryFunctionAttributes& entry_func_attrs() const; + PROTOBUF_NODISCARD ::xla::EntryFunctionAttributes* release_entry_func_attrs(); + ::xla::EntryFunctionAttributes* mutable_entry_func_attrs(); + void set_allocated_entry_func_attrs(::xla::EntryFunctionAttributes* entry_func_attrs); + private: + const ::xla::EntryFunctionAttributes& _internal_entry_func_attrs() const; + ::xla::EntryFunctionAttributes* _internal_mutable_entry_func_attrs(); + public: + void unsafe_arena_set_allocated_entry_func_attrs( + ::xla::EntryFunctionAttributes* entry_func_attrs); + ::xla::EntryFunctionAttributes* unsafe_arena_release_entry_func_attrs(); + + // @@protoc_insertion_point(class_scope:xla.gpu.XlaRuntimeGpuExecutableProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto > constants_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr gpu_asm_text_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr gpu_binary_; + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable_; + ::xla::EntryFunctionAttributes* entry_func_attrs_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fexecutable_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// XlaRuntimeGpuExecutableProto_ConstantInfoProto + +// string symbol_name = 1; +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::clear_symbol_name() { + _impl_.symbol_name_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::symbol_name() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) + return _internal_symbol_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_symbol_name(ArgT0&& arg0, ArgT... args) { + + _impl_.symbol_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::mutable_symbol_name() { + std::string* _s = _internal_mutable_symbol_name(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_symbol_name() const { + return _impl_.symbol_name_.Get(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_set_symbol_name(const std::string& value) { + + _impl_.symbol_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_mutable_symbol_name() { + + return _impl_.symbol_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::release_symbol_name() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) + return _impl_.symbol_name_.Release(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_allocated_symbol_name(std::string* symbol_name) { + if (symbol_name != nullptr) { + + } else { + + } + _impl_.symbol_name_.SetAllocated(symbol_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.symbol_name_.IsDefault()) { + _impl_.symbol_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) +} + +// bytes content = 2; +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::clear_content() { + _impl_.content_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::content() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) + return _internal_content(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_content(ArgT0&& arg0, ArgT... args) { + + _impl_.content_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::mutable_content() { + std::string* _s = _internal_mutable_content(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_content() const { + return _impl_.content_.Get(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_set_content(const std::string& value) { + + _impl_.content_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_mutable_content() { + + return _impl_.content_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::release_content() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) + return _impl_.content_.Release(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_allocated_content(std::string* content) { + if (content != nullptr) { + + } else { + + } + _impl_.content_.SetAllocated(content, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.content_.IsDefault()) { + _impl_.content_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) +} + +// int32 allocation_index = 3; +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::clear_allocation_index() { + _impl_.allocation_index_ = 0; +} +inline int32_t XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_allocation_index() const { + return _impl_.allocation_index_; +} +inline int32_t XlaRuntimeGpuExecutableProto_ConstantInfoProto::allocation_index() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.allocation_index) + return _internal_allocation_index(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_set_allocation_index(int32_t value) { + + _impl_.allocation_index_ = value; +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_allocation_index(int32_t value) { + _internal_set_allocation_index(value); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.allocation_index) +} + +// ------------------------------------------------------------------- + +// XlaRuntimeGpuExecutableProto + +// .xla.XlaRuntimeExecutableProto xla_runtime_executable = 1; +inline bool XlaRuntimeGpuExecutableProto::_internal_has_xla_runtime_executable() const { + return this != internal_default_instance() && _impl_.xla_runtime_executable_ != nullptr; +} +inline bool XlaRuntimeGpuExecutableProto::has_xla_runtime_executable() const { + return _internal_has_xla_runtime_executable(); +} +inline const ::xla::XlaRuntimeExecutableProto& XlaRuntimeGpuExecutableProto::_internal_xla_runtime_executable() const { + const ::xla::XlaRuntimeExecutableProto* p = _impl_.xla_runtime_executable_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_XlaRuntimeExecutableProto_default_instance_); +} +inline const ::xla::XlaRuntimeExecutableProto& XlaRuntimeGpuExecutableProto::xla_runtime_executable() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) + return _internal_xla_runtime_executable(); +} +inline void XlaRuntimeGpuExecutableProto::unsafe_arena_set_allocated_xla_runtime_executable( + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_runtime_executable_); + } + _impl_.xla_runtime_executable_ = xla_runtime_executable; + if (xla_runtime_executable) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::release_xla_runtime_executable() { + + ::xla::XlaRuntimeExecutableProto* temp = _impl_.xla_runtime_executable_; + _impl_.xla_runtime_executable_ = 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::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::unsafe_arena_release_xla_runtime_executable() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) + + ::xla::XlaRuntimeExecutableProto* temp = _impl_.xla_runtime_executable_; + _impl_.xla_runtime_executable_ = nullptr; + return temp; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::_internal_mutable_xla_runtime_executable() { + + if (_impl_.xla_runtime_executable_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::XlaRuntimeExecutableProto>(GetArenaForAllocation()); + _impl_.xla_runtime_executable_ = p; + } + return _impl_.xla_runtime_executable_; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::mutable_xla_runtime_executable() { + ::xla::XlaRuntimeExecutableProto* _msg = _internal_mutable_xla_runtime_executable(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) + return _msg; +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_xla_runtime_executable(::xla::XlaRuntimeExecutableProto* xla_runtime_executable) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_runtime_executable_); + } + if (xla_runtime_executable) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(xla_runtime_executable)); + if (message_arena != submessage_arena) { + xla_runtime_executable = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, xla_runtime_executable, submessage_arena); + } + + } else { + + } + _impl_.xla_runtime_executable_ = xla_runtime_executable; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) +} + +// .xla.EntryFunctionAttributes entry_func_attrs = 2; +inline bool XlaRuntimeGpuExecutableProto::_internal_has_entry_func_attrs() const { + return this != internal_default_instance() && _impl_.entry_func_attrs_ != nullptr; +} +inline bool XlaRuntimeGpuExecutableProto::has_entry_func_attrs() const { + return _internal_has_entry_func_attrs(); +} +inline const ::xla::EntryFunctionAttributes& XlaRuntimeGpuExecutableProto::_internal_entry_func_attrs() const { + const ::xla::EntryFunctionAttributes* p = _impl_.entry_func_attrs_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_EntryFunctionAttributes_default_instance_); +} +inline const ::xla::EntryFunctionAttributes& XlaRuntimeGpuExecutableProto::entry_func_attrs() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) + return _internal_entry_func_attrs(); +} +inline void XlaRuntimeGpuExecutableProto::unsafe_arena_set_allocated_entry_func_attrs( + ::xla::EntryFunctionAttributes* entry_func_attrs) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.entry_func_attrs_); + } + _impl_.entry_func_attrs_ = entry_func_attrs; + if (entry_func_attrs) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::release_entry_func_attrs() { + + ::xla::EntryFunctionAttributes* temp = _impl_.entry_func_attrs_; + _impl_.entry_func_attrs_ = 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::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::unsafe_arena_release_entry_func_attrs() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) + + ::xla::EntryFunctionAttributes* temp = _impl_.entry_func_attrs_; + _impl_.entry_func_attrs_ = nullptr; + return temp; +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::_internal_mutable_entry_func_attrs() { + + if (_impl_.entry_func_attrs_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::EntryFunctionAttributes>(GetArenaForAllocation()); + _impl_.entry_func_attrs_ = p; + } + return _impl_.entry_func_attrs_; +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::mutable_entry_func_attrs() { + ::xla::EntryFunctionAttributes* _msg = _internal_mutable_entry_func_attrs(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) + return _msg; +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_entry_func_attrs(::xla::EntryFunctionAttributes* entry_func_attrs) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.entry_func_attrs_); + } + if (entry_func_attrs) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(entry_func_attrs)); + if (message_arena != submessage_arena) { + entry_func_attrs = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, entry_func_attrs, submessage_arena); + } + + } else { + + } + _impl_.entry_func_attrs_ = entry_func_attrs; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) +} + +// string gpu_asm_text = 3; +inline void XlaRuntimeGpuExecutableProto::clear_gpu_asm_text() { + _impl_.gpu_asm_text_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto::gpu_asm_text() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) + return _internal_gpu_asm_text(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto::set_gpu_asm_text(ArgT0&& arg0, ArgT... args) { + + _impl_.gpu_asm_text_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) +} +inline std::string* XlaRuntimeGpuExecutableProto::mutable_gpu_asm_text() { + std::string* _s = _internal_mutable_gpu_asm_text(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto::_internal_gpu_asm_text() const { + return _impl_.gpu_asm_text_.Get(); +} +inline void XlaRuntimeGpuExecutableProto::_internal_set_gpu_asm_text(const std::string& value) { + + _impl_.gpu_asm_text_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::_internal_mutable_gpu_asm_text() { + + return _impl_.gpu_asm_text_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::release_gpu_asm_text() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) + return _impl_.gpu_asm_text_.Release(); +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_gpu_asm_text(std::string* gpu_asm_text) { + if (gpu_asm_text != nullptr) { + + } else { + + } + _impl_.gpu_asm_text_.SetAllocated(gpu_asm_text, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.gpu_asm_text_.IsDefault()) { + _impl_.gpu_asm_text_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) +} + +// bytes gpu_binary = 4; +inline void XlaRuntimeGpuExecutableProto::clear_gpu_binary() { + _impl_.gpu_binary_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto::gpu_binary() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) + return _internal_gpu_binary(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto::set_gpu_binary(ArgT0&& arg0, ArgT... args) { + + _impl_.gpu_binary_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) +} +inline std::string* XlaRuntimeGpuExecutableProto::mutable_gpu_binary() { + std::string* _s = _internal_mutable_gpu_binary(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto::_internal_gpu_binary() const { + return _impl_.gpu_binary_.Get(); +} +inline void XlaRuntimeGpuExecutableProto::_internal_set_gpu_binary(const std::string& value) { + + _impl_.gpu_binary_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::_internal_mutable_gpu_binary() { + + return _impl_.gpu_binary_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::release_gpu_binary() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) + return _impl_.gpu_binary_.Release(); +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_gpu_binary(std::string* gpu_binary) { + if (gpu_binary != nullptr) { + + } else { + + } + _impl_.gpu_binary_.SetAllocated(gpu_binary, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.gpu_binary_.IsDefault()) { + _impl_.gpu_binary_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) +} + +// repeated .xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto constants = 5; +inline int XlaRuntimeGpuExecutableProto::_internal_constants_size() const { + return _impl_.constants_.size(); +} +inline int XlaRuntimeGpuExecutableProto::constants_size() const { + return _internal_constants_size(); +} +inline void XlaRuntimeGpuExecutableProto::clear_constants() { + _impl_.constants_.Clear(); +} +inline ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* XlaRuntimeGpuExecutableProto::mutable_constants(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _impl_.constants_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >* +XlaRuntimeGpuExecutableProto::mutable_constants() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return &_impl_.constants_; +} +inline const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& XlaRuntimeGpuExecutableProto::_internal_constants(int index) const { + return _impl_.constants_.Get(index); +} +inline const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& XlaRuntimeGpuExecutableProto::constants(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _internal_constants(index); +} +inline ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* XlaRuntimeGpuExecutableProto::_internal_add_constants() { + return _impl_.constants_.Add(); +} +inline ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* XlaRuntimeGpuExecutableProto::add_constants() { + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* _add = _internal_add_constants(); + // @@protoc_insertion_point(field_add:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >& +XlaRuntimeGpuExecutableProto::constants() const { + // @@protoc_insertion_point(field_list:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _impl_.constants_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fexecutable_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fft_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fft_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..6b2224a7b13f01070c36d2ee8bb32896096491dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fft_thunk.h @@ -0,0 +1,100 @@ +/* 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_SERVICE_GPU_FFT_THUNK_H_ +#define XLA_SERVICE_GPU_FFT_THUNK_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +struct FftPlan { + // CuFFT thread-safety requires that separate host threads not share plans; + // protect each plan with a mutex. + absl::Mutex mu; + std::unique_ptr plan ABSL_GUARDED_BY(mu); + float scale_factor ABSL_GUARDED_BY(mu); +}; + +class FftPlanCache { + public: + // Returnes Fft plan cached for the given device ordinal or creates a new one. + FftPlan* GetOrCreate(int device_ordinal) { + absl::MutexLock lock(&mu_); + std::unique_ptr& plan = fft_plans_[device_ordinal]; + if (!plan) plan = std::make_unique(); + return plan.get(); + } + + private: + absl::Mutex mu_; + absl::flat_hash_map> fft_plans_ + ABSL_GUARDED_BY(mu_); +}; + +// This class stores everything that StreamExecutor needs to launch an FFT. +// It is generated by IrEmitter. +// +// This is thread-compatible. +class FftThunk : public Thunk { + public: + // Constructs a thunk for launching an FFT on a stream. + // Semantics of null hlo_instruction argument are as in Thunk. + FftThunk(ThunkInfo thunk_info, FftType fft_type, + absl::Span fft_length, + const BufferAllocation::Slice& input_buffer, + const BufferAllocation::Slice& output_buffer, + const Shape& input_shape, const Shape& output_shape); + + FftThunk(const FftThunk&) = delete; // Cannot share fft_plan_ + FftThunk& operator=(const FftThunk&) = delete; // Cannot share fft_plan_ + + // Does the FFT for the thunk on "stream". + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const se::fft::Type fft_type_; + const std::vector fft_length_; + + FftPlanCache fft_plan_cache_; + + const BufferAllocation::Slice input_buffer_; + const BufferAllocation::Slice output_buffer_; + + const Shape input_shape_; + const Shape output_shape_; +}; + +Status RunFft(se::DeviceMemoryBase input, const Shape& input_shape, + se::DeviceMemoryBase output, const Shape& output_shape, + se::fft::Type fft_type, absl::Span fft_length, + int device_ordinal, FftPlanCache* fft_plan_cache, + se::Stream* stream, se::DeviceMemoryAllocator* memory_allocator); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FFT_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/for_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/for_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..13e44ede16fa128e958ffacc5801d0ba6e1528c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/for_thunk.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_SERVICE_GPU_FOR_THUNK_H_ +#define XLA_SERVICE_GPU_FOR_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/sequential_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// ForThunk executes 'loop_limit' invocations of 'body_thunk_sequence'. +class ForThunk : public Thunk { + public: + ForThunk(ThunkInfo thunk_info, int64_t loop_limit, + std::unique_ptr body_thunk_sequence); + ForThunk(const ForThunk&) = delete; + ForThunk& operator=(const ForThunk&) = delete; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + SequentialThunk* body_thunk_sequence() { return body_thunk_sequence_.get(); } + + private: + const int64_t loop_limit_; + std::unique_ptr body_thunk_sequence_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FOR_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fused_mha_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fused_mha_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..a1db1d23e16c9e2c6d01508d6f4f864e785b2aee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fused_mha_thunk.h @@ -0,0 +1,129 @@ +/* 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_SERVICE_GPU_FUSED_MHA_THUNK_H_ +#define XLA_SERVICE_GPU_FUSED_MHA_THUNK_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/gpu/gpu_fused_mha_runner.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a DNN +// fMHA. It is generated by IrEmitter. +// +// This is thread-compatible. +class FusedMHAThunk : public Thunk { + public: + // Constructs a thunk for launching a DNN FMHA. + FusedMHAThunk(ThunkInfo thunk_info, GpufMHAConfig config, + BufferAllocation::Slice lhs_bmm1_slice, + BufferAllocation::Slice rhs_bmm1_slice, + BufferAllocation::Slice rhs_bmm2_slice, + BufferAllocation::Slice output_slice, + BufferAllocation::Slice scratch_slice, + BufferAllocation::Slice mask_slice, /* may be null */ + BufferAllocation::Slice bias_slice /* may be null */, + BufferAllocation::Slice activation_slice /* may be null */); + + FusedMHAThunk(const FusedMHAThunk&) = delete; + FusedMHAThunk& operator=(const FusedMHAThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + BufferAllocation::Slice lhs_bmm1_buffer_; + BufferAllocation::Slice rhs_bmm1_buffer_; + BufferAllocation::Slice rhs_bmm2_buffer_; + BufferAllocation::Slice output_buffer_; + BufferAllocation::Slice scratch_buffer_; + BufferAllocation::Slice mask_buffer_; + BufferAllocation::Slice bias_buffer_; + BufferAllocation::Slice activation_buffer_; + + FusedMultiHeadedAttentionRunner& GetOrCreateRunner( + const stream_executor::Stream* stream); + + // FusedMHA config + const GpufMHAConfig config_; + absl::Mutex mu_; + absl::flat_hash_map> + runner_cache_ ABSL_GUARDED_BY(mu_); +}; + +class FusedMHABackwardThunk : public Thunk { + public: + // Constructs a thunk for launching a DNN FMHA backward. + FusedMHABackwardThunk(ThunkInfo thunk_info, GpufMHABackwardConfig config, + BufferAllocation::Slice bmm1_grad_gemm1_rhs_slice, + BufferAllocation::Slice bmm1_grad_gemm2_rhs_slice, + BufferAllocation::Slice bmm2_grad_gemm1_lhs_slice, + BufferAllocation::Slice bmm2_grad_gemm2_rhs_slice, + BufferAllocation::Slice d_output_slice, + BufferAllocation::Slice scratch_slice, + BufferAllocation::Slice d_bmm1_lhs_slice, + BufferAllocation::Slice d_bmm1_rhs_slice, + BufferAllocation::Slice d_bmm2_rhs_slice, + BufferAllocation::Slice d_S_slice, + BufferAllocation::Slice mask_slice, + BufferAllocation::Slice d_bias_slice); + + FusedMHABackwardThunk(const FusedMHABackwardThunk&) = delete; + FusedMHABackwardThunk& operator=(const FusedMHABackwardThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + BufferAllocation::Slice bmm1_grad_gemm1_rhs_buffer_; + BufferAllocation::Slice bmm1_grad_gemm2_rhs_buffer_; + BufferAllocation::Slice bmm2_grad_gemm1_lhs_buffer_; + BufferAllocation::Slice bmm2_grad_gemm2_rhs_buffer_; + BufferAllocation::Slice d_output_buffer_; + BufferAllocation::Slice scratch_buffer_; + BufferAllocation::Slice d_bmm1_lhs_buffer_; + BufferAllocation::Slice d_bmm1_rhs_buffer_; + BufferAllocation::Slice d_bmm2_rhs_buffer_; + BufferAllocation::Slice d_s_buffer_; + BufferAllocation::Slice mask_buffer_; + BufferAllocation::Slice d_bias_buffer_; + + FusedMultiHeadedAttentionBackwardRunner& GetOrCreateRunner( + const stream_executor::Stream* stream); + + // FusedMHA backward config + const GpufMHABackwardConfig config_; + absl::Mutex mu_; + absl::flat_hash_map> + runner_cache_ ABSL_GUARDED_BY(mu_); +}; +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_FUSED_MHA_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_merger.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_merger.h new file mode 100644 index 0000000000000000000000000000000000000000..cefb945ba8a8f9b60613d4e2b6bd49c6505123c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_merger.h @@ -0,0 +1,82 @@ +/* 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_SERVICE_GPU_FUSION_MERGER_H_ +#define XLA_SERVICE_GPU_FUSION_MERGER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// An HLO pass that attempts to merge fusion instructions to reduce memory +// bandwidth requirements and kernel launch overhead. +// +// Consider the example below. On the left-hand side, op A is the producer and +// ops B and C are its consumers. FusionMerger duplicates producer ops and fuses +// them into all consumers. The result is depicted on the right-hand side below. +// +// p p +// | / \ +// v / \ +// A +fusion+ +fusion+ +// / \ | A' | | A" | +// | | | | | | | | +// v v | v | | v | +// B C | B | | C | +// +------+ +------+ +// +// Op A has been cloned twice and fused with B and C. The kernel launch overhead +// is reduced from 3 to 2. The memory bandwidth requirements may be reduced. +// We trade 1 read of input(A) + 1 write and 2 reads of output(A) for 2 reads of +// input(A). In general the achieveable savings in memory bandwidth depend on +// the differences in memory read and written and the number of consumers. The +// FusionMeger pass takes this into account when making fusion decisions. +// +// The pass traverses the HLO module in reverse post-order (defs before uses). +// Fusion instructions are merged into their users if some conditions are met: +// * The result of merging the fusion instruction into its users would not +// increase bytes transferred. +// * Producer ops are fusible with _all_ consumers. If they are not fusible with +// at least one consumers, they won't be fused at all. +// * Producers are kLoop fusion ops. +// +// None of these restrictions are necessary for correctness. In fact, lifting +// the latter two could be beneficial. + +class FusionMerger : public HloModulePass { + public: + explicit FusionMerger(const se::DeviceDescription& d, + HloCostAnalysis::ShapeSizeFunction f) + : gpu_device_info_(d), shape_size_function_(f) {} + absl::string_view name() const override { return "fusion_merger"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::DeviceDescription gpu_device_info_; + HloCostAnalysis::ShapeSizeFunction shape_size_function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSION_MERGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_pipeline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..cecb1a9809127067365aab14189ddd85c7c16e0f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_pipeline.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_GPU_FUSION_PIPELINE_H_ +#define XLA_SERVICE_GPU_FUSION_PIPELINE_H_ + +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_pipeline.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Function wrapper around the (non-horizontal) XLA GPU fusion pipeline. +HloPassPipeline FusionPipeline( + const DebugOptions& debug_options, + HloCostAnalysis::ShapeSizeFunction shape_size_bytes_function, + const se::DeviceDescription& gpu_device_info); + +// Function wrapper around the horizontal XLA GPU fusion pipeline. +HloPassPipeline HorizontalFusionPipeline( + const se::DeviceDescription& gpu_device_info); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSION_PIPELINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_wrapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..3dd05047ce3428b801d902ef5038f5e598788778 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusion_wrapper.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_FUSION_WRAPPER_H_ +#define XLA_SERVICE_GPU_FUSION_WRAPPER_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Wraps leftover unfused instruction that are in the entry computation that +// have no LHLO equivalent in fusions containing just that instruction. +class FusionWrapper : public HloModulePass { + public: + absl::string_view name() const override { return "fusion-wrapper"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSION_WRAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/copy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/copy.h new file mode 100644 index 0000000000000000000000000000000000000000..173517d73384c7eae9e36aab5f29bd7a509f3b9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/copy.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_GPU_FUSIONS_COPY_H_ +#define XLA_SERVICE_GPU_FUSIONS_COPY_H_ + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/ir_emitter_context.h" + +namespace xla { +namespace gpu { + +// Special case of a fusion consisting only of a kCopy instruction that can be +// implemented using a memcpy. +class MemcpyFusion : public FusionInterface { + public: + MemcpyFusion(mlir::Value src, mlir::Value dst) : src_(src), dst_(dst) {} + + StatusOr Emit(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + KernelReuseCache& kernel_cache, + llvm::IRBuilder<>*) const final; + + private: + mlir::Value src_; + mlir::Value dst_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_COPY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/fusion_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/fusion_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..1cd527d0788081449b8d4edde66555a3d7bf2a6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/fusion_emitter.h @@ -0,0 +1,88 @@ +/* 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_SERVICE_GPU_FUSIONS_FUSION_EMITTER_H_ +#define XLA_SERVICE_GPU_FUSIONS_FUSION_EMITTER_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/gpu/kernel_reuse_cache.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/llvm_ir/ir_array.h" + +namespace xla { +namespace gpu { + +struct FusionEmissionResult { + std::vector> thunks; +}; + +class FusionInterface { + public: + virtual ~FusionInterface() = default; + + virtual StatusOr Emit( + IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, KernelReuseCache& kernel_cache, + llvm::IRBuilder<>* builder) const = 0; +}; + +class KernelFusionEmitterBase : public FusionInterface { + public: + // The downstream code that is used by this emitter operates on a mix of MLIR + // and HLO classes. Ideally this would not be the case, but it's hard to + // change. + StatusOr Emit(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + KernelReuseCache& kernel_cache, + llvm::IRBuilder<>* builder) const final; + virtual StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const = 0; + + protected: + virtual Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const = 0; + virtual int num_kernels() const { return 1; } +}; + +std::tuple, + std::vector /*outputs*/> +BuildKernelPrototype(IrEmitterContext& ir_emitter_context, + const std::string& suggested_name, + absl::Span arguments, + size_t num_inputs, + const LaunchDimensions& launch_dimensions, + llvm::IRBuilder<>* builder); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_FUSION_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/fusions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/fusions.h new file mode 100644 index 0000000000000000000000000000000000000000..1899fea07caa606790d594bd37e88e7d17d403d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/fusions.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_GPU_FUSIONS_FUSIONS_H_ +#define XLA_SERVICE_GPU_FUSIONS_FUSIONS_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" + +namespace xla { +namespace gpu { + +// Returns the emitter for the given fusion. Returns nullopt if the fusion +// type is not yet supported. +// `allocations` may be empty and `fusion_op` may be nullptr if buffer +// assignment didn't run yet. +std::optional> GetFusionEmitter( + HloFusionAnalysis& analysis, absl::Span allocations, + mlir::lmhlo::FusionOp fusion_op); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_FUSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/in_place_dynamic_update_slice.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/in_place_dynamic_update_slice.h new file mode 100644 index 0000000000000000000000000000000000000000..c6e15c2811b37aa76807bc972b8b0da8fc755de8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/in_place_dynamic_update_slice.h @@ -0,0 +1,77 @@ +/* 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_SERVICE_GPU_FUSIONS_IN_PLACE_DYNAMIC_UPDATE_SLICE_H_ +#define XLA_SERVICE_GPU_FUSIONS_IN_PLACE_DYNAMIC_UPDATE_SLICE_H_ + +#include + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emission_utils.h" + +namespace xla { +namespace gpu { + +// Fusion node where the root is either: +// 1. a dynamic-update-slice op +// 2. a bitcast of a dynamic-update-slice op +// 3. a tuple op returning the result of several dynamic-update-slice ops +// 4. a tuple op returning the result of several bitcast +// dynamic-update-slice ops +// +// Additionally, all the dynamic-update-slice ops have exactly one user. The +// fusion parameter that they update can have users (in addition to the +// dynamic-update-slice op) that read in either +// a. a dynamic-slice corresponding exactly to the slice of the parameter that +// is updated by the dynamic-update-slice op +// b. a dynamic-slice reading in a single element anywhere in the parameter. +// This is only allowed if the dynamic-update-slice op updates a single +// element +// +// In both cases, the additional users must not flow into any other output +// than the dynamic-slice-update corresponding to that particular slice of the +// parameter. +// +// The assumption is that each op's input (i.e. array to update) shares the +// same slice as its output. In this case, we have a special algorithm that +// modifies the output in place without touching the un-updated elements. The +// update slice is assumed to be the exact same for all the +// dynamic-update-slice ops. +class InPlaceDynamicUpdateSliceEmitter : public KernelFusionEmitterBase { + public: + explicit InPlaceDynamicUpdateSliceEmitter(const HloFusionAnalysis& analysis) + : dus_ops_( + GetOutputDefiningDynamicUpdateSlices(analysis.fusion_roots())) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override; + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + std::vector dus_ops_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_IN_PLACE_DYNAMIC_UPDATE_SLICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/input_slices.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/input_slices.h new file mode 100644 index 0000000000000000000000000000000000000000..886e23609732e65ccea2fe873c524ed1505c409a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/input_slices.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 XLA_SERVICE_GPU_FUSIONS_INPUT_SLICES_H_ +#define XLA_SERVICE_GPU_FUSIONS_INPUT_SLICES_H_ + +#include + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" + +namespace xla { +namespace gpu { + +// Generates code for input-fusible slices. +// +// Prerequisite: ROOT is either a slice or a tuple of slices. The input shapes +// of all ROOT slices need to be the same while their output shapes can be +// different. On the other hand, the input ranges of slices can be +// overlapping. Further generalization/specialization when the needs are seen +// in the future. +class InputSlicesFusion : public KernelFusionEmitterBase { + public: + explicit InputSlicesFusion(HloFusionAnalysis& analysis) + : analysis_(analysis) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override; + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_INPUT_SLICES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/loop.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/loop.h new file mode 100644 index 0000000000000000000000000000000000000000..6d539355c6a5d326bb3604584e5e832710e6e912 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/loop.h @@ -0,0 +1,55 @@ +/* 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_SERVICE_GPU_FUSIONS_LOOP_H_ +#define XLA_SERVICE_GPU_FUSIONS_LOOP_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emitter_context.h" + +namespace xla { +namespace gpu { + +// Generic loop fusion. +class LoopFusion : public KernelFusionEmitterBase { + public: + explicit LoopFusion(HloFusionAnalysis& analysis) : analysis_(analysis) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override; + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_LOOP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/reduction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..3b3e7897b2cc69f546bd8353afb62a8a8ef30a03 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/reduction.h @@ -0,0 +1,107 @@ +/* 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_SERVICE_GPU_FUSIONS_REDUCTION_H_ +#define XLA_SERVICE_GPU_FUSIONS_REDUCTION_H_ + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" + +namespace xla { +namespace gpu { + +// Generates code for reduction to contiguous dimensions. +// +// Row reduction uses the following algorithm described in CUDA-like +// pseudocode: +// +// ``` +// __global__ void reduce(int num_rows, float *in, float out) { +// __shared__ float[32] cache; +// int offset = blockDim.x * blockIdx.x + threadIdx.x; +// if (offset >= num_rows) return; +// int tile_bound = std::min(offset + kTileSizeX, num_rows); +// float accum = 0; +// for (int i=offset; i Emit( + IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, KernelReuseCache& kernel_cache, + llvm::IRBuilder<>* builder) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_REDUCTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/thunk_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/thunk_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0ac5dad3f9009951e4b0df97fb91dba665590a90 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/thunk_util.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 XLA_SERVICE_GPU_FUSIONS_THUNK_UTIL_H_ +#define XLA_SERVICE_GPU_FUSIONS_THUNK_UTIL_H_ + +#include +#include + +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/gpu/thunk.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Attempts to build an initializer constant for the given value. Returns an +// empty optional if the value is not a constant. +StatusOr>> BuildConstantInitializerThunk( + IrEmitterContext& ir_emitter_context, mlir::Operation* op, + mlir::Value init_value, mlir::Value dest); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_THUNK_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/tiling_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/tiling_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7765d02de9a6f1e22358968b7a29267589a17de0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/tiling_util.h @@ -0,0 +1,149 @@ +/*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_SERVICE_GPU_FUSIONS_TILING_UTIL_H_ +#define XLA_SERVICE_GPU_FUSIONS_TILING_UTIL_H_ + +#include + +#include "xla/service/gpu/kernel_mapping_scheme.h" +#include "xla/service/llvm_ir/ir_array.h" + +namespace xla { +namespace gpu { + +// Contains threading information. Note that for performance we might apply +// thread id "scaling" where the physical thread id (to achieve good SM +// occupancy) will differ from logical thread id. This struct contains +// logical thread ids, along with meta-information about the scaling applied. +struct TilingThreadIdInfo { + TilingThreadIdInfo(llvm::Value* thread_id, llvm::Value* thread_id_x, + llvm::Value* thread_id_y, llvm::Value* lane_id, + llvm::Value* block_id, llvm::Value* scaling) + : thread_id(thread_id), + thread_id_x(thread_id_x), + thread_id_y(thread_id_y), + lane_id(lane_id), + block_id(block_id), + scaling(scaling) {} + + llvm::Value* thread_id; + + // X-coordinate calculated from thread id: `thread_id % num_threads_x` + llvm::Value* thread_id_x; + + // Y-coordinate calculated from thread id: `thread_id / num_threads_x` + llvm::Value* thread_id_y; + + // Lane id: `thread_id % WarpSize` + llvm::Value* lane_id; + + // Block id. + llvm::Value* block_id; + + // Emits GEP into a shared memory, taking virtual thread scaling into + // account. Automatically inserts the first zero required by LLVM GEP. + // Defined on ThreadIdInfo to keep `scaling` private. + // + // Same semantics as CreateInBoundsGEP. + llvm::Value* GEPIntoSharedMemory( + llvm::IRBuilder<>* b, llvm::GlobalVariable* shared, + absl::Span idx_major_to_minor, + const llvm::Twine& name = "") const; + + // Calculate the pointee type of the llvm::Value returned by + // GEPIntoSharedMemory + llvm::Type* GEPIntoSharedMemoryType( + llvm::GlobalVariable* shared, + absl::Span idx_major_to_minor) const; + + private: + llvm::Value* scaling; +}; + +struct TilingKernelInfo { + // Tiling bounds. + std::array output_tile_bounds; + + // Starting tile, as calculated from block id only. + llvm_ir::IrArray::Index tile_origin; + + // Thread meta-info. + TilingThreadIdInfo thread_id_info; +}; + +// A function to generate the code to emit the entire tile. +// +// index: Absolute coordinate of the start of the tile in input. +// tile_dimensions: Size of the tile +using TileElementGenerator = + std::function tile_dimensions)>; + +// A function object to generate code to process one element in a tile. +// +// index: the index for the first output element of the current thread. +// y_loc: The y coordinate within a tile. +// x_loc: The x coordinate within a tile. +using EmitTileElementFunction = + std::function; + +// Emits code to iterate through a 2-dimensional tile with a given tile +// dimensions and given strides, and call the callback at each iteration., +// +// thread_id_y` and `thread_id_x` are the intra-tile coordinates for +// the first element to process, and `index` is the index for the origin of +// the tile. Emits bounds check to ensure that each processed element +// is within the boundary defined by `tile_dimensions`. +// +// Rough pseudocode: +// +// Given: tile_dimensions, x_offset, y_offset +// +// for (y = 0; y < tile_dimensions[0]; y += num_threads_y) { +// for (x = 0; x < tile_dimensions[1]; x++) { +// +// y_pos = y_offset + y +// x_pos = x_offset + x * stride +// +// if (x_loc < tile_width) { +// emit_elem_function(y_offset + y, x_loc); +// } +// } +// } +// +void EmitTile(llvm::IRBuilder<>* builder, const TilingScheme& tiling_scheme, + const llvm_ir::IrArray::Index& tile_origin_index, + const TilingThreadIdInfo& thread_id_info, + std::array tile_dimensions, + const EmitTileElementFunction& emit_elem_function); + +// Emits a kernel for the hlo instruction using the given kernel mapping +// scheme. +StatusOr EmitTilingKernel( + llvm::IRBuilder<>* builder, const TilingScheme& tiling_scheme, + llvm::Type* index_ty, const TileElementGenerator& tile_element_generator); + +llvm_ir::IrArray::Index GetUnnormalizedIndex( + const llvm_ir::IrArray::Index& normalized_shape_index, + const Shape& unnormalized_shape, llvm::IRBuilder<>* builder, + absl::Span dims_in_elems); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_TILING_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/transpose.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/transpose.h new file mode 100644 index 0000000000000000000000000000000000000000..85f7292d524077d6688dc5970346e3169e4da898 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/fusions/transpose.h @@ -0,0 +1,79 @@ +/* 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_SERVICE_GPU_FUSIONS_TRANSPOSE_H_ +#define XLA_SERVICE_GPU_FUSIONS_TRANSPOSE_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emitter_context.h" + +namespace xla { +namespace gpu { + +// Emits a kernel for the given hlo instruction using a tiled 0-2-1 transpose +// algorithm to improve the memory access patterns for the input parameters +// with a shape that is a 0-2-1 transpose of the output tensor shape. The +// caller is responsible for making sure that it is safe to apply the shared +// memory transpose on the input parameters. +// +// For the purpose of tiling, the output tensors have a logical shape of three +// components 0-2-1 while the relevant input parameters have a logical shape +// of three components 0-1-2 in the order major to minor. The x- and y- +// dimensions of the tensors are tiled in square tiles with an edge length +// `kTileSize`. Each thread block of `kTileSize` x `kNumRows` threads +// transposes one tile: each thread copies kTileSize/kNumRows elements from +// the input to a shared memory tile, then the otherwise "regular HLO kernel" +// reads from the shared memory instead of the original input. +// +// This is similar to the following CUDA algorithm in TensorFlow: +// https://goo.gl/MStRV6. +// +// `kTileSize` should usually be same as warp size. We currently choose 32 for +// `kTileSize` and 4 for `kNumRows`. The CUDA algorithm uses 8 for `kNumRows`. +// +// TODO(b/33320379): Here each block transposes 1 tile. It may be more +// efficient to launch fewer blocks so each transposes many tiles. +class TransposeFusion : public KernelFusionEmitterBase { + public: + explicit TransposeFusion(HloFusionAnalysis& analysis) : analysis_(analysis) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override { + return analysis_.GetLaunchDimensions(); + } + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_TRANSPOSE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_algorithm_picker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_algorithm_picker.h new file mode 100644 index 0000000000000000000000000000000000000000..9675d8968bfebf26762361a2d5880eef8e52929b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_algorithm_picker.h @@ -0,0 +1,78 @@ +/* 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_SERVICE_GPU_GEMM_ALGORITHM_PICKER_H_ +#define XLA_SERVICE_GPU_GEMM_ALGORITHM_PICKER_H_ + +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/autotune_results.pb.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) +#include "xla/service/gpu/gpu_conv_runner.h" +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#include "xla/stream_executor/gpu/redzone_allocator.h" +#endif + +namespace xla { +namespace gpu { + +StatusOr GetBestBlasAlgorithm( + se::Stream* stream, se::RedzoneAllocator& allocator, + std::optional gemm_str, + const AutotuneConfig& autotune_config, se::DeviceMemoryBase lhs_buffer, + se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer, + absl::Span algorithms, + const Shape& output_shape, const HloModuleConfig& hlo_module_config, + double beta, + const std::function( + const se::blas::AlgorithmType&)>& run_benchmark); + +// GemmAlgorithmPicker supports two modes: device and deviceless. +// In device mode, we run autotuning on the device and store autotune results. +// In deviceless mode, we pass in some information related to the device and +// use stored autotune results to rewrite Gemm instructions. If the required +// autotune result is not stored, then algorithm is set to kRuntimeAutotuning. +class GemmAlgorithmPicker : public HloModulePass { + public: + explicit GemmAlgorithmPicker(AutotuneConfig config) : config_(config) {} + + absl::string_view name() const override { return "gemm-algorithm-picker"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + AutotuneConfig config_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_ALGORITHM_PICKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_broadcast_folding_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_broadcast_folding_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..46fdc839738768befc3fd25fab706f4c30b37e32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_broadcast_folding_rewriter.h @@ -0,0 +1,51 @@ +/* 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_SERVICE_GPU_GEMM_BROADCAST_FOLDING_REWRITER_H_ +#define XLA_SERVICE_GPU_GEMM_BROADCAST_FOLDING_REWRITER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// cuBLAS GEMM has support for strided batched calls, where the stride is used +// to determine the offset between the batches. +// +// This allows (kCustomCall:gemm A kBroadcast(B)) or +// (kCustomCall:gemm kBroadcast(A) B) +// to be rewritten as (kCustomCall:gemm A B) with a zero stride for the +// broadcasted operand if the broadcast operates on all the batch dimensions. +// +// This pattern matches the above case and removes the unnecessary broadcast. +class GemmBroadcastFoldingRewriter : public HloModulePass { + public: + absl::string_view name() const override { + return "cublas-gemm-broadcast-folding-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_BROADCAST_FOLDING_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..65efd940450e468ed4424f727351da8ff5b0b2e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_rewriter.h @@ -0,0 +1,62 @@ +/* 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_SERVICE_GPU_GEMM_REWRITER_H_ +#define XLA_SERVICE_GPU_GEMM_REWRITER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// cuBLAS GEMM in the most general form can run the following operation: +// +// (kAdd +// (kMultiply (kDot A B) alpha) +// (kMultiply C beta)) +// +// where A, B, C are matrixes and `alpha` and `beta` are host constants. +// The additional requirement is that C has no other users (otherwise, +// it does not make sense to fuse it inside the custom call). +// +// Both multiplication and addition can be avoided (equivalent to setting +// `alpha` to one and `beta` to zero). +// +// This pass pattern-matches the most general form of this instruction +// (we assume transposes are already folded), and rewrites it into a custom call +// where (A, B, C) are three operands respectively, and `alpha` and `beta` are +// stored in the backend config. +class GemmRewriter : public HloModulePass { + public: + explicit GemmRewriter(se::GpuComputeCapability gpu_version); + absl::string_view name() const override { return "cublas-gemm-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_rewriter_triton.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_rewriter_triton.h new file mode 100644 index 0000000000000000000000000000000000000000..db52fa54aadb31456780a82e24b3a9273d10caec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_rewriter_triton.h @@ -0,0 +1,173 @@ +/* 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_SERVICE_GPU_GEMM_REWRITER_TRITON_H_ +#define XLA_SERVICE_GPU_GEMM_REWRITER_TRITON_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/autotuning.pb.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" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/instruction_fusion.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// Tells if f(a+b) == f(a) + f(b). +bool IsDistributiveOverAddition(const HloInstruction& hlo); + +// Allowlist of unary elementwise operations supported by Triton GEMM codegen. +std::vector TritonSupportedUnaryElementwise(PrimitiveType); + +// Allowlist of binary elementwise operations supported by Triton GEMM codegen. +std::vector TritonSupportedBinaryElementwise(PrimitiveType); + +// Allowlist of ternary elementwise operations supported by Triton GEMM codegen. +std::vector TritonSupportedTernaryElementwise(PrimitiveType); + +// Data types that are supported by the Triton emitters. +bool IsTritonSupportedDataType(PrimitiveType, se::GpuComputeCapability); + +// Checks elementwise operation against all supported by Triton GEMM codegen. +bool IsTritonSupportedElementwise(HloOpcode, PrimitiveType); + +// Filters GEMMs which can be handled using Triton. +FusionDecision CanTritonHandleGEMM(const HloInstruction&, + se::GpuComputeCapability gpu_version); + +// Filters GEMMs which are better to handle using Triton. +bool ShouldTritonHandleGEMM(HloInstruction&, + se::GpuComputeCapability gpu_version); + +class TensorIterationSpec { + public: + // Description of basic iteration: `count` elements separated by `stride`. + struct IterationSpecFragment { + int64_t stride; + int64_t count; + int64_t slice_start; + int64_t slice_limit; + // Logical subfragments when this iteration is composed + // of several HLO dimensions. + std::vector subfragments; + + bool is_sliced() const { return count != slice_limit - slice_start; } + bool operator!=(const IterationSpecFragment& other) const; + std::string ToString() const; + }; + // Description of complex iteration over a sequence of several strides. + // Describes a logically contiguous dimension of a tensor physically + // separated into multiple fragments by other dimensions. + using DimIterationSpec = std::vector; + + using StorageType = absl::flat_hash_map; + const DimIterationSpec& operator[](const int dimension) const { + return dim_iteration_specs_.at(dimension); + } + DimIterationSpec& operator[](const int dimension) { + return dim_iteration_specs_[dimension]; + } + const StorageType& Storage() const { return dim_iteration_specs_; } + void RemoveEmptyDimensions() { + absl::erase_if(dim_iteration_specs_, + [](const auto& it) { return it.second.empty(); }); + } + + // Compares physical layouts of tensors ignoring subfragments of dimensions. + bool operator==(const TensorIterationSpec& other) const; + + std::string ToString() const; + + private: + StorageType dim_iteration_specs_; +}; + +// Analysis of tensor iteration orders within tiled fusions. +class TritonFusionAnalysis { + Status ExecuteForDotFusion(const HloInstruction& dot, int split_k); + Status ExecuteForSoftmaxFusion(const HloInstruction& root); + + public: + // Execute the analysis of a fusion computation. + // `split_k` indicates whether this operation was converted to the split-K + // form and tells the analysis how to interpret the batch dimensions. + static StatusOr Execute( + const HloComputation& computation, int split_k = 1); + + // A scope is an HLO graph that can be tiled efficiently using same or + // compatible tile shapes on all operations. GEMM fusion has 3 scopes + // defined by left operand, right operand and output. + enum class Scope { LHS = 0, RHS = 1, OUTPUT = 2 }; + + using IterationSpecByInstructionMap = + ConstHloInstructionMap; + using IterationSpecByInstructionByScopeMap = + std::map; + + // Every parameter requires a separate piece of shared memory for asynchronous + // loads. Multiple parameters are approximately equivalent to multiple + // pipeline stages. + static constexpr int kMaxParameterPerScope = 4; + + // Scope -> HLO -> dot dimension number -> iteration spec at the HLO's output. + const TensorIterationSpec::DimIterationSpec* IterSpec(Scope scope, + const HloInstruction*, + int dimension) const; + // Parameter HLO instructions used in a scope of `dot`. + const ConstHloInstructionSet& ScopeParameters(const Scope scope) const { + return parameters_.at(scope); + } + + std::string ToString() const; + + private: + IterationSpecByInstructionByScopeMap iter_specs_; + // HLO computation parameters per scope. + std::map parameters_; +}; + +// Rewrite compatible dot() calls into custom calls with fused computations +// that target Triton-based matmul emitter. +class GemmRewriterTriton : public HloModulePass { + public: + explicit GemmRewriterTriton(se::GpuComputeCapability gpu_version) + : gpu_version_(gpu_version) {} + absl::string_view name() const override { return "triton-gemm-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_REWRITER_TRITON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..548ff737425557d154f208ae82ea76cdfd8b2cfb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gemm_thunk.h @@ -0,0 +1,57 @@ +/* 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_SERVICE_GPU_GEMM_THUNK_H_ +#define XLA_SERVICE_GPU_GEMM_THUNK_H_ + +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/matmul_utils.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// This is thread-compatible. +class GemmThunk : public Thunk { + public: + // Constructs a thunk that computes "output = (lhs rhs) * alpha" using + // BLAS gemm (alpha is stored in the instruction GemmBackendConfig). + GemmThunk(ThunkInfo thunk_info, GemmConfig config, + const BufferAllocation::Slice& lhs_buffer, + const BufferAllocation::Slice& rhs_buffer, + const BufferAllocation::Slice& output_buffer, bool deterministic); + + GemmThunk(const GemmThunk&) = delete; + GemmThunk& operator=(const GemmThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + + private: + const GemmConfig config_; + const BufferAllocation::Slice lhs_buffer_; + const BufferAllocation::Slice rhs_buffer_; + const BufferAllocation::Slice output_buffer_; + // Whether to run deterministically. + const bool deterministic_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_all_gather_optimizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_all_gather_optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..717c6088f06e4b5f87bcab369a34033fc09fee77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_all_gather_optimizer.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_GPU_ALL_GATHER_OPTIMIZER_H_ +#define XLA_SERVICE_GPU_GPU_ALL_GATHER_OPTIMIZER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Transforms binary_op(all-gather(reduce_scatter(a)), +// all-gather(reduce_scatter(b))) to allgather(binary_op(reduce_scatter(a), +// reduce_scatter(b))) + +class AllGatherOptimizer : public HloModulePass { + public: + AllGatherOptimizer() = default; + absl::string_view name() const override { return "all-gather-optimizer"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_ALL_GATHER_OPTIMIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_asm_opts_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_asm_opts_util.h new file mode 100644 index 0000000000000000000000000000000000000000..22a08f8657a99b7006134011a871d9aee3b6581b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_asm_opts_util.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_SERVICE_GPU_GPU_ASM_OPTS_UTIL_H_ +#define XLA_SERVICE_GPU_GPU_ASM_OPTS_UTIL_H_ + +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Create GpuAsmOpts out of DebugOptions. +stream_executor::GpuAsmOpts PtxOptsFromDebugOptions( + const DebugOptions& debug_options); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_ASM_OPTS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_async_collective_annotator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_async_collective_annotator.h new file mode 100644 index 0000000000000000000000000000000000000000..94955ff6395b616826edfa3bff63b36487ac11a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_async_collective_annotator.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_GPU_GPU_ASYNC_COLLECTIVE_ANNOTATOR_H_ +#define XLA_SERVICE_GPU_GPU_ASYNC_COLLECTIVE_ANNOTATOR_H_ + +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Annotate async collectives with CollectiveBackendConfig. +class GpuAsyncCollectiveAnnotator : public HloModulePass { + public: + explicit GpuAsyncCollectiveAnnotator(HloPredicate is_collective_async) + : is_collective_async_(std::move(is_collective_async)) {} + absl::string_view name() const override { + return "gpu-async-collective-annotator"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + HloPredicate is_collective_async_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_ASYNC_COLLECTIVE_ANNOTATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_autotuning.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_autotuning.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..620b191fd4a9cfac804eb7133247471a7ccb6e71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_autotuning.pb.h @@ -0,0 +1,1494 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/gpu_autotuning.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fgpu_5fautotuning_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" +#include "xla/service/hlo.pb.h" +#include "xla/xla_data.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +namespace xla { +namespace gpu { +class AlgorithmDenylist; +struct AlgorithmDenylistDefaultTypeInternal; +extern AlgorithmDenylistDefaultTypeInternal _AlgorithmDenylist_default_instance_; +class AlgorithmDenylistEntry; +struct AlgorithmDenylistEntryDefaultTypeInternal; +extern AlgorithmDenylistEntryDefaultTypeInternal _AlgorithmDenylistEntry_default_instance_; +class ConvInstructionLog; +struct ConvInstructionLogDefaultTypeInternal; +extern ConvInstructionLogDefaultTypeInternal _ConvInstructionLog_default_instance_; +class DenylistedAlgorithm; +struct DenylistedAlgorithmDefaultTypeInternal; +extern DenylistedAlgorithmDefaultTypeInternal _DenylistedAlgorithm_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::AlgorithmDenylist* Arena::CreateMaybeMessage<::xla::gpu::AlgorithmDenylist>(Arena*); +template<> ::xla::gpu::AlgorithmDenylistEntry* Arena::CreateMaybeMessage<::xla::gpu::AlgorithmDenylistEntry>(Arena*); +template<> ::xla::gpu::ConvInstructionLog* Arena::CreateMaybeMessage<::xla::gpu::ConvInstructionLog>(Arena*); +template<> ::xla::gpu::DenylistedAlgorithm* Arena::CreateMaybeMessage<::xla::gpu::DenylistedAlgorithm>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +// =================================================================== + +class ConvInstructionLog final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.ConvInstructionLog) */ { + public: + inline ConvInstructionLog() : ConvInstructionLog(nullptr) {} + ~ConvInstructionLog() override; + explicit PROTOBUF_CONSTEXPR ConvInstructionLog(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ConvInstructionLog(const ConvInstructionLog& from); + ConvInstructionLog(ConvInstructionLog&& from) noexcept + : ConvInstructionLog() { + *this = ::std::move(from); + } + + inline ConvInstructionLog& operator=(const ConvInstructionLog& from) { + CopyFrom(from); + return *this; + } + inline ConvInstructionLog& operator=(ConvInstructionLog&& 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 ConvInstructionLog& default_instance() { + return *internal_default_instance(); + } + static inline const ConvInstructionLog* internal_default_instance() { + return reinterpret_cast( + &_ConvInstructionLog_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(ConvInstructionLog& a, ConvInstructionLog& b) { + a.Swap(&b); + } + inline void Swap(ConvInstructionLog* 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(ConvInstructionLog* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ConvInstructionLog* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ConvInstructionLog& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ConvInstructionLog& from) { + ConvInstructionLog::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(ConvInstructionLog* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.ConvInstructionLog"; + } + protected: + explicit ConvInstructionLog(::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 { + kOperandShapesFieldNumber = 2, + kResultAddressesFieldNumber = 3, + kOperandAddressesFieldNumber = 4, + kInstructionFieldNumber = 1, + }; + // repeated .xla.ShapeProto operand_shapes = 2; + int operand_shapes_size() const; + private: + int _internal_operand_shapes_size() const; + public: + void clear_operand_shapes(); + ::xla::ShapeProto* mutable_operand_shapes(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >* + mutable_operand_shapes(); + private: + const ::xla::ShapeProto& _internal_operand_shapes(int index) const; + ::xla::ShapeProto* _internal_add_operand_shapes(); + public: + const ::xla::ShapeProto& operand_shapes(int index) const; + ::xla::ShapeProto* add_operand_shapes(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >& + operand_shapes() const; + + // repeated uint64 result_addresses = 3; + int result_addresses_size() const; + private: + int _internal_result_addresses_size() const; + public: + void clear_result_addresses(); + private: + uint64_t _internal_result_addresses(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + _internal_result_addresses() const; + void _internal_add_result_addresses(uint64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + _internal_mutable_result_addresses(); + public: + uint64_t result_addresses(int index) const; + void set_result_addresses(int index, uint64_t value); + void add_result_addresses(uint64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + result_addresses() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + mutable_result_addresses(); + + // repeated uint64 operand_addresses = 4; + int operand_addresses_size() const; + private: + int _internal_operand_addresses_size() const; + public: + void clear_operand_addresses(); + private: + uint64_t _internal_operand_addresses(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + _internal_operand_addresses() const; + void _internal_add_operand_addresses(uint64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + _internal_mutable_operand_addresses(); + public: + uint64_t operand_addresses(int index) const; + void set_operand_addresses(int index, uint64_t value); + void add_operand_addresses(uint64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + operand_addresses() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + mutable_operand_addresses(); + + // .xla.HloInstructionProto instruction = 1; + bool has_instruction() const; + private: + bool _internal_has_instruction() const; + public: + void clear_instruction(); + const ::xla::HloInstructionProto& instruction() const; + PROTOBUF_NODISCARD ::xla::HloInstructionProto* release_instruction(); + ::xla::HloInstructionProto* mutable_instruction(); + void set_allocated_instruction(::xla::HloInstructionProto* instruction); + private: + const ::xla::HloInstructionProto& _internal_instruction() const; + ::xla::HloInstructionProto* _internal_mutable_instruction(); + public: + void unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction); + ::xla::HloInstructionProto* unsafe_arena_release_instruction(); + + // @@protoc_insertion_point(class_scope:xla.gpu.ConvInstructionLog) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto > operand_shapes_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t > result_addresses_; + mutable std::atomic _result_addresses_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t > operand_addresses_; + mutable std::atomic _operand_addresses_cached_byte_size_; + ::xla::HloInstructionProto* instruction_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class DenylistedAlgorithm final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.DenylistedAlgorithm) */ { + public: + inline DenylistedAlgorithm() : DenylistedAlgorithm(nullptr) {} + ~DenylistedAlgorithm() override; + explicit PROTOBUF_CONSTEXPR DenylistedAlgorithm(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DenylistedAlgorithm(const DenylistedAlgorithm& from); + DenylistedAlgorithm(DenylistedAlgorithm&& from) noexcept + : DenylistedAlgorithm() { + *this = ::std::move(from); + } + + inline DenylistedAlgorithm& operator=(const DenylistedAlgorithm& from) { + CopyFrom(from); + return *this; + } + inline DenylistedAlgorithm& operator=(DenylistedAlgorithm&& 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 DenylistedAlgorithm& default_instance() { + return *internal_default_instance(); + } + static inline const DenylistedAlgorithm* internal_default_instance() { + return reinterpret_cast( + &_DenylistedAlgorithm_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(DenylistedAlgorithm& a, DenylistedAlgorithm& b) { + a.Swap(&b); + } + inline void Swap(DenylistedAlgorithm* 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(DenylistedAlgorithm* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DenylistedAlgorithm* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DenylistedAlgorithm& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DenylistedAlgorithm& from) { + DenylistedAlgorithm::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(DenylistedAlgorithm* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.DenylistedAlgorithm"; + } + protected: + explicit DenylistedAlgorithm(::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 { + kIdFieldNumber = 1, + kTensorOpsFieldNumber = 2, + }; + // int64 id = 1; + void clear_id(); + int64_t id() const; + void set_id(int64_t value); + private: + int64_t _internal_id() const; + void _internal_set_id(int64_t value); + public: + + // bool tensor_ops = 2; + void clear_tensor_ops(); + bool tensor_ops() const; + void set_tensor_ops(bool value); + private: + bool _internal_tensor_ops() const; + void _internal_set_tensor_ops(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.DenylistedAlgorithm) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t id_; + bool tensor_ops_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AlgorithmDenylistEntry final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.AlgorithmDenylistEntry) */ { + public: + inline AlgorithmDenylistEntry() : AlgorithmDenylistEntry(nullptr) {} + ~AlgorithmDenylistEntry() override; + explicit PROTOBUF_CONSTEXPR AlgorithmDenylistEntry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AlgorithmDenylistEntry(const AlgorithmDenylistEntry& from); + AlgorithmDenylistEntry(AlgorithmDenylistEntry&& from) noexcept + : AlgorithmDenylistEntry() { + *this = ::std::move(from); + } + + inline AlgorithmDenylistEntry& operator=(const AlgorithmDenylistEntry& from) { + CopyFrom(from); + return *this; + } + inline AlgorithmDenylistEntry& operator=(AlgorithmDenylistEntry&& 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 AlgorithmDenylistEntry& default_instance() { + return *internal_default_instance(); + } + static inline const AlgorithmDenylistEntry* internal_default_instance() { + return reinterpret_cast( + &_AlgorithmDenylistEntry_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(AlgorithmDenylistEntry& a, AlgorithmDenylistEntry& b) { + a.Swap(&b); + } + inline void Swap(AlgorithmDenylistEntry* 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(AlgorithmDenylistEntry* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AlgorithmDenylistEntry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AlgorithmDenylistEntry& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AlgorithmDenylistEntry& from) { + AlgorithmDenylistEntry::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(AlgorithmDenylistEntry* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.AlgorithmDenylistEntry"; + } + protected: + explicit AlgorithmDenylistEntry(::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 { + kAlgosFieldNumber = 4, + kHloFieldNumber = 1, + kBlasVersionFieldNumber = 5, + kCcFieldNumber = 2, + kCudnnVersionFieldNumber = 3, + }; + // repeated .xla.gpu.DenylistedAlgorithm algos = 4; + int algos_size() const; + private: + int _internal_algos_size() const; + public: + void clear_algos(); + ::xla::gpu::DenylistedAlgorithm* mutable_algos(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >* + mutable_algos(); + private: + const ::xla::gpu::DenylistedAlgorithm& _internal_algos(int index) const; + ::xla::gpu::DenylistedAlgorithm* _internal_add_algos(); + public: + const ::xla::gpu::DenylistedAlgorithm& algos(int index) const; + ::xla::gpu::DenylistedAlgorithm* add_algos(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >& + algos() const; + + // string hlo = 1; + 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: + + // string blas_version = 5; + 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: + + // .xla.ComputeCapability cc = 2; + bool has_cc() const; + private: + bool _internal_has_cc() const; + public: + void clear_cc(); + const ::xla::ComputeCapability& cc() const; + PROTOBUF_NODISCARD ::xla::ComputeCapability* release_cc(); + ::xla::ComputeCapability* mutable_cc(); + void set_allocated_cc(::xla::ComputeCapability* cc); + private: + const ::xla::ComputeCapability& _internal_cc() const; + ::xla::ComputeCapability* _internal_mutable_cc(); + public: + void unsafe_arena_set_allocated_cc( + ::xla::ComputeCapability* cc); + ::xla::ComputeCapability* unsafe_arena_release_cc(); + + // .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(); + + // @@protoc_insertion_point(class_scope:xla.gpu.AlgorithmDenylistEntry) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm > algos_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr hlo_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr blas_version_; + ::xla::ComputeCapability* cc_; + ::xla::CudnnVersion* cudnn_version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AlgorithmDenylist final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.AlgorithmDenylist) */ { + public: + inline AlgorithmDenylist() : AlgorithmDenylist(nullptr) {} + ~AlgorithmDenylist() override; + explicit PROTOBUF_CONSTEXPR AlgorithmDenylist(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AlgorithmDenylist(const AlgorithmDenylist& from); + AlgorithmDenylist(AlgorithmDenylist&& from) noexcept + : AlgorithmDenylist() { + *this = ::std::move(from); + } + + inline AlgorithmDenylist& operator=(const AlgorithmDenylist& from) { + CopyFrom(from); + return *this; + } + inline AlgorithmDenylist& operator=(AlgorithmDenylist&& 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 AlgorithmDenylist& default_instance() { + return *internal_default_instance(); + } + static inline const AlgorithmDenylist* internal_default_instance() { + return reinterpret_cast( + &_AlgorithmDenylist_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(AlgorithmDenylist& a, AlgorithmDenylist& b) { + a.Swap(&b); + } + inline void Swap(AlgorithmDenylist* 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(AlgorithmDenylist* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AlgorithmDenylist* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AlgorithmDenylist& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AlgorithmDenylist& from) { + AlgorithmDenylist::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(AlgorithmDenylist* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.AlgorithmDenylist"; + } + protected: + explicit AlgorithmDenylist(::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 { + kEntriesFieldNumber = 1, + }; + // repeated .xla.gpu.AlgorithmDenylistEntry entries = 1; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + ::xla::gpu::AlgorithmDenylistEntry* mutable_entries(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >* + mutable_entries(); + private: + const ::xla::gpu::AlgorithmDenylistEntry& _internal_entries(int index) const; + ::xla::gpu::AlgorithmDenylistEntry* _internal_add_entries(); + public: + const ::xla::gpu::AlgorithmDenylistEntry& entries(int index) const; + ::xla::gpu::AlgorithmDenylistEntry* add_entries(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >& + entries() const; + + // @@protoc_insertion_point(class_scope:xla.gpu.AlgorithmDenylist) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry > entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// ConvInstructionLog + +// .xla.HloInstructionProto instruction = 1; +inline bool ConvInstructionLog::_internal_has_instruction() const { + return this != internal_default_instance() && _impl_.instruction_ != nullptr; +} +inline bool ConvInstructionLog::has_instruction() const { + return _internal_has_instruction(); +} +inline const ::xla::HloInstructionProto& ConvInstructionLog::_internal_instruction() const { + const ::xla::HloInstructionProto* p = _impl_.instruction_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloInstructionProto_default_instance_); +} +inline const ::xla::HloInstructionProto& ConvInstructionLog::instruction() const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.instruction) + return _internal_instruction(); +} +inline void ConvInstructionLog::unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + _impl_.instruction_ = instruction; + if (instruction) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.ConvInstructionLog.instruction) +} +inline ::xla::HloInstructionProto* ConvInstructionLog::release_instruction() { + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = 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::HloInstructionProto* ConvInstructionLog::unsafe_arena_release_instruction() { + // @@protoc_insertion_point(field_release:xla.gpu.ConvInstructionLog.instruction) + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = nullptr; + return temp; +} +inline ::xla::HloInstructionProto* ConvInstructionLog::_internal_mutable_instruction() { + + if (_impl_.instruction_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloInstructionProto>(GetArenaForAllocation()); + _impl_.instruction_ = p; + } + return _impl_.instruction_; +} +inline ::xla::HloInstructionProto* ConvInstructionLog::mutable_instruction() { + ::xla::HloInstructionProto* _msg = _internal_mutable_instruction(); + // @@protoc_insertion_point(field_mutable:xla.gpu.ConvInstructionLog.instruction) + return _msg; +} +inline void ConvInstructionLog::set_allocated_instruction(::xla::HloInstructionProto* instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + if (instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(instruction)); + if (message_arena != submessage_arena) { + instruction = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, instruction, submessage_arena); + } + + } else { + + } + _impl_.instruction_ = instruction; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.ConvInstructionLog.instruction) +} + +// repeated .xla.ShapeProto operand_shapes = 2; +inline int ConvInstructionLog::_internal_operand_shapes_size() const { + return _impl_.operand_shapes_.size(); +} +inline int ConvInstructionLog::operand_shapes_size() const { + return _internal_operand_shapes_size(); +} +inline ::xla::ShapeProto* ConvInstructionLog::mutable_operand_shapes(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.ConvInstructionLog.operand_shapes) + return _impl_.operand_shapes_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >* +ConvInstructionLog::mutable_operand_shapes() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.ConvInstructionLog.operand_shapes) + return &_impl_.operand_shapes_; +} +inline const ::xla::ShapeProto& ConvInstructionLog::_internal_operand_shapes(int index) const { + return _impl_.operand_shapes_.Get(index); +} +inline const ::xla::ShapeProto& ConvInstructionLog::operand_shapes(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.operand_shapes) + return _internal_operand_shapes(index); +} +inline ::xla::ShapeProto* ConvInstructionLog::_internal_add_operand_shapes() { + return _impl_.operand_shapes_.Add(); +} +inline ::xla::ShapeProto* ConvInstructionLog::add_operand_shapes() { + ::xla::ShapeProto* _add = _internal_add_operand_shapes(); + // @@protoc_insertion_point(field_add:xla.gpu.ConvInstructionLog.operand_shapes) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >& +ConvInstructionLog::operand_shapes() const { + // @@protoc_insertion_point(field_list:xla.gpu.ConvInstructionLog.operand_shapes) + return _impl_.operand_shapes_; +} + +// repeated uint64 result_addresses = 3; +inline int ConvInstructionLog::_internal_result_addresses_size() const { + return _impl_.result_addresses_.size(); +} +inline int ConvInstructionLog::result_addresses_size() const { + return _internal_result_addresses_size(); +} +inline void ConvInstructionLog::clear_result_addresses() { + _impl_.result_addresses_.Clear(); +} +inline uint64_t ConvInstructionLog::_internal_result_addresses(int index) const { + return _impl_.result_addresses_.Get(index); +} +inline uint64_t ConvInstructionLog::result_addresses(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.result_addresses) + return _internal_result_addresses(index); +} +inline void ConvInstructionLog::set_result_addresses(int index, uint64_t value) { + _impl_.result_addresses_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.gpu.ConvInstructionLog.result_addresses) +} +inline void ConvInstructionLog::_internal_add_result_addresses(uint64_t value) { + _impl_.result_addresses_.Add(value); +} +inline void ConvInstructionLog::add_result_addresses(uint64_t value) { + _internal_add_result_addresses(value); + // @@protoc_insertion_point(field_add:xla.gpu.ConvInstructionLog.result_addresses) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::_internal_result_addresses() const { + return _impl_.result_addresses_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::result_addresses() const { + // @@protoc_insertion_point(field_list:xla.gpu.ConvInstructionLog.result_addresses) + return _internal_result_addresses(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::_internal_mutable_result_addresses() { + return &_impl_.result_addresses_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::mutable_result_addresses() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.ConvInstructionLog.result_addresses) + return _internal_mutable_result_addresses(); +} + +// repeated uint64 operand_addresses = 4; +inline int ConvInstructionLog::_internal_operand_addresses_size() const { + return _impl_.operand_addresses_.size(); +} +inline int ConvInstructionLog::operand_addresses_size() const { + return _internal_operand_addresses_size(); +} +inline void ConvInstructionLog::clear_operand_addresses() { + _impl_.operand_addresses_.Clear(); +} +inline uint64_t ConvInstructionLog::_internal_operand_addresses(int index) const { + return _impl_.operand_addresses_.Get(index); +} +inline uint64_t ConvInstructionLog::operand_addresses(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.operand_addresses) + return _internal_operand_addresses(index); +} +inline void ConvInstructionLog::set_operand_addresses(int index, uint64_t value) { + _impl_.operand_addresses_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.gpu.ConvInstructionLog.operand_addresses) +} +inline void ConvInstructionLog::_internal_add_operand_addresses(uint64_t value) { + _impl_.operand_addresses_.Add(value); +} +inline void ConvInstructionLog::add_operand_addresses(uint64_t value) { + _internal_add_operand_addresses(value); + // @@protoc_insertion_point(field_add:xla.gpu.ConvInstructionLog.operand_addresses) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::_internal_operand_addresses() const { + return _impl_.operand_addresses_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::operand_addresses() const { + // @@protoc_insertion_point(field_list:xla.gpu.ConvInstructionLog.operand_addresses) + return _internal_operand_addresses(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::_internal_mutable_operand_addresses() { + return &_impl_.operand_addresses_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::mutable_operand_addresses() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.ConvInstructionLog.operand_addresses) + return _internal_mutable_operand_addresses(); +} + +// ------------------------------------------------------------------- + +// DenylistedAlgorithm + +// int64 id = 1; +inline void DenylistedAlgorithm::clear_id() { + _impl_.id_ = int64_t{0}; +} +inline int64_t DenylistedAlgorithm::_internal_id() const { + return _impl_.id_; +} +inline int64_t DenylistedAlgorithm::id() const { + // @@protoc_insertion_point(field_get:xla.gpu.DenylistedAlgorithm.id) + return _internal_id(); +} +inline void DenylistedAlgorithm::_internal_set_id(int64_t value) { + + _impl_.id_ = value; +} +inline void DenylistedAlgorithm::set_id(int64_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:xla.gpu.DenylistedAlgorithm.id) +} + +// bool tensor_ops = 2; +inline void DenylistedAlgorithm::clear_tensor_ops() { + _impl_.tensor_ops_ = false; +} +inline bool DenylistedAlgorithm::_internal_tensor_ops() const { + return _impl_.tensor_ops_; +} +inline bool DenylistedAlgorithm::tensor_ops() const { + // @@protoc_insertion_point(field_get:xla.gpu.DenylistedAlgorithm.tensor_ops) + return _internal_tensor_ops(); +} +inline void DenylistedAlgorithm::_internal_set_tensor_ops(bool value) { + + _impl_.tensor_ops_ = value; +} +inline void DenylistedAlgorithm::set_tensor_ops(bool value) { + _internal_set_tensor_ops(value); + // @@protoc_insertion_point(field_set:xla.gpu.DenylistedAlgorithm.tensor_ops) +} + +// ------------------------------------------------------------------- + +// AlgorithmDenylistEntry + +// string hlo = 1; +inline void AlgorithmDenylistEntry::clear_hlo() { + _impl_.hlo_.ClearToEmpty(); +} +inline const std::string& AlgorithmDenylistEntry::hlo() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.hlo) + return _internal_hlo(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AlgorithmDenylistEntry::set_hlo(ArgT0&& arg0, ArgT... args) { + + _impl_.hlo_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.AlgorithmDenylistEntry.hlo) +} +inline std::string* AlgorithmDenylistEntry::mutable_hlo() { + std::string* _s = _internal_mutable_hlo(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.hlo) + return _s; +} +inline const std::string& AlgorithmDenylistEntry::_internal_hlo() const { + return _impl_.hlo_.Get(); +} +inline void AlgorithmDenylistEntry::_internal_set_hlo(const std::string& value) { + + _impl_.hlo_.Set(value, GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::_internal_mutable_hlo() { + + return _impl_.hlo_.Mutable(GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::release_hlo() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.hlo) + return _impl_.hlo_.Release(); +} +inline void AlgorithmDenylistEntry::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.gpu.AlgorithmDenylistEntry.hlo) +} + +// .xla.ComputeCapability cc = 2; +inline bool AlgorithmDenylistEntry::_internal_has_cc() const { + return this != internal_default_instance() && _impl_.cc_ != nullptr; +} +inline bool AlgorithmDenylistEntry::has_cc() const { + return _internal_has_cc(); +} +inline const ::xla::ComputeCapability& AlgorithmDenylistEntry::_internal_cc() const { + const ::xla::ComputeCapability* p = _impl_.cc_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ComputeCapability_default_instance_); +} +inline const ::xla::ComputeCapability& AlgorithmDenylistEntry::cc() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.cc) + return _internal_cc(); +} +inline void AlgorithmDenylistEntry::unsafe_arena_set_allocated_cc( + ::xla::ComputeCapability* cc) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cc_); + } + _impl_.cc_ = cc; + if (cc) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.AlgorithmDenylistEntry.cc) +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::release_cc() { + + ::xla::ComputeCapability* temp = _impl_.cc_; + _impl_.cc_ = 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* AlgorithmDenylistEntry::unsafe_arena_release_cc() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.cc) + + ::xla::ComputeCapability* temp = _impl_.cc_; + _impl_.cc_ = nullptr; + return temp; +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::_internal_mutable_cc() { + + if (_impl_.cc_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ComputeCapability>(GetArenaForAllocation()); + _impl_.cc_ = p; + } + return _impl_.cc_; +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::mutable_cc() { + ::xla::ComputeCapability* _msg = _internal_mutable_cc(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.cc) + return _msg; +} +inline void AlgorithmDenylistEntry::set_allocated_cc(::xla::ComputeCapability* cc) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cc_); + } + if (cc) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(cc)); + if (message_arena != submessage_arena) { + cc = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, cc, submessage_arena); + } + + } else { + + } + _impl_.cc_ = cc; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.AlgorithmDenylistEntry.cc) +} + +// .xla.CudnnVersion cudnn_version = 3; +inline bool AlgorithmDenylistEntry::_internal_has_cudnn_version() const { + return this != internal_default_instance() && _impl_.cudnn_version_ != nullptr; +} +inline bool AlgorithmDenylistEntry::has_cudnn_version() const { + return _internal_has_cudnn_version(); +} +inline const ::xla::CudnnVersion& AlgorithmDenylistEntry::_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& AlgorithmDenylistEntry::cudnn_version() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.cudnn_version) + return _internal_cudnn_version(); +} +inline void AlgorithmDenylistEntry::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.gpu.AlgorithmDenylistEntry.cudnn_version) +} +inline ::xla::CudnnVersion* AlgorithmDenylistEntry::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* AlgorithmDenylistEntry::unsafe_arena_release_cudnn_version() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.cudnn_version) + + ::xla::CudnnVersion* temp = _impl_.cudnn_version_; + _impl_.cudnn_version_ = nullptr; + return temp; +} +inline ::xla::CudnnVersion* AlgorithmDenylistEntry::_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* AlgorithmDenylistEntry::mutable_cudnn_version() { + ::xla::CudnnVersion* _msg = _internal_mutable_cudnn_version(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.cudnn_version) + return _msg; +} +inline void AlgorithmDenylistEntry::set_allocated_cudnn_version(::xla::CudnnVersion* cudnn_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cudnn_version_); + } + if (cudnn_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(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.gpu.AlgorithmDenylistEntry.cudnn_version) +} + +// string blas_version = 5; +inline void AlgorithmDenylistEntry::clear_blas_version() { + _impl_.blas_version_.ClearToEmpty(); +} +inline const std::string& AlgorithmDenylistEntry::blas_version() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.blas_version) + return _internal_blas_version(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AlgorithmDenylistEntry::set_blas_version(ArgT0&& arg0, ArgT... args) { + + _impl_.blas_version_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.AlgorithmDenylistEntry.blas_version) +} +inline std::string* AlgorithmDenylistEntry::mutable_blas_version() { + std::string* _s = _internal_mutable_blas_version(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.blas_version) + return _s; +} +inline const std::string& AlgorithmDenylistEntry::_internal_blas_version() const { + return _impl_.blas_version_.Get(); +} +inline void AlgorithmDenylistEntry::_internal_set_blas_version(const std::string& value) { + + _impl_.blas_version_.Set(value, GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::_internal_mutable_blas_version() { + + return _impl_.blas_version_.Mutable(GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::release_blas_version() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.blas_version) + return _impl_.blas_version_.Release(); +} +inline void AlgorithmDenylistEntry::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.gpu.AlgorithmDenylistEntry.blas_version) +} + +// repeated .xla.gpu.DenylistedAlgorithm algos = 4; +inline int AlgorithmDenylistEntry::_internal_algos_size() const { + return _impl_.algos_.size(); +} +inline int AlgorithmDenylistEntry::algos_size() const { + return _internal_algos_size(); +} +inline void AlgorithmDenylistEntry::clear_algos() { + _impl_.algos_.Clear(); +} +inline ::xla::gpu::DenylistedAlgorithm* AlgorithmDenylistEntry::mutable_algos(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.algos) + return _impl_.algos_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >* +AlgorithmDenylistEntry::mutable_algos() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.AlgorithmDenylistEntry.algos) + return &_impl_.algos_; +} +inline const ::xla::gpu::DenylistedAlgorithm& AlgorithmDenylistEntry::_internal_algos(int index) const { + return _impl_.algos_.Get(index); +} +inline const ::xla::gpu::DenylistedAlgorithm& AlgorithmDenylistEntry::algos(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.algos) + return _internal_algos(index); +} +inline ::xla::gpu::DenylistedAlgorithm* AlgorithmDenylistEntry::_internal_add_algos() { + return _impl_.algos_.Add(); +} +inline ::xla::gpu::DenylistedAlgorithm* AlgorithmDenylistEntry::add_algos() { + ::xla::gpu::DenylistedAlgorithm* _add = _internal_add_algos(); + // @@protoc_insertion_point(field_add:xla.gpu.AlgorithmDenylistEntry.algos) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >& +AlgorithmDenylistEntry::algos() const { + // @@protoc_insertion_point(field_list:xla.gpu.AlgorithmDenylistEntry.algos) + return _impl_.algos_; +} + +// ------------------------------------------------------------------- + +// AlgorithmDenylist + +// repeated .xla.gpu.AlgorithmDenylistEntry entries = 1; +inline int AlgorithmDenylist::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int AlgorithmDenylist::entries_size() const { + return _internal_entries_size(); +} +inline void AlgorithmDenylist::clear_entries() { + _impl_.entries_.Clear(); +} +inline ::xla::gpu::AlgorithmDenylistEntry* AlgorithmDenylist::mutable_entries(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylist.entries) + return _impl_.entries_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >* +AlgorithmDenylist::mutable_entries() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.AlgorithmDenylist.entries) + return &_impl_.entries_; +} +inline const ::xla::gpu::AlgorithmDenylistEntry& AlgorithmDenylist::_internal_entries(int index) const { + return _impl_.entries_.Get(index); +} +inline const ::xla::gpu::AlgorithmDenylistEntry& AlgorithmDenylist::entries(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylist.entries) + return _internal_entries(index); +} +inline ::xla::gpu::AlgorithmDenylistEntry* AlgorithmDenylist::_internal_add_entries() { + return _impl_.entries_.Add(); +} +inline ::xla::gpu::AlgorithmDenylistEntry* AlgorithmDenylist::add_entries() { + ::xla::gpu::AlgorithmDenylistEntry* _add = _internal_add_entries(); + // @@protoc_insertion_point(field_add:xla.gpu.AlgorithmDenylist.entries) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >& +AlgorithmDenylist::entries() const { + // @@protoc_insertion_point(field_list:xla.gpu.AlgorithmDenylist.entries) + return _impl_.entries_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..d4d500d352c6033b4d6d7e7099fcd87a79516dc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_compiler.h @@ -0,0 +1,260 @@ +/* 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_SERVICE_GPU_GPU_COMPILER_H_ +#define XLA_SERVICE_GPU_GPU_COMPILER_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/autotune_results.pb.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/executable.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/gpu/buffer_sharing.h" +#include "xla/service/gpu/executable.pb.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/gpu/gpu_target_config.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_pass_pipeline.h" +#include "xla/service/llvm_compiler.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +// TODO(b/232263665): It should be shared between GPU and CPU. +class GpuXlaRuntimeAotCompilationResult : public AotCompilationResult { + public: + GpuXlaRuntimeAotCompilationResult( + HloModuleProto hlo, std::string_view obj_file, + std::string_view mlir_module, EntryFunctionAttributes entry_func_attrs, + std::string_view gpu_asm_text, absl::Span gpu_binary, + absl::Span constants = {}) { + XlaRuntimeExecutableProto xla_runtime_executable; + *xla_runtime_executable.mutable_hlo_module_proto() = hlo; + xla_runtime_executable.set_obj_file(std::string(obj_file)); + xla_runtime_executable.set_mlir_module(std::string(mlir_module)); + *xla_runtime_gpu_executable_.mutable_xla_runtime_executable() = + xla_runtime_executable; + + *xla_runtime_gpu_executable_.mutable_entry_func_attrs() = entry_func_attrs; + xla_runtime_gpu_executable_.set_gpu_asm_text(std::string(gpu_asm_text)); + xla_runtime_gpu_executable_.set_gpu_binary(gpu_binary.data(), + gpu_binary.size()); + + for (const GpuExecutable::ConstantInfo& cst : constants) { + auto* cst_proto = xla_runtime_gpu_executable_.add_constants(); + cst_proto->set_symbol_name(cst.symbol_name); + cst_proto->set_allocation_index(cst.allocation_index); + cst_proto->set_content(cst.content.data(), cst.content.size()); + } + } + + explicit GpuXlaRuntimeAotCompilationResult( + XlaRuntimeGpuExecutableProto executable) + : xla_runtime_gpu_executable_(executable) {} + + StatusOr SerializeAsString() const override { + return xla_runtime_gpu_executable_.SerializeAsString(); + } + + static StatusOr> + FromString(const std::string& serialized) { + XlaRuntimeGpuExecutableProto xla_runtime_gpu_executable; + if (!xla_runtime_gpu_executable.ParseFromString(serialized)) { + return InternalError("Failed to parse serialized JitRtExecutableProto."); + } + return std::make_unique( + xla_runtime_gpu_executable); + } + + StatusOr> LoadExecutable( + Compiler* compiler, se::StreamExecutor* executor) const override; + + private: + XlaRuntimeGpuExecutableProto xla_runtime_gpu_executable_; +}; + +// The GPU compiler generates efficient GPU executables. +class GpuCompiler : public LLVMCompiler { + public: + GpuCompiler(se::Platform::Id platform_id, const char* target_triple, + const char* data_layout); + + using LLVMCompiler::Compile; + + // An attached device is passed in via stream_exec. We get GPU configuration + // from the attached device. GemmAlgorithmPicker and GpuConvAlgorithmPicker + // can run on the attached device. + StatusOr> RunHloPasses( + std::unique_ptr module, se::StreamExecutor* stream_exec, + const CompileOptions& options) override; + + // Run HloPasses without an attached deivce. So GemmAlgorithmPicker and + // GpuConvAlgorithmPicker can not run. + StatusOr> RunHloPassesWithoutDevice( + std::unique_ptr module, const CompileOptions& options, + const GpuTargetConfig& gpu_target_config, + const AutotuneResults& autotune_results); + + StatusOr> AssignBuffers( + HloModule* hlo_module, se::StreamExecutor* stream_exec) override; + + se::GpuComputeCapability GetGpuVersion(se::StreamExecutor* stream_exec); + + GpuTargetConfig GetGpuTargetConfig(se::StreamExecutor* stream_exec) { + return GpuTargetConfig(stream_exec); + } + + StatusOr> RunBackend( + std::unique_ptr module, se::StreamExecutor* stream_exec, + const CompileOptions& options) override; + + StatusOr>> + CompileAheadOfTime(std::unique_ptr module_group, + AotCompilationOptions const& options) override; + + StatusOr>> CompileToTargetBinary( + const HloModuleConfig& module_config, + std::unique_ptr llvm_module, + se::GpuComputeCapability gpu_version, se::StreamExecutor* stream_exec, + const CompileOptions& options, const HloModule* debug_module); + + se::Platform::Id PlatformId() const override { return platform_id_; } + + HloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const override; + + // Returns a (deserialized) AotCompilationResult from a serialized + // AotCompilationResult. + StatusOr> LoadAotCompilationResult( + const std::string& serialized_aot_result) override { + return GpuXlaRuntimeAotCompilationResult::FromString(serialized_aot_result); + } + + StatusOr> Export( + Executable* executable) const override; + + Status RunPostSchedulingPipelines(HloModule* module, + int64_t scheduler_mem_limit) const; + + protected: + // During compilation with device, stream_exec != null and autotune_results + // == null. During deviceless AOT compilation, stream_exec == null and + // autotune_results != null. + // thread_pool is used to speed up compilation during autotuning. + virtual Status OptimizeHloPostLayoutAssignment( + HloModule* hlo_module, se::StreamExecutor* stream_exec, + const CompileOptions& options, const GpuTargetConfig& gpu_target_config, + const AutotuneResults* autotune_results, + tsl::thread::ThreadPool* thread_pool); + + // CollectivesScheduleLinearizer enforces a total ordering between collectives + // to work around divergence in executables introduced due to auto tuning, + // specifically the use of extra scratch space for convolutions. This + // function decided whether to apply this pass. If convolutions are present in + // the code and we are using "online" autotuning (i.e., not AOT) we need to + // use the pass, else we do not need to enable the pass. + virtual bool RequiresCollectiveScheduleLinearizer( + const HloModule* module, se::StreamExecutor* stream_exec) { + return false; + } + + // Add autotuning passes for convolution and gemm (except triton). + virtual Status AddConvAndGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, tsl::thread::ThreadPool* thread_pool) { + return OkStatus(); + } + + // Add autotuning passes for triton gemm. + virtual Status AddTritonGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, tsl::thread::ThreadPool* thread_pool) { + return OkStatus(); + } + + private: + Status LoadAutotuneResultsFromFile(const DebugOptions& debug_options); + Status SerializeAutotuneResultsToFile(const DebugOptions& debug_options); + + // During compilation with device, stream_exec != null and autotune_results + // == null. During deviceless AOT compilation, stream_exec == null and + // autotune_results != null. + Status OptimizeHloModule(HloModule* hlo_module, + se::StreamExecutor* stream_exec, + const CompileOptions& options, + const GpuTargetConfig& gpu_target_config, + const AutotuneResults* autotune_results); + + virtual Status OptimizeHloConvolutionCanonicalization( + HloModule* hlo_module, se::GpuComputeCapability gpu_version, + se::dnn::VersionInfo dnn_version, + se::DeviceMemoryAllocator* device_allocator) = 0; + + virtual HloDataflowAnalysis::CanShareBuffer GetCanShareBuffer() const { + return &FusionCanShareBufferHint; + } + + // TODO(timshen): Replace `debug_module` with some portable debug information + // that accommodates both HLO and MLIR. + virtual StatusOr>> + CompileTargetBinary(const HloModuleConfig& module_config, + llvm::Module* llvm_module, + se::GpuComputeCapability gpu_version, bool relocatable, + const HloModule* debug_module, + const CompileOptions& options) = 0; + + Status PrepareHloModuleForIrEmitting(HloModule* hlo_module); + + virtual StatusOr CanUseLinkModules(const HloModuleConfig& config) { + return false; + } + + virtual StatusOr> LinkModules( + se::StreamExecutor* stream_exec, + std::vector> modules, + const DebugOptions& debug_options) { + return Unimplemented("LinkModules is not implemented."); + } + + se::Platform::Id platform_id_; + + // The triple that represents our target. + const char* target_triple_; + + // The data layout of the emitted module. + const char* data_layout_; + + // The size in bytes of a pointer. Used by ShapeSizeBytesFunction. + const int64_t pointer_size_; + + GpuCompiler(const GpuCompiler&) = delete; + GpuCompiler& operator=(const GpuCompiler&) = delete; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..68eda89b715fa9e39d00cb914d81e1372f959cf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_constants.h @@ -0,0 +1,50 @@ +/* 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_SERVICE_GPU_GPU_CONSTANTS_H_ +#define XLA_SERVICE_GPU_GPU_CONSTANTS_H_ + +#include + +namespace xla { +namespace gpu { + +// Minimum alignment for buffers passed as incoming arguments by TensorFlow. +// +// kEntryParameterAlignBytes is equal to EIGEN_MAX_ALIGN_BYTES, though including +// Eigen headers here to get that symbol may not be a good idea. +// EIGEN_MAX_ALIGN_BYTES may differ between CUDA-enabled builds vs CUDA-disabled +// builds and we don't want the IR generated by XLA:GPU to depend on that. +// +// TODO(b/111767313): Consider raising EIGEN_MAX_ALIGN_BYTES if it helps. +inline constexpr int64_t kEntryParameterAlignBytes = 16; + +// Minimum alignment for buffers allocated by XLA: the temp buffers and the live +// out (result) buffers. +// +// cudnn requires 128-bit (16-byte) alignment for TensorCore operations, but +// says that 1024-bit (128-byte) alignment "may deliver better performance". +// https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#tensor-ops-guidelines-for-dl-compiler +// +inline constexpr int64_t kXlaAllocatedBufferAlignBytes = 128; + +// Minimum alignment for constant buffers. +inline constexpr int64_t kConstantBufferAlignBytes = + kXlaAllocatedBufferAlignBytes; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONSTANTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_padding_legalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_padding_legalization.h new file mode 100644 index 0000000000000000000000000000000000000000..15e5de46e5a9376312882e5e4df877000732e005 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_padding_legalization.h @@ -0,0 +1,49 @@ +/* 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_SERVICE_GPU_GPU_CONV_PADDING_LEGALIZATION_H_ +#define XLA_SERVICE_GPU_GPU_CONV_PADDING_LEGALIZATION_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// An HLO pass that canonicalizes convolution instructions for GPU codegen. It +// inserts Pad instructions before Convolution instructions with uncanonicalized +// padding, so that they can be lowered to Cudnn/Miopen convolution. +class GpuConvPaddingLegalization : public HloModulePass { + public: + absl::string_view name() const override { + return "gpu-conv-padding-legalization"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation* computation); + // Returns if any changes are made to the parent computation. + bool CanonicalizeForwardConvolution(HloInstruction* conv); + bool CanonicalizeBackwardFilterConvolution(HloInstruction* backward_conv); + bool CanonicalizeBackwardInputConvolution(HloInstruction* backward_conv); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONV_PADDING_LEGALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..4e36a69ceaa11cd03b3e74837cb705416350ba54 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_rewriter.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_SERVICE_GPU_GPU_CONV_REWRITER_H_ +#define XLA_SERVICE_GPU_GPU_CONV_REWRITER_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Rewrites plain convolutions, backwards-filter convolutions, and +// backwards-input convolutions into CustomCall HLOs that call into +// Cudnn/Miopen. +// For integer convolution, it requires the following pattern: +// conv( +// convert(int8_x), convert(int8_y)) +// We transform it to: +// custom_call(int8_x, int8_y, target=cudnnForwardConvolution) +// Note that this pattern is necessary but not sufficient to map convolutions +// to CuDNN. More patterns will be matched in cudnn_fused_conv_rewriter. + +class GpuConvRewriter : public HloModulePass { + public: + absl::string_view name() const override { return "gpu-conv-rewriter"; } + + static bool ConvIsLowerable(HloInstruction* conv); + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONV_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..ff85fceb74cf6ea8600dc91a4b8d29f7fc896286 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_conv_runner.h @@ -0,0 +1,266 @@ +/* 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_SERVICE_GPU_GPU_CONV_RUNNER_H_ +#define XLA_SERVICE_GPU_GPU_CONV_RUNNER_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/cublas_cudnn.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/lazy_op_runner.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// Structure to describe static properties of a GPU convolution. +struct GpuConvConfig { + // Field related to cuDNN's fused convolution are in FusionConfig & + // FusionParams structures. The result thus is defined as: + // activation(conv_result_scale * conv(x, w) + + // side_input_scale * side_input + broadcast(bias)) + // + // The most common fused conv is conv forward + relu/identity, for example. + // + // bias_buf is a single-dimensional array, with the length equal to the number + // of output features. It'll be broadcasted to the output shape in order to be + // added to the final results. + // + // side_input_buf, if valid, must have the same shape as the output buffer. + struct FusionConfig { + se::dnn::ActivationMode mode; + double side_input_scale; + double leakyrelu_alpha = 0.0; + }; + + PrimitiveType input_type; + PrimitiveType output_type; + CudnnConvKind kind; + se::dnn::AlgorithmDesc algorithm; + double conv_result_scale; + + se::dnn::BatchDescriptor input_descriptor; + se::dnn::FilterDescriptor filter_descriptor; + se::dnn::BatchDescriptor output_descriptor; + se::dnn::ConvolutionDescriptor conv_desc; + se::dnn::BatchDescriptor bias_descriptor; + + Shape input_shape; + Shape filter_shape; + Shape output_shape; + std::optional fusion; + + // String serialization of the subgraph of adjacent ops to be fused into the + // cuDNN convolution Custom Call. Currently used for FP8 convolutions only. + // Additional information is provided in gpu_fused_conv_rewriter.cc. + std::string serialized_graph; +}; + +// Implementation struct exposed for debugging and log analysis. +struct GpuConvParams { + const GpuConvConfig* config; // Not owned + struct FusionParams { + se::DeviceMemoryBase bias_buf; + se::DeviceMemoryBase side_input_buf; // nullable + }; + + se::DeviceMemoryBase input_buf; + se::DeviceMemoryBase filter_buf; + se::DeviceMemoryBase output_buf; + + // Buffers for operands of ops to be fused into the cuDNN + // convolution Custom Call. + std::vector operand_bufs; + + // Buffers for additional outputs of ops to be fused into the cuDNN + // convolution Custom Call. + std::vector aux_bufs; + + std::optional fusion; +}; + +// The XLA convolution plumbing is all dynamically-typed w.r.t. whether a +// convolution is fused (and has extra arguments) or unfused, which doesn't +// naturally play well with the typed APIs provided by StreamExecutor; rather +// than rewriting everything here, just propagate the dynamic typing to one more +// place by having a ConvRunner, FusedConvRunner or GraphConvRunner. +class GenericConvRunner { + public: + GenericConvRunner() = default; + + explicit GenericConvRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit GenericConvRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit GenericConvRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit GenericConvRunner(const GpuConvConfig& config) + : GenericConvRunner(FromGpuConvConfig(config)) {} + + static GenericConvRunner FromGpuConvConfig(const GpuConvConfig& config) { + if (config.kind == CudnnConvKind::kForwardGraph) { + return GenericConvRunner( + std::make_unique>( + config.algorithm)); + } else if (config.kind == CudnnConvKind::kForwardActivation) { + return GenericConvRunner( + std::make_unique>( + config.algorithm)); + } else { + return GenericConvRunner( + std::make_unique>( + config.algorithm)); + } + } + + se::dnn::AlgorithmDesc ToAlgorithmDesc() const { + return std::visit(ToAlgorithmDescVisitor{}, repr_); + } + + se::dnn::LazyOpRunner* AsConvRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get>>( + repr_) + .get(); + } + + se::dnn::LazyOpRunner* AsGraphConvRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get< + std::unique_ptr>>( + repr_) + .get(); + } + + se::dnn::LazyOpRunner* AsFusedConvRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get< + std::unique_ptr>>( + repr_) + .get(); + } + + private: + struct ToAlgorithmDescVisitor { + template + se::dnn::AlgorithmDesc operator()(const RunnerPtr& runner) { + return runner->ToAlgorithmDesc(); + } + + se::dnn::AlgorithmDesc operator()(const std::monostate&) { + CHECK(false) << "Internal error: uninitialized runner in ToAlgorithmDesc"; + } + }; + + using Repr = + std::variant>, + std::unique_ptr>, + std::unique_ptr>>; + Repr repr_; +}; + +struct RunConvOptions { + // Nullable output-parameter pointer for profiling results. + se::dnn::ProfileResult* profile_result = nullptr; + + // Use this runner cache (and its configured algorithm), instead of the one + // from the instruction. + GenericConvRunner* runner_cache; +}; + +// This file contains low-level routines for running cudnn convolutions. + +// Calls into cudnn to run the specified convolution. +// +// We provide one overload which takes a scratch buffer, and another which takes +// an allocator which is responsible for allocating the scratch space. In +// theory the second one shouldn't be necessary -- users of this function could +// just ask cudnn how much scratch space it needs for a particular convolution. +// But in practice, StreamExecutor does not expose such an API, and in the name +// of parsimony, perhaps it's better not to add it. Instead, the first time you +// call a convolution, you should call the version that takes a scratch +// allocator and take note of how much memory is used. The next time you call +// the same conv, you can provide an explicitly preallocated scratch buffer of +// that size, if you like. +Status RunGpuConv(const GpuConvConfig& conv_config, + absl::Span operand_buffers, + absl::Span result_buffers, + se::DeviceMemoryBase scratch_memory, se::Stream* stream, + RunConvOptions = {}); + +// Struct to describe properties of a convolution without being tied to specific +// IR. Will be used to help build Convolution thunks from either XLA HLO or +// LHLO GPU dialect in MLIR. +struct GpuConvDescriptor { + CudnnConvKind kind; + CudnnConvBackendConfig backend_config; + Shape operand0_shape; + Shape operand1_shape; + Shape result_shape; + size_t scratch_size; + Window window; + ConvolutionDimensionNumbers dnums; + int64_t feature_group_count; +}; + +// Returns the convolution configuration given a XLA HLO instruction. +StatusOr GetGpuConvConfig( + const HloCustomCallInstruction* cudnn_call); + +// Returns the convolution configuration given a convolution descriptor `desc` +// and a string representation of the convolution instruction `inst_as_string` +// (for error reporting). +StatusOr GetGpuConvConfig(const GpuConvDescriptor& desc, + absl::string_view inst_as_string); + +// Implementation details exposed for debugging and log analysis. +StatusOr GetGpuConvParams( + const GpuConvConfig& conv_config, + absl::Span operand_buffers, + absl::Span result_buffers); + +inline se::dnn::DataType BiasTypeForInputType(se::dnn::DataType input_type) { + switch (input_type) { + default: + return input_type; + case se::dnn::DataType::kInt8: + return se::dnn::DataType::kFloat; + } +} + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONV_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_convert_async_collectives_to_sync.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_convert_async_collectives_to_sync.h new file mode 100644 index 0000000000000000000000000000000000000000..01713f8dd3cef4158ef17d20466d8686e1a6473e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_convert_async_collectives_to_sync.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_GPU_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ +#define XLA_SERVICE_GPU_GPU_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ + +#include + +#include "xla/service/convert_async_collectives_to_sync.h" + +namespace xla { +namespace gpu { + +class GpuConvertAsyncCollectivesToSync : public ConvertAsyncCollectivesToSync { + public: + using ConvertAsyncCollectivesToSync::ConvertAsyncCollectivesToSync; + absl::string_view name() const override { + return "gpu-convert-async-collectives-to-sync"; + } + + Status ConvertAsyncInstructionsToSync( + HloComputation* computation, + absl::Span> async_pairs) + const override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_cost_model_stats_collection.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_cost_model_stats_collection.h new file mode 100644 index 0000000000000000000000000000000000000000..678327c899cae144a4fb9f79a3f093c195af5dc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_cost_model_stats_collection.h @@ -0,0 +1,59 @@ +/* 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_SERVICE_GPU_GPU_COST_MODEL_STATS_COLLECTION_H_ +#define XLA_SERVICE_GPU_GPU_COST_MODEL_STATS_COLLECTION_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Calculates costs for each fusion op and stores the result in backend +// config. +class GpuCostModelStatsCollection : public HloModulePass { + public: + explicit GpuCostModelStatsCollection( + const se::DeviceDescription& d, + const GpuHloCostAnalysis::Options& cost_analysis_options) + : device_info_(d), cost_analysis_(cost_analysis_options, &device_info_) {} + + absl::string_view name() const override { + return "gpu_cost_model_stats_collection"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::DeviceDescription device_info_; + GpuHloCostAnalysis cost_analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_COST_MODEL_STATS_COLLECTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_executable.h new file mode 100644 index 0000000000000000000000000000000000000000..7984ae2c8fab27e960cff2989fda2844cfdb71a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_executable.h @@ -0,0 +1,353 @@ +/* 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_SERVICE_GPU_GPU_EXECUTABLE_H_ +#define XLA_SERVICE_GPU_GPU_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "absl/types/variant.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/executable.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/non_atomically_upgradeable_rw_lock.h" +#include "xla/service/gpu/runtime/executable.h" +#include "xla/service/gpu/runtime2/executable.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/hlo_execution_profile.h" +#include "xla/service/shaped_buffer.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Returns whether GpuExecutable runs with Xla Runtime. +bool IsXlaRuntimeExecutableEnabled(const HloModuleConfig& config); + +// Returns whether GpuExecutable runs with experimental XLA:GPU Runtime. +bool IsXlaGpu2RuntimeEnabled(const HloModuleConfig& config); + +// GPU-targeting implementation of the XLA Executable interface. +// +// Launches the given GPU kernel via the StreamExecutor. +// +// This is an immutable data type after initialization, and thus thread safe. +class GpuExecutable : public Executable { + public: + using OwnedThunkSequence = std::unique_ptr; + using OwnedGpuRuntimeProgram = std::unique_ptr; + using OwnedGpu2RuntimeProgram = std::unique_ptr; + + struct ConstantInfo { + std::string symbol_name; + std::vector content; + int allocation_index = -1; + }; + + struct OutputInfo { + // Corresponding allocation index. + int allocation_index; + + // Output is passed-through from a parameter. + bool passthrough = false; + + // Whether this output is hinted to alias a parameter (BufferAllocation* + // would indicate the aliased parameter), and what kind of alias it is. + std::optional alias_config; + }; + + struct Params { + std::string asm_text; + std::vector binary; + se::GpuComputeCapability gpu_version; + // The GpuExecutable will either execute Thunks, XLA runtime executable + // (native function) or experimental XLA runtime executable (IREE VM + // function) depending on which is supplied. + std::variant + executable; + xla::EntryFunctionAttributes entry_func_attrs; + std::vector constants; + absl::flat_hash_map output_info; + std::string module_name; + xla::Shape output_shape; + std::vector allocations; + bool enable_persistent_temp_buffers; + std::unique_ptr debug_buffer_assignment = nullptr; + + // A callable that dumps out a debug string upon device OOM. It's not the + // string itself, as the string can be huge and increase peak host memory + // usage for the common (non-OOM) case. + std::function verbose_buffer_assignment_string_dumper = [] { + return std::string(); + }; + + std::unique_ptr debug_module = nullptr; + bool enable_debug_info_manager = true; + }; + + // Analyze the entry function to construct buffer allocation and other output + // information. + // + // TODO(ezhulenev): Once Xla runtime enabled by default, hide this method as + // an implementation detail of GpuExecutable. + static Status SetUpMlirAllocation( + mlir::func::FuncOp func, llvm::ArrayRef buffer_sizes, + std::vector* allocations, + absl::flat_hash_map* output_info, + Shape* output_shape); + + // Returns an Executable that is loaded from an object file (XLA program + // compiled to a native function using the XLA Runtime stack). + static StatusOr> LoadFromObjFile( + std::shared_ptr hlo_module, absl::string_view obj_file, + absl::string_view mlir_module, + xla::EntryFunctionAttributes entry_func_attrs, DebugOptions debug_options, + absl::string_view asm_text, absl::string_view binary, + std::vector constants, se::GpuComputeCapability gpu_version, + stream_executor::StreamExecutor* executor); + + // Constructor to use when loading a GpuExecutable from an object file (native + // function compiled for XLA Runtime). Omits setting class members that aren't + // used in XLA Runtime execution mode. + GpuExecutable(std::shared_ptr hlo_module, std::string asm_text, + std::vector binary, + std::vector constants, + se::GpuComputeCapability gpu_version, + xla::EntryFunctionAttributes entry_func_attrs, + absl::string_view module_name, Shape xla_output_shape, + std::vector allocations, + absl::flat_hash_map output_info, + std::unique_ptr runtime_executable); + + static StatusOr> Create(Params params); + ~GpuExecutable() override; + + int64_t SizeOfGeneratedCodeInBytes() const override; + + // This should be called after set_ir_module_string. + const std::string& ir_module_string() const { return ir_module_string_; } + + // This should be called before ExecuteOnStream. + void set_ir_module_string(const std::string& ir_module_string) { + ir_module_string_ = ir_module_string; + } + + // Returns the compiled code for the computation. + // + // The compiled code is PTX in Cuda and unused empty string in ROCm. + // This may be left empty for saving memory if we have a non-empty binary. + // If both text() and binary() are empty, that means the HLO required no + // custom kernels to be compiled. + const std::string& text() const { return text_; } + + // Returns the binary stored in this GpuExecutable. + // + // The binary is cubin in Cuda, and HSA code object in ROCm. It may be empty, + // in which case compilation is left up to the GPU driver. If both text() and + // binary() are empty, that means the HLO required no custom kernels to be + // compiled. + const std::vector& binary() const { return binary_; } + + // ExecuteAsyncOnStream will fail if the compute capability of the stream + // doesn't match the compute capability passed to this object's constructor. + StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + std::vector arguments, + HloExecutionProfile* hlo_execution_profile) override; + + StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + absl::Span arguments, + HloExecutionProfile* hlo_execution_profile) override; + + using VariantArguments = std::variant, + absl::Span>; + StatusOr ExecuteAsyncOnStreamImpl( + const ServiceExecutableRunOptions* run_options, + VariantArguments arguments); + + absl::Span GetAllocations() const { + return allocations_; + } + + const std::vector& constants() const { return constants_; } + + xla::EntryFunctionAttributes entry_func_attrs() const { + return entry_func_attrs_; + } + + StatusOr GetObjFile() const; + StatusOr GetMlirModule() const; + + private: + // Use GpuExecutable::Create() to create an instance. + explicit GpuExecutable(Params params); + + // If `block_host_until_done` is false, execution will not block the host + // until the kernels have completed. This is used as an optimization for + // clients, such as Tensorflow, that use a single stream of execution for + // computations, and allow host-side deallocation from the allocator before + // GPU execution completes. + Status ExecuteThunksOrXlaRuntime( + const ServiceExecutableRunOptions* run_options, + const BufferAllocations& buffer_allocations, bool block_host_until_done, + NonAtomicallyUpgradeableRWLock& gpu_lock); + + using BufferAllocToDeviceMemoryMap = + absl::flat_hash_map; + + // Loads the PTX or CUBIN for this executable and initializes all + // constants that haven't already been initialized by the CUDA driver. Loaded + // modules are owned by this executable. + // + // Returns a map from buffer allocation indices to device memory pointers + // (only for allocations that contain constants). + // + // The returned map is cached. If the above process has already been run for + // the given stream, it is skipped and the cached map is immediately returned + // instead. + StatusOr ResolveConstantGlobals( + stream_executor::Stream* stream); + + // Allocate the temp buffers and store them with the GpuExecutable. This + // function only allocates buffers on the first run for each executor. + Status PopulatePersistentTempBuffers(se::StreamExecutor* executor) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(persistent_temp_buffers_mu_); + + // GpuExecutable check with either AMD's ISA version, or Nvidia's major minor + // version for compute capability, depending on the hardware. + Status CheckCompatibilityWithServiceExecutableRunOptions( + const ServiceExecutableRunOptions* run_options); + + StatusOr GenerateBufferAllocations( + VariantArguments arguments, + const GpuExecutable::BufferAllocToDeviceMemoryMap* globals, + se::DeviceMemoryAllocator* memory_allocator, int device_ordinal, + const BufferAllocToDeviceMemoryMap& + buffer_alloc_to_persistent_memory_map); + + StatusOr BufferForAllocation( + VariantArguments arguments, + const GpuExecutable::BufferAllocToDeviceMemoryMap* globals, + const BufferAllocation& allocation, + se::DeviceMemoryAllocator* memory_allocator, int device_ordinal, + int64_t arg_idx); + + // The LLVM IR, in string format, of the unoptimized module generated for + // this GpuExecutable. We save a string instead of an llvm::Module* because + // leaving llvm::Module* in a singleton can cause the heap checker to emit + // false positives. + // + // This string should be modified only before ExecuteOnStream. + std::string ir_module_string_; + + // The compiled code for the computation. + const std::string text_; + + // The GPU machine code for the computation, targeting GPUs at + // compute_capability_. + // + // May be empty, in which case we leave compilation up to the GPU driver. +#ifdef TENSORFLOW_USE_ROCM + std::vector binary_; +#else + const std::vector binary_; +#endif + // The GPU version for compute compatibility check. + se::GpuComputeCapability gpu_version_; + + // The thunks to be invoked by this GpuExecutable. They are generated by the + // IrEmitter (null if XLA:GPU runtime is enabled). + OwnedThunkSequence thunks_; + + // Gpu runtime executable that encapsulates all the state for running Gpu + // runtime custom calls implementing gpu abstraction layer (available only if + // Xla runtime is enabled). + std::unique_ptr gpu_runtime_executable_; + + // XLA:GPU runtime executable that encapsulates all the state for running + // XLA:GPU executables compiled to IREE VM modules, including VM module + // itself. Available only if experimental XLA:GPU runtime is enabled. + std::unique_ptr gpu2_runtime_executable_; + + xla::EntryFunctionAttributes entry_func_attrs_; + + std::string module_name_; + + xla::Shape output_shape_; + + // Owns the buffer data at runtime. It provides information to allocate + // memory for every output/temp buffers. + const std::vector allocations_; + + bool enable_persistent_temp_buffers_ = false; + + absl::Mutex persistent_temp_buffers_mu_; + // Temp buffers can be allocated once and be reused whenever the GpuExecutable + // is executed. The persistent temp buffer is stored in a map that maps from + // a BufferAllocation to the temp buffer. + absl::flat_hash_map + persistent_temp_buffers_ ABSL_GUARDED_BY(persistent_temp_buffers_mu_); + + std::shared_ptr debug_buffer_assignment_; + std::function verbose_buffer_assignment_string_dumper_; + + absl::Mutex module_handle_mutex_; + // Cache of module handles. Required to keep loaded modules alive until this + // executable is destroyed. + absl::flat_hash_map + module_handles_ ABSL_GUARDED_BY(module_handle_mutex_); + // Cache of constant buffer allocation maps used by `ResolveConstantGlobals`. + absl::flat_hash_map> + module_globals_ ABSL_GUARDED_BY(module_handle_mutex_); + + std::vector constants_; + const absl::flat_hash_map output_info_; + // Retains shared ownership of on-device constants that are managed by XLA and + // potentially shared with other executables. + std::vector> shared_constants_; + bool enable_debug_info_manager_; + + GpuExecutable(const GpuExecutable&) = delete; + GpuExecutable& operator=(const GpuExecutable&) = delete; +}; + +StatusOr> +GetOutputInfo(const HloModule& hlo_module, const BufferAssignment& assignment); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_executable_run_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_executable_run_options.h new file mode 100644 index 0000000000000000000000000000000000000000..ffb8785bf7cce924623addb7746554640257883d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_executable_run_options.h @@ -0,0 +1,133 @@ +/* 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_SERVICE_GPU_GPU_EXECUTABLE_RUN_OPTIONS_H_ +#define XLA_SERVICE_GPU_GPU_EXECUTABLE_RUN_OPTIONS_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/service/global_device_id.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Key for naming up a particular NCCL clique. This is just a set of unique +// device IDs (i.e. GPU IDs) and a stream_id. The device IDs must be global +// within a cluster. The stream_id is used to create different NCCL clique and +// communicators for collectives executed on different streams within an +// executable. +class NcclCliqueKey { + public: + explicit NcclCliqueKey(std::vector devices, + int64_t stream_id = 0) + : devices_(std::move(devices)), stream_id_(stream_id) {} + + template + friend H AbslHashValue(H h, const NcclCliqueKey& k) { + return H::combine(std::move(h), k.devices_, k.stream_id_); + } + friend bool operator==(const NcclCliqueKey& a, const NcclCliqueKey& b) { + return a.devices_ == b.devices_ && a.stream_id_ == b.stream_id_; + } + + const std::vector& devices() const { return devices_; } + + std::string ToString() const { + return absl::StrCat("stream[", stream_id_, "]", + GlobalDeviceIdsToString(devices_)); + } + + private: + const std::vector devices_; + const int64_t stream_id_; +}; + +using NcclUniqueIdCallback = + std::function(const NcclCliqueKey&)>; + +// GPU-specific executable options. +// We keep these separate from ExecutableRunOptions to avoid adding +// dependencies to ExecutableRunOptions. +class GpuExecutableRunOptions { + public: + // Sets a mapping from local device ordinals to global device IDs. + // Used only on NVidia GPUs for cross-host NCCL collectives. If set, the + // elements of `device_assignment` are interpreted as global device IDs, not + // local device ordinals. + GpuExecutableRunOptions& set_gpu_global_device_ids( + std::optional> gpu_global_device_ids); + const std::optional>& gpu_global_device_ids() + const; + + // Callback that returns a ncclUniqueId encoded as a string for a group of + // communicating GPU devices. Used only on NVidia GPUs. + GpuExecutableRunOptions& set_nccl_unique_id_callback( + NcclUniqueIdCallback nccl_unique_id_callback); + const NcclUniqueIdCallback& nccl_unique_id_callback() const; + + // Whether the run requires an exclusive lock on the GPU. + bool requires_exclusive_lock_on_gpu() const { + return requires_exclusive_lock_on_gpu_; + } + + // Require writers lock on the GPU. + GpuExecutableRunOptions& set_requires_exclusive_lock_on_gpu() { + requires_exclusive_lock_on_gpu_ = true; + return *this; + } + + bool enable_mock_nccl_collectives() const { + return enable_mock_nccl_collectives_; + } + + // Enable mocking nccl collective operations on the GPU + GpuExecutableRunOptions& set_enable_mock_nccl_collectives() { + enable_mock_nccl_collectives_ = true; + return *this; + } + + private: + bool requires_exclusive_lock_on_gpu_ = false; + bool enable_mock_nccl_collectives_ = false; + std::optional> gpu_global_device_ids_; + NcclUniqueIdCallback nccl_unique_id_callback_; +}; + +// NCCL-related execution parameters. +struct NcclExecuteParams { + NcclExecuteParams(const ServiceExecutableRunOptions& run_options, + se::StreamExecutor* stream_executor); + + se::StreamExecutor* stream_executor; + RunId run_id; + const DeviceAssignment* device_assn; // never null + const std::map* gpu_global_device_ids; // may be null + const NcclUniqueIdCallback* nccl_unique_id_callback; // may be null + + StatusOr GetGlobalDeviceId() const; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_EXECUTABLE_RUN_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_float_support.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_float_support.h new file mode 100644 index 0000000000000000000000000000000000000000..c9e0e2ac0c48e71925e67b96ae9598a1100bc572 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_float_support.h @@ -0,0 +1,52 @@ +/* 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_SERVICE_GPU_GPU_FLOAT_SUPPORT_H_ +#define XLA_SERVICE_GPU_GPU_FLOAT_SUPPORT_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/float_support.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +class GpuFloatSupport : public FloatSupport { + public: + explicit GpuFloatSupport(PrimitiveType low_precision_type) + : FloatSupport(low_precision_type) {} + + bool SupportsLowPrecisionOperand(const HloInstruction& hlo, + int64_t operand_index) const override { + return FloatSupport::SupportsLowPrecisionOperand(hlo, operand_index) || + IsSupported(hlo); + } + + bool SupportsLowPrecisionOutput(const HloInstruction& hlo) const override { + return FloatSupport::SupportsLowPrecisionOutput(hlo) || IsSupported(hlo); + } + + bool SupportsMixedPrecisions(const HloInstruction& hlo) const override; + + private: + bool IsSupported(const HloInstruction& hlo) const; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_FLOAT_SUPPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_fused_mha_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_fused_mha_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..637a3c474c4f7e6d9aeba0874596a4a55ebe996c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_fused_mha_runner.h @@ -0,0 +1,393 @@ +/* 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_SERVICE_GPU_GPU_FUSED_MHA_RUNNER_H_ +#define XLA_SERVICE_GPU_GPU_FUSED_MHA_RUNNER_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/cublas_cudnn.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/lazy_op_runner.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// This is an interim structure to hold the parameters to construct a +// GpufMHAConfig. +// Struct to describe properties of a FMHA without being tied to specific +// IR. Will be used to help build FMHA thunks from either XLA HLO or +// LHLO GPU dialect in MLIR. +struct GpufMHADescriptor { + CudnnfMHAKind kind; + CudnnfMHABackendConfig backend_config; + Shape lhs_bmm1_shape; + Shape rhs_bmm1_shape; + Shape rhs_bmm2_shape; + Shape intermediate_lhs_bmm2_shape; + // This will contain both output shape and activation shape + std::vector output_shapes; + DotDimensionNumbers bmm1_dnums; + DotDimensionNumbers bmm2_dnums; + + std::optional mask_shape; + std::optional bias_shape; +}; + +struct GpufMHABackwardDescriptor { + CudnnfMHAKind kind; + CudnnfMHABackendConfig backend_config; + Shape bmm1_grad_gemm1_rhs_shape; + Shape bmm1_grad_gemm2_rhs_shape; + Shape bmm2_grad_gemm1_lhs_shape; + Shape bmm2_grad_gemm2_rhs_shape; + Shape d_output_shape; + Shape d_bmm1_lhs_shape; + Shape d_bmm1_rhs_shape; + Shape d_bmm2_rhs_shape; + DotDimensionNumbers bmm1_grad_gemm1_dnums; + DotDimensionNumbers bmm1_grad_gemm2_dnums; + DotDimensionNumbers bmm2_grad_gemm1_dnums; + DotDimensionNumbers bmm2_grad_gemm2_dnums; + + std::optional mask_shape; + std::optional d_bias_shape; +}; +// Structure to describe static properties of a GPU fused Multi-Headed +// Attention. +struct GpufMHAConfig { + static StatusOr For(const GpufMHADescriptor& fmha_desc); + PrimitiveType + input_type; // Capture the primitive type of one of the inputs of BMM1 + PrimitiveType output_type; + CudnnfMHAKind kind; + std::optional fmha_scale; + std::optional dropout_rate; + std::optional seed; + + se::dnn::AlgorithmDesc algorithm; + + // bias -> [1, num_attn_heads, q_seq_len, kv_seq_len] + // mask -> [batch_size, 1, q_seq_len, kv_seq_len] + se::dnn::MatmulTensorDescriptor lhs_bmm1; + se::dnn::MatmulTensorDescriptor rhs_bmm1; + se::dnn::MatmulTensorDescriptor rhs_bmm2; + se::dnn::MatmulTensorDescriptor intermediate_lhs_bmm2; + se::dnn::TensorDescriptor output; + + std::optional activation; + std::optional mask; + std::optional bias; +}; + +// Structure to describe static properties of a GPU fused Multi-Headed +// Attention backward. +struct GpufMHABackwardConfig { + static StatusOr For( + const GpufMHABackwardDescriptor& fmha_desc); + PrimitiveType + input_type; // Capture the primitive type of one of the inputs of BMM1 + PrimitiveType output_type; + CudnnfMHAKind kind; + std::optional fmha_scale; + std::optional dropout_rate; + std::optional seed; + + se::dnn::AlgorithmDesc algorithm; + + // mask -> [batch_size, 1, q_seq_len, kv_seq_len] + // d_bias -> [1, num_heads, q_seq_len, kv_seq_len] + se::dnn::MatmulTensorDescriptor bmm1_grad_gemm1_rhs; + se::dnn::MatmulTensorDescriptor bmm1_grad_gemm2_rhs; + se::dnn::MatmulTensorDescriptor bmm2_grad_gemm1_lhs; + se::dnn::MatmulTensorDescriptor bmm2_grad_gemm2_rhs; + se::dnn::MatmulTensorDescriptor d_output; + se::dnn::TensorDescriptor d_bmm1_lhs; + se::dnn::TensorDescriptor d_bmm1_rhs; + se::dnn::TensorDescriptor d_bmm2_rhs; + se::dnn::TensorDescriptor d_s; + std::optional d_bias; + std::optional mask; +}; + +// Implementation struct exposed for debugging and log analysis. +struct GpufMHAParams { + static StatusOr For( + const GpufMHAConfig& config, se::DeviceMemoryBase lhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm2_buffer, se::DeviceMemoryBase output_buffer, + std::optional mask_buffer, + std::optional bias_buffer, + std::optional activation_buffer); + + const GpufMHAConfig* config; // Not owned + se::DeviceMemoryBase lhs_bmm1_buffer; + se::DeviceMemoryBase rhs_bmm1_buffer; + se::DeviceMemoryBase rhs_bmm2_buffer; + se::DeviceMemoryBase output_buffer; + std::optional activation_buffer; + std::optional mask_buffer; + std::optional bias_buffer; +}; + +struct GpufMHABackwardParams { + static StatusOr For( + const GpufMHABackwardConfig& config, + se::DeviceMemoryBase bmm1_grad_gemm1_rhs_buffer, + se::DeviceMemoryBase bmm1_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm1_lhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase d_output_buffer, + se::DeviceMemoryBase d_bmm1_lhs_buffer, + se::DeviceMemoryBase d_bmm1_rhs_buffer, + se::DeviceMemoryBase d_bmm2_rhs_buffer, se::DeviceMemoryBase d_s_buffer, + std::optional mask_buffer, + std::optional d_bias_buffer); + + const GpufMHABackwardConfig* config; // Not owned + se::DeviceMemoryBase bmm1_grad_gemm1_rhs_buffer; + se::DeviceMemoryBase bmm1_grad_gemm2_rhs_buffer; + se::DeviceMemoryBase bmm2_grad_gemm1_lhs_buffer; + se::DeviceMemoryBase bmm2_grad_gemm2_rhs_buffer; + se::DeviceMemoryBase d_output_buffer; + se::DeviceMemoryBase d_bmm1_lhs_buffer; + se::DeviceMemoryBase d_bmm1_rhs_buffer; + se::DeviceMemoryBase d_bmm2_rhs_buffer; + se::DeviceMemoryBase d_s_buffer; + std::optional d_bias_buffer; + std::optional mask_buffer; +}; + +class FusedMultiHeadedAttentionRunner { + public: + using Repr = + std::variant>>; + + FusedMultiHeadedAttentionRunner() = default; + + explicit FusedMultiHeadedAttentionRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionRunner(Repr runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionRunner(const GpufMHAConfig& config) + : FusedMultiHeadedAttentionRunner(CreateRunner(config)) { + if (std::holds_alternative(repr_)) { + CHECK(false) << "Cannot construct FusedMultiHeadedAttentionRunner with " + "std::monostate"; + } + } + + se::dnn::AlgorithmDesc ToAlgorithmDesc() const { + return std::visit(ToAlgorithmDescVisitor{}, repr_); + } + + se::dnn::LazyOpRunner* AsFusedMHARunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get< + std::unique_ptr>>( + repr_) + .get(); + } + + private: + // The CreateRunner function is defined as static because it + // doesn't need access to any non-static member variables of the + // FusedMultiHeadedAttentionRunner class. Defining it static makes it easy to + // use and makes it clear that it is a utility function that doesn't rely on + // the state of any specific instance of the class. + static Repr CreateRunner(const GpufMHAConfig& config) { + switch (config.kind) { + case CudnnfMHAKind::kBmmBmm: + case CudnnfMHAKind::kSoftmaxDropout: + case CudnnfMHAKind::kSoftmax: + case CudnnfMHAKind::kScaleBiasSoftmax: + case CudnnfMHAKind::kScaleBiasSoftmaxDropout: + case CudnnfMHAKind::kScaleMaskSoftmax: + case CudnnfMHAKind::kScaleMaskSoftmaxDropout: + case CudnnfMHAKind::kScaleBiasMaskSoftmax: + case CudnnfMHAKind::kScaleBiasMaskSoftmaxDropout: + return std::make_unique>( + config.algorithm); + default: + LOG(FATAL) << "Internal error: unsupported CUDNN MHA kind in " + "FusedMultiHeadedAttentionRunner"; + } + } + + struct ToAlgorithmDescVisitor { + template + se::dnn::AlgorithmDesc operator()(const RunnerPtr& runner) { + return runner->ToAlgorithmDesc(); + } + + se::dnn::AlgorithmDesc operator()(const std::monostate&) { + CHECK(false) << "Internal error: uninitialized runner in ToAlgorithmDesc"; + } + }; + + Repr repr_; +}; + +class FusedMultiHeadedAttentionBackwardRunner { + public: + using Repr = std::variant< + std::monostate, // To allow XXX default ctor + std::unique_ptr>>; + + FusedMultiHeadedAttentionBackwardRunner() = default; + + explicit FusedMultiHeadedAttentionBackwardRunner( + std::unique_ptr> + runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionBackwardRunner(Repr runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionBackwardRunner( + const GpufMHABackwardConfig& config) + : FusedMultiHeadedAttentionBackwardRunner(CreateRunner(config)) { + if (std::holds_alternative(repr_)) { + CHECK(false) + << "Cannot construct FusedMultiHeadedAttentionBackwardRunner with " + "std::monostate"; + } + } + + se::dnn::AlgorithmDesc ToAlgorithmDesc() const { + return std::visit(ToAlgorithmDescVisitor{}, repr_); + } + + se::dnn::LazyOpRunner* + AsFusedMHABackwardRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>( + repr_)); + return std::get>>(repr_) + .get(); + } + + private: + // The CreateRunner function is defined as static because it + // doesn't need access to any non-static member variables of the + // FusedMultiHeadedAttentionBackwardRunner class. Defining it static makes it + // easy to use and makes it clear that it is a utility function that doesn't + // rely on the state of any specific instance of the class. + static Repr CreateRunner(const GpufMHABackwardConfig& config) { + switch (config.kind) { + case CudnnfMHAKind::kBackwardBmmBmm: + case CudnnfMHAKind::kBackwardSoftmaxDropout: + case CudnnfMHAKind::kBackwardSoftmax: + case CudnnfMHAKind::kBackwardScaleBiasSoftmax: + case CudnnfMHAKind::kBackwardScaleBiasSoftmaxDropout: + case CudnnfMHAKind::kBackwardScaleBiasMaskSoftmax: + case CudnnfMHAKind::kBackwardScaleBiasMaskSoftmaxDropout: + case CudnnfMHAKind::kBackwardScaleMaskSoftmax: + case CudnnfMHAKind::kBackwardScaleMaskSoftmaxDropout: + return std::make_unique< + se::dnn::LazyOpRunner>( + config.algorithm); + default: + LOG(FATAL) << "Internal error: unsupported CUDNN MHA kind in " + "FusedMultiHeadedAttentionBackwardRunner"; + } + } + + struct ToAlgorithmDescVisitor { + template + se::dnn::AlgorithmDesc operator()(const RunnerPtr& runner) { + return runner->ToAlgorithmDesc(); + } + + se::dnn::AlgorithmDesc operator()(const std::monostate&) { + CHECK(false) << "Internal error: uninitialized runner in ToAlgorithmDesc"; + } + }; + + Repr repr_; +}; + +struct RunFusedMHAOptions { + // Nullable output-parameter pointer for profiling results. + // Profile results remain unused for now since cuDNN FMHA has only one + // algorithm for now. + se::dnn::ProfileResult* profile_result = nullptr; + + // Use this runner cache (and its configured algorithm), instead of the one + // from the instruction. + FusedMultiHeadedAttentionRunner* runner_cache; +}; + +struct RunFusedMHABackwardOptions { + // Nullable output-parameter pointer for profiling results. + // Profile results remain unused for now since cuDNN FMHA has only one + // algorithm for now. + se::dnn::ProfileResult* profile_result = nullptr; + + // Use this runner cache (and its configured algorithm), instead of the one + // from the instruction. + FusedMultiHeadedAttentionBackwardRunner* runner_cache; +}; + +Status RunGpuFMHA(const GpufMHAConfig& fmha_config, + se::DeviceMemoryBase lhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm2_buffer, + se::DeviceMemoryBase output_buffer, + se::DeviceMemoryBase scratch_buffer, + std::optional mask_buffer, + std::optional bias_buffer, + std::optional activation_buffer, + se::Stream* stream, RunFusedMHAOptions = {}); + +Status RunGpuFMHABackward(const GpufMHABackwardConfig& fmha_config, + se::DeviceMemoryBase bmm1_grad_gemm1_rhs_buffer, + se::DeviceMemoryBase bmm1_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm1_lhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase d_output_buffer, + se::DeviceMemoryBase scratch_buffer, + se::DeviceMemoryBase d_bmm1_lhs_buffer, + se::DeviceMemoryBase d_bmm1_rhs_buffer, + se::DeviceMemoryBase d_bmm2_rhs_buffer, + se::DeviceMemoryBase d_s_buffer, + std::optional mask_buffer, + std::optional d_bias_buffer, + se::Stream* stream, RunFusedMHABackwardOptions = {}); + +std::string ToString(const GpufMHAConfig& config); + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_GPU_FUSED_MHA_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_fusible.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_fusible.h new file mode 100644 index 0000000000000000000000000000000000000000..ec02a6c2d04ad4e833b086cfdf160029b2e3c026 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_fusible.h @@ -0,0 +1,197 @@ +/* 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_SERVICE_GPU_GPU_FUSIBLE_H_ +#define XLA_SERVICE_GPU_GPU_FUSIBLE_H_ + +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/reduction_utils.h" +#include "xla/service/instruction_fusion.h" +#include "xla/stream_executor/device_description.h" + +// TODO(b/112957171): Extract logic to determine fusibility of HLO ops from +// GpuInstructionFusion, FusionMerger, and GpuMultiOutputFusion. + +namespace xla { +namespace gpu { + +// Check if the operation accesses the same inputs multiple times +// while generating its outputs. +bool IfFusedReadsElementsMultipleTimes(const HloInstruction& instr); + +// Check if the operation is memory or computationally expensive +// to repeat. +bool IsExpensiveToRepeat(const HloInstruction& instr); + +// Fusion passes frequently do checks across all pairs of "interesting" nodes. +// Computing e.g. FusionFitsInBudget(a, b) requires computing expensive +// properties of `a` and `b` individually. This cache lets us avoid recomputing +// those properties n^2 times. +// +// Invariant: After modifying or removing a fusion node, call Invalidate(node). +struct FusionInfoCache { + public: + // Must be called after modifying or removing a fusion node (or other node + // that's part of this cache). + void Invalidate(const HloInstruction* instr) { + shared_memory_usage.erase(instr); + num_unnested_reductions.erase(instr); + } + + // The rest of the members of this class are for internal use within + // gpu_fusible. You shouldn't need to use them yourself. + absl::flat_hash_map shared_memory_usage; + absl::flat_hash_map num_unnested_reductions; +}; + +// Returns projected shared memory usage of a given instruction in bytes. +int64_t SharedMemoryUsage(const HloInstruction& instr, + FusionInfoCache* cache = nullptr); + +// Returns projected shared memory usage of a reduction fusion. +int64_t ReductionProjectedShmemUsageBytes( + const ReductionDimensions& reduction_dimensions, + const std::vector>& instr_index_groups); + +inline constexpr int64_t MaxOperandsAndOutputsPerFusion() { return 64; } + +// Whether the op tranposes the physical data layout. Fusing such ops may lead +// to uncoalesced data access and may thus not be beneficial. +bool IsPhysicallyTransposing(const HloInstruction& instr); + +// Note that reduction ops are lowered in different ways. Reduce input fusions +// are lowered by IrEmitterUnnested::EmitReductionToVector and must be rooted at +// reduction-to-vector ops. Other reduction ops are lowered by +// GpuElementalIrEmitter and fused like elementwise ops. + +// Whether `instr` is an input fusion rooted at a reduction-to-vector op or a +// multi-output input fusion with at least one reduction-to-vector op root. +bool IsReduceInputFusion(const HloInstruction& instr); + +// Whether `instr` is fusible as root of a reduce input fusions, i.e. `instr` +// is either an unfused reduction-to-vector op or a reduce input fusion. +bool IsInputFusibleReduction(const HloInstruction& instr); + +// Whether `instr` is a nestable variadic reduction +// or a loop fusion rooted with such. +bool IsNestableVariadicReduction(const HloInstruction& instr); + +// Whether `instr` is fusible as root of a scatter input fusions, i.e. `instr` +// is either an unfused scatter op or a scatter input fusion. +bool IsInputFusibleScatter(const HloInstruction& instr); + +// Determines whether the combination of `instr1` and `instr2` into a (possibly +// multi-output) fusion fits within a "budget" -- i.e., does have more operands +// and outputs than is allowed or occupy too much shared memory. If the fusion +// is a producer/consumer fusion and `instr1` is the consumer and `instr2` is +// the producer, set consumer_producer_fusion to true to enable more fusion. +FusionDecision FusionFitsInBudget(const HloInstruction& instr1, + const HloInstruction& instr2, + const se::DeviceDescription& device_info, + bool is_consumer_producer_fusion = false, + FusionInfoCache* cache = nullptr); + +// Check if fusing producer and consumer will generate a heavy computation, e.g. +// producer has a complex computation per output and consumer calls this +// computations multiple times. +bool CreatesHeavyComputation(const HloInstruction& producer, + const HloInstruction& consumer); + +// Returns the instruction that determines the emitter used for lowering, +// sometimes referred to as "the real hero". +const HloInstruction* GetRealHeroForMultiOutputFusion( + const HloInstruction& instr); + +// Whether 'hero1' and 'hero2' are compatible if the two fusions containing +// 'hero1' and 'hero2' are merged together. For example merging two fusions with +// a reduction hero and a transpose here, respectively, does not work. +FusionDecision FusionHeroesAreCompatible(const HloInstruction* hero1, + const HloInstruction* hero2); + +// Whether instruction shapes are compatible for multi-output fusion, i.e. +// whether the emitters support lowering the resulting fusion. +// This function works for both, sibling and producer-consumer multi-output +// fusion. +// So far, multi-output fusion is supported for loop fusions and reduce +// input fusions only. It is up to the caller to ensure the instructions +// themselves are fusible! +FusionDecision ShapesCompatibleForMultiOutputFusion( + const HloInstruction& instr1, const HloInstruction& instr2); + +// Whether the instructions are compatible for producer-consumer fusion +// i.e. whether the producer and consumer are loop/input fusible and +// they are not library calls. +// Used both by instruction fusion and fusion-fusion merging. +FusionDecision IsProducerConsumerFusible(const HloInstruction& producer, + const HloInstruction& consumer); + +// Whether the producer is a valid candidate for a multi-output fusion. +// That is, the root tuple of the multi-output fusion will contain the results +// of both, the producer and consumer. +FusionDecision IsProducerMultiOutputFusible(const HloInstruction& producer); +// Whether `instr` is a candidate for sibling fusion or as a consumer in +// a producer-consumer multi-output fusion. +bool IsFusibleAsMultiOutputFusionRoot(const HloInstruction& instr); + +// Determines the fusion kind to be used when fusing `producer` and `consumer`. +HloInstruction::FusionKind ChooseFusionKind(const HloInstruction& producer, + const HloInstruction& consumer); + +// Returns whether `consumer` is the only non-root user of `instr`. +bool IsConsumerTheOnlyNonRootUser(const HloInstruction& instr, + const HloInstruction& consumer); + +// Returns number of instructions in the fusible `instr`. If `instr` is not a +// fusion instruction, 1 is returned. +size_t GetInstrCountOfFusible(const HloInstruction& instr); + +// Returns the outputs of the fusible `instr`. +absl::InlinedVector GetOutputsOfFusible( + const HloInstruction& instr); + +// Returns the output size of the fusible `instr`. +size_t GetOutputSizeOfFusible(const HloInstruction& instr); + +// Returns instructions which are roots of the fusion, following the operands of +// GTE instructions in the root tuple. Groups multiple subsequent instructions +// with the same root. CHECKs that the fusion never outputs the same instruction +// twice, as well as that there are no explicitly created tuples or nested gtes +// in fusion output. +// +// For input: (tuple (gte R1) (gte R1) O2) +// Expected output: [R1, O2] +// +// For input: (tuple R1 R2 O2) +// Expected output: [R1, R2, O2] +// +// For input: (tuple (gte R1) (gte R1) R2 O3) +// Expected output: [R1, R2, O3] +// +// For input: R1 +// Expected output: [R1] +std::vector GetFusionRoots( + const HloComputation& computation); + +// Whether the instruction is a reduction hero for the given root. +bool IsRealReductionHero(const HloInstruction& root, + const HloInstruction& hero); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_FUSIBLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_hlo_cost_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_hlo_cost_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..10b44ba5c3bca92f16a1886d62ffbdaf5e4fce1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_hlo_cost_analysis.h @@ -0,0 +1,109 @@ +/* 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_SERVICE_GPU_GPU_HLO_COST_ANALYSIS_H_ +#define XLA_SERVICE_GPU_GPU_HLO_COST_ANALYSIS_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Cost analysis for GPUs. +class GpuHloCostAnalysis : public HloCostAnalysis { + // Each instruction creating a new basic block roughly doubles the total + // number of basic blocks and the IR code size accordingly. + static constexpr int64_t kMaxBasicBlockSplitsPerFusion = 10; + static constexpr int64_t kMaxIRSize = 10000; + + public: + explicit GpuHloCostAnalysis( + const Options& options, + const se::DeviceDescription* device_info = nullptr) + : HloCostAnalysis(options), device_info_(device_info) {} + + Status Preprocess(const HloInstruction* hlo) override; + + float ScalingRatio(const HloInstruction& hlo) const; + int64_t NumOfDevices(const HloInstruction& hlo) const; + + Status HandleCustomCall(const HloInstruction* call) override; + + int64_t GetConvolutionFlops(const HloInstruction* convolution) override; + + Status HandleElementwiseOp(const HloInstruction* hlo); + Status HandleElementwiseUnary(const HloInstruction* hlo) override; + Status HandleElementwiseBinary(const HloInstruction* hlo) override; + + Status HandleAllReduce(const HloInstruction* allreduce) override; + + // Estimate the total size of IR accounting for both duplication + // of producer code by consumer and the total number of basic blocks. + // Tell if merged IR size would be too slow to compile. + bool ProducerConsumerMergedTooLarge(const HloInstruction& producer, + const HloInstruction& consumer); + + // IR size scale of an instruction: 1 for most instructions, + // but for fusions is the number of instructions emitted including the + // duplication due to non-element-wise accesses. + float IrSize(const HloInstruction& hlo) const; + + // Total common elementwise utilization of two instructions within a fusion. + // If two parameters have several common elementwise use roots returned is + // the sum of these utilizations. Can also be used to query if a parameter + // is used elementwise from the fusion's root. + float CommonElementwiseUtilization(const HloInstruction* a, + const HloInstruction* b) const; + + const se::DeviceDescription* device_info_; + + protected: + std::unique_ptr CreateNestedCostAnalysis() override; + int64_t FusionParameterReadBytes(const HloInstruction* hlo) const override; + Status FusionCalculateUtilizations(const HloInstruction* fusion) override; + + size_t immediate_constant_max_elements() const override { return 8; } + + bool KeyToCopyFromSubcomputation(absl::string_view key) const override; + + // Some instructions create new LLVM basic blocks; with our current code + // generation this means in the worst case doubling the IR size of a fusion + // containing such an instruction. + // Count these to avoid unmanageable IR code size. + float IrBasicBlockSplitCount(const HloInstruction& hlo) const; + + // To estimate where within the computation an instruction output can be + // reused and where it has to be recomputed again we group accesses to the + // instruction by their origin from "element-wise use roots". All access + // paths from such a root to the instruction are element-wise. + absl::flat_hash_map> + elementwise_use_roots_; + + // Elementwise utilization of instruction's input subtree if it is a root. + // This is different from hlo_properties_[instr][kUtilizationKey] which + // is the utilization of the instruction by other roots. + absl::flat_hash_map root_utilizations_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_HLO_COST_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_hlo_schedule.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_hlo_schedule.h new file mode 100644 index 0000000000000000000000000000000000000000..792dfbd2633c11154506882633becd33e8f930be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_hlo_schedule.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_GPU_HLO_SCHEDULE_H_ +#define XLA_SERVICE_GPU_GPU_HLO_SCHEDULE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +int64_t GetSizeOfShape(const Shape& shape, int pointer_size); + +// Determines the schedule of HLO instructions for a module run on the GPU. +Status ScheduleGpuModule(HloModule* module, int64_t pointer_size, + int64_t memory_limit, + const se::DeviceDescription& gpu_device_info); +HloInstructionSequence PostProcessSchedule(const HloInstructionSequence& input); + +int64_t GetSchedulerMemoryLimit(const HloModule* module, + const se::DeviceDescription& gpu_device_info, + int pointer_size); + +constexpr absl::string_view kFingerprintBeforeLHS = "fingerprint_before_lhs"; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_HLO_SCHEDULE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_layout_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_layout_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..27ca9bcfb72be850489bb74622c9d71a36e19fb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_layout_assignment.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_GPU_GPU_LAYOUT_ASSIGNMENT_H_ +#define XLA_SERVICE_GPU_GPU_LAYOUT_ASSIGNMENT_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/computation_layout.h" +#include "xla/service/layout_assignment.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// GPU-specific layout assignment pass which preassigns layouts to satisfy +// layout constraints for operands and results of library calls. +class GpuLayoutAssignment : public LayoutAssignment { + public: + explicit GpuLayoutAssignment( + ComputationLayout* entry_computation_layout, + se::StreamExecutor* stream_executor, + ChannelLayoutConstraints* channel_constraints = nullptr) + : LayoutAssignment(entry_computation_layout, channel_constraints), + stream_executor_(stream_executor) {} + ~GpuLayoutAssignment() override = default; + + protected: + Status AddBackendConstraints(LayoutConstraints* constraints) override; + + private: + Status AddBackendConstraintsToDnnConvCustomCall( + HloCustomCallInstruction* instr, LayoutConstraints* constraints); + + // dim_groups are ordered from major to minor dimensions. + Status SetOperandMajorToMinorLayout( + const HloInstruction* instruction, int64_t operand, + std::initializer_list> dim_groups); + + Status SetDotOperandLayout(const HloInstruction* instruction, int64_t operand, + absl::Span batch_dims, + absl::Span row_dims, + absl::Span col_dims); + + Status SetDotLayout(const HloInstruction* instruction, + LayoutConstraints* constraints); + + bool PropagateReductionLayoutToOperand(const HloInstruction* user) override; + + se::StreamExecutor* stream_executor_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_LAYOUT_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_performance_model.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_performance_model.h new file mode 100644 index 0000000000000000000000000000000000000000..419255686f352fa47642c9e71283f3b33b8bb11e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_performance_model.h @@ -0,0 +1,160 @@ +/* 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_SERVICE_GPU_GPU_PERFORMANCE_MODEL_H_ +#define XLA_SERVICE_GPU_GPU_PERFORMANCE_MODEL_H_ + +#include +#include + +#include "absl/time/time.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/stream_executor/device_description.h" + +#if GOOGLE_CUDA +#include + +#include "third_party/gpus/cuda/nvml/include/nvml.h" +// Below is a list of function pointers to be used +// for querying device properties through nvml library. +#define NVML_FUNCTOR(name, rettype, args) rettype(*xla_##name) args = nullptr; + +NVML_FUNCTOR(nvmlInit, nvmlReturn_t, ()) +NVML_FUNCTOR(nvmlShutdown, nvmlReturn_t, ()) +NVML_FUNCTOR(nvmlDeviceGetHandleByIndex, nvmlReturn_t, + (unsigned int index, nvmlDevice_t* device)) +NVML_FUNCTOR(nvmlDeviceGetNvLinkCapability, nvmlReturn_t, + (nvmlDevice_t device, unsigned int link, + nvmlNvLinkCapability_t capability, unsigned int* capResult)) + +#endif + +namespace xla { +namespace gpu { + +struct EstimateRunTimeData { + int64_t flops; + int64_t bytes_written; + int64_t num_threads; + absl::Duration write_time; + absl::Duration exec_time; +}; + +class GpuPerformanceModel { + public: + struct RunTimes { + absl::Duration time_unfused; + absl::Duration time_fused; + }; + + static EstimateRunTimeData EstimateRunTimeForInstruction( + const HloInstruction* instr, const GpuHloCostAnalysis* cost_analysis); + + static RunTimes EstimateRunTimes( + const HloInstruction* producer, const GpuHloCostAnalysis* cost_analysis, + std::vector fused_consumers = {}, + bool multi_output = false); + + // Writes estimated execution time to FusionBackendConfig.reification_cost. + static void RecordEstimatedRunTime(HloInstruction* instruction, + const GpuHloCostAnalysis* cost_analysis); + static absl::Duration ComputeTime( + const se::DeviceDescription& gpu_device_info, int64_t n_flops, + int64_t n_threads); + + static absl::Duration ProducerInputAccessTime( + const GpuHloCostAnalysis* cost_analysis, + const se::DeviceDescription& gpu_device_info, + const HloInstruction* producer, + const HloInstruction* fused_consumer = nullptr); +}; + +class GpuPerformanceWithCollectiveModel : public GpuPerformanceModel { + public: + // Different algorithms that can be used to perform the collective. + enum CollectiveAlgo { + RING = 0, + TREE, + }; + + // Table for max system bandwidths GB/s for using NCCL's low latency + // algorithm. This is used for intra-node estimate. + static constexpr std::array kLowLatencyMaxBandwidths = { + 39.0 /* Volta*/, 87.7 /* Ampere*/, 87.7 /* Hopper*/ + }; + + // Max bandwidth in GB/s for ring low latency 128 algorithm per channel on a + // single-node + static constexpr std::array kPerChannelMaxRingLL128Bandwidths = { + 20.0 /* Volta */, + 20.0 /* Ampere */, + 36.7 /* Hopper */, + }; + + // Nvlink unidirectional bandwidth for different compute cap. Note this is per + // lane bandwidth. + static constexpr double kSm60NvlinkBandwidth = 18.0; + static constexpr double kSm70NvlinkBandwidth = 20.0; + static constexpr double kSm80NvlinkBandwidth = 20.0; + static constexpr double kSm90NvlinkBandwidth = 20.0; + + // PCIE bandwidth for PCI Gen3 x16 + static constexpr double kPciBandwidth = 12.0; + + // Discount factor for ring algorithm + static constexpr double kRingAlgorithmDiscountFactor = 0.92; + + // Different tiers for intra-node bandwidth. + static constexpr std::array kIntraNodeSpeeds = { + 40.0, 30.0, 20.0, 18.0, 15.0, 12.0, 10.0, 9.0, 7.0, 6.0, 5.0, 4.0, 3.0}; + // SM90 has different bandwidths. + static constexpr std::array kIntraNodeSpeedsSm90 = { + 60.0, 40.0, 30.0, 24.0, 20.0, 15.0, 12.0, 6.0, 3.0}; + + // Maximum number of channels allowed by NCCL + static constexpr int64_t kMaxNumChannelsRing = 16; + + // ll128 is by default enabled for Volta, Ampere and Hopper, ll128 by default + // launches 640 threads. + static constexpr int64_t kLL128NumThreads = 640; + + static absl::Duration ComputeCollectiveTime( + const HloInstruction& instr, const GpuHloCostAnalysis* cost_analysis, + const se::DeviceDescription& gpu_device_info); + + // Returns NVLink bw in GB/s + static float GetNvlinkBw(se::CudaComputeCapability compute_capability); + + // Initialize nvml library. + static bool InitNvml(); + + // Shut down nvml library. + static bool ShutdownNvml(); + + // This checks if the nvlink supports direct P2P communication, + // If not, we will use PCIE bandwidth to estimate latency. + static uint32_t CheckIfNvlinkSupportsP2P(); + + private: + static absl::Duration ComputeAllreduceTime( + const HloInstruction& instr, const GpuHloCostAnalysis* cost_analysis, + const se::DeviceDescription& gpu_device_info); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_PERFORMANCE_MODEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_reduce_scatter_creator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_reduce_scatter_creator.h new file mode 100644 index 0000000000000000000000000000000000000000..4bc1da7d003fccdb3775caaea3e0d0cadee91176 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_reduce_scatter_creator.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_GPU_GPU_REDUCE_SCATTER_CREATOR_H_ +#define XLA_SERVICE_GPU_GPU_REDUCE_SCATTER_CREATOR_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Transforms dynamic-slice(all-reduce) to a reduce-scatter. +class ReduceScatterCreator : public HloModulePass { + public: + ReduceScatterCreator() = default; + absl::string_view name() const override { return "reduce-scatter-creator"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_REDUCE_SCATTER_CREATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_sanitize_constant_names.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_sanitize_constant_names.h new file mode 100644 index 0000000000000000000000000000000000000000..70bbebd426ca5f9c133f7a9469f877c03814ab08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_sanitize_constant_names.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_SERVICE_GPU_GPU_SANITIZE_CONSTANT_NAMES_H_ +#define XLA_SERVICE_GPU_GPU_SANITIZE_CONSTANT_NAMES_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Sanitizes HLO instruction names for the GPU backend. Currently, it only +// replaces . and - in the HLO constant instruction names with _ to please the +// LLVM PTX backend. +class GpuSanitizeConstantNames : public HloModulePass { + public: + absl::string_view name() const override { return "sanitize-constant-names"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_SANITIZE_CONSTANT_NAMES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_scatter_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_scatter_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..7a91c309b1728b2218d2ab5d10411f5044f45e4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_scatter_expander.h @@ -0,0 +1,38 @@ +/* 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_SERVICE_GPU_GPU_SCATTER_EXPANDER_H_ +#define XLA_SERVICE_GPU_GPU_SCATTER_EXPANDER_H_ + +#include "xla/service/scatter_expander.h" + +namespace xla { + +// Legalizes scatters on the GPU. +class GpuScatterExpander : public ScatterExpander { + public: + // Although we pass kEliminateAllScatters, we override this behavior in + // InstruuctionMatchesPattern and select only some scatters to expand. + GpuScatterExpander() : ScatterExpander(kEliminateAllScatters) {} + + absl::string_view name() const override { return "gpu_scatter_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_SCATTER_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_target_config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_target_config.h new file mode 100644 index 0000000000000000000000000000000000000000..1845bc755116cfb9cfe81a87e447cc0b851d1dae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_target_config.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_GPU_TARGET_CONFIG_H_ +#define XLA_SERVICE_GPU_GPU_TARGET_CONFIG_H_ + +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/dnn.h" + +namespace xla { +namespace gpu { + +struct GpuTargetConfig { + GpuTargetConfig() = default; + explicit GpuTargetConfig(const stream_executor::GpuTargetConfigProto& proto); + explicit GpuTargetConfig(stream_executor::StreamExecutor* s); + + stream_executor::GpuTargetConfigProto ToProto() const; + + stream_executor::DeviceDescription gpu_device_info; + std::string platform_name; + stream_executor::dnn::VersionInfo dnn_version_info; + std::string device_description_str; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_TARGET_CONFIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_transfer_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_transfer_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..5dcc291a9ff4036996088e8d91ecfb8533e2e133 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/gpu_transfer_manager.h @@ -0,0 +1,107 @@ +/* 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_SERVICE_GPU_GPU_TRANSFER_MANAGER_H_ +#define XLA_SERVICE_GPU_GPU_TRANSFER_MANAGER_H_ + +#include + +#include "xla/service/generic_transfer_manager.h" +#include "xla/service/gpu/infeed_manager.h" +#include "xla/service/transfer_manager.h" +#include "xla/shape_tree.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// An implementation of the XLA GenericTransferManager that +// handles GPU-specific infeed. +class GpuTransferManager : public GenericTransferManager { + public: + GpuTransferManager(se::Platform::Id id, unsigned pointer_size); + ~GpuTransferManager() override; + + Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal) override; + Status TransferLiteralFromOutfeed(se::StreamExecutor* executor, + MutableBorrowingLiteral literal) override; + Status ReadDynamicShapes(se::Stream* stream, + const ShapedBuffer* device_buffer, + Shape* device_shape) override; + + private: + GpuTransferManager(const GpuTransferManager&) = delete; + GpuTransferManager& operator=(const GpuTransferManager&) = delete; + + // This class keeps a pool of pinned memory + // (StreamExecutor::HostMemoryAllocate()) that serves ReadDynamicShapes(). + // This is a bit of a hack: Callers like TensorFlow already have a full pinned + // memory allocator, and we could in theory use it here and elsewhere in XLA. + // But because GpuTransferManager is a singleton, we can't really access that. + // + // To keep things relatively simple, our allocator does the following. + // + // - Allocate one chunk of 128 KiB pinned memory. + // - Divide each chunk into 128-byte buffers. + // - During ReadDynamicShapes(), "check out" one buffer for each dynamic + // subshape. Copy one subshape into one buffer. If it doesn't fit or + // there are no free buffers, fall back to an unpinned memcpy. + // + // A 128-byte buffer is large enough to hold a shape of rank 128/sizeof(int32) + // = 32, which is much larger than we normally see in XLA programs. A 128 KiB + // chunk is large enough to hold 128 KiB/128B = 1024 dynamically-shaped + // buffers, which is also way larger than we should need, even if we're + // running multiple programs in parallel. + // + // This pool is lazily initialized on first use. It would be better to + // initialize it in the constructor, but doing so poses a challenge in the + // presence of multiple GPUs. We need a StreamExecutor in order to allocate + // pinned memory. We don't care which GPU's SE we use, because SE allocates + // pinned memory with the PORTABLE flag, making it available to all CUDA + // contexts. But we do need to avoid calling platform->ExecutorForDevice for + // a device that we're not "supposed" to use, because this will create a CUDA + // context for that device, consuming significant resources on the GPU, + // b/228207839. + // + // Lazy initialization works around this, because at that point we have a + // stream, and therefore we have an already-initialized StreamExecutor. + void EnsurePinnedBuffersAllocated(se::StreamExecutor* executor) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + static constexpr int64_t kPinnedChunkBytes = 128 * 1024; + static constexpr int64_t kPinnedBufferBytes = 128; + + absl::Mutex mu_; + + // The StreamExecutor on which our pinned memory was allocated. We use this + // when freeing the pinned memory. Lazily initialized. + se::StreamExecutor* pinned_chunk_se_ ABSL_GUARDED_BY(mu_) = nullptr; + + // Chunk of pinned memory of size kPinnedChunkBytes. The pointers in + // pinned_buffers_ point into this chunk. Lazily initialized. + char* pinned_chunk_ ABSL_GUARDED_BY(mu_) = nullptr; + + // Host buffers for reading dynamic shapes. Each buffer has size + // kPinnedBufferBytes. Lazily initialized. + std::vector pinned_buffers_ ABSL_GUARDED_BY(mu_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_TRANSFER_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_algorithm_denylist.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_algorithm_denylist.h new file mode 100644 index 0000000000000000000000000000000000000000..5dfcb189a954e7fab04ce975abc4d04924cb3032 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_algorithm_denylist.h @@ -0,0 +1,34 @@ +/* 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_SERVICE_GPU_HLO_ALGORITHM_DENYLIST_H_ +#define XLA_SERVICE_GPU_HLO_ALGORITHM_DENYLIST_H_ + +#include + +#include "xla/autotuning.pb.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +absl::Span GetDisabledConvAlgorithms( + ComputeCapability cc, CudnnVersion cudnn_version, + const std::string& blas_version, const std::string& hlo); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_ALGORITHM_DENYLIST_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_fusion_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_fusion_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..131d9c090424702728170e84bd776d78c3234edb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_fusion_analysis.h @@ -0,0 +1,139 @@ +/* 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_SERVICE_GPU_HLO_FUSION_ANALYSIS_H_ +#define XLA_SERVICE_GPU_HLO_FUSION_ANALYSIS_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/hlo_traversal.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/service/gpu/kernel_mapping_scheme.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/gpu/reduction_utils.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +class HloFusionAnalysis { + public: + // The type of emitted fusion. + enum class EmitterFusionKind { + kLoop, + kTriton, + kReduction, + kTranspose, + kInputSlices, + kScatter, + }; + + static StatusOr Create( + FusionBackendConfig backend_config, + std::vector hlo_roots, + FusionBoundaryFn boundary_fn, const se::DeviceDescription* device_info); + static StatusOr Create( + const HloFusionInstruction* fusion, + const se::DeviceDescription* device_info); + + const std::vector& fusion_roots() const { + return fusion_roots_; + } + const FusionBoundaryFn& fusion_boundary() const { + return fusion_boundary_fn_; + } + + // Determines the fusion type for the emitter. + EmitterFusionKind GetEmitterFusionKind() const; + + // Determines the launch dimensions for the fusion. The fusion kind must not + // be `kTriton`. + StatusOr GetLaunchDimensions(); + + // Calculates the reduction information. Returns `nullptr` if the fusion is + // not a reduction. + const ReductionCodegenInfo* GetReductionCodegenInfo(); + + // Calculates the transpose tiling information. Returns `nullptr` if the + // fusion is not a transpose. + const TilingScheme* GetTransposeTilingScheme(); + + // Calculates the loop fusion config. Returns `nullptr` if the fusion is not a + // loop. + const LaunchDimensionsConfig* GetLoopFusionConfig(); + + // Returns the hero reduction of the computation. + const HloInstruction* FindHeroReduction() const; + + private: + HloFusionAnalysis(FusionBackendConfig fusion_backend_config, + std::vector fusion_roots, + FusionBoundaryFn fusion_boundary_fn, + std::vector fusion_arguments, + std::vector fusion_heroes, + const se::DeviceDescription* device_info, + std::optional tiled_transpose) + : fusion_backend_config_(std::move(fusion_backend_config)), + fusion_roots_(std::move(fusion_roots)), + fusion_boundary_fn_(std::move(fusion_boundary_fn)), + fusion_arguments_(std::move(fusion_arguments)), + fusion_heroes_(std::move(fusion_heroes)), + device_info_(device_info), + tiled_transpose_(tiled_transpose) {} + + const Shape& GetElementShape() const; + int SmallestInputDtypeBits() const; + int64_t MaxBeneficialColumnReductionUnrollBasedOnBlockSize() const; + std::vector> GroupDisjointReductions() + const; + bool IsUnrollingColumnReductionBeneficial(const Shape& input_shape, + int64_t num_kept_minor, + bool reduction_is_race_free) const; + bool CanVectorizeReduction(const ReductionDimensions& reduction_dimensions, + int num_threads_x, Vector3 reduction_tiling, + const Shape& input_shape, + bool reduction_is_race_free) const; + int CalculateVirtualThreadScalingFactorForReduction( + const ReductionDimensions& reduction_dimensions) const; + ReductionCodegenInfo ComputeReductionCodegenInfo( + const HloInstruction* hero_reduction) const; + bool HasConsistentTransposeHeros() const; + + FusionBackendConfig fusion_backend_config_; + std::vector fusion_roots_; + FusionBoundaryFn fusion_boundary_fn_; + // The HLO instructions that are inputs into the fusion. These instructions + // are /outside/ the fusion. + std::vector fusion_arguments_; + std::vector fusion_heroes_; + const se::DeviceDescription* device_info_; + std::optional tiled_transpose_; + + std::optional reduction_codegen_info_; + std::optional transpose_tiling_scheme_; + std::optional loop_fusion_config_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_FUSION_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_fusion_stats.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_fusion_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..22e9348200d5b4185e5b5245402fc664da047151 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_fusion_stats.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_SERVICE_GPU_HLO_FUSION_STATS_H_ +#define XLA_SERVICE_GPU_HLO_FUSION_STATS_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +// Read-only pass logging statistics about HLO fusion ops in the module. Enabled +// at VLOG level 1 only. +namespace xla { +namespace gpu { + +class HloOpcodeHistogram : public std::map, int64_t> { + public: + std::string ToString(); +}; + +class HloFusionStatsVisitor : public ConstDfsHloVisitorWithDefault { + public: + Status RunOnModule(HloModule* module); + + std::string ToString(); + + protected: + Status DefaultAction(const xla::HloInstruction* instr) final; + + Status HandleFusion(const HloInstruction* fusion) override; + + private: + int64_t num_fusions_ = 0; + int64_t num_loop_fusions_ = 0; + int64_t num_input_fusions_ = 0; + HloOpcodeHistogram loop_fusion_opcode_histogram_; + HloOpcodeHistogram input_fusion_opcode_histogram_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_FUSION_STATS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_op_profile.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_op_profile.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..a72a24080ed645f4ec9b58abec38249616c088aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_op_profile.pb.h @@ -0,0 +1,803 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/hlo_op_profile.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_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 "xla/service/hlo.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +namespace xla { +namespace gpu { +class DeviceHloInstructionProfiles; +struct DeviceHloInstructionProfilesDefaultTypeInternal; +extern DeviceHloInstructionProfilesDefaultTypeInternal _DeviceHloInstructionProfiles_default_instance_; +class DeviceHloInstructionProfiles_EntriesEntry_DoNotUse; +struct DeviceHloInstructionProfiles_EntriesEntry_DoNotUseDefaultTypeInternal; +extern DeviceHloInstructionProfiles_EntriesEntry_DoNotUseDefaultTypeInternal _DeviceHloInstructionProfiles_EntriesEntry_DoNotUse_default_instance_; +class HloInstructionProfile; +struct HloInstructionProfileDefaultTypeInternal; +extern HloInstructionProfileDefaultTypeInternal _HloInstructionProfile_default_instance_; +class HloInstructionProfileList; +struct HloInstructionProfileListDefaultTypeInternal; +extern HloInstructionProfileListDefaultTypeInternal _HloInstructionProfileList_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::DeviceHloInstructionProfiles* Arena::CreateMaybeMessage<::xla::gpu::DeviceHloInstructionProfiles>(Arena*); +template<> ::xla::gpu::DeviceHloInstructionProfiles_EntriesEntry_DoNotUse* Arena::CreateMaybeMessage<::xla::gpu::DeviceHloInstructionProfiles_EntriesEntry_DoNotUse>(Arena*); +template<> ::xla::gpu::HloInstructionProfile* Arena::CreateMaybeMessage<::xla::gpu::HloInstructionProfile>(Arena*); +template<> ::xla::gpu::HloInstructionProfileList* Arena::CreateMaybeMessage<::xla::gpu::HloInstructionProfileList>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +// =================================================================== + +class HloInstructionProfile final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.HloInstructionProfile) */ { + public: + inline HloInstructionProfile() : HloInstructionProfile(nullptr) {} + ~HloInstructionProfile() override; + explicit PROTOBUF_CONSTEXPR HloInstructionProfile(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInstructionProfile(const HloInstructionProfile& from); + HloInstructionProfile(HloInstructionProfile&& from) noexcept + : HloInstructionProfile() { + *this = ::std::move(from); + } + + inline HloInstructionProfile& operator=(const HloInstructionProfile& from) { + CopyFrom(from); + return *this; + } + inline HloInstructionProfile& operator=(HloInstructionProfile&& 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 HloInstructionProfile& default_instance() { + return *internal_default_instance(); + } + static inline const HloInstructionProfile* internal_default_instance() { + return reinterpret_cast( + &_HloInstructionProfile_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(HloInstructionProfile& a, HloInstructionProfile& b) { + a.Swap(&b); + } + inline void Swap(HloInstructionProfile* 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(HloInstructionProfile* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInstructionProfile* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInstructionProfile& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInstructionProfile& from) { + HloInstructionProfile::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(HloInstructionProfile* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.HloInstructionProfile"; + } + protected: + explicit HloInstructionProfile(::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 { + kInstructionFieldNumber = 1, + kClockCyclesFieldNumber = 2, + }; + // .xla.HloInstructionProto instruction = 1; + bool has_instruction() const; + private: + bool _internal_has_instruction() const; + public: + void clear_instruction(); + const ::xla::HloInstructionProto& instruction() const; + PROTOBUF_NODISCARD ::xla::HloInstructionProto* release_instruction(); + ::xla::HloInstructionProto* mutable_instruction(); + void set_allocated_instruction(::xla::HloInstructionProto* instruction); + private: + const ::xla::HloInstructionProto& _internal_instruction() const; + ::xla::HloInstructionProto* _internal_mutable_instruction(); + public: + void unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction); + ::xla::HloInstructionProto* unsafe_arena_release_instruction(); + + // int64 clock_cycles = 2; + void clear_clock_cycles(); + int64_t clock_cycles() const; + void set_clock_cycles(int64_t value); + private: + int64_t _internal_clock_cycles() const; + void _internal_set_clock_cycles(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.HloInstructionProfile) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::HloInstructionProto* instruction_; + int64_t clock_cycles_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; +// ------------------------------------------------------------------- + +class HloInstructionProfileList final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.HloInstructionProfileList) */ { + public: + inline HloInstructionProfileList() : HloInstructionProfileList(nullptr) {} + ~HloInstructionProfileList() override; + explicit PROTOBUF_CONSTEXPR HloInstructionProfileList(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInstructionProfileList(const HloInstructionProfileList& from); + HloInstructionProfileList(HloInstructionProfileList&& from) noexcept + : HloInstructionProfileList() { + *this = ::std::move(from); + } + + inline HloInstructionProfileList& operator=(const HloInstructionProfileList& from) { + CopyFrom(from); + return *this; + } + inline HloInstructionProfileList& operator=(HloInstructionProfileList&& 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 HloInstructionProfileList& default_instance() { + return *internal_default_instance(); + } + static inline const HloInstructionProfileList* internal_default_instance() { + return reinterpret_cast( + &_HloInstructionProfileList_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(HloInstructionProfileList& a, HloInstructionProfileList& b) { + a.Swap(&b); + } + inline void Swap(HloInstructionProfileList* 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(HloInstructionProfileList* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInstructionProfileList* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInstructionProfileList& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInstructionProfileList& from) { + HloInstructionProfileList::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(HloInstructionProfileList* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.HloInstructionProfileList"; + } + protected: + explicit HloInstructionProfileList(::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 { + kEntriesFieldNumber = 1, + }; + // repeated .xla.gpu.HloInstructionProfile entries = 1; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + ::xla::gpu::HloInstructionProfile* mutable_entries(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >* + mutable_entries(); + private: + const ::xla::gpu::HloInstructionProfile& _internal_entries(int index) const; + ::xla::gpu::HloInstructionProfile* _internal_add_entries(); + public: + const ::xla::gpu::HloInstructionProfile& entries(int index) const; + ::xla::gpu::HloInstructionProfile* add_entries(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >& + entries() const; + + // @@protoc_insertion_point(class_scope:xla.gpu.HloInstructionProfileList) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile > entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; +// ------------------------------------------------------------------- + +class DeviceHloInstructionProfiles_EntriesEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + DeviceHloInstructionProfiles_EntriesEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR DeviceHloInstructionProfiles_EntriesEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit DeviceHloInstructionProfiles_EntriesEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const DeviceHloInstructionProfiles_EntriesEntry_DoNotUse& other); + static const DeviceHloInstructionProfiles_EntriesEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_DeviceHloInstructionProfiles_EntriesEntry_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, "xla.gpu.DeviceHloInstructionProfiles.EntriesEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; + +// ------------------------------------------------------------------- + +class DeviceHloInstructionProfiles final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.DeviceHloInstructionProfiles) */ { + public: + inline DeviceHloInstructionProfiles() : DeviceHloInstructionProfiles(nullptr) {} + ~DeviceHloInstructionProfiles() override; + explicit PROTOBUF_CONSTEXPR DeviceHloInstructionProfiles(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DeviceHloInstructionProfiles(const DeviceHloInstructionProfiles& from); + DeviceHloInstructionProfiles(DeviceHloInstructionProfiles&& from) noexcept + : DeviceHloInstructionProfiles() { + *this = ::std::move(from); + } + + inline DeviceHloInstructionProfiles& operator=(const DeviceHloInstructionProfiles& from) { + CopyFrom(from); + return *this; + } + inline DeviceHloInstructionProfiles& operator=(DeviceHloInstructionProfiles&& 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 DeviceHloInstructionProfiles& default_instance() { + return *internal_default_instance(); + } + static inline const DeviceHloInstructionProfiles* internal_default_instance() { + return reinterpret_cast( + &_DeviceHloInstructionProfiles_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(DeviceHloInstructionProfiles& a, DeviceHloInstructionProfiles& b) { + a.Swap(&b); + } + inline void Swap(DeviceHloInstructionProfiles* 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(DeviceHloInstructionProfiles* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DeviceHloInstructionProfiles* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DeviceHloInstructionProfiles& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DeviceHloInstructionProfiles& from) { + DeviceHloInstructionProfiles::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(DeviceHloInstructionProfiles* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.DeviceHloInstructionProfiles"; + } + protected: + explicit DeviceHloInstructionProfiles(::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 { + kEntriesFieldNumber = 2, + }; + // map entries = 2; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& + _internal_entries() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* + _internal_mutable_entries(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& + entries() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* + mutable_entries(); + + // @@protoc_insertion_point(class_scope:xla.gpu.DeviceHloInstructionProfiles) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + DeviceHloInstructionProfiles_EntriesEntry_DoNotUse, + std::string, ::xla::gpu::HloInstructionProfileList, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// HloInstructionProfile + +// .xla.HloInstructionProto instruction = 1; +inline bool HloInstructionProfile::_internal_has_instruction() const { + return this != internal_default_instance() && _impl_.instruction_ != nullptr; +} +inline bool HloInstructionProfile::has_instruction() const { + return _internal_has_instruction(); +} +inline const ::xla::HloInstructionProto& HloInstructionProfile::_internal_instruction() const { + const ::xla::HloInstructionProto* p = _impl_.instruction_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloInstructionProto_default_instance_); +} +inline const ::xla::HloInstructionProto& HloInstructionProfile::instruction() const { + // @@protoc_insertion_point(field_get:xla.gpu.HloInstructionProfile.instruction) + return _internal_instruction(); +} +inline void HloInstructionProfile::unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + _impl_.instruction_ = instruction; + if (instruction) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.HloInstructionProfile.instruction) +} +inline ::xla::HloInstructionProto* HloInstructionProfile::release_instruction() { + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = 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::HloInstructionProto* HloInstructionProfile::unsafe_arena_release_instruction() { + // @@protoc_insertion_point(field_release:xla.gpu.HloInstructionProfile.instruction) + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = nullptr; + return temp; +} +inline ::xla::HloInstructionProto* HloInstructionProfile::_internal_mutable_instruction() { + + if (_impl_.instruction_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloInstructionProto>(GetArenaForAllocation()); + _impl_.instruction_ = p; + } + return _impl_.instruction_; +} +inline ::xla::HloInstructionProto* HloInstructionProfile::mutable_instruction() { + ::xla::HloInstructionProto* _msg = _internal_mutable_instruction(); + // @@protoc_insertion_point(field_mutable:xla.gpu.HloInstructionProfile.instruction) + return _msg; +} +inline void HloInstructionProfile::set_allocated_instruction(::xla::HloInstructionProto* instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + if (instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(instruction)); + if (message_arena != submessage_arena) { + instruction = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, instruction, submessage_arena); + } + + } else { + + } + _impl_.instruction_ = instruction; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.HloInstructionProfile.instruction) +} + +// int64 clock_cycles = 2; +inline void HloInstructionProfile::clear_clock_cycles() { + _impl_.clock_cycles_ = int64_t{0}; +} +inline int64_t HloInstructionProfile::_internal_clock_cycles() const { + return _impl_.clock_cycles_; +} +inline int64_t HloInstructionProfile::clock_cycles() const { + // @@protoc_insertion_point(field_get:xla.gpu.HloInstructionProfile.clock_cycles) + return _internal_clock_cycles(); +} +inline void HloInstructionProfile::_internal_set_clock_cycles(int64_t value) { + + _impl_.clock_cycles_ = value; +} +inline void HloInstructionProfile::set_clock_cycles(int64_t value) { + _internal_set_clock_cycles(value); + // @@protoc_insertion_point(field_set:xla.gpu.HloInstructionProfile.clock_cycles) +} + +// ------------------------------------------------------------------- + +// HloInstructionProfileList + +// repeated .xla.gpu.HloInstructionProfile entries = 1; +inline int HloInstructionProfileList::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int HloInstructionProfileList::entries_size() const { + return _internal_entries_size(); +} +inline void HloInstructionProfileList::clear_entries() { + _impl_.entries_.Clear(); +} +inline ::xla::gpu::HloInstructionProfile* HloInstructionProfileList::mutable_entries(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.HloInstructionProfileList.entries) + return _impl_.entries_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >* +HloInstructionProfileList::mutable_entries() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.HloInstructionProfileList.entries) + return &_impl_.entries_; +} +inline const ::xla::gpu::HloInstructionProfile& HloInstructionProfileList::_internal_entries(int index) const { + return _impl_.entries_.Get(index); +} +inline const ::xla::gpu::HloInstructionProfile& HloInstructionProfileList::entries(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.HloInstructionProfileList.entries) + return _internal_entries(index); +} +inline ::xla::gpu::HloInstructionProfile* HloInstructionProfileList::_internal_add_entries() { + return _impl_.entries_.Add(); +} +inline ::xla::gpu::HloInstructionProfile* HloInstructionProfileList::add_entries() { + ::xla::gpu::HloInstructionProfile* _add = _internal_add_entries(); + // @@protoc_insertion_point(field_add:xla.gpu.HloInstructionProfileList.entries) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >& +HloInstructionProfileList::entries() const { + // @@protoc_insertion_point(field_list:xla.gpu.HloInstructionProfileList.entries) + return _impl_.entries_; +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// DeviceHloInstructionProfiles + +// map entries = 2; +inline int DeviceHloInstructionProfiles::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int DeviceHloInstructionProfiles::entries_size() const { + return _internal_entries_size(); +} +inline void DeviceHloInstructionProfiles::clear_entries() { + _impl_.entries_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& +DeviceHloInstructionProfiles::_internal_entries() const { + return _impl_.entries_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& +DeviceHloInstructionProfiles::entries() const { + // @@protoc_insertion_point(field_map:xla.gpu.DeviceHloInstructionProfiles.entries) + return _internal_entries(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* +DeviceHloInstructionProfiles::_internal_mutable_entries() { + return _impl_.entries_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* +DeviceHloInstructionProfiles::mutable_entries() { + // @@protoc_insertion_point(field_mutable_map:xla.gpu.DeviceHloInstructionProfiles.entries) + return _internal_mutable_entries(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_op_profiles.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_op_profiles.h new file mode 100644 index 0000000000000000000000000000000000000000..e8b73f73fd22a12e7e69ea945e5e5d9ef817838e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_op_profiles.h @@ -0,0 +1,3092 @@ +/* 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_SERVICE_GPU_HLO_OP_PROFILES_H_ +#define XLA_SERVICE_GPU_HLO_OP_PROFILES_H_ + +namespace xla { +namespace gpu { + +// The data below is obtained with +// xla/service/gpu:hlo_op_profiler_run + +constexpr char kDeviceHloOpProfiles[] = R"pb( + entries { + key: "sm_90" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 351 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S8 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: S8 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 375 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: S16 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 298 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S32 } + } + clock_cycles: 3 + } + entries { + instruction { + opcode: "power" + shape { element_type: S32 } + } + clock_cycles: 66 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 698 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S64 } + } + clock_cycles: 10 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 238 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 308 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U8 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 301 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U32 } + } + clock_cycles: 119 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U32 } + } + clock_cycles: 3 + } + entries { + instruction { + opcode: "power" + shape { element_type: U32 } + } + clock_cycles: 66 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 621 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U64 } + } + clock_cycles: 10 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 238 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 466 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 329 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 105 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 217 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 182 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 245 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 94 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F16 } + } + clock_cycles: 333 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 98 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 200 + } + entries { + instruction { + opcode: "add" + shape { element_type: F16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F16 } + } + clock_cycles: 449 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F16 } + } + clock_cycles: 45 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 491 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 400 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 326 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 80 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 196 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 157 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 221 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F32 } + } + clock_cycles: 77 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 933 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F32 } + } + clock_cycles: 77 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 179 + } + entries { + instruction { + opcode: "add" + shape { element_type: F32 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 428 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F32 } + } + clock_cycles: 24 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F32 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 487 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F32 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1656 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 568 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 382 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 403 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 800 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1210 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 277 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 561 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 333 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 393 + } + entries { + instruction { + opcode: "add" + shape { element_type: F64 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 866 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 530 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F64 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 2179 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F64 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C64 } + } + clock_cycles: 579 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C64 } + } + clock_cycles: 635 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C64 } + } + clock_cycles: 631 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 807 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 614 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 2815 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C64 } + } + clock_cycles: 723 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 4113 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C64 } + } + clock_cycles: 2348 + } + entries { + instruction { + opcode: "add" + shape { element_type: C64 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 6047 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 452 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C64 } + } + clock_cycles: 77 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 4706 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C64 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 1779 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 1333 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 1288 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 2337 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2299 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 5036 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 1997 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 6181 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 4419 + } + entries { + instruction { + opcode: "add" + shape { element_type: C128 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 12453 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 2270 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C128 } + } + clock_cycles: 38 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 7339 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C128 } + } + clock_cycles: 14 + } + } + } + entries { + key: "sm_86" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 370 + } + entries { + instruction { + opcode: "power" + shape { element_type: S8 } + } + clock_cycles: 392 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 367 + } + entries { + instruction { + opcode: "power" + shape { element_type: S16 } + } + clock_cycles: 396 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 306 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 918 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 601 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 306 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 388 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 302 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 399 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U32 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 838 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 604 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 925 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 691 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 108 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 396 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 266 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 284 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F16 } + } + clock_cycles: 226 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 212 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F16 } + } + clock_cycles: 482 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 975 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 867 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 662 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 86 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 381 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 244 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 262 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F32 } + } + clock_cycles: 176 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F32 } + } + clock_cycles: 75 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 662 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F32 } + } + clock_cycles: 75 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 190 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 486 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 925 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 6339 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 1717 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 1652 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 1900 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 608 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 2073 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F64 } + } + clock_cycles: 2412 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 698 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 1789 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 986 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 1609 + } + entries { + instruction { + opcode: "add" + shape { element_type: F64 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 3747 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 2016 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F64 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 5511 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F64 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C64 } + } + clock_cycles: 1360 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C64 } + } + clock_cycles: 1400 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 950 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 842 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 2383 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 3193 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 5353 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 687 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 3351 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 6613 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 4028 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 4161 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 7599 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 6962 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 11318 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 5878 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 15606 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 9939 + } + entries { + instruction { + opcode: "add" + shape { element_type: C128 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 39027 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 7941 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C128 } + } + clock_cycles: 270 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 18205 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C128 } + } + clock_cycles: 97 + } + } + } + + entries { key: "sm_80" + value { entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 417 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 468 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 1094 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 420 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 417 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 391 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 454 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 908 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 744 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 1195 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 321 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 346 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 124 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 499 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 259 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 504 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1221 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1638 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 572 + })pb" + R"pb( + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 699 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1223 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 329 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 597 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 397 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 733 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 1080 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 831 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 1861 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 1037 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 1029 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 6618 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 4131 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 2309 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 2371 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2405 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 3945 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 2284 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 5304 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 3618 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 13564 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 3037 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 6054 + } + } + } + + entries { + key: "sm_70" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 345 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 345 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 954 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 302 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 526 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 309 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 544 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 749 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 820 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 1227 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 865 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 137 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 544 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 354 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 388 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 122 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F16 } + } + clock_cycles: 841 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 134 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 556 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 1279 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 1168 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 823 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 110 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 514 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 333 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 361 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 529 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 660 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1214 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1392 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 673 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 474 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 676 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 618 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1061 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 290 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 667 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 391 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 709 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 1178 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 682 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 1679 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C64 } + } + clock_cycles: 1762 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 1450 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 1141 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C64 } + } + clock_cycles: 1787 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 3935 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 7025 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 948 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 4277 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 2386 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 1881 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 1875 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 2622 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2328 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 4531 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 2408 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 5388 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 3867 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 13794 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 3001 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 6046 + } + } + } + + entries { + key: "sm_60" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 438 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 479 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 758 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 2037 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 2937 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 307 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 293 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 1708 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 2993 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 1661 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 213 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 778 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 598 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 538 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F16 } + } + clock_cycles: 402 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 130 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 453 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 1717 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 1672 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 168 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 731 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 435 + } + )pb" + R"pb( + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 589 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F32 } + } + clock_cycles: 343 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 1024 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 417 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 873 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1779 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1649 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 1175 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 639 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 911 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 935 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1421 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F64 } + } + clock_cycles: 1098 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 355 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 1187 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 645 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 917 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 1394 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 959 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 2667 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 1726 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 1518 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 4142 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 5069 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C64 } + } + clock_cycles: 4053 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 9469 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 1317 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 5617 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 3416 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 2730 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 2765 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 3106 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2895 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 5922 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 3496 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 7014 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 5400 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 21766 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 4133 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 10458 + } + } + } + + entries { + key: "sm_75" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 360 + } + entries { + instruction { + opcode: "power" + shape { element_type: S8 } + } + clock_cycles: 336 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 357 + } + entries { + instruction { + opcode: "power" + shape { element_type: S16 } + } + clock_cycles: 339 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 296 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 979 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 495 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 293 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 334 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 290 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 336 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U32 } + } + clock_cycles: 118 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 812 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 515 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 792 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 815 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 132 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 342 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 239 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 239 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F16 } + } + clock_cycles: 262 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 126 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F16 } + } + clock_cycles: 794 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 123 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 175 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F16 } + } + clock_cycles: 414 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F16 } + } + clock_cycles: 74 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 1120 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 783 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 737 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 83 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 319 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 201 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 218 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F32 } + } + clock_cycles: 181 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F32 } + } + clock_cycles: 74 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 717 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F32 } + } + clock_cycles: 74 + } + )pb" + R"pb( + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 167 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 414 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1085 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 6494 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 1800 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 1630 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 1929 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 596 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1774 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F64 } + } + clock_cycles: 2430 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 705 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 1805 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 984 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 1535 + } + entries { + instruction { + opcode: "add" + shape { element_type: F64 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 3744 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 1915 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F64 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 5538 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F64 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C64 } + } + clock_cycles: 1702 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C64 } + } + clock_cycles: 1503 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C64 } + } + clock_cycles: 1474 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 835 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 737 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 2232 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C64 } + } + clock_cycles: 1632 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 2989 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C64 } + } + clock_cycles: 2263 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 4847 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 3219 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 6474 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 4962 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 4037 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 7286 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 6848 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 10748 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 5391 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 15981 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 9653 + } + entries { + instruction { + opcode: "add" + shape { element_type: C128 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 38206 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 8040 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C128 } + } + clock_cycles: 273 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 18550 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C128 } + } + clock_cycles: 97 + } + } + } +)pb"; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_OP_PROFILES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_to_ir_bindings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_to_ir_bindings.h new file mode 100644 index 0000000000000000000000000000000000000000..3696968160ad1fee484ab917403d1fe12752bfaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_to_ir_bindings.h @@ -0,0 +1,116 @@ +/* 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_SERVICE_GPU_HLO_TO_IR_BINDINGS_H_ +#define XLA_SERVICE_GPU_HLO_TO_IR_BINDINGS_H_ + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/map_util.h" +#include "xla/service/llvm_ir/ir_array.h" + +namespace xla { +namespace gpu { + +// This class encapsulates the bindings between HloInstructions and LLVM IR +// values that represent their addresses. +class HloToIrBindings { + public: + HloToIrBindings(llvm::IRBuilder<>* b, llvm::Module* llvm_module, + bool is_nested) + : is_nested_(is_nested), b_(b), module_(llvm_module) {} + + void EmitBasePointersForHlos( + absl::Span io_hlos, + absl::Span non_io_hlos); + + // Rebinds the given HLO to the LLVM IR value that represent its address. + void BindHloToIrValue(const HloInstruction& hlo, llvm::Value* ir_value, + ShapeIndexView shape_index = {}); + + // Unbinds all IR values that's defined in an LLVM function, e.g., function + // arguments and stack variables. Global variables will be kept in bindings_. + // + // This method is called after emitting code for each top-level HLO. The local + // IR values are out of scope at that point and should not be used. + void UnbindAllLocalIrValues(); + + // Returns whether `hlo` is bound to an LLVM IR value. + bool BoundToIrValue(const HloInstruction& hlo) const { + return base_ptrs_.contains(&hlo); + } + + llvm::Value* GetTempBufferBase() const { return temp_buffer_base_; } + void SetTempBufferBase(llvm::Value* v) { temp_buffer_base_ = v; } + + // A helper method that returns the base pointer of the IrArray containing the + // output of "inst".at the given ShapeIndex. + llvm::Value* GetBasePointer(const HloInstruction& hlo, + ShapeIndexView shape_index = {}) const { + auto it = base_ptrs_.find(&hlo); + CHECK(it != base_ptrs_.end()) << hlo.ToString(); + return it->second.element(shape_index); + } + + // Returns the IrArray which contains the output of hlo. + // + // consumer is the HLO in which this IrArray is used -- we use this to (try + // to) add metadata indicating that the array is invariant within consumer. + // + // To get the buffer into which hlo should write its own output, call + // GetIrArray(hlo, hlo). + llvm_ir::IrArray GetIrArray(const HloInstruction& hlo, + const HloInstruction& consumer, + const ShapeIndex& shape_index = {}); + + std::string ToString() const; + + private: + // Emits IR to resolve (possibly) recursive GetTupleElement instructions. + llvm::Value* EmitGetTupleElement(const HloInstruction* gte, + llvm::Value* base_ptr); + + // Returns an llvm typed ir representation of 'ir_value' based on 'hlo' shape. + llvm::Value* GetTypedIrValue(const HloInstruction& hlo, + ShapeIndexView shape_index, + llvm::Value* ir_value); + + const bool is_nested_; + + llvm::IRBuilder<>* b_; + llvm::Module* module_; + + // Stores the underlying llvm::IrArray for each HloInstruction. + // For an instruction that generates multiple outputs, the root will be a + // tuple shape. The IrArray for each element output is stored in the subnode + // in the ShapeTree. + absl::flat_hash_map> + base_ptrs_; + + // The address of the memory block that contains all temporary buffers. + llvm::Value* temp_buffer_base_ = nullptr; +}; + +// Converts `ir_value` with type i8* to a typed LLVM Value* based on `shape`. +llvm::Value* CastToTypedValue(const Shape& shape, llvm::Value* ir_value, + llvm::IRBuilder<>* b); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_TO_IR_BINDINGS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_traversal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_traversal.h new file mode 100644 index 0000000000000000000000000000000000000000..799a427de94fcc8a46b8679bf280f828eba77eab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/hlo_traversal.h @@ -0,0 +1,81 @@ +/* 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_SERVICE_GPU_HLO_TRAVERSAL_H_ +#define XLA_SERVICE_GPU_HLO_TRAVERSAL_H_ + +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { +namespace gpu { + +enum class TraversalResult { + // Visit the operands of this node. + kVisitOperands, + // Do not visit any more nodes. + kAbortTraversal, + // Do not visit the operands of this node (but continue the traversal + // otherwise). If the node visitation function returns this, the `boundary` + // condition will not be evaluated. + kDoNotVisitOperands, +}; + +using FusionBoundaryFn = std::function; + +// Boundary function for HloFusionInstructions. +bool DefaultFusionBoundaryFn(const HloInstruction& producer, + const HloInstruction& consumer); + +// Creates a fusion boundary function for fusing the given producer and +// consumer. `fused_consumer` must be a consumer of `fused_producer`. +FusionBoundaryFn MakeProducerConsumerFusion( + const HloInstruction& fused_producer, const HloInstruction& fused_consumer); + +// Visit the HLO nodes starting from `roots` in BFS order (consumers before +// producers). Each node will be visited exactly once. The graph is not +// traversed along edges for which `boundary` returns true. +void HloBfsConsumersFirstTraversal( + absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +// Visit the HLO nodes starting from `roots`, returning true if the return value +// of `visit` for any of nodes is true. Uses the same order as +// `HloBfsConsumersFirstTraversal`. +bool HloAnyOf(absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +// Visit the HLO nodes stating from `roots`, returning the first +// node for which `visit` returns true, or `nullptr` if no node matches. Uses +// the same order as `HloBfsConsumersFirstTraversal`. +const HloInstruction* HloFindIf( + absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +// Visit the producers of all parameters that are needed by the fusion. +void FindFusionArguments( + absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_TRAVERSAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/horizontal_input_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/horizontal_input_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..0dc45c90adb5f765cc86b94793100ae5b2bc1c53 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/horizontal_input_fusion.h @@ -0,0 +1,62 @@ +/* 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_SERVICE_GPU_HORIZONTAL_INPUT_FUSION_H_ +#define XLA_SERVICE_GPU_HORIZONTAL_INPUT_FUSION_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// This optimization pass horizontally fuses kInput fusions to both reduce the +// kernel launch overhead and increase parallelism degree. See +// GpuHorizontalFusion for general description and motivation about horizontal +// fusion. GpuHorizontalFusion deals with kLoop fusions while this pass deals +// with kInput fusions. +// +// Following GpuHorizontalFusion, a simple yet effective heuristic is used +// to search the fusion candidates while avoiding creating cycles. That is, +// we simply search for fusion candidates by looking for instructions whose +// outputs are all consumed by the same instruction. This catches the typical +// target cases; often, the candidate instructions are just consumed by the +// ROOT tuple of the entry computation. +class GpuHorizontalInputFusion : public HloModulePass { + public: + explicit GpuHorizontalInputFusion(const se::DeviceDescription& d) + : device_info_(d) {} + + absl::string_view name() const override { + return "gpu_horizontal_input_fusion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation*); + + const se::DeviceDescription& device_info_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HORIZONTAL_INPUT_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/horizontal_loop_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/horizontal_loop_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..4d81ba65412f4d6370f93e8d172dc84be3c5666d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/horizontal_loop_fusion.h @@ -0,0 +1,142 @@ +/* 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_SERVICE_GPU_HORIZONTAL_LOOP_FUSION_H_ +#define XLA_SERVICE_GPU_HORIZONTAL_LOOP_FUSION_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// This optimization pass horizontally fuses computations for reducing kernel +// launch overhead while increasing kernel launch dims on GPU. The initial +// motivation of this horizontal fusion is due to the observation that the +// training optimizer phase (e.g., AdamOptimizer and L2Loss, etc.) typically +// has many small kernels as a result of applying the same formula on many +// training parameters (or variables in Tensorflow). Fusing these small +// kernels, hence, provides performance gain. +// +// Theoretically speaking, we may implement a cycle detection algorithm to make +// sure no cycles are created after fusion. However, cycle detection check is +// somewhat cumbersome; also, we observe that naive horizontal fusion of +// arbitrary kernels may not be profitable due to control divergence and +// possible increase of memory bandwidth pressure due to uncoalesced memory +// accesses (note that horizontal fusion does not change the amount of memory +// read+written at all). In practice, a simple yet effective heuristic is used +// to avoid these issues while addressing the known beneficial cases. That is, +// we simply search for fusion candidates by looking for instructions whose +// outputs are all consumed by the same instruction. This catches the cases in +// the training optimizer phase, as the candidate instructions are typically +// consumed only by the ROOT tuple of the entry computation. +// +// The following illustrates the mechanism of the horizontal fusion. Before +// fusion, there are two trivial kernels in the illustrating example. One has +// only a Mul op, while the other consists of only an Add op. Since they are +// only consumed by the same (ROOT) tuple instruction, horizontal fusion is +// triggered. +// +// i0 i1 i2 i3 +// | | | | +// v v v v +// Mul Add +// | | +// v v +// (ROOT) tuple +// +// We fuse into one of two possible patterns, depending on whether all the +// fused operations have the same shape or not. +// +// case 1: if Mul and Add's output shape and type are the same, then we fuse +// them into the below pattern: i0 i1 i2 i3 +// | | | | +// v v v v +// Mul Add +// | | +// v v +// (ROOT) tuple +// the fused kernel will be kLoop type, i.e, GPU code is emitted through +// IrEmitterUnnested::EmitLoopFusion +// +// case 2: if Mul and Add's output shape are diffent, then we fuse them into +// the below pattern that adds extra indexing: +// i0 i1 i2 i3 +++ (Slice) Input Fusion +// | | | | + +// v v v v + +// Mul Add + +// | | + +// v v + +// Reshape0 Reshape1 + +// | | + +// v v + +// Concatenate + +// | | + +// v v + +// Slice0 Slice1 +++ +// | | +// v v +// Reshape2 Reshape3 +// | | +// v v +// (ROOT) tuple +// +// the fused kernel will be kInput type, and, the GPU code is emitted through +// IrEmitterUnnested::EmitInputFusibleNonStridedSlices +// +// In theory, the pattern in case 1 could also be fused into the case2 target +// graph, but we prefer to fuse into kLoop type, because the codegen for it does +// not have the slicing range check cost introduced by case 2 pattern. +// +// Note that the fusion style by case 2 provides an important advantage that +// kernels of different shapes can be horizontally fused. The first pair of +// reshapes (i.e., Reshape0 and Reshape1) reshape the dims to 1 dimension, so +// that the outputs of the fused kernels can (always) be concatenated. The +// second pair of reshapes (Reshape2 and Reshape3) restore the original shapes +// to the output tensors. +// +// No extra copies are introduced by the horizontal fusion. Besides Reshape2 +// and Reshape3, the other instructions are fused into an input fusion; the +// output dims of the concatenate will be used as the kernel launch dims. +// Instruction bitcasts can be used for Reshape2 and Reshape3 as long as the +// outputs of Mul and Add are row-major. +// +// Note, reshapes are added only if the tensors isn't already a vector. +class GpuHorizontalLoopFusion : public HloModulePass { + public: + GpuHorizontalLoopFusion() = default; + explicit GpuHorizontalLoopFusion(absl::string_view prefix) + : prefix_(prefix) {} + + absl::string_view name() const override { + return "gpu_horizontal_loop_fusion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation*); + std::string prefix_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HORIZONTAL_LOOP_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/infeed_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/infeed_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..055e3139affa768b1f2afb363a9b77717b975532 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/infeed_manager.h @@ -0,0 +1,67 @@ +/* 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. +==============================================================================*/ + +// This header declares classes for the infeed manager and the infeed +// buffer that are used by the GPU runtime to transfer buffers into an +// executing GPU computation, e.g., to feed data into a while loop. + +#ifndef XLA_SERVICE_GPU_INFEED_MANAGER_H_ +#define XLA_SERVICE_GPU_INFEED_MANAGER_H_ + +#include "absl/base/thread_annotations.h" +#include "xla/literal.h" +#include "xla/service/gpu/xfeed_queue.h" +#include "xla/shape_tree.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" + +namespace xla { +namespace gpu { + +// TODO(b/30467474) Once GPU infeed implementation settles, consider +// folding back the cpu and gpu infeed implementations into a generic +// one if possible. +// +// Current limitations: +// * Does not handle multiple devices/replicas. +// +// * Buffer space on GPU is allocated on every infeed enqueue request, +// and it does not handle the case when it runs out of +// memory. Potential solution is to pre-allocate a fixed amount of +// memory and block when that memory is full. + +// Client-side class used to enqueue infeed buffers. +class InfeedManager + : public BlockingXfeedQueue>> { + public: + explicit InfeedManager(se::StreamExecutor* executor); + + Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal); + + private: + se::Stream* stream() const { return stream_.get(); } + + // Stream used to enqueue infeed device copies. + std::unique_ptr stream_; +}; + +// Returns the GPU infeed manager for the given stream executor, +InfeedManager* GetOrCreateInfeedManager(se::StreamExecutor* executor); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_INFEED_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/infeed_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/infeed_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..c2d1cd325e2f184ebbeb9c72679da2b01b71aeae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/infeed_thunk.h @@ -0,0 +1,49 @@ +/* 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_SERVICE_GPU_INFEED_THUNK_H_ +#define XLA_SERVICE_GPU_INFEED_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that infeeds data. Data must be already resident on the +// device. This thunk performs an intra-device copy from that location +// to the buffer allocated for the infeed op. +class InfeedThunk : public Thunk { + public: + // Constructs a InfeedThunk that copies data from the on-device + // infeed queue into the buffers in the given shape tree. + InfeedThunk(ThunkInfo thunk_info, std::vector dest_slices); + + InfeedThunk(const InfeedThunk&) = delete; + InfeedThunk& operator=(const InfeedThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const std::vector dest_slices_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_INFEED_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/instruction_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/instruction_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..bf036cbdd45017627276ae73cb5161332de04218 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/instruction_fusion.h @@ -0,0 +1,86 @@ +/* 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_SERVICE_GPU_INSTRUCTION_FUSION_H_ +#define XLA_SERVICE_GPU_INSTRUCTION_FUSION_H_ + +#include + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/fusion_node_indexing_evaluation.h" +#include "xla/service/fusion_queue.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/instruction_fusion.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +class GpuInstructionFusion : public InstructionFusion { + public: + explicit GpuInstructionFusion(bool may_duplicate, + const se::DeviceDescription& d) + : InstructionFusion(GpuInstructionFusion::IsExpensive, may_duplicate), + device_info_(d) {} + + static bool IsExpensive(const HloInstruction& instruction); + + using HloPassInterface::Run; + StatusOr Run(HloModule* module, + const absl::flat_hash_set& + execution_threads) override { + fusion_node_evaluations_.clear(); + return InstructionFusion::Run(module, execution_threads); + } + + protected: + std::unique_ptr GetFusionQueue( + HloComputation* computation) override; + FusionDecision ShouldFuse(HloInstruction* consumer, + int64_t operand_index) override; + + HloInstruction::FusionKind ChooseKind( + const HloInstruction* producer, const HloInstruction* consumer) override; + + private: + // This method is called by ShouldFuse() to do all the computationally + // inexpensive checks whether we should fuse the operand into 'consumer'. + FusionDecision ShouldFuseInexpensiveChecks(HloInstruction* consumer, + int64_t operand_index); + + HloInstruction* FuseInstruction(HloInstruction* fusion_instruction, + HloInstruction* producer) override; + + // Keep track of the number of times each instruction inside a fusion node is + // indexed with different index vectors. + absl::flat_hash_map + fusion_node_evaluations_; + + se::DeviceDescription device_info_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_INSTRUCTION_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emission_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emission_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a7daa4ccaadcfddba6fc01c7d9416b63a6142552 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emission_utils.h @@ -0,0 +1,219 @@ +/* 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_SERVICE_GPU_IR_EMISSION_UTILS_H_ +#define XLA_SERVICE_GPU_IR_EMISSION_UTILS_H_ + +#include +#include +#include + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/buffer_assignment.h" + +namespace xla { +namespace gpu { + +// If a dimensions is smaller than this, untiled transposition may be more +// efficient. +inline constexpr int64_t kMinDimensionToTransposeTiled = 16; +// But if both swap dimensions are larger than 'kMinDimensionToTransposeTiled2', +// and the product of the dimensions to be swapped is larger than +// 'kMinTotalDimensionsToTransposeTiled', tiled transposition may be more +// efficient. +inline constexpr int64_t kMinDimensionToTransposeTiled2 = 8; +inline constexpr int64_t kMinTotalDimensionsToTransposeTiled = 64 * 128; + +// Matrix multiplication before the rewrite. +// +// This function should never return "true" on instructions after +// GemmRewriter pass has finished. +bool IsMatrixMultiplication(const HloInstruction& dot); + +inline constexpr int64_t WarpSize() { return 32; } + +// Fusions that use Triton have FusionBackendConfig.kind equal to this string. +inline constexpr absl::string_view kTritonGemmFusionKind = "__triton_gemm"; + +// SoftmaxRewriterTriton sets backend_config of Triton Softmax custom fusions to +// this string. +inline constexpr absl::string_view kTritonSoftmaxFusionKind = + "__triton_softmax"; + +inline constexpr absl::string_view kUncompilableFusion = + "__uncompilable_fusion"; + +// Returns true if `hlo` will be implemented as a call to a cuSolver routine. +// +// This returns true if `hlo` is a CustomCall HLO with a call target equal to +// one of the kCusolver... constants, but returns *false* for HLOs with +// say, a kCholesky opcode. +bool IsCustomCallToCusolver(const HloInstruction& hlo); + +// Cholesky decomposition. Takes a (batched) matrix as input, and returns a +// tuple of (result, workspace, info), where result is the result of the +// Cholesky decomposition, workspace is scratch space for cuSolver, and info +// is a success/failure code per batch element. +extern const char* const kCusolverCholeskyCallTarget; + +// Returns whether unnested_hlo is an input fusion whose root is either a slice +// or a tuple of slices. If verify_no_strides is true, returns false unless all +// ROOT slices have no strides. +bool IsInputFusibleSlices(mlir::Operation* unnested_hlo, + bool verify_no_strides); + +// Emits call to "vprintf" with given format and arguments. +llvm::Value* EmitPrintf(absl::string_view fmt, + absl::Span arguments, + llvm::IRBuilder<>* builder); + +// Emits code to shuffle data between threads of a warp. This has the same +// semantics as the PTX "shfl.sync.down" instruction but works for values that +// aren't 32 bits in size. The last operand of the emitted "shfl" is +// `WarpSize() - 1`. +// +// This function emits a "full-warp" shuffle, which all threads of a warp +// participate in. *Do not use this function from a divergent context:* You +// can't correctly do so on both Volta and earlier GPUs. +// +// https://docs.nvidia.com/cuda/parallel-thread-execution/#data-movement-and-conversion-instructions-shfl-sync +llvm::Value* EmitFullWarpShuffleDown(llvm::Value* value, llvm::Value* offset, + llvm::IRBuilder<>* builder); + +// Emits code that determines whether the current thread is thread 0 within +// block 0 of the kernel. +llvm::Value* IsBlock0Thread0(llvm::IRBuilder<>* b); + +int PartitionLmhloOperandsAndOutputs(mlir::Operation* op); +llvm::SmallVector GetHloOperands(mlir::Operation* op); +llvm::SmallVector GetHloOutputs(mlir::Operation* op); + +bool WritesMlirBuffer(mlir::Operation* op, mlir::Value operand); + +template +std::vector ToStdVector(const llvm::SmallVectorImpl& v) { + return std::vector(v.begin(), v.end()); +} + +StatusOr GetAllocationSlice( + mlir::Value v, absl::Span allocations, + std::string* constant_name = nullptr); + +bool CanEmitFusedDynamicUpdateSliceInPlaceForGpu( + mlir::lmhlo::FusionOp fusion, + absl::Span allocations); + +// Returns the dynamic-update-slice instructions defining the results of a +// fusion node. A dynamic slice update is said to be "defining" of a result if +// that result is the output of a dynamic slice update, or if that result is the +// output of a bitcast of a dynamic slice update---since such bitcast may be +// handled as a no-op. +std::vector GetOutputDefiningDynamicUpdateSlices( + const std::vector& roots); + +// Returns the DynamicUpdateSliceOp(s) defining the results of a fusion node. +// A dynamic slice update is said to be "defining" of a result if that result is +// the output of a dynamic slice update, or if that result is the output of a +// bitcast of a dynamic slice update---since such bitcast may be handled as a +// no-op. +std::vector +GetOutputDefiningDynamicUpdateSliceOps(mlir::lmhlo::FusionOp fusion); + +Shape GetShape(mlir::Value value); + +// `is_boundary` returns `true` for edges that are on the boundary of the +// fusion, i.e., they go from an instruction inside the fusion to one outside, +// or vice versa. +const HloInstruction& FindNonTrivialHero( + const HloInstruction& instr, + const std::function& is_boundary); +const HloInstruction& FindNonTrivialHero(const HloInstruction& instr); + +/// Description of how to emit a given transposition. +struct TransposeDescription { + // Transpose instruction. + const HloInstruction* instr; + + // Normalized transpose dimensions. + Vector3 dimensions; + + // Permutations of normalized transpose dimensions. + Vector3 permutation; + + TransposeDescription(Vector3 dimensions, Vector3 permutation) + : TransposeDescription(/*instr=*/nullptr, dimensions, permutation) {} + + TransposeDescription(const HloInstruction* instr, Vector3 dimensions, + Vector3 permutation) + : instr(instr), dimensions(dimensions), permutation(permutation) {} + + std::string ToString() const { + return absl::StrCat("dimensions=", VectorString(dimensions), + ", permutation=", VectorString(permutation)); + } + + // Transpose instruction input shape. + const Shape& input_shape() const { return instr->operand(0)->shape(); } + + // Returns true, if both descriptions have the same dimensions and + // permutation, even if they're produced by different instructions. + bool IsEquivalent(const TransposeDescription& other) const { + return dimensions == other.dimensions && permutation == other.permutation; + } +}; + +std::optional FindTiledTranspose( + const HloInstruction& instr); + +std::optional FindTiledLogicalTranspose( + const HloInstruction& instr); + +std::optional GetDescriptionForTiledTransposeEmitter( + const HloInstruction& root, const HloInstruction& hero); + +bool IsIntermediate(const HloInstruction* instr, int allowed_operand_count = 1); + +// Log and verify an LLVM module. +void LogAndVerify(const llvm::Module* m); + +// Returns the llvm type for the indices used in the kernel that contains the +// hlo instruction. Such indices include the index for the parallel loop and +// the indices for the tensors accessed by the kernel. The return type is i32 +// iff the following conditions are met: +// . The launch_size of the kernel is within the range of i32. +// . The sizes of all the tensors accessed within the kernel are within the +// range of i32. +// Otherwise, the return type is i64. +llvm::Type* GetIndexTypeForKernel(const HloInstruction* hlo, + int64_t launch_size, llvm::IRBuilder<>* b); + +// The same as GetIndexTypeForKernel, but works with MLIR ops. +llvm::Type* GetIndexTypeForKernel(mlir::Operation* op, int64_t launch_size, + llvm::IRBuilder<>* b); + +// Returns a sanitized (doesn't need quoting) identifier name from a location. +std::string GetIrNameFromLoc(mlir::Location loc); + +// Whether the module's target is an AMD GPU. +bool IsAMDGPU(const llvm::Module* module); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMISSION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..8ac0b2075d3cd7a2c77844257a69d8c6138a78ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter.h @@ -0,0 +1,155 @@ +/* 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_SERVICE_GPU_IR_EMITTER_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_H_ + +#include + +#include "llvm/IR/Function.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/hlo_to_ir_bindings.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/llvm_ir/fused_ir_emitter.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/ir_builder_mixin.h" +#include "xla/service/llvm_ir/loop_emitter.h" + +namespace xla { +namespace gpu { + +// Abstract base class for translating HLO graphs to LLVM IR for a GPU. +// +// There are two concrete subclasses of IrEmitter: IrEmitterNested and +// IrEmitterUnnested. In the unnested variety, each HLO gets its own kernel +// function, whereas in the nested version the whole computation is emitted as +// one *non-kernel* function. +// +// In XLA, kernel functions never call other kernel functions. This means that +// if we have a kernel -- e.g. implementing a kReduce HLO -- that wants to use +// an HLO computation as a "subroutine" -- e.g. the HLO computation that +// specifies how to reduce two elements -- then the subroutine computation must +// be emitted using IrEmitterNested. +// +// Fusion nodes are a special case. A fusion node is emitted using +// IrEmitterUnnested, but the code is generated using FusedIrEmitter, which is +// not a subclass of gpu::IrEmitter, and in fact is better understood as an IR +// generator generator. See comments on that class. +class IrEmitter : public DfsHloVisitorWithDefault, + public IrBuilderMixin { + public: + IrEmitter(const IrEmitter&) = delete; + IrEmitter& operator=(const IrEmitter&) = delete; + + Status DefaultAction(HloInstruction* hlo) override; + Status HandleConstant(HloInstruction* constant) override; + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + Status HandleConvolution(HloInstruction* convolution) override; + Status HandleFft(HloInstruction* fft) override; + Status HandleAllReduce(HloInstruction* crs) override; + Status HandleInfeed(HloInstruction* infeed) override; + Status HandleOutfeed(HloInstruction* outfeed) override; + Status HandleSend(HloInstruction* send) override; + Status HandleSendDone(HloInstruction* send_done) override; + Status HandleRecv(HloInstruction* recv) override; + Status HandleRecvDone(HloInstruction* recv_done) override; + Status HandleParameter(HloInstruction* parameter) override; + Status HandleTuple(HloInstruction* tuple) override; + Status HandleScatter(HloInstruction* scatter) override; + Status HandleFusion(HloInstruction* fusion) override; + Status HandleCall(HloInstruction* call) override; + Status HandleCustomCall(HloInstruction* custom_call) override; + Status HandleBatchNormInference(HloInstruction* batch_norm) override; + Status HandleBatchNormTraining(HloInstruction* batch_norm) override; + Status HandleBatchNormGrad(HloInstruction* batch_norm) override; + Status HandleAddDependency(HloInstruction* add_dependency) override; + + Status FinishVisit(HloInstruction* root) override { return OkStatus(); } + + llvm::IRBuilder<>* builder() { return &b_; } + + protected: + // Constructs an IrEmitter with the given IrEmitter context. + // ir_emitter_context is owned by the caller and should outlive the IrEmitter + // object. + explicit IrEmitter(IrEmitterContext* ir_emitter_context, bool is_nested); + + // Helper for calling HloToIrBindings::GetIrArray. + // + // Gets the IrArray which contains inst. This array has metadata that makes + // it valid only within the IR that implements consumer. If you are + // implementing an HLO and want to get its own output buffer, call + // GetIrArray(hlo, hlo). + llvm_ir::IrArray GetIrArray(const HloInstruction& inst, + const HloInstruction& consumer, + const ShapeIndex& shape_index = {}) { + return bindings_.GetIrArray(inst, consumer, shape_index); + } + // A convenient helper for calling HloToIrBindings::GetBasePointer. + llvm::Value* GetBasePointer(const HloInstruction& inst, + ShapeIndexView shape_index = {}) const { + return bindings_.GetBasePointer(inst, shape_index); + } + + // Generates the IrArray for each output of an hlo instruction and returns + // a vector containing such IrArrays. + std::vector ConstructIrArrayForOutputs( + const HloInstruction& hlo); + + // Emit a single-threaded or multi-threaded loop that computes every element + // in the result of the given HLO instruction. This produces a series of + // nested loops (e.g. one for each dimension of the `hlo`'s shape). The body + // of the inner-most loop is provided by the body_emitter function. + virtual Status EmitTargetElementLoop( + const HloInstruction& hlo, + const llvm_ir::ElementGenerator& body_emitter) = 0; + + IrEmitterContext* ir_emitter_context_; + llvm::Module* module_; + + // The following fields track the IR emission state. According to LLVM memory + // management rules, their memory is owned by the module. + llvm::IRBuilder<> b_; + + // Mapping from HLO to its underlying LLVM value. + HloToIrBindings bindings_; + + // Bind all argument IrArrays of `fusion` to `fused_emitter`. + void BindFusionArguments(const HloInstruction* fusion, + FusedIrEmitter* fused_emitter); + + // Emit a fence for AMDGPU if necessary. + void MaybeEmitFenceForAMDGPU(llvm::AtomicOrdering atomic_ordering, + const char* sync_scope_id); + + private: + // A helper method for HandleSort(). It adds the inner comparison loop where + // we compare elements pointed to by 'keys_index' and 'compare_keys_index'. + void EmitCompareLoop(int64_t dimension_to_sort, + const llvm_ir::IrArray::Index& keys_index, + const llvm_ir::IrArray::Index& compare_keys_index, + const llvm_ir::IrArray& keys_array); + + // A convenience method to determine whether or not IR is emitted for AMDGPU. + bool IsEmittingForAMDGPU() const; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_context.h new file mode 100644 index 0000000000000000000000000000000000000000..a981f0d2a2244bb2827bd2c1c0a014d25a84b15a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_context.h @@ -0,0 +1,117 @@ +/* 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_SERVICE_GPU_IR_EMITTER_CONTEXT_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_CONTEXT_H_ + +#include +#include +#include +#include + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/name_uniquer.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// IrEmitterContext encapsulates common (mutable and immutable) data structures +// used by both IrEmitterNested and IrEmitterUnnested, such as the buffer +// assignment and the name uniquer. +class IrEmitterContext { + public: + IrEmitterContext(const HloModule* hlo_module, + const BufferAssignment* buffer_assignment, + std::string platform_name, + const se::DeviceDescription& gpu_device_info, + mlir::MLIRContext* mlir_context, llvm::Module* llvm_module) + : hlo_module_(hlo_module), + buffer_assignment_(buffer_assignment), + platform_name_(std::move(platform_name)), + gpu_device_info_(gpu_device_info), + mlir_context_(mlir_context), + llvm_module_(llvm_module) {} + // Disallow copy and assign. + IrEmitterContext(const IrEmitterContext&) = delete; + IrEmitterContext& operator=(const IrEmitterContext&) = delete; + + // Simple accessors. + const HloModule& hlo_module() const { return *hlo_module_; } + const BufferAssignment& buffer_assignment() const { + return *buffer_assignment_; + } + absl::string_view platform_name() const { return platform_name_; } + const se::DeviceDescription& gpu_device_info() const { + return gpu_device_info_; + } + se::CudaComputeCapability cuda_compute_capability() const { + auto* cc = std::get_if( + &gpu_device_info_.gpu_compute_capability()); + return cc != nullptr ? *cc : se::CudaComputeCapability(); + } + se::RocmComputeCapability rocm_compute_capability() const { + auto* cc = std::get_if( + &gpu_device_info_.gpu_compute_capability()); + return cc != nullptr ? *cc : se::RocmComputeCapability(); + } + mlir::MLIRContext* mlir_context() { return mlir_context_; } + llvm::Module* llvm_module() { return llvm_module_; } + NameUniquer* name_uniquer() { return &name_uniquer_; } + + std::vector& constants() { return constants_; } + + absl::Span allocations() const { + if (buffer_assignment_) { + return buffer_assignment_->Allocations(); + } + return allocations_; + } + + void set_allocations(absl::Span allocations) { + CHECK_EQ(nullptr, buffer_assignment_); + allocations_ = allocations; + } + + // Emit a constant with a given number of element, given byte size of the + // element, given symbol name and content. + void emit_constant(int64_t num_elements, int64_t bytes_per_element, + absl::string_view symbol_name, int allocation_idx, + llvm::ArrayRef content, llvm::IRBuilder<>* b); + + const DebugOptions& debug_options() const { + return hlo_module_->config().debug_options(); + } + + private: + const HloModule* hlo_module_; + const BufferAssignment* buffer_assignment_; + absl::Span allocations_; + std::string platform_name_; + const se::DeviceDescription& gpu_device_info_; + mlir::MLIRContext* mlir_context_; + llvm::Module* llvm_module_; + NameUniquer name_uniquer_; + std::vector constants_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_nested.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_nested.h new file mode 100644 index 0000000000000000000000000000000000000000..9f1b6e1baf9839768b4fc226dcef974ea8da28fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_nested.h @@ -0,0 +1,78 @@ +/* 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_SERVICE_GPU_IR_EMITTER_NESTED_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_NESTED_H_ + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/hlo_module_config.h" + +namespace xla { +namespace gpu { + +// Emits LLVM IR for a "nested computation" into a non-kernel device function. +// +// This is used to emit code for HloComputations that don't require a separate +// kernel call. For example, IrEmitterNested is used to emit code for a kReduce +// HLO's elementwise reduction computation. Notably, IrEmitterNested is *not* +// used to emit code for fusion nodes -- fusion nodes use FusedIrEmitter, which +// is a different beast altogether. +// +// IrEmitterNested generates a non-kernel function with the following +// parameters: +// +// - N pointers to the buffers of each of the N parameters to the computation, +// - a pointer to the output buffer of the computation, and +// - a pointer to the top-level temp buffer. +Status CallNestedComputation(llvm::IRBuilder<>* builder, + IrEmitterContext& ir_emitter_context, + const HloComputation& computation, + absl::Span operands, + llvm::Value* output); + +// Like CallNestedComputation, but parameters and results are scalars. +StatusOr> CallNestedComputationWithScalars( + llvm::IRBuilder<>* builder, IrEmitterContext& ir_emitter_context, + const HloComputation& computation, + absl::Span parameter_elements); + +// Like CallNestedComputationWithScalars, but parameters are scalar addresses. +StatusOr> CallNestedComputationWithScalarAddrs( + llvm::IRBuilder<>* builder, IrEmitterContext& ir_emitter_context, + const HloComputation& computation, + absl::Span parameter_elements_addrs); + +// Emits an atomic operation that implements `nested_computation` in the +// sequentially consistent memory model. `output_address` and `source_address` +// are the arguments of the nested computation. For example, +// atomicAdd(output_address, *source_address). +// +// If the computation can be implemented using a single atomic operation, it +// will, otherwise it will be emitted as a compare-and-swap and a loop. +// +// The computation must have exactly two parameters. +Status EmitAtomicOperationForNestedComputation( + llvm::IRBuilder<>* builder, IrEmitterContext& ir_emitter_context, + const HloComputation& computation, llvm::Value* output_address, + llvm::Value* source_address, llvm::Type* element_type); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_NESTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_triton.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_triton.h new file mode 100644 index 0000000000000000000000000000000000000000..9edf27853e22fd97b597269f2a2a6535d4617427 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_triton.h @@ -0,0 +1,97 @@ +/* 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_SERVICE_GPU_IR_EMITTER_TRITON_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_TRITON_H_ + +#include + +#include "absl/strings/string_view.h" +#include "llvm/IR/Module.h" +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/gpu/gemm_rewriter_triton.h" +#include "xla/service/gpu/hlo_traversal.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "triton/Dialect/Triton/IR/Dialect.h" + +namespace xla { +namespace gpu { + +struct TritonWrapperResult { + int64_t shmem_bytes; +}; + +// Compute the launch dimensions for the given Triton MatMul. +LaunchDimensions GetMatMulLaunchDimensions( + const TritonFusionAnalysis& analysis, + absl::Span roots, + const FusionBoundaryFn& fusion_boundary, + const AutotuneResult::TritonGemmKey& config); +// Use tiling and execution parameters from 'config'. +Status EmitMatMul(mlir::OpBuilder b, absl::string_view libdevice_path, + const TritonFusionAnalysis& analysis, + const HloComputation* computation, mlir::triton::FuncOp fn, + const AutotuneResult::TritonGemmKey& config, + int shmem_budget); + +// Compute the launch dimensions for the given Triton SoftMax. +LaunchDimensions GetSoftMaxLaunchDimensions( + absl::Span roots, + const FusionBoundaryFn& fusion_boundary, + const AutotuneResult::TritonGemmKey& config); +// Generate Softmax in Triton IR inside 'fn'. +// Use execution parameters from 'config'. +Status EmitSoftMax(mlir::OpBuilder b, absl::string_view libdevice_path, + const TritonFusionAnalysis& analysis, + const HloComputation* computation, mlir::triton::FuncOp fn, + const AutotuneResult::TritonGemmKey& config, + int shmem_budget); + +using TritonIrEmitter = std::function; + +// Generate Triton IR by running the provided generator and compile it into LLVM +// IR. +// MatMul and SoftMax above are some such IR generators. +StatusOr TritonWrapper( + const TritonFusionAnalysis& analysis, absl::string_view fn_name, + const HloComputation* hlo_computation, absl::string_view fusion_kind, + const se::CudaComputeCapability& cc, + const se::DeviceDescription& device_info, + const AutotuneResult::TritonGemmKey& config, llvm::Module* llvm_module, + TritonIrEmitter ir_emitter, mlir::MLIRContext& mlir_context); + +// Creates the initial Triton module for the given fusion. Visible for testing, +// use TritonWrapper instead. +StatusOr> CreateTritonModule( + const TritonFusionAnalysis& analysis, absl::string_view fn_name, + const HloComputation* hlo_computation, + const se::DeviceDescription& device_info, + const AutotuneResult::TritonGemmKey& config, TritonIrEmitter ir_emitter, + mlir::MLIRContext& mlir_context); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_TRITON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_unnested.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_unnested.h new file mode 100644 index 0000000000000000000000000000000000000000..0a2830aae4c9d551e35a1a05e17f78f4bb4b90c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/ir_emitter_unnested.h @@ -0,0 +1,442 @@ +/* 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_SERVICE_GPU_IR_EMITTER_UNNESTED_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_UNNESTED_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/elemental_ir_emitter.h" +#include "xla/service/gpu/fusions/tiling_util.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emitter.h" +#include "xla/service/gpu/kernel_mapping_scheme.h" +#include "xla/service/gpu/kernel_reuse_cache.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/llvm_util.h" + +namespace xla { +namespace gpu { + +struct BufferSlice { + // The root buffer to look at. + BufferAllocation::Slice buffer_slice; + + // The global constant name of the buffer, if it's a constant. + std::string constant_name; + + // The buffer is modified by the kernel. + bool written = false; + + Shape shape; +}; + +// Emits LLVM IR for an "unnested computation". +// +// An unnested computation is an HloComputation which you run by executing one +// or more kernels for each HloInstruction it contains. Examples of unnested +// computations: +// +// - An HloModule's root computation, +// - The body of an HLO while loop, +// - The true/false computation of an HLO conditional. +// +// Note the opportunity for confusion -- the while loop's computation is nested +// within the root computation, but it's emitted using IrEmitterUnnested! Don't +// think about it too hard. +// +// Examples of things that are not unnested computations: +// +// - The body of a fusion node. IrEmitterUnnested emits the relevant code +// within a kernel function using FusedIrEmitter. (FusedIrEmitter is not +// really an IrEmitter, but is more an "IR generator generator".) +// +class IrEmitterUnnested : public IrEmitter { + public: + absl::string_view platform_name() const { + return ir_emitter_context_->platform_name(); + } + + using ValueVector3 = std::array; + using ValueVector2 = std::array; + + using ConstantGenerator = std::function; + + IrEmitterUnnested(const IrEmitterUnnested&) = delete; + IrEmitterUnnested& operator=(const IrEmitterUnnested&) = delete; + + static std::unique_ptr Create( + IrEmitterContext* ir_emitter_context); + + // Transfers the ownship of thunk_sequence_ out. + std::unique_ptr ConsumeThunkSequence() { + return std::make_unique(std::move(thunk_sequence_)); + } + + // Emits code for the given LMHLO region. + // + // Also populates related information to 'ir_emitter_context_' for + // large-constant initializations. Large constants don't get initializers in + // the generated code and so must be initialized by XLA. The value of these + // constants will be stored in 'content'. Constants with initializers in the + // generated code will have empty 'content'. + Status EmitLmhloRegion( + mlir::Region* region, + const absl::flat_hash_map& + hlo_for_lmhlo); + + static void GetDependentDialects(mlir::DialectRegistry& registry); + + private: + explicit IrEmitterUnnested(IrEmitterContext* ir_emitter_context); + + Status EmitUnreachable(mlir::Operation* op, std::string error_message); + + // IrEmitterUnnested handles the following instructions differently from + // IrEmitter. It also mixes in some special handling for custom kernels + // via the ThunkEmitter. + Status EmitConstant(mlir::Operation* op); + + Status EmitConditional( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitConvolutionThunk(mlir::Operation* op); + Status EmitGemmThunk(mlir::Operation* op); +#if GOOGLE_CUDA || TF_HIPBLASLT + Status EmitCublasLtMatmulThunk(mlir::Operation* op); +#endif // GOOGLE_CUDA || TF_HIPBLASLT +#if GOOGLE_CUDA + Status EmitCublasLtMatmulThunkF8(mlir::Operation* op); + Status EmitConvolutionReorderThunk(mlir::Operation* op); + Status EmitTritonFusion( + const HloFusionAnalysis& hlo_fusion_analysis, mlir::Operation* op, + const AutotuneResult::TritonGemmKey& config, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitFusedMHAThunk(mlir::Operation* op); + Status EmitFusedMHABackwardThunk(mlir::Operation* op); +#endif // GOOGLE_CUDA +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + Status EmitCholeskyThunk(mlir::Operation* op); +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + Status EmitCustomCallThunk(mlir::Operation* op); + Status EmitFftThunk(mlir::Operation* op); + Status EmitFusion( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitSelectAndScatter( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitWhile( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitInfeed(mlir::Operation* op); + Status EmitOutfeed(mlir::Operation* op); + Status EmitRngGetAndUpdateState(mlir::Operation* op); + Status EmitScatter( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitSort( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + Status EmitTriangularSolveCustomCall(mlir::Operation* op); +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + + template + Status EmitNcclThunk(mlir::Operation* op); + template + Status EmitNcclAsyncDone(Thunk::Kind kind, mlir::Operation* op); + + template + Status EmitReplicaOrPartitionId(mlir::Operation* op); + + template + Status EmitCollectivePermute(mlir::Operation* op); + + Status EmitOp( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + + static Thunk::ThunkInfo GetThunkInfo(mlir::Operation* op); + + Status EmitTargetElementLoop( + const HloInstruction& hlo, + const llvm_ir::ElementGenerator& body_emitter) override; + + // Add a owning Thunk object to the thunk sequence. + void AddThunkToThunkSequence(std::unique_ptr thunk) { + thunk_sequence_.emplace_back(std::move(thunk)); + } + + // Load data from potentially unaligned address. If address is offset by + // `alignment_bytes`, data is read in the unit of `alignment_bytes` to avoid + // memory read misalignment in CUDA; otherwise, the entire data are loaded + // from the given memory address. + // + // address: the memory address to load data from. + // data_type: the type of data to load. + // alignment_bytes: the number of bytes required to align. The number of + // bytes of the data_type must be divisible by alignment_bytes. + llvm::Value* CreateLoad(llvm::Value* address, llvm::Type* data_type, + int alignment_bytes); + + // Store data at a potentially unaligned address. If the address is offset by + // `alignment_bytes`, data is stored in the unit of `alignment_bytes` to avoid + // memory write misalignment in CUDA; otherwise, the entire data is stored at + // the given memory address. + // + // data: the data to be stored. + // address: the memory address to store data. + // alignment_bytes: the number of bytes required to align. The number of + // bytes of the data_type must be divisible by alignment_bytes. + void CreateStore(llvm::Value* data, llvm::Value* address, + int alignment_bytes); + + // Input = {static array, dynamic_dim0, dynamic_dim1} + // Output = {dynamic array(with dynamic dimension meta data at the end)} + // For a tensor with static dimension [2][<=5] and dynamic dimension [2][3] + // (`_` stands for padding) + // Input = {{1,2,3,_,_,4,5,6_,_}, 2, 3} + // Output = {{1,2,3,4,5,6,_,_,_,_,2,3}} + + // pseudo code for padToStatic on a 2d array + // ``` + // void padToStatic(int** input, int** output, int threads_per_block, + // int meta_data_offset, int max_num_element, + // int static_dim0_size, int static_dim1_size) { + // int* source_array = input[0]; + // int* dest_array = output[0]; + + // // extract the dynamic dimension from the source array's metadata + // int* dyn_dim0_size = source_array + meta_data_offset; + // int* dyn_dim1_size = source_array + meta_data_offset + sizeof(int); + + // // only one thread need to store the dynamic index + // int thread_id = GetThreadId(); + // int block_id = GetBlockId(); + // if (thread_id == 0 && block_id == 0) { + // *output[1] = *dyn_dim0_size; + // *output[2] = *dyn_dim1_size; + // } + + // int dyn_element_total = 1; + // dyn_element_total *= *dyn_dim0_size; + // dyn_element_total *= *dyn_dim1_size; + // linear_index = block_id * threads_per_block + thread_id; + // if (linear_index < max_num_element) { + // Index static_index = + // delinerized(linerized_index, static_dim0_size, static_dim1_size); + // if (linerized_index < dyn_element_total) { + // Index dyn_index = + // delinerized(linerized_index, *dyn_dim0_size, *dyn_dim1_size); + // dest_array[dyn_index.dim0][dyn_index.dim1] = + // source_array[static_index.dim0][static_index.dim1]; + // } + // } + // return; + // } + // ``` + Status EmitPadToStatic(mlir::Operation* op); + + // Input = {dynamic array(with dynamic dimension meta data at the end)} + // Output = {static array, dynamic_dim0, dynamic_dim1} + // For a tensor with static dimension [2][<=5] and dynamic dimension [2][3] + // (`_` stands for padding) + // Input = {{1,2,3,4,5,6,_,_,_,_,2,3}} + // Output = {{1,2,3,_,_,4,5,6_,_}, 2, 3} + + // pseudo code for sliceToDynamic on a 2d array + // ``` + // void sliceToDynamic(int** input, int** output, int threads_per_block, + // int meta_data_offset, int max_num_element, + // int static_dim0_size, int static_dim1_size) { + // int* source_array = input[0]; + // int* dest_array = output[0]; + + // // calculate the location where metadata needs to be inserted + // int* dyn_dim0_size = dest_array + meta_data_offset; + // int* dyn_dim1_size = dest_array + meta_data_offset + sizeof(int); + + // // only one thread need to store the dynamic index + // int thread_id = GetThreadId(); + // int block_id = GetBlockId(); + // if (thread_id == 0 && block_id == 0) { + // *dyn_dim0_size = *output[1]; + // *dyn_dim1_size = *output[2]; + // } + + // int dyn_element_total = 1; + // dyn_element_total *= *dyn_dim0_size; + // dyn_element_total *= *dyn_dim1_size; + // linear_index = block_id * threads_per_block + thread_id; + // if (linear_index < max_num_element) { + // Index static_index = + // delinerized(linerized_index, static_dim0_size, static_dim1_size); + // if (linerized_index < dyn_element_total) { + // Index dyn_index = + // delinerized(linerized_index, *dyn_dim0_size, *dyn_dim1_size); + // dest_array[static_index.dim0][static_index.dim1] = + // source_array[dyn_index.dim0][dyn_index.dim1]; + // } + // } + // return; + // } + // ``` + Status EmitSliceToDynamic(mlir::Operation* op); + + StatusOr GetAllocationSlice(mlir::Value v); + + int64_t ByteSizeOf(const Shape& shape) const { + return llvm_ir::ByteSizeOf( + shape, ir_emitter_context_->llvm_module()->getDataLayout()); + } + + // Emits code for an in-place scatter, modifying `thunk`s launch dimensions in + // the process. Scatter indices are taken from `scatter_indices_gen`, updates + // from `updates_gen`. The output buffer is expected to have the operand + // values in it already. If unique_indices is false, we will use an atomic + // update. Using true for unique_indices behaves properly only when it is + // guaranteed that the indices to be updated do not overlap. The caller is + // responsible for ensuring this is the case. + Status EmitScatter( + mlir::lmhlo::ScatterOp scatter, const LaunchDimensions& launch_dimensions, + const llvm_ir::IrArray& output, + const llvm_ir::ElementGenerator& scatter_indices_gen, + const llvm_ir::ElementGenerator& updates_gen, + std::function get_index_type, + const absl::flat_hash_map& + hlo_for_lmhlo); + + // Structure describing a scatter operation for IR emission. + // TODO(jurahul): Migrate element generators to use MLIR. + // Migrate update_computation to be an MLIR Region. + struct ScatterDescriptor { + std::string name; + Shape operand_shape; + Shape scatter_indices_shape; + Shape updates_shape; + mlir::mhlo::ScatterDimensionNumbersAttr dim_numbers; + bool unique_indices; + const HloComputation* update_computation; + llvm_ir::IrArray output; + llvm_ir::ElementGenerator scatter_indices_gen; + llvm_ir::ElementGenerator updates_gen; + std::function get_index_type; + }; + + // Emits code for an in-place scatter using the provided scatter operation + // description. + Status EmitScatter(const ScatterDescriptor& desc, + const LaunchDimensions& launch_dimensions); + + Status EmitScatter(mlir::lmhlo::FusionOp fusion_op, + const HloComputation* fused_computation, + HloFusionAnalysis& fusion_analysis); + + // Builds a kernel thunk for a non-fusion operation, without reuse. + // + // All input and output tensors of `op` are passed to the kernel. + // + // TODO(tdanyluk): Consider also reusing non-fusion kernels. + StatusOr /*inputs*/, + std::vector /*outputs*/>> + BuildKernelThunkForNonFusionOp(mlir::Operation* op, + const LaunchDimensions& launch_dimensions); + + // Builds a kernel thunk for a non-fusion operation, without reuse. + // + // Only the tensors specified in `needed_operands` are passed to the kernel. + // + // TODO(tdanyluk): Consider also reusing non-fusion kernels. + StatusOr /*inputs*/, + std::vector /*outputs*/>> + BuildKernelThunkForNonFusionOp(mlir::Operation* op, + mlir::ValueRange needed_operands, + const LaunchDimensions& launch_dimensions); + + Status BuildInitializerThunk(mlir::Operation* op, mlir::Value init_value, + mlir::Value dest); + + // Returns a WhileThunk that invokes thunk sequences for 'condition' and + // 'body' sub-computations of while instruction 'hlo'. + StatusOr> BuildWhileThunk( + mlir::lmhlo::WhileOp while_op, const Thunk::ThunkInfo& thunk_info, + const absl::flat_hash_map& + hlo_for_lmhlo); + + // Returns a ForThunk which executes 'loop_limit' invocations of a thunk + // sequence from the 'body' sub-computation of the while instruction 'hlo'. + StatusOr> BuildForThunk( + mlir::lmhlo::WhileOp while_op, const Thunk::ThunkInfo& thunk_info, + int64_t loop_limit, + const absl::flat_hash_map& + hlo_for_lmhlo); + + // Returns a ConditionalThunk which executes the thunk sequence for the + // 'branch_computation' corresponding to the predicate/branch_index of the + // given conditional instruction. + StatusOr> BuildConditionalThunk( + const HloInstruction* conditional); + + Status AssertNonDeterminismIsOkay(const std::string& op_name); + + // The thunk sequence this IrEmitter generates for the input computation. + ThunkSequence thunk_sequence_; + + // Maps async start ops to their executors so done can access the thunk. + // Executor may be null if the start op is degenerate (so not emitted). + absl::flat_hash_map + async_executors_; + + // Begin optional members for XLA HLO -> LMHLO: + absl::flat_hash_map> + scratch_nested_computations_; + // End optional members for XLA HLO -> LMHLO. + + // Returns the ShapedSlices for the given operands. + StatusOr> GetShapedSlices( + mlir::Operation::operand_range operands); + + GpuElementalIrEmitter elemental_emitter_; + + KernelReuseCache kernel_reuse_cache_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_UNNESTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_arguments.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_arguments.h new file mode 100644 index 0000000000000000000000000000000000000000..a7953030b01e7f88fd8958ac2aecbc3740ee617a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_arguments.h @@ -0,0 +1,92 @@ +/*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_SERVICE_GPU_KERNEL_ARGUMENTS_H_ +#define XLA_SERVICE_GPU_KERNEL_ARGUMENTS_H_ + +#include +#include +#include + +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/buffer_assignment.h" +#include "xla/shape.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// An argument descriptor for kernels. +// Thread-safe. +class KernelArgument { + public: + static StatusOr Create( + absl::Span allocations, mlir::Value value, + bool is_written); + + mlir::Value value() const { return value_; } + const Shape& shape() const { return shape_; } + const BufferAllocation::Slice& slice() const { return slice_; } + bool written() const { return written_; } + int64_t alignment() const { return alignment_; } + std::optional first_with_same_slice() const { + return first_with_same_slice_; + } + bool aliased() const { return aliased_; } + + private: + KernelArgument(mlir::Value value, Shape shape, BufferAllocation::Slice slice, + bool written) + : value_(value), shape_(shape), slice_(slice), written_(written) {} + + mlir::Value value_; + Shape shape_; + BufferAllocation::Slice slice_; + bool aliased_ = true; + int64_t alignment_ = 1; + bool written_ = true; + // Holds the index of the first argument which has the same slice as this, + // if this is not the first such argument. + std::optional first_with_same_slice_; + + friend class KernelArguments; +}; + +class KernelArguments { + public: + static StatusOr Create( + absl::Span allocations, + mlir::lmhlo::FusionOp fusion); + + static StatusOr Create( + absl::Span allocations, + mlir::Operation* non_fusion_op, mlir::ValueRange needed_operands); + + const std::vector& args() const { return args_; } + + private: + explicit KernelArguments(std::vector args) + : args_(ProcessArguments(std::move(args))) {} + + static std::vector ProcessArguments( + std::vector kernel_arguments); + + std::vector args_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_ARGUMENTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_mapping_scheme.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_mapping_scheme.h new file mode 100644 index 0000000000000000000000000000000000000000..4a6f0f7ae3c6fa1904b8d2a0adb2364213e8070d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_mapping_scheme.h @@ -0,0 +1,265 @@ +/* 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_SERVICE_GPU_KERNEL_MAPPING_SCHEME_H_ +#define XLA_SERVICE_GPU_KERNEL_MAPPING_SCHEME_H_ + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/llvm_ir/loop_emitter.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +// Describes tiling used by the kernel. +// +// Used by reductions and 021 transpose algorithm. Both algorithms operate over +// "logical" 3D views over input arrays, hence tiling and number of threads +// information has only 3 dimensions. +// +// In the presence of virtual threadIdx/blockIdx scaling, all accessors are +// "logical", unless otherwise specified. +class TilingScheme { + public: + enum { DimZ = 0, DimY, DimX, DimTot }; + + enum IndexingOrder { + // Thread reads consecutive elements. + LinearIndexingX, + // Thread reads strided elements while keeping memory coalescing. + StridedIndexingX, + }; + + TilingScheme(Vector3 dims_in_elems, Vector3 tile_sizes, Vector3 num_threads, + IndexingOrder indexing_order, int vector_size, + int scaling_factor, Vector2 tiling_dimensions = Vector2{1, 2}) + : dims_in_elems_(dims_in_elems), + tile_sizes_(tile_sizes), + tiling_dimensions_(tiling_dimensions), + num_threads_(num_threads), + indexing_order_(indexing_order), + vector_size_(vector_size), + thread_id_virtual_scaling_(scaling_factor) { + CHECK_EQ(tile_sizes[2] % vector_size_, 0) + << "tile sizes = " << absl::StrJoin(tile_sizes, ", ") + << "; vector size = " << vector_size_; + } + + static std::string IndexingOrderToString(IndexingOrder order) { + switch (order) { + case LinearIndexingX: + return "linear"; + case StridedIndexingX: + return "strided"; + } + } + + std::string ToString() const { + return absl::StrJoin( + {absl::StrFormat("dims_in_elems = {%s}", + absl::StrJoin(dims_in_elems_, ", ")), + absl::StrFormat("tile_sizes = {%s}", absl::StrJoin(tile_sizes_, ", ")), + absl::StrFormat("num_threads = {%s}", + absl::StrJoin(num_threads_, ", ")), + absl::StrFormat("indexing_order = %s", + IndexingOrderToString(indexing_order_)), + absl::StrFormat("vector_size = %d", vector_size_), + absl::StrFormat("thread_id_virtual_scaling = %d", + thread_id_virtual_scaling_), + absl::StrFormat("tiling_dimensions = {%s}", + absl::StrJoin(tiling_dimensions_, ", "))}, + ", "); + } + + // Number of elements in each dimension (Z/Y/X respectively). + absl::Span GetDimsInElems() const { return dims_in_elems_; } + + Vector3 GetDimsInBlocks() const { + return {GetDimInBlock(0), GetDimInBlock(1), GetDimInBlock(2)}; + } + + // Number of blocks required to "cover" the given dimension. + int64_t GetDimInBlock(int d) const { + return CeilOfRatio(dims_in_elems_[d], GetBlockTileSizeFor(d)); + } + + // Tile size for a given dimensions per thread. + // + // Equals to the number of iterations in the loop each tile will make. + int64_t GetTileSizeFor(int d) const { return tile_sizes_.at(d); } + + // The tiling dimension for dimension 'd' of the shared memory tile. + int64_t GetTilingDimension(int d) const { return tiling_dimensions_.at(d); } + + // Tile size for a given dimension per entire thread block. + int64_t GetBlockTileSizeFor(int d) const { + return num_threads_.at(d) * tile_sizes_.at(d); + } + + // Number of threads in given dimension. + int64_t GetNumThreadsFor(int d) const { return num_threads_.at(d); } + + // Number of logical threads per block. + int64_t GetNumThreadsPerBlock() const { + return GetNumThreadsFor(0) * GetNumThreadsFor(1) * GetNumThreadsFor(2); + } + + // Number of logical blocks. + int64_t GetNumberOfBlocks() const { + return GetDimInBlock(0) * GetDimInBlock(1) * GetDimInBlock(2); + } + + // Number of physical blocks launched (with scaling applied). + int64_t GetNumberOfBlocksPhysical() const { + return CeilOfRatio(GetNumberOfBlocks(), thread_id_virtual_scaling_); + } + + // Number of physical threads per block launched (with scaling applied). + int64_t GetNumThreadsPerBlockPhysical() const { + return GetNumThreadsPerBlock() * thread_id_virtual_scaling_; + } + + IndexingOrder GetIndexingOrder() const { return indexing_order_; } + int GetVectorSize() const { return vector_size_; } + + // Scaling factor for transforming physical threadId to logical. + int GetThreadIdScalingFactor() const { return thread_id_virtual_scaling_; } + + private: + // The number of elements in each dimension. + const Vector3 dims_in_elems_; + + // The number of elements for each dimension of a tile. + const Vector3 tile_sizes_; + + // The dimensions which are used for the shared memory tile. + const Vector2 tiling_dimensions_; + + // Number of threads implicitly assigned to each dimension. + const Vector3 num_threads_; + + const IndexingOrder indexing_order_; + + // Vector size for dimension X. + const int vector_size_; + + // Scaling apply to transform physical threadIdx into logical. + const int64_t thread_id_virtual_scaling_ = 1; +}; + +class ReductionCodegenInfo { + public: + using IndexGroups = std::vector>; + + explicit ReductionCodegenInfo(TilingScheme mapping_scheme, + int num_partial_results, bool is_row_reduction, + bool is_race_free, IndexGroups index_groups, + const HloInstruction* first_reduce) + : tiling_scheme_(mapping_scheme), + num_partial_results_(num_partial_results), + is_row_reduction_(is_row_reduction), + is_race_free_(is_race_free), + index_groups_(std::move(index_groups)), + first_reduce_(first_reduce) { + if (!is_row_reduction && num_partial_results > 1) { + CHECK_EQ(num_partial_results, + mapping_scheme.GetTileSizeFor(TilingScheme::DimX)); + } + } + + const TilingScheme& GetTilingScheme() const { return tiling_scheme_; } + const IndexGroups& GetIndexGroups() const { return index_groups_; } + Shape GetReduceOperandShape() const { + return first_reduce_->operand(0)->shape(); + } + + int GetNumPartialResults() const { return num_partial_results_; } + bool IsRaceFree() const { return is_race_free_; } + + private: + friend class ReductionCodegenState; + + const TilingScheme tiling_scheme_; + int num_partial_results_; + bool is_row_reduction_; + bool is_race_free_; + IndexGroups index_groups_; + const HloInstruction* first_reduce_; +}; + +class ReductionCodegenState { + public: + struct ReductionCalculationState { + llvm::GlobalVariable* shared_cache; + llvm::Value* initial_value; + llvm::AllocaInst* partial_result_address; + llvm::AllocaInst* input_address; + llvm_ir::ElementGenerator input_gen; + }; + + explicit ReductionCodegenState( + const ReductionCodegenInfo& reduction_codegen_info) + : reduction_codegen_info_(reduction_codegen_info) {} + + const TilingScheme& GetTilingScheme() const { + return reduction_codegen_info_.tiling_scheme_; + } + + int GetNumPartialResults() const { + return reduction_codegen_info_.num_partial_results_; + } + + bool IsRowReduction() const { + return reduction_codegen_info_.is_row_reduction_; + } + + bool IsRaceFree() const { return reduction_codegen_info_.IsRaceFree(); } + + const ReductionCalculationState& GetCalculationStateFor( + const HloInstruction* instruction, int operand_idx) const { + const ReductionOpState& op_state = state_.at(instruction); + CHECK_LT(operand_idx, op_state.size()); + return op_state[operand_idx]; + } + + void SetCalculationStateFor( + const ReductionCalculationState& calculation_state, + const HloInstruction* instruction, int operand_idx) { + ReductionOpState& op_state = state_[instruction]; + CHECK_EQ(operand_idx, op_state.size()); + op_state.push_back(calculation_state); + } + + private: + ReductionCodegenInfo reduction_codegen_info_; + + // One state per reduction operand. + using ReductionOpState = absl::InlinedVector; + + // HloInstruction -> operand_idx -> cache + absl::flat_hash_map state_; +}; + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_MAPPING_SCHEME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_reuse_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_reuse_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..33cddb7d5c15cea8d026a49ef531407af5988112 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_reuse_cache.h @@ -0,0 +1,74 @@ +/*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_SERVICE_GPU_KERNEL_REUSE_CACHE_H_ +#define XLA_SERVICE_GPU_KERNEL_REUSE_CACHE_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/gpu/kernel_arguments.h" +#include "xla/service/gpu/launch_dimensions.h" + +namespace xla { +namespace gpu { + +// Caches identical Kernels for deduplication. +// Thread-compatible. +class KernelReuseCache { + public: + struct Entry { + std::string kernel_name; + LaunchDimensions launch_dimensions; + int64_t shmem_bytes; + }; + + // Retrieves the cache entry for the given computation, or generates it using + // the given generator function and stores it in the cache. + std::pair Get( + const HloComputation* fused_computation, + absl::Span kernel_arguments, + absl::string_view discriminator, const std::function& generator); + + // Like `Get`, but for generator functions that can fail. + std::pair, bool /*was_cached*/> GetWithStatus( + const HloComputation* fused_computation, + absl::Span kernel_arguments, + absl::string_view discriminator, + const std::function()>& generator); + + private: + absl::flat_hash_map cache_; +}; + +// Calculates the fingerprint of a (fused_computation, kernel_arguments, +// discriminator) tuple. +// +// If a given fusion is implemented using multiple kernels, then for each +// kernel we should provide a discriminator, such as "init" and "impl". +// +// If the same fingerprint is returned twice, then we can reuse the kernel +// generated for the first computation. +std::string GetComputationFingerprint( + const HloComputation* fused_computation, + absl::Span kernel_arguments, + absl::string_view discriminator = ""); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_REUSE_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..8b5f6c91cb89c163364d1c6d04591d040944c2ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/kernel_thunk.h @@ -0,0 +1,117 @@ +/* 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_SERVICE_GPU_KERNEL_THUNK_H_ +#define XLA_SERVICE_GPU_KERNEL_THUNK_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/kernel_arguments.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" + +namespace xla { +namespace gpu { + +class GpuExecutable; + +// This class stores everything that StreamExecutor needs for launching a +// kernel. It implements the ExecuteOnStream interface for GpuExecutable to +// invoke the corresponding kernel. +// +// This is thread-compatible. +class KernelThunk : public Thunk { + public: + // Constructs a thunk for the given kernel. + // + // KernelThunk takes args as `BufferAllocation::Slice`s (wrapped in + // `KernelArgument`s). Each slice directly corresponds to an argument or + // output of the computation. Also, the values must correspond to each arg + // directly, not to their base allocation (e.g. they can be the result of an + // `mlir::memref::ViewOp`). + KernelThunk(mlir::Operation* op, std::string kernel_name, + absl::Span kernel_arguments, + LaunchDimensions launch_dimensions, int64_t shmem_bytes); + KernelThunk(const KernelThunk&) = delete; + KernelThunk& operator=(const KernelThunk&) = delete; + ~KernelThunk() override = default; + + std::string ToStringExtra(int indent) const override; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + for (auto& value : values_) { + value = nullptr; + } + } + + const std::vector& arguments() const { + return args_; + } + const std::vector& written() const { return written_; } + + const std::string& kernel_name() const { return kernel_name_; } + const LaunchDimensions& launch_dimensions() const { + return launch_dimensions_; + } + // The shared memory required by the kernel. + int64_t shmem_bytes() const { return shmem_bytes_; } + absl::Span values() const { return values_; } + + private: + // Buffer slices passed to the kernel as arguments. + std::vector args_; + + // args_[i] is written iff (written_[i] == true). + std::vector written_; + + // Entry kernel name for the computation. + const std::string kernel_name_; + + // The thread and block dimension used to launch the kernel. + const LaunchDimensions launch_dimensions_; + + int64_t shmem_bytes_; + + // mlir::Value(s) corresponding to the buffer slice arguments. + std::vector values_; + + mutable absl::Mutex mutex_; + + // Loaded kernels for each `StreamExecutor`. Requires pointer stability of + // values. + absl::flat_hash_map> + kernel_cache_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/launch_dimensions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/launch_dimensions.h new file mode 100644 index 0000000000000000000000000000000000000000..5bde8059e3bb5ec1c0acb27892aef1fe5fe6369d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/launch_dimensions.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_SERVICE_GPU_LAUNCH_DIMENSIONS_H_ +#define XLA_SERVICE_GPU_LAUNCH_DIMENSIONS_H_ + +#include +#include + +#include "xla/shape.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Encapsulates the launch dimensions of a kernel, e.g., the block count and the +// number of threads per block. +class LaunchDimensions { + public: + struct Dim3D { + int64_t x, y, z; + + bool operator==(const Dim3D& other) const { + return x == other.x && y == other.y && z == other.z; + } + + bool operator!=(const Dim3D& other) const { return !(*this == other); } + }; + + // The default constructor creates a launch dimension that indicate + // single-threaded execution. + LaunchDimensions() + : block_counts_({1, 1, 1}), thread_counts_per_block_({1, 1, 1}) {} + + LaunchDimensions(int64_t block_x_count, int64_t thread_x_count_per_block) + : block_counts_({block_x_count, 1, 1}), + thread_counts_per_block_({thread_x_count_per_block, 1, 1}) {} + + LaunchDimensions(const Dim3D& block_counts, + const Dim3D& thread_counts_per_block) + : block_counts_(block_counts), + thread_counts_per_block_(thread_counts_per_block) {} + + Dim3D block_counts() const { return block_counts_; } + + Dim3D thread_counts_per_block() const { return thread_counts_per_block_; } + + // Returns the total number of threads in a block. + int64_t total_nb_threads() const { + return thread_counts_per_block_.x * thread_counts_per_block_.y * + thread_counts_per_block_.z; + } + + int64_t launch_bound() const { + return block_counts_.x * thread_counts_per_block_.x * block_counts_.y * + thread_counts_per_block_.y * block_counts_.z * + thread_counts_per_block_.z; + } + + std::string ToString() const { + return absl::StrCat("blocks: {", block_counts_.x, ", ", block_counts_.y, + ", ", block_counts_.z, "}, threads/block: {", + thread_counts_per_block_.x, ", ", + thread_counts_per_block_.y, ", ", + thread_counts_per_block_.z, "}"); + } + + bool operator==(const LaunchDimensions& other) const { + return block_counts_ == other.block_counts_ && + thread_counts_per_block_ == other.thread_counts_per_block_; + } + + bool operator!=(const LaunchDimensions& other) const { + return !(*this == other); + } + + private: + Dim3D block_counts_; + Dim3D thread_counts_per_block_; +}; + +std::ostream& operator<<(std::ostream& out, + const LaunchDimensions& launch_dims); + +struct LaunchDimensionsConfig { + // The kernel implementation will be unrolled if `unroll_factor` is + // greater than one. + int unroll_factor = 1; + // A wave is a group of blocks that execute at the same time on the + // GPU. If there are more blocks then the number that can run + // concurrently, there are multiple waves of blocks running + // sequentially. If `few_waves` is true, each thread will loop over + // a block of unroll_factor elements. Otherwise each thread will + // handle only unroll_factor. + bool few_waves = false; + // If `row_optimized` is true, then the block size will equal to + // `hlo.shape().dimensions().back()/unroll_factor`. + // Currently few_waves and row_vectorized do not work together. + bool row_vectorized = false; + + std::string ToString() { + return absl::StrCat("unroll_factor=", unroll_factor, + ", few_waves=", few_waves, + ", row_vectorized=", row_vectorized); + } +}; + +// Returns -1 if the shape doesn't allow the row vectorization code path. +// If supported, return the number of threads to use in that case. +int64_t ThreadsPerBlockRowVectorized( + const Shape& shape, const se::DeviceDescription& gpu_device_info, + LaunchDimensionsConfig dim_config); + +// Calculates the launch dimensions used to invoke `hlo`. +StatusOr CalculateLaunchDimensions( + const Shape& shape, const se::DeviceDescription& gpu_device_info, + LaunchDimensionsConfig dim_config = {}); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_LAUNCH_DIMENSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..9ff362c2df33911b099e860409b8019eab3e003a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h @@ -0,0 +1,72 @@ +/* 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. +==============================================================================*/ + +// LLVM-based compiler backend. +#ifndef XLA_SERVICE_GPU_LLVM_GPU_BACKEND_GPU_BACKEND_LIB_H_ +#define XLA_SERVICE_GPU_LLVM_GPU_BACKEND_GPU_BACKEND_LIB_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "llvm/IR/Module.h" +#include "llvm/Target/TargetMachine.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/types.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +namespace nvptx { + +std::string CantFindCudaMessage(absl::string_view msg, + absl::string_view xla_gpu_cuda_data_dir); + +// Get path to NVVM libdevice file. +std::string LibDevicePath(absl::string_view xla_gpu_cuda_data_dir); + +// Link libdevice if functions using it are detected in the module. +Status LinkLibdeviceIfNecessary(llvm::Module* module, + const std::string& libdevice_path); + +// Compiles the argument module and returns it. libdevice_dir_path is the parent +// directory of the libdevice bitcode libraries. The contents of the module may +// be changed. +// +// The Compile.* interfaces each create their own llvm::LLVMContext objects for +// thread safety, but note that LLVM's multithreaded support is very +// preliminary; multithreaded use is not recommended at this time. +StatusOr CompileToPtx( + llvm::Module* module, se::GpuComputeCapability gpu_version, + const DebugOptions& debug_options, + std::function configure_target = nullptr); +} // namespace nvptx + +namespace amdgpu { +// Compiles the argument module and returns it with LLVM AMDGPU backend. +// rocdl_dir_path is the parent directory of ROCm-Device-Libs bitcode libraries. +// The contents of the module may be changed. +StatusOr> CompileToHsaco( + llvm::Module* module, se::GpuComputeCapability gpu_version, + const DebugOptions& debug_options, const std::string& rocdl_dir_path, + const std::string& module_config_cache_key); +} // namespace amdgpu + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_LLVM_GPU_BACKEND_GPU_BACKEND_LIB_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/llvm_gpu_backend/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/llvm_gpu_backend/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..5c6a07ae3514e6ac667362c123dd40d160b3df45 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/llvm_gpu_backend/utils.h @@ -0,0 +1,51 @@ +/* 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_SERVICE_GPU_LLVM_GPU_BACKEND_UTILS_H_ +#define XLA_SERVICE_GPU_LLVM_GPU_BACKEND_UTILS_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/types.h" + +namespace llvm { +class LLVMContext; +class Module; +} // namespace llvm + +namespace xla { +namespace gpu { + +// Convenience function for loading a LLVM module from an IR file. The module +// is created in the given LLVM context. +// +// If loading fails for some reason, dies printing a diagnostic error. +std::unique_ptr LoadIRModule(const std::string& filename, + llvm::LLVMContext* llvm_context); + +// Convenience function for replacing the extension of the given filename. +// If the filename has no extension, the new extension is appended to its name. +// +// For example: +// ReplaceFilenameExtension("/foo/baz.txt", "cc") --> "/foo/baz.cc" +std::string ReplaceFilenameExtension(absl::string_view filename, + absl::string_view new_extension); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_LLVM_GPU_BACKEND_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/loop_double_buffer_transformer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/loop_double_buffer_transformer.h new file mode 100644 index 0000000000000000000000000000000000000000..b9fb70a1853f41fe69f69af61c0c011bf26ccd86 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/loop_double_buffer_transformer.h @@ -0,0 +1,54 @@ +/* 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_SERVICE_GPU_LOOP_DOUBLE_BUFFER_TRANSFORMER_H_ +#define XLA_SERVICE_GPU_LOOP_DOUBLE_BUFFER_TRANSFORMER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// This pass performs the unrolling-by-2 loop transformation +// to effectively achieve double buffering between inputs and outputs +// of previously rolled iterations. +// This pass only runs on loops with known trip counts. +// For even number of iterations, unrolling-by-2 will be done directly. +// For odd number of iterations, the first iteration of the loop will be +// peeled outside of the while loop to make the trip count an even number, +// then proceed to unroll by 2. +// It also updates the trip count property of the loop to the correct one (n/2). +class LoopDoubleBufferTransformer : public HloModulePass { + public: + LoopDoubleBufferTransformer() = default; + ~LoopDoubleBufferTransformer() override = default; + absl::string_view name() const override { + return "loop-double-buffer-transformer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_LOOP_DOUBLE_BUFFER_TRANSFORMER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/matmul_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/matmul_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..78c11c5bccae85e32557e14ad5389de8be2c1252 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/matmul_utils.h @@ -0,0 +1,275 @@ +/* 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_SERVICE_GPU_MATMUL_UTILS_H_ +#define XLA_SERVICE_GPU_MATMUL_UTILS_H_ + +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/stream_executor/blas.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#include "xla/stream_executor/scratch_allocator.h" + +#elif TENSORFLOW_USE_ROCM +#include "rocm/rocm_config.h" +#if TF_HIPBLASLT +#include "xla/stream_executor/rocm/hip_blas_lt.h" +#include "xla/stream_executor/scratch_allocator.h" +#endif // TF_HIPBLASLT +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +namespace xla { +namespace gpu { + +StatusOr> GetNonContractingDims( + const Shape& shape, absl::Span batch_dims, + absl::Span contracting_dims); + +// Batch dimensions of an operand of a dot instruction. +// Just an unified accessor to lhs_batch_dimensions and rhs_batch_dimensions. +const tsl::protobuf::RepeatedField& BatchDimensionsForOperand( + const HloInstruction& dot, int operand_number); + +// Index of the only contracting dimension of dot instruction operand. +int64_t ContractingDimensionIndex(const HloInstruction& dot, + int operand_number); + +// Index of the only non-contracting dimension of dot instruction operand. +int64_t NonContractingDimensionIndex(const HloInstruction& dot, + int operand_number); + +// Normalize shape to (batch, rows, columns) logical dimensions. +StatusOr GetBatchRowColumnShape(const Shape& shape, + absl::Span batch_dims, + absl::Span row_dims, + absl::Span col_dims); + +struct MatrixLayout { + enum class Order { + kRowMajor, // Elements in the same row are contiguous in memory. + kColumnMajor, // Elements in the same column are contiguous in memory. + }; + + // Returns the matrix layout for a logical shape (batch, rows, columns). + static StatusOr For(const Shape& shape); + // Returns the matrix layout with the given batch, row, col dimensions. + static StatusOr For(const Shape& shape, + absl::Span batch_dims, + absl::Span row_dims, + absl::Span col_dims); + // Returns the matrix layout for the output. + static StatusOr For(const Shape& shape, + size_t lhs_num_batch_dims, + size_t lhs_num_row_dims, + size_t rhs_num_batch_dims, + size_t rhs_num_col_dims); + + void Transpose(); + + PrimitiveType dtype; + // `num_rows` / `num_cols` are for the "logical" matrix shape: + // i.e. the contracting dim has size `num_cols` for LHS operands and + // `num_rows` for RHS operands. + int64_t num_rows; + int64_t num_cols; + Order order; + int64_t leading_dim_stride; + int64_t batch_size; + int64_t batch_stride; // `batch_stride` is set to `0` when `batch_size == 1`. +}; + +// GPU folding rule for the `TransposeFolding` pass. +StatusOr CanFoldTransposeOperandIntoDot(const HloInstruction& dot, + int64_t operand_idx); + +struct GemmConfig { + static StatusOr For(const HloInstruction* gemm); + static StatusOr For(mlir::lmhlo_gpu::GEMMOp op); + + static StatusOr For( + const Shape& lhs_shape, absl::Span lhs_batch_dims, + absl::Span lhs_contracting_dims, const Shape& rhs_shape, + absl::Span rhs_batch_dims, + absl::Span rhs_contracting_dims, const Shape& output_shape, + double alpha_real, double alpha_imag, double beta, + std::optional algorithm, int64_t compute_precision); + + // As above with additional `c_shape` and `bias_shape_ptr` parameter, both + // which are only necessarily for F8 gemms. + static StatusOr For( + const Shape& lhs_shape, absl::Span lhs_batch_dims, + absl::Span lhs_contracting_dims, const Shape& rhs_shape, + absl::Span rhs_batch_dims, + absl::Span rhs_contracting_dims, const Shape& c_shape, + const Shape* bias_shape_ptr, const Shape& output_shape, double alpha_real, + double alpha_imag, double beta, std::optional algorithm, + int64_t compute_precision); + + template ::value || + std::is_same::value>> + static StatusOr For(CublasLtMatmulMaybeF8Op op) { + mlir::mhlo::DotDimensionNumbersAttr dot_dims = op.getDotDimensionNumbers(); + + int64_t compute_precision = 0; // Default + if (op.getPrecisionConfig().has_value()) { + auto precision_config = op.getPrecisionConfig(); + for (auto attr : precision_config.value()) { + int64_t value = static_cast( + attr.template cast().getValue()); + if (value > compute_precision) { + compute_precision = value; + } + } + } + + Shape bias_shape; + if (op.getBias() != nullptr) { + bias_shape = GetShape(op.getBias()); + } + return GemmConfig::For( + GetShape(op.getA()), dot_dims.getLhsBatchingDimensions(), + dot_dims.getLhsContractingDimensions(), GetShape(op.getB()), + dot_dims.getRhsBatchingDimensions(), + dot_dims.getRhsContractingDimensions(), GetShape(op.getC()), + op.getBias() == nullptr ? nullptr : &bias_shape, GetShape(op.getD()), + op.getAlphaReal().convertToDouble(), + op.getAlphaImag().convertToDouble(), op.getBeta().convertToDouble(), + op.getAlgorithm(), compute_precision); + } + + MatrixLayout lhs_layout; + MatrixLayout rhs_layout; + MatrixLayout c_layout; + MatrixLayout output_layout; + complex128 alpha; + double beta; + std::optional algorithm; + int64_t compute_precision; +}; + +StatusOr GetBlasComputationType( + PrimitiveType lhs_dtype, PrimitiveType output_dtype, + int64_t compute_precision); + +namespace cublas_lt { + +// Returns the type for the alpha and beta scalars. +se::blas::DataType GetScaleType(se::blas::DataType c_type, + se::blas::ComputationType computation_type); + +} // namespace cublas_lt + +// Run the given GEMM instruction `gemm` subject to the configuration +// in `gemm_config` and the passed buffers. +// +// If `algorithm` is provided, it overrides the one specified in `config`. +Status RunGemm(const GemmConfig& config, se::DeviceMemoryBase lhs_buffer, + se::DeviceMemoryBase rhs_buffer, + se::DeviceMemoryBase output_buffer, bool deterministic_ops, + se::Stream* stream, + std::optional algorithm = std::nullopt, + se::blas::ProfileResult* profile_result = nullptr); + +namespace cublas_lt { + +StatusOr EpilogueAddsVectorBias(GemmBackendConfig_Epilogue epilogue); +StatusOr EpilogueHasAuxiliaryOutput(GemmBackendConfig_Epilogue epilogue); + +} // namespace cublas_lt + +StatusOr AsBlasDataType(PrimitiveType dtype); + +#if GOOGLE_CUDA || TF_HIPBLASLT + +namespace cublas_lt { + +StatusOr AsBlasLtEpilogue( + mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue); + +class MatmulPlan { + public: + static StatusOr From(const GemmConfig& config, + se::gpu::BlasLt::Epilogue epilogue); + + Status ExecuteOnStream( + se::Stream* stream, se::DeviceMemoryBase a_buffer, + se::DeviceMemoryBase b_buffer, se::DeviceMemoryBase c_buffer, + se::DeviceMemoryBase d_buffer, + se::DeviceMemoryBase bias_buffer, // may be null + se::DeviceMemoryBase aux_buffer, // may be null + se::DeviceMemoryBase a_scale_buffer, se::DeviceMemoryBase b_scale_buffer, + se::DeviceMemoryBase c_scale_buffer, se::DeviceMemoryBase d_scale_buffer, + se::DeviceMemoryBase d_amax_buffer, + const se::gpu::BlasLt::MatmulAlgorithm& algorithm, + se::ScratchAllocator& scratch_allocator, + se::blas::ProfileResult* profile_result = nullptr) const; + + StatusOr> GetAlgorithms( + se::Stream* stream) const; + + private: + MatmulPlan(se::gpu::BlasLt::MatmulPlan plan, complex128 alpha, double beta, + bool must_swap_operands) + : plan_(std::move(plan)), + alpha_(alpha), + beta_(beta), + must_swap_operands_(must_swap_operands) {} + + template + Status DoMatmul(se::Stream* stream, se::DeviceMemoryBase a_buffer, + se::DeviceMemoryBase b_buffer, se::DeviceMemoryBase c_buffer, + se::DeviceMemoryBase d_buffer, + se::DeviceMemoryBase bias_buffer, // may be null + se::DeviceMemoryBase aux_buffer, // may be null + se::DeviceMemoryBase a_scale, se::DeviceMemoryBase b_scale, + se::DeviceMemoryBase c_scale, se::DeviceMemoryBase d_scale, + se::DeviceMemoryBase d_amax, + const se::gpu::BlasLt::MatmulAlgorithm& algorithm, + se::ScratchAllocator& scratch_allocator, + se::blas::ProfileResult* profile_result) const; + + se::gpu::BlasLt::MatmulPlan plan_; + complex128 alpha_; + double beta_; + bool must_swap_operands_; +}; + +} // namespace cublas_lt + +#endif // GOOGLE_CUDA || TF_HIPBLASLT + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_MATMUL_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/memset_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/memset_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..4529571b0ebca8b4e0b591a27cea7b52e0ed5a04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/memset_thunk.h @@ -0,0 +1,88 @@ +/* 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_SERVICE_GPU_MEMSET_THUNK_H_ +#define XLA_SERVICE_GPU_MEMSET_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "xla/stream_executor/stream_executor.h" + +// This file contains thunks that set a buffer's elements to a particular value. +// This can be faster than emitting a kernel to set the elements. + +namespace xla { +namespace gpu { + +// Thunk that zeroes out a given chunk of memory. +class MemzeroThunk : public Thunk { + public: + explicit MemzeroThunk(ThunkInfo thunk_info, + const BufferAllocation::Slice& dest, + mlir::Value dest_value) + : Thunk(Kind::kMemzero, thunk_info), + dest_(dest), + dest_value_(dest_value) {} + + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + dest_value_ = nullptr; + } + + const BufferAllocation::Slice& destination() const { return dest_; } + mlir::Value dest_value() const { return dest_value_; } + + private: + const BufferAllocation::Slice dest_; + mlir::Value dest_value_; +}; + +// Thunk that sets a given chunk of memory to a particular 32-bit value. The +// destination chunk must have size divisible by 32 bits. +class Memset32BitValueThunk : public Thunk { + public: + explicit Memset32BitValueThunk(ThunkInfo thunk_info, uint32_t value, + const BufferAllocation::Slice& dest, + mlir::Value dest_value) + : Thunk(Kind::kMemset32BitValue, thunk_info), + value_(value), + dest_(dest), + dest_value_(dest_value) {} + + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + dest_value_ = nullptr; + } + + const BufferAllocation::Slice& destination() const { return dest_; } + uint32_t value() const { return value_; } + mlir::Value dest_value() const { return dest_value_; } + + private: + const uint32_t value_; + const BufferAllocation::Slice dest_; + mlir::Value dest_value_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_MEMSET_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/metrics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/metrics.h new file mode 100644 index 0000000000000000000000000000000000000000..d660743838a26fcf4097a56399c0c3df0d538a27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/metrics.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 XLA_SERVICE_GPU_METRICS_H_ +#define XLA_SERVICE_GPU_METRICS_H_ + +#include + +namespace xla { + +// HLO passes (HLO -> HLO). +void RecordHloPassesDuration(uint64_t time_usecs); + +// Compiling HLO to LLVM. +void RecordHloToLlvmDuration(uint64_t time_usecs); + +// The entire LLVM to PTX pipeline, including both LLVM optimization (LLVM -> +// LLVM) and compiling LLVM -> PTX. +void RecordLlvmPassesAndLlvmToPtxDuration(uint64_t time_usecs); + +// LLVM passes (linking and optimization) only (LLVM -> LLVM). +void RecordLlvmPassesDuration(uint64_t time_usecs); + +// Compiling LLVM to PTX only. +void RecordLlvmToPtxDuration(uint64_t time_usecs); + +// Compiling PTX to cubin. +void RecordPtxToCubinDuration(uint64_t time_usecs); + +// Counts compiled programs numbers. +void IncrementCompiledProgramsCount(); + +// Gets compiled programs numbers. +int64_t GetCompiledProgramsCount(); + +// Records the size of the XLA device binary in bytes. +void RecordXlaDeviceBinarySize(int64_t size); + +} // namespace xla + +#endif // XLA_SERVICE_GPU_METRICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/move_copy_to_users.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/move_copy_to_users.h new file mode 100644 index 0000000000000000000000000000000000000000..a01d8e97d186f4ab5b3181d310664fda636e8e31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/move_copy_to_users.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_GPU_MOVE_COPY_TO_USERS_H_ +#define XLA_SERVICE_GPU_MOVE_COPY_TO_USERS_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Sink kCopy operations as far down the graph as possible. +class MoveCopyToUsers : public HloModulePass { + public: + absl::string_view name() const override { return "move_copy_to_users"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // end namespace xla + +#endif // XLA_SERVICE_GPU_MOVE_COPY_TO_USERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/multi_output_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/multi_output_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..103694857407ac4d8464a2cda6c20b61f8e28cf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/multi_output_fusion.h @@ -0,0 +1,133 @@ +/* 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_SERVICE_GPU_MULTI_OUTPUT_FUSION_H_ +#define XLA_SERVICE_GPU_MULTI_OUTPUT_FUSION_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_reachability.h" +#include "xla/service/gpu/gpu_fusible.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Multi-output fusion of sibling and producer-consumer instructions for the +// GPU backend to reduce memory bandwidth requirements. +// +// 0) Before multi- 1) Sibling multi- 2) Producer-consumer +// output fusion output fusion multi-output fusion +// +// p p p +// | | | +// v v v +// A A +-fusion--+ +// / \ | | A | +// | | +-fusion--+ | / \ | +// v v | / \ | | B | | +// B C | B C | | | | | +// \ / | | | | | v v | +// v v | v v | | tuple | +// ROOT | tuple | +---------+ +// +---------+ / \ +// / \ gte_b gte_a +// gte_b gte_c | | +// | | | v +// \ / | C +// v v \ / +// ROOT v v +// ROOT +// +// Multi-output fusion ops have a tuple op at their root containing multiple +// elements as outputs. GetTupleElement ops (depicted as gte_* above) are +// inserted to extract tuple elements for consumers. +// +// The two different flavors of multi-output fusion this pass performs are +// depicted above. +// 1) Fusion of sibling ops reduces memory bandwidth requirements, because +// common input parameters have to be read only once. +// 2) Fusion of producer-consumer ops reduces memory bandwidth requirements by +// saving one read from memory. In the example above, B does not need to read +// the output of A from memory, while C still does (using gte_a). +// Note that sibling (1) and producer-consumer (2) multi-output fusion can be +// combined. +// +// The GpuMultiOutputFusion pass modifies the HLO in reverse post-order (defs +// before uses). First, it attempts to fuse the consumer ops of the current op, +// which are siblings (1). Hereafter, it attempts to fuse the current op with +// one of its consumers (2). This order avoids a phase ordering issue (described +// in go/fusionfusion). It ensures that all GetTupleElement ops inserted as a +// by-product of multi-output fusion will occur before the current op in the +// order of traversal, and hence, not get into the way of subsequent fusion +// attempts. +// +// The GpuMultiOutputFusion pass ensures several conditions are met for fusion. +// Some of them are relevant for correctness. In particular, no cycles must be +// introduced into the HLO module. Moreover, the code emitters for multi-output +// fusion must support the combination of ops and their shapes. Other +// restrictions are rather arbitrary and lifting them could be beneficial. +// * Sibling fusion (1) requires at least one op to be a kFusion. +// * Sibling fusion (1) does not fuse kInput fusions with kLoop fusions, i.e. +// the fusion kinds must match. + +class GpuMultiOutputFusion : public HloModulePass { + public: + explicit GpuMultiOutputFusion( + const se::DeviceDescription& device_info, + HloCostAnalysis::ShapeSizeFunction shape_size_function) + : device_info_(device_info), shape_size_function_(shape_size_function) {} + + absl::string_view name() const override { return "multi_output_fusion"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + bool FuseSiblings(HloInstruction* parent, FusionInfoCache* fusion_info_cache, + GpuHloCostAnalysis* cost_analysis); + + StatusOr DoMultiOutputFusion(); + + // Recompute reachability for the current computation. + void RecomputeReachability(); + + void DumpFusionState(const HloInstruction& consumer, absl::string_view label, + const HloInstruction* producer = nullptr); + + // Computation for the pass. + HloComputation* computation_; + + // The reachability map of current computation. + std::unique_ptr reachability_; + + se::DeviceDescription device_info_; + HloCostAnalysis::ShapeSizeFunction shape_size_function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_MULTI_OUTPUT_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_gather_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_gather_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..dfd4e39b4ebb593372b4105df0d9abe76ac0e2f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_gather_thunk.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. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_ALL_GATHER_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_ALL_GATHER_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +struct NcclAllGatherConfig { + NcclCollectiveConfig config; +}; + +// Thunk that performs a NCCL-based All-Gather among CUDA GPU-based replicas. +class NcclAllGatherStartThunk : public NcclCollectiveThunk { + public: + NcclAllGatherStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::AllGatherStartOp op, + std::vector buffers); + + static const char* GetHloOpName() { return "all-gather-start"; } + + static Status CheckImplementable(mlir::lmhlo_gpu::AllGatherStartOp op, + int64_t replica_count, + int64_t partition_count); + static bool IsDegenerate(mlir::lmhlo_gpu::AllGatherStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::AllGatherStartOp op); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + + private: + const NcclAllGatherConfig config_; + const std::vector buffers_; +}; + +Status RunAllGather(std::vector& buffers, se::Stream& stream, + ncclComm_t comm); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_ALL_GATHER_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_reduce_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_reduce_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..b70e7dc317f15625810bb6620be4fb365c5ca158 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_reduce_thunk.h @@ -0,0 +1,115 @@ +/* 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_SERVICE_GPU_NCCL_ALL_REDUCE_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_ALL_REDUCE_THUNK_H_ + +#include +#include + +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +struct NcclAllReduceConfig { + NcclCollectiveConfig config; + ReductionKind reduction_kind; +}; + +// Thunk that performs a NCCL-based All-Reduce or Reduce-Scatter among CUDA +// GPU-based replicas. +class NcclAllReduceReduceScatterThunkBase : public NcclCollectiveThunk { + public: + static std::optional MatchAllReduceComputation( + mlir::Region& computation); + + NcclAllReduceReduceScatterThunkBase(Kind kind, ThunkInfo thunk_info, + NcclAllReduceConfig config, + std::vector buffers, + bool is_sync); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + + const NcclAllReduceConfig config_; + const std::vector buffers_; +}; + +// ----------------------------------------------------------------------------- +// AllReduce thunk. +// ----------------------------------------------------------------------------- + +class NcclAllReduceStartThunk : public NcclAllReduceReduceScatterThunkBase { + public: + NcclAllReduceStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::AllReduceStartOp op, + std::vector buffers); + + static const char* GetHloOpName() { return "all-reduce-start"; } + + static Status CheckImplementable(mlir::lmhlo_gpu::AllReduceStartOp op, + int64_t replica_count, + int64_t partition_count); + static bool IsDegenerate(mlir::lmhlo_gpu::AllReduceStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::AllReduceStartOp op); + + protected: + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; +}; + +// ----------------------------------------------------------------------------- +// ReduceScatter thunk +// ----------------------------------------------------------------------------- +class NcclReduceScatterStartThunk : public NcclAllReduceReduceScatterThunkBase { + public: + NcclReduceScatterStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::ReduceScatterStartOp op, + std::vector buffers); + + static const char* GetHloOpName() { return "reduce-scatter-start"; } + + static Status CheckImplementable(mlir::lmhlo_gpu::ReduceScatterStartOp op, + int64_t replica_count, + int64_t partition_count); + static bool IsDegenerate(mlir::lmhlo_gpu::ReduceScatterStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::ReduceScatterStartOp op); + + protected: + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; +}; + +// ----------------------------------------------------------------------------- + +Status RunAllReduce(ReductionKind reduction_kind, + std::vector& buffers, se::Stream& stream, + ncclComm_t comm); + +Status RunReduceScatter(ReductionKind reduction_kind, + std::vector& buffers, + se::Stream& stream, ncclComm_t comm); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_ALL_REDUCE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_to_all_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_to_all_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..e6e60c5d0fb65e37316afce98291a0a8e9e255b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_all_to_all_thunk.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_GPU_NCCL_ALL_TO_ALL_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_ALL_TO_ALL_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +struct NcclAllToAllConfig { + NcclCollectiveConfig config; + bool has_split_dimension; +}; + +// Thunk that performs a NCCL-based All-to-All among CUDA GPU-based replicas. +class NcclAllToAllStartThunk : public NcclCollectiveThunk { + public: + NcclAllToAllStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::AllToAllStartOp op, + std::vector buffers); + + // Returns whether the given instruction can be lowered to a nccl all-to-all + // call. + static Status CheckImplementable(mlir::lmhlo_gpu::AllToAllStartOp op, + int64_t replica_count, + int64_t partition_count); + + static const char* GetHloOpName() { return "all-to-all-start"; } + static bool IsDegenerate(mlir::lmhlo_gpu::AllToAllStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::AllToAllStartOp op); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + + private: + const NcclAllToAllConfig config_; + const std::vector buffers_; +}; + +Status RunAllToAll(bool has_split_dimension, + std::vector& buffers, se::Stream& stream, + ncclComm_t comm); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_ALL_TO_ALL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_collective_permute_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_collective_permute_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..8f2a675e782c2b827e02e495bf4c1d150000f26b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_collective_permute_thunk.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_SERVICE_GPU_NCCL_COLLECTIVE_PERMUTE_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_COLLECTIVE_PERMUTE_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/nccl_p2p_thunk_common.h" + +namespace xla { +namespace gpu { + +// Thunk that performs a NCCL-based collective permute. +class NcclCollectivePermuteStartThunk : public NcclCollectiveThunk { + public: + static NcclP2PConfig GetNcclP2PConfig( + mlir::lmhlo_gpu::CollectivePermuteStartOp op, int64_t replica_count, + int64_t partition_count); + + static Status CheckImplementable(mlir::lmhlo_gpu::CollectivePermuteStartOp op, + int64_t replica_count, + int64_t partition_count); + + static bool IsDegenerate(mlir::lmhlo_gpu::CollectivePermuteStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::CollectivePermuteStartOp op); + + static const char* GetHloOpName() { return "collective-permute-start"; } + + NcclCollectivePermuteStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::CollectivePermuteStartOp op, + int64_t replica_count, + int64_t partition_count, + const Buffer& buffer); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + + private: + const NcclP2PConfig config_; + const Buffer buffer_; +}; + +Status RunCollectivePermute(NcclP2PConfig::SourceTargetMapEntry source_target, + DeviceBufferPair& buffer, se::Stream& stream, + ncclComm_t comm, absl::string_view device_string, + int64_t current_id); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_COLLECTIVE_PERMUTE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_collective_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_collective_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..a4b5c1ec5041436519a739427f36f3c4089985e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_collective_thunk.h @@ -0,0 +1,216 @@ +/* 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_SERVICE_GPU_NCCL_COLLECTIVE_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_COLLECTIVE_THUNK_H_ + +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/llvm_ir/llvm_util.h" +#include "xla/translate/mhlo_to_hlo/attribute_exporter.h" +#include "xla/xla_data.pb.h" + +#if XLA_ENABLE_XCCL +#include "xla/service/gpu/nccl_utils.h" +#endif // XLA_ENABLE_XCCL + +struct ncclComm; +using ncclComm_t = ncclComm*; + +namespace xla { +namespace gpu { + +class NcclClique; + +struct NcclCollectiveConfig { + NcclCollectiveConfig(); + NcclCollectiveConfig(NcclCollectiveConfig&&); + ~NcclCollectiveConfig(); + + NcclCollectiveConfig& operator=(NcclCollectiveConfig&&); + + int64_t operand_count; + std::vector operand_element_type; + std::vector replica_groups; + RendezvousKey::CollectiveOpKind collective_op_kind; + int64_t op_id; + CollectiveOpGroupMode group_mode; + + template + void SetCollectiveOpKindAndID(OpT op); + bool IsDegenerate(int64_t replica_count, int64_t partition_count) const; +}; + +template +void NcclCollectiveConfig::SetCollectiveOpKindAndID(OpT op) { + if (op.getChannelId()) { + collective_op_kind = RendezvousKey::kCrossModule; + op_id = static_cast(op.getChannelId()->getHandle()); + } else { + collective_op_kind = RendezvousKey::kCrossReplica; + mlir::ModuleOp parent = op->template getParentOfType(); + mlir::IntegerAttr unique_id = + parent->getAttrOfType("hlo.unique_id"); + op_id = static_cast(unique_id.getInt()); + } +} + +template +NcclCollectiveConfig GetNcclCollectiveConfigForMlir( + OpT op, std::optional use_global_device_ids) { + NcclCollectiveConfig config; + config.operand_count = op.getInputs().size(); + config.operand_element_type.reserve(config.operand_count); + for (int i = 0; i < config.operand_count; i++) { + const Shape shape = GetShape(op.getInputs()[i]); + config.operand_element_type.push_back(shape.element_type()); + } + config.replica_groups = ConvertReplicaGroups(op.getReplicaGroups()).value(); + config.SetCollectiveOpKindAndID(op); + config.group_mode = GetCollectiveOpGroupMode(op.getChannelId().has_value(), + use_global_device_ids) + .value(); + return config; +} + +// Thunk base class for NCCL collective operations. +class NcclCollectiveThunk : public Thunk { + public: + NcclCollectiveThunk(Kind kind, ThunkInfo thunk_info, bool is_sync); + + struct Buffer { + int64_t element_count; + BufferAllocation::Slice source_buffer; + BufferAllocation::Slice destination_buffer; + mlir::Value source_value; + mlir::Value destination_value; + }; + + class AsyncExecutor { + public: + // Executes the function on the async communications stream and records a + // completion event. + Status Execute( + absl::FunctionRef + fn, + const ExecuteParams& params, ncclComm_t comm, + AsyncStreamKind stream_kind); + // Blocks the compute stream until async communication is complete. + Status Await(const ExecuteParams& params); + + private: + absl::Mutex mu_; + // Store done events (by device ordinal) for the done thunk to wait on. + absl::flat_hash_map done_events_ ABSL_GUARDED_BY(mu_); + }; + + // Returns whether NCCL operations appear possible to perform; e.g. if we + // haven't done a build with the CUDA compiler enabled, we can't compile the + // NCCL header, and thus this will be false. + // + // When this is false, the ExecuteOnStream() call will simply return a status + // error. + static bool NcclIsEnabled(); + static Status CheckImplementable(); + + // Logging support. + static std::string GetDeviceString(const NcclExecuteParams& params); + + AsyncExecutor* async_executor() { return async_.get(); } + Status ExecuteOnStream(const ExecuteParams& params) override; + + protected: + virtual Status RunNcclCollective(const ExecuteParams& params, + se::Stream& stream, ncclComm_t comm) = 0; + virtual const NcclCollectiveConfig& config() const = 0; + virtual AsyncStreamKind GetAsyncStreamKind() const { + return kAsyncStreamCollective; + } + + private: + bool IsAsync() const { return async_ != nullptr; } + int64_t GetStreamId() const { + return xla::gpu::GetStreamId(IsAsync(), GetAsyncStreamKind()); + } + +#if XLA_ENABLE_XCCL + bool first_call_to_execute_ = true; +#endif // XLA_ENABLE_XCCL + std::unique_ptr async_; // null if not async. +}; + +class NcclCollectiveDoneThunk : public Thunk { + public: + NcclCollectiveDoneThunk(Thunk::Kind kind, ThunkInfo thunk_info, + NcclCollectiveThunk::AsyncExecutor& async); + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + NcclCollectiveThunk::AsyncExecutor& async_; +}; + +Status IsValidOperand(mlir::Value operand, Thunk::Kind reduction_op); + +template +Status AddOpDescription(Status status, OpT op, int64_t replica_count, + int64_t partition_count) { + if (status.ok()) { + return status; + } + CollectiveOpGroupMode group_mode = NcclThunkType::GetGroupMode(op); + return Status( + status.code(), + absl::StrFormat( + "%s\n" + "%s with replica_count: %d, partition_count: %d, group_mode: %s, " + "operand_count: %d\n%s", + status.message(), NcclThunkType::GetHloOpName(), replica_count, + partition_count, CollectiveOpGroupModeToString(group_mode), + op->getNumOperands() / 2, llvm_ir::DumpToString(op.getOperation()))); +} + +#if XLA_ENABLE_XCCL +// TODO(hanbinyoon): Consider moving to nccl_utils.h when deprecating Thunks. +StatusOr LockNcclComm( + const NcclExecuteParams& params, + const std::vector& replica_groups, + CollectiveOpGroupMode group_mode, int64_t op_id, int64_t stream_id, + bool enable_clique_optimization); +#endif // XLA_ENABLE_XCCL + +struct DeviceBufferPair { + PrimitiveType element_type; + int64_t element_count; + se::DeviceMemoryBase source_buffer; + se::DeviceMemoryBase destination_buffer; +}; +StatusOr> ConvertToDeviceBuffers( + const Thunk::ExecuteParams& params, + const std::vector& buffers, + const std::vector& element_types); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_COLLECTIVE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_p2p_thunk_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_p2p_thunk_common.h new file mode 100644 index 0000000000000000000000000000000000000000..25814402491fc0c29f1eb89f85cf71faac840bda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_p2p_thunk_common.h @@ -0,0 +1,136 @@ +/* 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_SERVICE_GPU_NCCL_P2P_THUNK_COMMON_H_ +#define XLA_SERVICE_GPU_NCCL_P2P_THUNK_COMMON_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +// Records the information for implementing CollectivePermute, Send and Recv. +struct NcclP2PConfig { + // Record the target ID for sending a data and the source ID from which to + // receive a data. Either target or source can be optional. + struct SourceTargetMapEntry { + std::optional source; + std::optional target; + }; + + using IdToSourceTargetMap = + absl::flat_hash_map; + + // Returns the source and target ID corresponding to the given ID (these IDs + // are replica_ids for cross replica permute or partition_ids for cross + // partition permute). The source ID is the id which will send data to this + // ID and the target ID is the id to which this ID will send its data. Either + // can be optional. + static SourceTargetMapEntry GetSourceTarget( + const IdToSourceTargetMap& id_to_source_target, int64_t id) { + auto it = id_to_source_target.find(id); + if (it != id_to_source_target.end()) return it->second; + return SourceTargetMapEntry{}; + } + + NcclCollectiveConfig config; + IdToSourceTargetMap id_to_source_target; +}; + +// Extracts source/target pairs for send/recv from frontend attributes. +StatusOr>> GetSourceTargetPairs( + mlir::DictionaryAttr frontend_attributes); + +// Returns the GroupMode for Send and Recv. +template +std::enable_if_t || + std::is_same_v, + CollectiveOpGroupMode> +GetGroupModeForSendRecv(OpT op) { + return GetCollectiveOpGroupMode(op.getChannelHandle().getHandle() > 1, + std::nullopt) + .value(); +} + +// Constructs the NcclP2PConfig for Send and Recv. +template +std::enable_if_t || + std::is_same_v, + NcclP2PConfig> +GetNcclP2PConfigForSendRecv(OpT op, int64_t replica_count, + int64_t partition_count) { + NcclP2PConfig p2p_config; + auto& config = p2p_config.config; + + config.operand_count = 1; + const Shape shape = GetShape(op.getOperand(0)); + config.operand_element_type.push_back(shape.element_type()); + + const int64_t channel_id = op.getChannelHandle().getHandle(); + config.group_mode = GetGroupModeForSendRecv(op); + // Emulate SetCollectiveOpKindAndID. + // Send and Recv ops have a non-optional channel id while collective-permute + // has an optional channel id. We use 0 to encode the send/recv transformed + // from collective-permute without a channel id. + if (channel_id >= 1) { + config.collective_op_kind = RendezvousKey::kCrossModule; + config.op_id = channel_id; + } else { + config.collective_op_kind = RendezvousKey::kCrossReplica; + mlir::ModuleOp parent = op->template getParentOfType(); + mlir::IntegerAttr unique_id = + parent->getAttrOfType("hlo.unique_id"); + config.op_id = static_cast(unique_id.getInt()); + } + + // All execution instances of a send/recv together form a replica group. + const int64_t num_participants = + config.group_mode == CollectiveOpGroupMode::kCrossReplica + ? replica_count + : partition_count; + config.replica_groups.emplace_back(); + ReplicaGroup& replica_group = config.replica_groups.front(); + for (int i = 0; i < num_participants; ++i) { + replica_group.add_replica_ids(i); + } + + auto source_target_pairs = GetSourceTargetPairs(op.getFrontendAttributes()); + TF_CHECK_OK(source_target_pairs.status()); + for (const std::pair& source_target : + *source_target_pairs) { + int64_t source = source_target.first; + int64_t target = source_target.second; + + p2p_config.id_to_source_target.insert({target, {}}).first->second.source = + source; + p2p_config.id_to_source_target.insert({source, {}}).first->second.target = + target; + } + + return p2p_config; +} + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_P2P_THUNK_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_recv_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_recv_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..d8dbc22f9822926a6dd3b34ef9ea83f4e8b08d42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_recv_thunk.h @@ -0,0 +1,66 @@ +/* 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_SERVICE_GPU_NCCL_RECV_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_RECV_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/nccl_p2p_thunk_common.h" + +namespace xla { +namespace gpu { + +// Thunk that performs a NCCL-recv. +class NcclRecvThunk : public NcclCollectiveThunk { + public: + static NcclP2PConfig GetNcclP2PConfig(mlir::lmhlo::RecvOp, + int64_t replica_count, + int64_t partition_count); + + static Status CheckImplementable(mlir::lmhlo::RecvOp op, + int64_t replica_count, + int64_t partition_count); + + static CollectiveOpGroupMode GetGroupMode(mlir::lmhlo::RecvOp op); + static const char* GetHloOpName() { return "recv"; } + + NcclRecvThunk(ThunkInfo thunk_info, mlir::lmhlo::RecvOp op, + int64_t replica_count, int64_t partition_count, + const Buffer& buffer); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + AsyncStreamKind GetAsyncStreamKind() const override { + return kAsyncStreamP2P; + } + + private: + const NcclP2PConfig config_; + const Buffer buffer_; +}; + +Status RunRecv(NcclP2PConfig::SourceTargetMapEntry source_target, + DeviceBufferPair& buffer, se::Stream& stream, ncclComm_t comm, + absl::string_view device_string, int64_t current_id); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_RECV_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_send_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_send_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..b57b1ee3279d70ce78b65c26c0a7f71a237c9c85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_send_thunk.h @@ -0,0 +1,65 @@ +/* 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_SERVICE_GPU_NCCL_SEND_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_SEND_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/nccl_p2p_thunk_common.h" + +namespace xla { +namespace gpu { + +// Thunk that performs a NCCL-send. +class NcclSendThunk : public NcclCollectiveThunk { + public: + static NcclP2PConfig GetNcclP2PConfig(mlir::lmhlo::SendOp, + int64_t replica_count, + int64_t partition_count); + + static Status CheckImplementable(mlir::lmhlo::SendOp op, + int64_t replica_count, + int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode(mlir::lmhlo::SendOp op); + static const char* GetHloOpName() { return "send"; } + + NcclSendThunk(ThunkInfo thunk_info, mlir::lmhlo::SendOp op, + int64_t replica_count, int64_t partition_count, + const Buffer& buffer); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + AsyncStreamKind GetAsyncStreamKind() const override { + return kAsyncStreamP2P; + } + + private: + const NcclP2PConfig config_; + const Buffer buffer_; +}; + +Status RunSend(NcclP2PConfig::SourceTargetMapEntry source_target, + DeviceBufferPair& buffer, se::Stream& stream, ncclComm_t comm, + absl::string_view device_string, int64_t current_id); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_SEND_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1d8c9571a81d890a62507aa47d2340293c337e4e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nccl_utils.h @@ -0,0 +1,138 @@ +/* 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_SERVICE_GPU_NCCL_UTILS_H_ +#define XLA_SERVICE_GPU_NCCL_UTILS_H_ + +#if TENSORFLOW_USE_ROCM +#define __HIP_DISABLE_CPP_FUNCTIONS__ +#endif + +#include +#include +#include + +#include "absl/synchronization/mutex.h" +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/gpu_executable_run_options.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +// Common place for all collective thunks to include nccl/rccl headers. +#if TENSORFLOW_USE_ROCM +#include "rocm/rocm_config.h" +#if (TF_ROCM_VERSION >= 50200) +#include "rocm/include/rccl/rccl.h" +#else +#include "rocm/include/rccl.h" +#endif +#else +#include "third_party/nccl/nccl.h" +#endif + +namespace xla { +namespace gpu { + +ncclRedOp_t ToNcclReduction(ReductionKind kind); +StatusOr> ToNcclDataTypeAndCountMultiplier( + PrimitiveType element_type, Thunk::Kind reduction_op); + +bool IsGlobalNcclConfig(); + +Status ToStatus(ncclResult_t s, const char* file, int64_t line, + const char* expr); + +// Macros to return or warn on CUDA/NCCL errors. (The same macro works for both +// NCCL and CUDA errors.) +// +// It's tempting to say these macros belong in an XLA header somewhere, but in +// practice we don't do much direct-to-CUDA-API stuff outside of this file. +#define XLA_CUDA_STATUS(expr) \ + xla::gpu::ToStatus(expr, __FILE__, __LINE__, #expr) + +#define XLA_CUDA_RETURN_IF_ERROR(expr) \ + do { \ + Status s = XLA_CUDA_STATUS(expr); \ + if (!s.ok()) { \ + return s; \ + } \ + } while (0) + +#define XLA_CUDA_WARN_IF_ERROR(expr) \ + do { \ + Status s = XLA_CUDA_STATUS(expr); \ + if (!s.ok()) { \ + LOG(ERROR) << s.ToString(); \ + } \ + } while (0) + +size_t GetNumLocalParticipants( + const std::vector& participants, + const std::vector* local_devices); // may be null + +StatusOr GetNcclUniqueIdCallback( + const NcclUniqueIdCallback* unique_id_callback, // may be null + bool is_local); + +// Represents a type that requires mutually exclusive access. +template +class Lockable { + public: + // RAII type that will release the exclusive lock when it is destroyed. + using Lock = std::unique_ptr>; + + Lockable() = default; + explicit Lockable(T value) : value_(std::move(value)) {} + Lockable(const Lockable&) = delete; + Lockable(Lockable&&) = delete; + Lockable& operator=(const Lockable&) = delete; + Lockable& operator=(Lockable&&) = delete; + + Lock Acquire() { + absl::MutexLock lock(&mutex_); + mutex_.Await(absl::Condition(&is_unlocked_)); + is_unlocked_ = false; + + return {&value_, [this](T*) { + absl::MutexLock lock(&mutex_); + CHECK(!is_unlocked_); + is_unlocked_ = true; + }}; + } + + private: + T value_; + absl::Mutex mutex_; + bool is_unlocked_ ABSL_GUARDED_BY(mutex_) = true; +}; + +TSL_LIB_GTL_DEFINE_INT_TYPE(OpId, int64_t); + +struct NcclComm : public Lockable { + explicit NcclComm(ncclComm_t comm) : Lockable(comm) {} +}; + +StatusOr AcquireNcclComm( + RunId run_id, OpId op_id, std::vector participants, + size_t num_local_participants, + const NcclUniqueIdCallback& unique_id_callback, int rank, int64_t stream_id, + bool enable_clique_optimization); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/non_atomically_upgradeable_rw_lock.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/non_atomically_upgradeable_rw_lock.h new file mode 100644 index 0000000000000000000000000000000000000000..ea09016bd6f30b7047e0f90198a10a23177e5321 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/non_atomically_upgradeable_rw_lock.h @@ -0,0 +1,95 @@ +/* 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_SERVICE_GPU_NON_ATOMICALLY_UPGRADEABLE_RW_LOCK_H_ +#define XLA_SERVICE_GPU_NON_ATOMICALLY_UPGRADEABLE_RW_LOCK_H_ + +#include +#include + +#include "absl/synchronization/mutex.h" + +namespace xla { +namespace gpu { + +// Augments absl::ReaderMutexLock with a poor man's upgrade/downgrade pair using +// RAII. Instead of a true upgrade (or downgrade), we simply drop the read +// (write) lock and then reacquire it as a write (read) lock. +class ABSL_SCOPED_LOCKABLE NonAtomicallyUpgradeableRWLock { + public: + explicit NonAtomicallyUpgradeableRWLock(absl::Mutex* mu) + ABSL_SHARED_LOCK_FUNCTION(mu) + : mu_(mu), is_reader_(true) { + mu_->ReaderLock(); + } + + NonAtomicallyUpgradeableRWLock(const NonAtomicallyUpgradeableRWLock&) = + delete; + NonAtomicallyUpgradeableRWLock(NonAtomicallyUpgradeableRWLock&&) = delete; + NonAtomicallyUpgradeableRWLock& operator=( + const NonAtomicallyUpgradeableRWLock&) = delete; + NonAtomicallyUpgradeableRWLock& operator=(NonAtomicallyUpgradeableRWLock&&) = + delete; + + ~NonAtomicallyUpgradeableRWLock() ABSL_UNLOCK_FUNCTION() { + if (is_reader_) { + mu_->ReaderUnlock(); + } else { + mu_->WriterUnlock(); + } + } + + // Upgrade and downgrade the reader lock via RAII. + class ABSL_SCOPED_LOCKABLE WriterLock { + public: + explicit WriterLock(NonAtomicallyUpgradeableRWLock* parent) + ABSL_EXCLUSIVE_LOCK_FUNCTION(parent->mu_) + : parent_(parent) { + assert(parent_->is_reader_); + parent_->mu_->ReaderUnlock(); + parent_->mu_->WriterLock(); + parent_->is_reader_ = false; + } + + WriterLock(const WriterLock&) = delete; + WriterLock(WriterLock&&) = delete; + WriterLock& operator=(const WriterLock&) = delete; + WriterLock& operator=(WriterLock&&) = delete; + + ~WriterLock() ABSL_UNLOCK_FUNCTION() { + parent_->mu_->WriterUnlock(); + parent_->mu_->ReaderLock(); + parent_->is_reader_ = true; + } + + private: + NonAtomicallyUpgradeableRWLock* parent_; + }; + + // Update the reader lock to a writer lock. The function is invalid if the + // lock is already upgraded. + WriterLock UpgradeToWriterMutexLock() ABSL_NO_THREAD_SAFETY_ANALYSIS { + return WriterLock(this); + } + + private: + absl::Mutex* const mu_; + bool is_reader_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NON_ATOMICALLY_UPGRADEABLE_RW_LOCK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nvptx_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nvptx_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..ea2162aa95aec5d5f7a2f4872d1e88f96eb4f6a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/nvptx_compiler.h @@ -0,0 +1,156 @@ +/* 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_SERVICE_GPU_NVPTX_COMPILER_H_ +#define XLA_SERVICE_GPU_NVPTX_COMPILER_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/node_hash_map.h" +#include "xla/autotune_results.pb.h" +#include "xla/service/gpu/gpu_compiler.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" +#include "tsl/platform/threadpool.h" + +namespace xla { +namespace gpu { + +void WarnIfBadDriverJITVersion(); + +// NVPTXCompiler generates efficient GPU executables for NVPTX target. +class NVPTXCompiler : public GpuCompiler { + public: + NVPTXCompiler(); + + Status OptimizeHloConvolutionCanonicalization( + HloModule* hlo_module, se::GpuComputeCapability gpu_version, + se::dnn::VersionInfo dnn_version, + se::DeviceMemoryAllocator* device_allocator) override; + + Status OptimizeHloPostLayoutAssignment( + HloModule* hlo_module, se::StreamExecutor* stream_exec, + const CompileOptions& options, const GpuTargetConfig& gpu_target_config, + const AutotuneResults* autotune_results, + tsl::thread::ThreadPool* thread_pool) override; + + bool RequiresCollectiveScheduleLinearizer( + const HloModule* module, se::StreamExecutor* stream_exec) override; + + Status AddConvAndGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, + tsl::thread::ThreadPool* thread_pool) override; + + Status AddTritonGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, + tsl::thread::ThreadPool* thread_pool) override; + + HloDataflowAnalysis::CanShareBuffer GetCanShareBuffer() const override; + + StatusOr>> CompileTargetBinary( + const HloModuleConfig& module_config, llvm::Module* llvm_module, + se::GpuComputeCapability gpu_version, bool relocatable, + const HloModule* debug_module, const CompileOptions& options) override; + + private: + StatusOr CanUseLinkModules( + const HloModuleConfig& module_config) override; + + StatusOr> LinkModules( + se::StreamExecutor* stream_exec, + std::vector> modules, + const DebugOptions& debug_options) override; + + absl::Mutex mutex_; + + enum class LinkingMethod { + kNone, + kNvLink, + kDriver, + }; + absl::flat_hash_map linking_methods_ + ABSL_GUARDED_BY(mutex_); + + StatusOr ChooseLinkingMethod( + const std::string& preferred_cuda_dir); + + // Tries to compile the given ptx string to cubin. Returns a vector with the + // compiled cubin if compilation succeeded. + StatusOr> CompileGpuAsmOrGetCachedResult( + const std::string& ptx, se::CudaComputeCapability cc, + const HloModuleConfig& hlo_module_config, absl::string_view module_name, + bool relocatable, const CompileOptions& options); + + // The compilation_cache_ map is a cache from {ptx string, cc_major, cc_minor} + // -> cubin so we don't recompile the same ptx twice. This is important for + // some interactive workflows. (We also cache at the HLO level, but sometimes + // we can't realize that two modules are the same until we lower to ptx.) + // + // Compilation of distinct PTX happens in parallel. If more than one thread + // attempts to compile the same PTX, the fist thread to obtain + // cache_value_->mutex_ performs the compilation. The rest wait() on + // cache_value_->compilation_done_cv_ until the compilation is done. + // + // If compiling the ptx fails, we return an empty cubin, cross our fingers, + // and leave compilation up to the driver. + struct CompilationCacheKey { + CompilationCacheKey(std::string ptx, int cc_major, int cc_minor, + bool relocatable) + : ptx(std::move(ptx)), + cc_major(cc_major), + cc_minor(cc_minor), + relocatable(relocatable) {} + template + friend H AbslHashValue(H h, const CompilationCacheKey& key) { + return H::combine(std::move(h), key.ptx, key.cc_major, key.cc_minor, + key.relocatable); + } + friend bool operator==(const CompilationCacheKey& a, + const CompilationCacheKey& b) { + return a.cc_major == b.cc_major && a.cc_minor == b.cc_minor && + a.ptx == b.ptx && a.relocatable == b.relocatable; + } + std::string ptx; + int cc_major; + int cc_minor; + bool relocatable; + }; + struct CompilationCacheValue { + bool compilation_done = false; + std::vector cubin_data; + // mutex and condition variable to serialize compilation completing. + absl::Mutex mutex; + absl::CondVar compilation_done_cv; + }; + + // Don't even think about switching this to flat_hash_map; iterator stability + // is critical here. + absl::node_hash_map + compilation_cache_ ABSL_GUARDED_BY(mutex_); + + NVPTXCompiler(const NVPTXCompiler&) = delete; + NVPTXCompiler& operator=(const NVPTXCompiler&) = delete; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NVPTX_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/outfeed_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/outfeed_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4da268a26b0b996a489e5eb8c9906d96d00fe637 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/outfeed_manager.h @@ -0,0 +1,74 @@ +/* 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_SERVICE_GPU_OUTFEED_MANAGER_H_ +#define XLA_SERVICE_GPU_OUTFEED_MANAGER_H_ + +#include +#include + +#include "xla/literal.h" +#include "xla/service/gpu/xfeed_queue.h" +#include "xla/shape_tree.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/notification.h" + +namespace xla { +namespace gpu { + +// TODO(b/30467474) Once GPU outfeed implementation settles, consider +// folding back the cpu and gpu outfeed implementations into a generic +// one if possible. + +// Defines a buffer holding the destination for an outfeed in host memory and a +// notification when that triggers when the transfer is done. +class OutfeedBuffer { + public: + explicit OutfeedBuffer(int64_t length) : length_(length) {} + + // Waits for the device transfer to be finished. + void WaitUntilAvailable() { done_.WaitForNotification(); } + + int64_t length() const { return length_; } + void set_destination(std::unique_ptr destination) { + destination_ = std::move(destination); + } + MutableBorrowingLiteral* destination() { return destination_.get(); } + + // Callback to signal that this buffer is consumed. + void Done() { done_.Notify(); } + + private: + std::unique_ptr destination_; + const int64_t length_; + tsl::Notification done_; +}; + +// Manages a thread-safe queue of buffers. The buffers are supposed to be +// produced by the transfer manager and consumed by the device. +class OutfeedManager + : public XfeedQueue>*> { + public: + Status TransferLiteralFromOutfeed(se::StreamExecutor* executor, + MutableBorrowingLiteral literal); +}; + +// Returns the GPU outfeed manager for the given stream executor. +OutfeedManager* GetOrCreateOutfeedManager(se::StreamExecutor* executor); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_OUTFEED_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/outfeed_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/outfeed_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..e6abb189a605188c1bf955d9962fa469cd0e5225 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/outfeed_thunk.h @@ -0,0 +1,48 @@ +/* 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_SERVICE_GPU_OUTFEED_THUNK_H_ +#define XLA_SERVICE_GPU_OUTFEED_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that outfeeds data. Data must be already resident on the host. This +// thunk performs a device to host copy from the buffer allocated for the +// outfeed op to the host location. +class OutfeedThunk : public Thunk { + public: + // Constructs a OutfeedThunk that copies data to the host-side + // outfeed queue from the buffers in the given shape tree. + OutfeedThunk(ThunkInfo thunk_info, std::vector source_slices); + + OutfeedThunk(const OutfeedThunk&) = delete; + OutfeedThunk& operator=(const OutfeedThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const std::vector source_slices_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_OUTFEED_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/parallel_loop_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/parallel_loop_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..b6ed37ca74220f3ecc502604511f61113a292bde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/parallel_loop_emitter.h @@ -0,0 +1,93 @@ +/* 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_SERVICE_GPU_PARALLEL_LOOP_EMITTER_H_ +#define XLA_SERVICE_GPU_PARALLEL_LOOP_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/loop_emitter.h" + +namespace xla { +namespace gpu { + +// Emits a parallel loop for every element in the given array shape. This loop +// emitted will be executed by multiple threads in parallel. Therefore, each +// thread instance of the loop iterates over part of the array, and they +// collectively iterates over the entire array. +class ParallelLoopEmitter { + public: + // `launch_dimensions` specify the number of threads and blocks to + // parallelize the loop on. `launch_config` specify some detail on + // how to parallelize. + ParallelLoopEmitter(llvm_ir::BodyEmitter body_emitter, const Shape& shape, + const LaunchDimensions& launch_dimensions, + llvm::IRBuilder<>* b, + LaunchDimensionsConfig launch_config = {}); + + // Constructs a loop emitter for a loop that generates on element of each of N + // arrays on each iteration. + // + // This is used in multi-output fusion. target_element_generator should + // produce a struct with N elements, one for each of target_arrays. + ParallelLoopEmitter(const llvm_ir::ElementGenerator& target_element_generator, + absl::Span target_arrays, + const LaunchDimensions& launch_dimensions, + llvm::IRBuilder<>* b, + LaunchDimensionsConfig launch_config = {}); + + ParallelLoopEmitter(const ParallelLoopEmitter&) = delete; + ParallelLoopEmitter& operator=(const ParallelLoopEmitter&) = delete; + + std::vector EmitIndexAndSetExitBasicBlock( + absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_index); + + Status EmitLoop(absl::string_view loop_name = "", + llvm::Type* index_type = nullptr); + + private: + struct LinearBaseAndThreadIdx { + llvm::Value* linear_base; + llvm::Value* thread_idx; + }; + + LinearBaseAndThreadIdx EmitLinearBaseAndThreadIdx(llvm::Type* index_type, + llvm::Value* base_index); + Status EmitSerialLoop(absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_indvar = nullptr); + + // The thread and block dimension to parallelize the loop on. + const LaunchDimensions launch_dimensions_; + const LaunchDimensionsConfig launch_config_; + + // An IR emitter that generates the loop body. + llvm_ir::BodyEmitter body_emitter_; + + // The shape that the emitted loop iterates through. + Shape shape_; + + // Points to the exit block of the emitted loop. If the given shape is + // scalar, no loops are emitted and exit_bb_ is nullptr in that case. + llvm::BasicBlock* exit_bb_; + + llvm::IRBuilder<>* b_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_PARALLEL_LOOP_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/precompiled_kernels.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/precompiled_kernels.h new file mode 100644 index 0000000000000000000000000000000000000000..3d1e96afafbeb269bc4f3bcbeb3dfa8df6e807d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/precompiled_kernels.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_SERVICE_GPU_PRECOMPILED_KERNELS_H_ +#define XLA_SERVICE_GPU_PRECOMPILED_KERNELS_H_ + +#include "xla/status.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/stream.h" +#include "xla/types.h" + +// Hardcoded GPU kernels for various simple tasks. + +namespace xla { +namespace gpu { + +// In GPU memory, does +// +// char* base_ptr = ...; +// void* ptrs_out = ...; +// for (i = 0; i < n; i++) { +// ptrs_out[i] = base_ptr + i * stride; +// } +// +// This is useful for functions like cublasTrsmBatched that operate on an array +// of pointers in GPU memory. In XLA these aren't usually arbitrary pointers +// but rather are all contiguous values. +// +// Instead of using a kernel, a simpler way of doing this would be to create +// this buffer on the host and then copy it to device. But using a kernel +// instead of an H2D copy avoids a few performance pitfalls. +// +// - Only one H2D copy can run on a given GPU at a time. If there's already +// a copy ongoing as part of other work on the GPU, our copy here will +// block. In contrast, multiple kernels can run simultaneously. +// +// - H2D copies from CUDA unpinned memory can acquire a global lock in the +// driver and slow down *all* work on the GPU. So to do this right, we'd +// need to allocate the host memory as pinned, one alloc per stream. Then +// we'd need to manage this memory without leaks. This becomes complex! +Status MakeBatchPointers(se::Stream* stream, const se::GpuAsmOpts& asm_opts, + se::DeviceMemoryBase base_ptr, int stride_bytes, int n, + se::DeviceMemoryBase ptrs_out); + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_PRECOMPILED_KERNELS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..73881e82614eab3b57372dfd2b8547ba3556c2cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.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_SERVICE_GPU_PREPARE_HLO_FOR_IR_EMITTING_PIPELINE_H_ +#define XLA_SERVICE_GPU_PREPARE_HLO_FOR_IR_EMITTING_PIPELINE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_pass_pipeline.h" + +namespace xla { +namespace gpu { + +// Function wrapper around the XLA GPU base pre-IR emission module preparation +// pipeline. This pipeline must be run right before IR emission to ensure +// correctness of the input module. +HloPassPipeline PrepareHloModuleForIrEmittingPipeline( + HloModule& hlo_module, + HloDataflowAnalysis::CanShareBuffer can_share_buffer); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_PREPARE_HLO_FOR_IR_EMITTING_PIPELINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/priority_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/priority_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..b43a7954a5e58e02a3bd5c402b8ae6fd8444c97e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/priority_fusion.h @@ -0,0 +1,79 @@ +/* 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_SERVICE_GPU_PRIORITY_FUSION_H_ +#define XLA_SERVICE_GPU_PRIORITY_FUSION_H_ + +#include + +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/fusion_queue.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/instruction_fusion.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +class GpuPriorityFusion : public InstructionFusion { + public: + explicit GpuPriorityFusion( + const se::DeviceDescription& d, + const GpuHloCostAnalysis::Options& cost_analysis_options) + : InstructionFusion(GpuPriorityFusion::IsExpensive), + device_info_(d), + cost_analysis_options_(cost_analysis_options) {} + + absl::string_view name() const override { return "priority-fusion"; } + + static bool IsExpensive(const HloInstruction& instruction); + + protected: + std::unique_ptr GetFusionQueue( + HloComputation* computation) override; + FusionDecision ShouldFuse(HloInstruction* consumer, + int64_t operand_index) override; + + HloInstruction::FusionKind ChooseKind( + const HloInstruction* producer, const HloInstruction* consumer) override; + + private: + // This method is called by ShouldFuse() to do all the computationally + // inexpensive checks whether we should fuse the operand into 'consumer'. + FusionDecision ShouldFuseInexpensiveChecks(HloInstruction* consumer, + int64_t operand_index); + + HloInstruction* FuseInstruction(HloInstruction* fusion_instruction, + HloInstruction* producer) override; + + se::DeviceDescription device_info_; + + // Cost model options that defines priorities in the queue. + GpuHloCostAnalysis::Options cost_analysis_options_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_PRIORITY_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_degenerate_dim_remover.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_degenerate_dim_remover.h new file mode 100644 index 0000000000000000000000000000000000000000..e146a3a01cbd016e98adec16abe25c789fcd9ec6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_degenerate_dim_remover.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_GPU_REDUCTION_DEGENERATE_DIM_REMOVER_H_ +#define XLA_SERVICE_GPU_REDUCTION_DEGENERATE_DIM_REMOVER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Enforces the invariant that reduction input and output have no degenerate +// (size 1) dimension. Since these dimensions are physically meaningless, they +// are removed using bitcasts. +// +// For example, +// +// f[1] out = reduce(f[100, 1, 1] input, dimensions={0, 1}) +// +// becomes: +// +// +// f[100] tmp1 = f[100] bitcast(f[100, 1, 1], input) +// f[] tmp2 = reduce(f[100] tmp1, dimensions={0}) +// f[1] out = f[] bitcast(tmp2) +// +class ReductionDegenerateDimRemover : public HloModulePass { + public: + absl::string_view name() const override { + return "reduction-degenerate-dim-remover"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_DEGENERATE_DIM_REMOVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_dimension_grouper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_dimension_grouper.h new file mode 100644 index 0000000000000000000000000000000000000000..b0d02bde2253e75efd5e6a39b699efabf87c0c7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_dimension_grouper.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_GPU_REDUCTION_DIMENSION_GROUPER_H_ +#define XLA_SERVICE_GPU_REDUCTION_DIMENSION_GROUPER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Groups adjacent (logically and physically) reduced dimensions in reduction +// input. +// +// Precondition: ReductionLayoutNormalizer has been run (physical proximity and +// logical proximity become the same). +// +// For example, +// +// f[] out = reduce(f[10,20,30] input, dimensions={0,1,2}) +// +// becomes: +// +// f[600] tmp = f[600] bitcast(f[10,20,30] input) +// f[] out = reduce(f[600] tmp, dimensions={0}) +// +class ReductionDimensionGrouper : public HloModulePass { + public: + absl::string_view name() const override { + return "reduction-dimension-grouper"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_DIMENSION_GROUPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_layout_normalizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_layout_normalizer.h new file mode 100644 index 0000000000000000000000000000000000000000..b7f0defd619f25d1271b8d808d6317d280c264cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_layout_normalizer.h @@ -0,0 +1,54 @@ +/* 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_SERVICE_GPU_REDUCTION_LAYOUT_NORMALIZER_H_ +#define XLA_SERVICE_GPU_REDUCTION_LAYOUT_NORMALIZER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Enforces default (minor-to-major) layout on all reduction inputs. +// Note that since reduction output can request a custom layout, +// this pass only guarantees standard layout for the input. +// +// For example, +// +// f[20,30]{0,1} out = reduce(f[10,20,30]{2,0,1} input, dimensions={0}) +// +// becomes: +// +// f[20,10,30] tmp = f[20,10,30] bitcast(f[10,20,30]{2,0,1} input) +// f[20,30]{0,1} out = reduce(f[20,10,30]{2,1,0} tmp, dimensions={1}) +class ReductionLayoutNormalizer : public HloModulePass { + public: + absl::string_view name() const override { + return "reduction-layout-normalizer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_LAYOUT_NORMALIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..776055acd4bacd74e56bb4346db682f5c9135bc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_splitter.h @@ -0,0 +1,52 @@ +/* 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_SERVICE_GPU_REDUCTION_SPLITTER_H_ +#define XLA_SERVICE_GPU_REDUCTION_SPLITTER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Splits a reduce op into two consecutive reduce ops if +// * the reduce dimensions are not contiguous and +// * at least one reduce dimension is large (i.e. corresponds to a large input +// shape dimension). +// +// Reductions with non-contiguous dimensions are emitted as simple element-wise +// loops. This is inefficient when reducing large input shape dimensions. +// Splitting such reductions allows using more efficient reduction emitters. +// +// This pass splits reduce ops into two consecutive reduce ops. Run it to a +// fixpoint to split reduce ops along multiple large dimensions. +// +// Precondition: ReductionDimensionGrouper has been run and adjacent reduce +// dimentsions have been grouped. Reduction layouts have been normalized. + +class ReductionSplitter : public HloModulePass { + public: + absl::string_view name() const override { return "reduction-splitter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..610200c888464249d46f640b077cfa290f502e68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/reduction_utils.h @@ -0,0 +1,69 @@ +/* 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_SERVICE_GPU_REDUCTION_UTILS_H_ +#define XLA_SERVICE_GPU_REDUCTION_UTILS_H_ + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_module_config.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +// Need at least 1024 threads/block for reasonable tree reduction +// performance (assuming all data fits). +int64_t MinThreadsXRowReduction(const HloModuleConfig& hlo_module_config); + +// When doing batched row reduction, how big the batch dimension could be. +inline constexpr int64_t BatchedReductionRaceFreeBound() { return 8; } + +// Returns true if either the dimensions being reduced or the dimensions being +// kept are contiguous in the input of the reduce instruction. +bool IsReductionFromOrToContiguousDimensions(const HloInstruction& reduce); + +struct ReductionDimensions { + // Indicates whether the reduction is a row reduction or a column reduction. + bool is_row_reduction; + + // Contains the size of the three contiguous components for + // the reduction [depth, height, width] (major-to-minor ordering). + // + // For row reduction, we do: [D, H, W] -> [D, H]. + // For column reduction, we do: [D, H, W] -> [D, W]. + Vector3 dimensions; +}; + +// Given the input shape and dimensions to reduce for a reduction, returns +// ReductionDimensions. +// +// Prerequisite: the reduction instruction passes the check +// IsReductionFromOrToContiguousDimensions, which guarantees either the +// dimensions to reduce or the dimensions to keep are consecutive. +ReductionDimensions GetReductionKindAndContiguousComponents( + const HloInstruction& reduce); + +// Get tiling per thread for the given reduction in dimensions [D, H, W]. +Vector3 GetReductionTiling(const ReductionDimensions& reduction_dimensions); + +// Returns whether the given reduction can be safely generated without atomics : +// that is, at most one block will write to every output element. +bool ReductionIsRaceFree(const HloModuleConfig& hlo_module_config, + const ReductionDimensions& reduction_dimensions); + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_REDUCTION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/replica_id_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/replica_id_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..23f694a0654a8cfd7e0e64961519274a022c7a1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/replica_id_thunk.h @@ -0,0 +1,53 @@ +/* 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_SERVICE_GPU_REPLICA_ID_THUNK_H_ +#define XLA_SERVICE_GPU_REPLICA_ID_THUNK_H_ + +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/thunk.h" + +namespace xla { +namespace gpu { + +// Thunk that implements the ReplicaId(Idx == 0) or PartitionId(Idx == 1). +class ReplicaOrPartitionIdThunk : public Thunk { + Status ExecuteOnStream(const ExecuteParams& params) override; + + protected: + ReplicaOrPartitionIdThunk(Kind kind, ThunkInfo thunk_info, + const BufferAllocation::Slice& dest) + : Thunk(kind, thunk_info), dest_(dest) {} + + private: + const BufferAllocation::Slice dest_; +}; + +class ReplicaIdThunk : public ReplicaOrPartitionIdThunk { + public: + ReplicaIdThunk(ThunkInfo thunk_info, const BufferAllocation::Slice& dest) + : ReplicaOrPartitionIdThunk(Kind::kReplicaId, thunk_info, dest) {} +}; + +class PartitionIdThunk : public ReplicaOrPartitionIdThunk { + public: + PartitionIdThunk(ThunkInfo thunk_info, const BufferAllocation::Slice& dest) + : ReplicaOrPartitionIdThunk(Kind::kPartitionId, thunk_info, dest) {} +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REPLICA_ID_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/cholesky.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/cholesky.h new file mode 100644 index 0000000000000000000000000000000000000000..23e8da20198921873c241ff23e64eb79b451ae80 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/cholesky.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_SERVICE_GPU_RUNTIME_CHOLESKY_H_ +#define XLA_SERVICE_GPU_RUNTIME_CHOLESKY_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime cholesky custom calls. +void RegisterCholeskyCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CHOLESKY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/collectives.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/collectives.h new file mode 100644 index 0000000000000000000000000000000000000000..23bd700cc151fc07220ef2c6d698cfff1d400e62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/collectives.h @@ -0,0 +1,79 @@ +/* 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_SERVICE_GPU_RUNTIME_COLLECTIVES_H_ +#define XLA_SERVICE_GPU_RUNTIME_COLLECTIVES_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/stream_executor/event.h" + +namespace xla { +namespace gpu { + +// Support for running async collective operations communicating via events. +// Registers XLA Gpu runtime collective custom calls. +void RegisterCollectiveCustomCalls(runtime::DirectCustomCallRegistry& registry); + +class CollectivesSupport { + public: + // Maybe block host after the first call to the collective operation with the + // given uid, to ensure that all devices have allocated the required buffers + // for their communicators before allowing any device to continue enqueuing + // operations. Otherwise, the allocations can cause deadlock in the CUDA + // driver. + // + // This basically ports workaround from cr/435058849 to Xla runtime (see + // details in the b/215649390). + absl::Status MaybeBlockAfterFirstRun(int32_t uid, int32_t device_ordinal, + se::Stream* stream); + + private: + absl::Mutex mutex_; + + // Store if a particular collective operation was executed at least once. We + // rely on unique `uid` assigned to each collective operation by the lowering + // pass. + absl::flat_hash_set executed_ ABSL_GUARDED_BY(mutex_); +}; + +// Support for running async collective operations communicating via events. +class AsyncCollectivesSupport { + public: + explicit AsyncCollectivesSupport(absl::Span async_streams); + + absl::Status RecordEvent(int32_t uid, AsyncStreamKind async_stream_kind); + absl::StatusOr PopEvent(int32_t uid); + + se::Stream* async_comm_stream(AsyncStreamKind async_stream_kind) const { + return async_comm_streams_[async_stream_kind]; + } + + private: + absl::Mutex mutex_; + absl::InlinedVector async_comm_streams_; + + // Store done events for the Done ops to wait upon. + absl::flat_hash_map done_events_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_COLLECTIVES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/concurrent_region.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/concurrent_region.h new file mode 100644 index 0000000000000000000000000000000000000000..c662282ef6efa279c9812429b62b3280b465c63c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/concurrent_region.h @@ -0,0 +1,75 @@ +/* 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_SERVICE_GPU_RUNTIME_CONCURRENT_REGION_H_ +#define XLA_SERVICE_GPU_RUNTIME_CONCURRENT_REGION_H_ + +#include + +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/service_executable_run_options.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime kernel launch custom calls. +void RegisterConcurrentRegionCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// The state to keep track of the information regarding concurrent regions +// between custom calls. +class ConcurrentRegionStatus { + public: + explicit ConcurrentRegionStatus( + const ServiceExecutableRunOptions* run_options, + int num_borrowed_streams = 10); + + ~ConcurrentRegionStatus(); + + absl::Status StartConcurrentRegion(se::Stream* capture_stream, int64_t size); + void EndConcurrentRegion(); + + // Temporarily disable concurrent execution when we run GPU graphs op-by-op. + // If disabled_ is set to true, StartConcurrentRegion will become an no-op and + // IsInConcurrentRegion always returns false. + void DisableConcurrentRegion() { disabled_ = true; } + void EnableConcurrentRegion() { disabled_ = false; } + + // Get a stream on which the concurrent-executable kernel runs. It returns a + // different stream each time to avoid building dependencies in the CUDA + // graph. + se::Stream* GetNextStream(); + + absl::StatusOr GetStream(int index); + + bool IsInConcurrentRegion(); + + private: + const int num_borrowed_streams_; + std::vector borrowed_streams_; + const ServiceExecutableRunOptions* run_options_; + + bool disabled_ = false; + int32_t stream_index_; + + // It is set to nullptr if not in a concurrent region. + se::Stream* capture_stream_; + int region_size_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CONCURRENT_REGION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/conv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/conv.h new file mode 100644 index 0000000000000000000000000000000000000000..d8622c16136b41572df650bb23f7e175450de79a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/conv.h @@ -0,0 +1,67 @@ +/* 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_SERVICE_GPU_RUNTIME_CONV_H_ +#define XLA_SERVICE_GPU_RUNTIME_CONV_H_ + +#include +#include + +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/gpu_conv_runner.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime Conv custom calls. +void RegisterConvCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Register type names for convoluttion attributes defined by MHLO dialect. +void RegisterConvTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Add attributes encoding for convoluttion attributes defined by MHLO dialect. +void PopulateConvAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +//===----------------------------------------------------------------------===// +// Cache conv runners between invocations of convolution custom calls. +//===----------------------------------------------------------------------===// + +struct ConvRunner { + explicit ConvRunner(GpuConvConfig config) + : config(std::move(config)), runner(this->config) {} + GpuConvConfig config; + GenericConvRunner runner; +}; + +class StreamExecutorConvRunners : public runtime::StateVector {}; + +// Xla executable keeps a mapping from stream executors to convolution runners. +class ConvRunners { + public: + StreamExecutorConvRunners* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map runners_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CONV_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/conv_reorder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/conv_reorder.h new file mode 100644 index 0000000000000000000000000000000000000000..654e9dd56bcb5bdad0ab4ede49c1dfc7bd909219 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/conv_reorder.h @@ -0,0 +1,31 @@ +/* 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_SERVICE_GPU_RUNTIME_CONV_REORDER_H_ +#define XLA_SERVICE_GPU_RUNTIME_CONV_REORDER_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime convolution reorder custom calls. +void RegisterConvReorderCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CONV_REORDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/cublas_lt_matmul.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/cublas_lt_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..ee7f501caf12c3db7d9344bb720c1b46a9e34073 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/cublas_lt_matmul.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_SERVICE_GPU_RUNTIME_CUBLAS_LT_MATMUL_H_ +#define XLA_SERVICE_GPU_RUNTIME_CUBLAS_LT_MATMUL_H_ + +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "xla/service/gpu/matmul_utils.h" +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#else +#include "rocm/rocm_config.h" +#include "xla/stream_executor/rocm/hip_blas_lt.h" +#endif +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime cuBLASLt custom calls. +void RegisterMatmulCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Add cuBLASLt attributes encoding +void PopulateCublasLtMatmulAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +#if GOOGLE_CUDA || TF_HIPBLASLT +// Keep cublas_lt::MatmulPlan's for all matmul instances in the executable. +class MatmulPlans : public runtime::StateVector {}; +#endif // GOOGLE_CUDA || TF_HIPBLASLT + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CUBLAS_LT_MATMUL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/custom_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/custom_call.h new file mode 100644 index 0000000000000000000000000000000000000000..df1c9f9fca3ef5e6a68c868cb665a8d05059c8df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/custom_call.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_SERVICE_GPU_RUNTIME_CUSTOM_CALL_H_ +#define XLA_SERVICE_GPU_RUNTIME_CUSTOM_CALL_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +void RegisterXlaClassicCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CUSTOM_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/executable.h new file mode 100644 index 0000000000000000000000000000000000000000..05967e17afa3c6f87547562ad4ceb1ed6836539e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/executable.h @@ -0,0 +1,196 @@ +/* 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_SERVICE_GPU_RUNTIME_EXECUTABLE_H_ +#define XLA_SERVICE_GPU_RUNTIME_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/runtime/executable.h" +#include "xla/runtime/ffi.h" +#include "xla/runtime/jit_executable.h" +#include "xla/runtime/module_registry.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/non_atomically_upgradeable_rw_lock.h" +#include "xla/service/gpu/runtime/collectives.h" +#include "xla/service/gpu/runtime/conv.h" +#include "xla/service/gpu/runtime/cublas_lt_matmul.h" +#include "xla/service/gpu/runtime/fft.h" +#include "xla/service/gpu/runtime/fused_attention.h" +#include "xla/service/gpu/runtime/gemm.h" +#include "xla/service/gpu/runtime/graph_launch.h" +#include "xla/service/gpu/runtime/kernel_launch.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Register custom calls implementing Xla Gpu runtime. +void RegisterXlaGpuRuntimeCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Register mapping from XLA (SE) enums/structs type ids to symbol names. +void RegisterXlaGpuTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Register encoding for (L)MHLO attributes required by the runtime functions. +void RegisterXlaGpuAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +// Xla Gpu program lowered to the Xla runtime dialects. Gpu runtime executable +// jit-compiles this program to an executable artifact (via lowering to LLVM). +// +// We have this program as an intermediate step between lowering from HLO to +// runtime executable to be able to introspect the compilation process. Once we +// have this program, the Xla gpu compiler job is done, and lowering to LLVM is +// the responsibility of backend-agnostic Xla runtime passes. This is the last +// stage when IR is still at a fairly high level of abstraction and has a lot of +// Gpu specific details in it. +struct GpuRuntimeProgram { + GpuRuntimeProgram(std::string entry_point, std::string module, + std::vector buffer_sizes, + DebugOptions debug_options) + : entry_point(std::move(entry_point)), + module(std::move(module)), + buffer_sizes(std::move(buffer_sizes)), + debug_options(std::move(debug_options)) {} + + std::string entry_point; + std::string module; + std::vector buffer_sizes; + DebugOptions debug_options; +}; + +// Gpu runtime executable encapsulates the Xla runtime executable compiled from +// an Xla program and owns all the state required for running it (e.g. it owns +// various caches required for performance). +// +// TODO(ezhulenev): Once thunks are removed from Xla, it might make sense to +// merge this executable into GpuExecutable. Today we keep it separate to manage +// the complexity of mixing two execution modes in the same file. GpuExecutable +// provides an API at XLA level of abstraction (streams and buffers), and this +// executable provides a lower level API exposing some of the implementation +// details. +class GpuRuntimeExecutable { + using ModulesState = ::xla::runtime::ModulesState; + using FfiModulesState = ::xla::runtime::ffi::FfiModulesState; + + public: + // Creates GpuRuntimeExecutable from the Xla Gpu Program. + static StatusOr> Create( + std::string module_name, std::unique_ptr program); + + // Creates GpuRuntimeExecutable from the AOT compiled binary. + static StatusOr> Create( + std::string module_name, absl::Span buffer_sizes, + runtime::Executable executable, DebugOptions debug_options); + + // Executes entry function with the given buffer arguments. + Status Execute(const ServiceExecutableRunOptions* run_options, + const std::string& asm_text, + const std::vector& binary, + const BufferAllocations& buffer_allocations, + NonAtomicallyUpgradeableRWLock& gpu_lock, + const BufferAllocation* temp_alloc = nullptr); + + // Returns object file behind the runtime executable. This object file can + // be exported and loaded later to instantiate another executable. + StatusOr GetObjFile() const; + + // Returns MLIR module behind this executable if it is available. + StatusOr GetMlirModule() const; + + std::string_view module_name() const { return module_name_; } + + private: + GpuRuntimeExecutable(std::string module_name, + std::vector buffer_sizes, + std::unique_ptr jit_executable, + DebugOptions debug_options, ModulesState modules_state, + FfiModulesState ffi_modules_state); + + GpuRuntimeExecutable(std::string module_name, + std::vector buffer_sizes, + std::unique_ptr aot_executable, + DebugOptions debug_options, ModulesState modules_state, + FfiModulesState ffi_modules_state); + + std::string module_name_; + + // Depending on the state of `executable_` returns a reference to active + // Xla runtime executable. + runtime::Executable& executable(); + + std::vector buffer_sizes_; + + // In JIT compilation mode `JitExecutable` is used. In AOT compilation mode + // `Executable` is used. + std::variant, + std::unique_ptr> + executable_; + + const DebugOptions debug_options_; + + // Keep gpu kernels loaded by this executable. + GpuExecutableKernels gpu_kernels_; + + // Keep gemm configs for all gemm operation in the program. + GemmConfigs gemm_configs_; + + // Keep a cache for conv configs for all conv operations in the program. + ConvRunners conv_runners_; + + // Keep a cache for fused_dot_attention configs for all fused_dot_attention + // operations in the program. + FusedAttentionRunners fused_attention_runners_; + + // Keep a cache for fused_dot_attention configs for all fused_dot_attention + // backward + // operations in the program. + FusedAttentionBackwardRunners fused_attention_backward_runners_; + + // Support for running collective operations. + CollectivesSupport collectives_; + + // Keep a cache of fft plans for all FFT operations in the program. + FftPlans fft_plans_; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + // Keep matmul execution plans (only if cuBLASLt is available). + MatmulPlans cublas_lt_matmul_plans_; + // Keep captured and instantiated GPU graphs instances. + GraphInstances graph_instances_; + CapturedFunctionExecutionCounts captured_function_counts_; + OrdinalToFallback ordinal_to_fallback_; +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + + // Keep an executable state for all registered runtime modules. + ModulesState modules_state_; + + // Keeps an executable state for all registered FFI modules. + FfiModulesState ffi_modules_state_; + + // Dynamic custom calls exported from XLA runtime modules (and FFI modules). + runtime::DynamicCustomCallRegistry dynamic_custom_calls_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/fft.h new file mode 100644 index 0000000000000000000000000000000000000000..bc45e310272dc75857bcbdcc534ada5e952f4f46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/fft.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_GPU_RUNTIME_FFT_H_ +#define XLA_SERVICE_GPU_RUNTIME_FFT_H_ + +#include + +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/fft_thunk.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime fft custom calls. +void RegisterFftCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Adds attributes encoding set for fft custom calls +void PopulateFftAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +// Keep FftPlanCache for all FFT instances in the executable. +class FftPlans : public runtime::StateVector> {}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/fused_attention.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/fused_attention.h new file mode 100644 index 0000000000000000000000000000000000000000..d6458f31c4a27bf4407ee19a699ee9ac520786cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/fused_attention.h @@ -0,0 +1,108 @@ +/* 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_SERVICE_GPU_RUNTIME_FUSED_ATTENTION_H_ +#define XLA_SERVICE_GPU_RUNTIME_FUSED_ATTENTION_H_ + +#include +#include + +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/gpu_fused_mha_runner.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime fused attention custom calls. +void RegisterFusedAttentionCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Register type names for fused attention attributes defined by MHLO dialect. +void RegisterFusedAttentionTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Add attributes encoding for fused attention attributes defined by LMHLO +// dialect. +void PopulateFusedAttentionForwardDAGSignatureAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +// Registers XLA Gpu runtime fused attention backward custom calls. +void RegisterFusedAttentionBackwardCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Add attributes encoding for fused attention backward attributes defined by +// LMHLO dialect. +void PopulateFusedAttentionBackwardDAGSignatureAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +void PopulateFusedAttentionAlgorithmConfigAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +//===----------------------------------------------------------------------===// +// Cache fused dot attention runners between invocations of fused dot attention +// custom calls. +//===----------------------------------------------------------------------===// +struct FusedAttentionRunner { + explicit FusedAttentionRunner(GpufMHAConfig config) + : config(std::move(config)), runner(this->config) {} + GpufMHAConfig config; + FusedMultiHeadedAttentionRunner runner; +}; + +struct FusedAttentionBackwardRunner { + explicit FusedAttentionBackwardRunner(GpufMHABackwardConfig config) + : config(std::move(config)), runner(this->config) {} + GpufMHABackwardConfig config; + FusedMultiHeadedAttentionBackwardRunner runner; +}; + +class StreamExecutorFusedAttentionRunners + : public runtime::StateVector {}; + +class StreamExecutorFusedAttentionBackwardRunners + : public runtime::StateVector {}; + +// Xla executable keeps a mapping from stream executors to fused attention +// runners. +class FusedAttentionRunners { + public: + StreamExecutorFusedAttentionRunners* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map + runners_ ABSL_GUARDED_BY(mutex_); +}; + +// Xla executable keeps a mapping from stream executors to fused attention +// backward runners. +class FusedAttentionBackwardRunners { + public: + StreamExecutorFusedAttentionBackwardRunners* operator()( + se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map + runners_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_FUSED_ATTENTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/gemm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/gemm.h new file mode 100644 index 0000000000000000000000000000000000000000..828c8a10602f0571c75c0ef1efe1a8737955600a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/gemm.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. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_GEMM_H_ +#define XLA_SERVICE_GPU_RUNTIME_GEMM_H_ + +#include "absl/container/node_hash_map.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/state.h" +#include "xla/service/gpu/matmul_utils.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime Gemm# custom calls. +void RegisterGemmCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Keep GemmConfigs for all gemm/matmul instances in the executable. +class GemmConfigs : public runtime::StateVector {}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_GEMM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/graph_launch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/graph_launch.h new file mode 100644 index 0000000000000000000000000000000000000000..e4841541bc781e685a23fa2a1cb617454719b8db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/graph_launch.h @@ -0,0 +1,139 @@ +/* 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_SERVICE_GPU_RUNTIME_GRAPH_LAUNCH_H_ +#define XLA_SERVICE_GPU_RUNTIME_GRAPH_LAUNCH_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/node_hash_map.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/executable.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/stream_executor/stream_executor.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "xla/stream_executor/gpu/gpu_graph.h" +#endif // #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime graph launch custom calls. +void RegisterGraphLaunchCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +struct GraphInstance; // Forward declare +class StreamExecutorGraphInstances; // Forward declare + +// A state vector that keeps track of the number of times a capture function +// gets executed. Graph capture function ordinal is the key in this container. +class CapturedFunctionExecutionCount + : public runtime::StateVector>> {}; + +// Create the i-th value if the capture function with ordinal i causes graph +// update failure. +class OrdinalToFallback : public runtime::StateVector {}; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +// A state vector that owns all instantiated GPU graphs. Graph capture function +// ordinal is the key in this container. +class StreamExecutorGraphInstances + : public runtime::StateVector {}; + +// Instantiated GPU graph instance guarded with a mutex for exclusive access. +struct GraphInstance { + GraphInstance(size_t ptr_hash, se::gpu::OwnedGpuGraphExec exec) + : ptr_hash(ptr_hash), exec(std::move(exec)), mutex(new absl::Mutex) {} + + // Graph instance is fully identified by the hash of its pointer arguments + // because currently it's guaranteed that all shapes and launch dimensions + // will be constant from run to run. + size_t ptr_hash ABSL_GUARDED_BY(*mutex); + se::gpu::OwnedGpuGraphExec exec ABSL_GUARDED_BY(*mutex); + + // Access to a graph instance must be synchronized, because we potentially can + // run concurrent graph instance updates. + std::unique_ptr mutex; +}; + +#else // #if !GOOGLE_CUDA && !TENSORFLOW_USE_ROCM + +// Define empty struct and empty state when GPU is not enabled. +struct GraphInstance {}; +class StreamExecutorGraphInstances + : public runtime::StateVector {}; + +#endif // #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +// Xla executable keeps a mapping from stream executors to graph instances. +// +// Graph instances allocate on-device memory, so we periodically destroy +// them to free up some space on device. JAX for example keeps all XLA +// executables alive, and destroys them when the process shuts down, so we can +// end up with thousands of unused (or rarely used) graphs in device memory. +class GraphInstances { + public: + struct Impl; + + GraphInstances(std::string module_name, int64_t num_graphs); + ~GraphInstances(); + + std::shared_ptr operator()( + se::StreamExecutor* executor); + + // Instantiates all Gpu graphs defined by the given executable using user + // provided run options. This guarantees that once we start execution, all Gpu + // graphs are ready, and will only require cheap update operation and will not + // require allocating new resources (we avoid non deterministic OOM errors). + // + // If timeout is not nullopt it will evict all previously instantiated graphs + // that were used more than `eviction_timeout_seconds` seconds ago. + Status InstantiateAllGraphs( + const ServiceExecutableRunOptions* run_options, + const runtime::Executable& executable, + const runtime::CustomCall::UserData& user_data, void* ptr, + OrdinalToFallback::Snapshot* ordinal_to_fallback, + std::optional eviction_timeout_seconds = std::nullopt); + + // Returns true if all Gpu graphs were already instantiated. + bool InstantiatedAllGraphs(const ServiceExecutableRunOptions* run_options, + const runtime::Executable& executable); + + private: + std::shared_ptr impl_; +}; + +// Xla executable keeps a mapping from stream executors to execution counts. +class CapturedFunctionExecutionCounts { + public: + CapturedFunctionExecutionCount* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map + counts_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_GRAPH_LAUNCH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/io_feed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/io_feed.h new file mode 100644 index 0000000000000000000000000000000000000000..ef4e42d770e49a9cdb875145136849037df9ec63 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/io_feed.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_SERVICE_GPU_RUNTIME_IO_FEED_H_ +#define XLA_SERVICE_GPU_RUNTIME_IO_FEED_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime infeed and outfeed custom calls. +void RegisterIoFeedCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_IO_FEED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/kernel_launch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/kernel_launch.h new file mode 100644 index 0000000000000000000000000000000000000000..80040b0f55f411fd898c32848cd9914bf5123592 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/kernel_launch.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_GPU_RUNTIME_KERNEL_LAUNCH_H_ +#define XLA_SERVICE_GPU_RUNTIME_KERNEL_LAUNCH_H_ + +#include +#include +#include + +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/state.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime kernel launch custom calls. +void RegisterKernelLaunchCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Kernels loaded by Gpu executable for a single stream executor. +class StreamExecutorKernels + : public runtime::StateVector> {}; + +// Xla runtime Gpu executable owns the pre-compiled device module (PTX and +// Cubin for Nvidia Gpus) for all device kernels, and the cache keeps a mapping +// from stream executor to pre-loaded kernels +class GpuExecutableKernels { + public: + StreamExecutorKernels* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map kernels_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_KERNEL_LAUNCH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/memcpy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/memcpy.h new file mode 100644 index 0000000000000000000000000000000000000000..cd4ecb4d5020a8e8fa5cbd5a2f12cb81bc485ffb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/memcpy.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_SERVICE_GPU_RUNTIME_MEMCPY_H_ +#define XLA_SERVICE_GPU_RUNTIME_MEMCPY_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime memcpy custom calls. +void RegisterMemcpyCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_MEMCPY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/memset.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/memset.h new file mode 100644 index 0000000000000000000000000000000000000000..e6d717941865ff366b15c4f5a92ad1e95c43532e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/memset.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_SERVICE_GPU_RUNTIME_MEMSET_H_ +#define XLA_SERVICE_GPU_RUNTIME_MEMSET_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime memset custom calls. +void RegisterMemsetCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_MEMSET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/send_recv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/send_recv.h new file mode 100644 index 0000000000000000000000000000000000000000..fcbe1ddcc9f9c0398a0d831f0701fdb9a065332b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/send_recv.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_GPU_RUNTIME_SEND_RECV_H_ +#define XLA_SERVICE_GPU_RUNTIME_SEND_RECV_H_ + +#include +#include + +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/stream_executor/event.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime Send/Recv custom calls. +void RegisterSendRecvCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Register type names for communication attributes defined by MHLO dialect. +void RegisterSendRecvTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Adds attributes encoding for Send/Recv custom calls +void PopulateSendRecvAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +//===----------------------------------------------------------------------===// +// Support for running asynchronous Send/Recv SendDone/RecvDone operations. +//===----------------------------------------------------------------------===// + +class SendRecvEvents { + public: + absl::Status PushEvent(int32_t handle, tsl::AsyncValueRef event); + absl::StatusOr> PopEvent(int32_t handle); + + private: + absl::Mutex mutex_; + absl::flat_hash_map> events_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_SEND_RECV_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/sleep_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/sleep_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0bcaed7c56cfb35a6a15d0c9d0f0b785e5b45d28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/sleep_kernel.h @@ -0,0 +1,21 @@ +/* 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_SERVICE_GPU_RUNTIME_SLEEP_KERNEL_H_ +#define XLA_SERVICE_GPU_RUNTIME_SLEEP_KERNEL_H_ + +namespace xla::gpu { + +void* GetSleepKernel(); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_SLEEP_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/stream_synchronization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/stream_synchronization.h new file mode 100644 index 0000000000000000000000000000000000000000..11d3175057c8c2457ca63918e63319fdae774125 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/stream_synchronization.h @@ -0,0 +1,31 @@ +/* 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_SERVICE_GPU_RUNTIME_STREAM_SYNCHRONIZATION_H_ +#define XLA_SERVICE_GPU_RUNTIME_STREAM_SYNCHRONIZATION_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime stream synchronization custom calls. +void RegisterStreamSynchronizationCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_STREAM_SYNCHRONIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/support.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/support.h new file mode 100644 index 0000000000000000000000000000000000000000..57bce214a73e1107fc83d6a25d9426bb72dd3038 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/support.h @@ -0,0 +1,162 @@ +/* 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_SERVICE_GPU_RUNTIME_SUPPORT_H_ +#define XLA_SERVICE_GPU_RUNTIME_SUPPORT_H_ + +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "llvm/ADT/ArrayRef.h" +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call.h" +#include "xla/service/gpu/matmul_utils.h" +#include "xla/shape_util.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/device_memory.h" + +namespace xla { +namespace gpu { + +template +using FunctionWrapper = xla::runtime::CustomCall::FunctionWrapper; + +struct DotDimensionNumbers { + absl::Span lhs_batch; + absl::Span lhs_contract; + absl::Span rhs_batch; + absl::Span rhs_contract; +}; + +// Disable expensive CustomCall checks in optimized build. +inline constexpr runtime::CustomCall::RuntimeChecks checks = // NOLINT +#if defined(NDEBUG) + runtime::CustomCall::RuntimeChecks::kLess; +#else + runtime::CustomCall::RuntimeChecks::kDefault; +#endif + +template +absl::StatusOr ToAbsl(StatusOr status_or) { + if (!status_or.ok()) return status_or.status(); + return std::move(status_or).value(); +} + +inline se::DeviceMemoryBase GetDeviceAddress( + const runtime::FlatMemrefView& memref) { + return se::DeviceMemoryBase(memref.data, memref.size_in_bytes); +} + +inline se::DeviceMemoryBase GetDeviceAddress( + const runtime::MemrefView& memref) { + uint64_t size = primitive_util::ByteWidth(memref.dtype); + for (auto dim : memref.sizes) size *= dim; + return se::DeviceMemoryBase(memref.data, size); +} + +inline se::DeviceMemoryBase GetDeviceAddress( + const runtime::StridedMemrefView& memref) { + uint64_t size = primitive_util::ByteWidth(memref.dtype); + for (auto dim : memref.sizes) size *= dim; + return se::DeviceMemoryBase(memref.data, size); +} + +inline Shape ToShape(const runtime::StridedMemrefView& memref) { + // Recover `minor_to_major` dimensions permutation from strides. + auto indexed_strides_range = + llvm::map_range(llvm::enumerate(memref.strides), [](auto pair) { + return std::pair{pair.value(), pair.index()}; + }); + + auto indexed_strides = llvm::to_vector(indexed_strides_range); + llvm::stable_sort(indexed_strides); + + llvm::SmallVector minor_to_major; + minor_to_major.reserve(indexed_strides.size()); + for (auto& pair : indexed_strides) minor_to_major.push_back(pair.second); + + return ShapeUtil::MakeShapeWithDenseLayout(memref.dtype, memref.sizes, + minor_to_major); +} + +inline StatusOr GetGemmConfig( + const runtime::StridedMemrefView& lhs, + const runtime::StridedMemrefView& rhs, + const runtime::StridedMemrefView& out, int64_t algorithm, double alpha_real, + double alpha_imag, double beta, absl::Span lhs_batch, + absl::Span lhs_contract, absl::Span rhs_batch, + absl::Span rhs_contract, int64_t compute_precision, + const std::optional c = std::nullopt, + const std::optional& bias = std::nullopt) { + Shape c_shape = ToShape(c.value_or(out)); + Shape bias_shape; + Shape* bias_shape_ptr = nullptr; + if (bias) { + bias_shape = ToShape(*bias); + bias_shape_ptr = &bias_shape; + } + return GemmConfig::For(ToShape(lhs), lhs_batch, lhs_contract, ToShape(rhs), + rhs_batch, rhs_contract, c_shape, bias_shape_ptr, + ToShape(out), alpha_real, alpha_imag, beta, algorithm, + compute_precision); +} + +// adds Dot Dimension Attribute encodings for calls to Gemm and cuBLASLt +inline void PopulateDotDimsAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding) { + using DotDimsAttr = mlir::mhlo::DotDimensionNumbersAttr; + encoding.Add< + xla::runtime::AggregateAttrEncoding>( + encoding, + xla::runtime::AggregateAttrDef() + .Add("lhs_batch", &DotDimsAttr::getLhsBatchingDimensions) + .Add("lhs_contract", &DotDimsAttr::getLhsContractingDimensions) + .Add("rhs_batch", &DotDimsAttr::getRhsBatchingDimensions) + .Add("rhs_contract", &DotDimsAttr::getRhsContractingDimensions)); +} + +// Appends to `diagnostic_engine` a handler that appends all emitted errors to +// the `diagnostic` string. If `append_annotation_stack` is true, it will append +// current profiler annotation stack to the diagnostic message (annotation used +// in Xprof). +void AppendDiagnosticToString(runtime::DiagnosticEngine& diagnostic_engine, + std::string* diagnostic, + bool append_annotation_stack = false); + +// Sets the current tracing scope that will be added to all emitted diagnostics. +void SetCurrentTracingScope(std::string_view scope); +void ResetCurrentTracingScope(); + +} // namespace gpu +} // namespace xla + +namespace xla { +namespace runtime { + +// using llvm::ArrayRef; + +XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING( + xla::gpu::DotDimensionNumbers, + AggregateMember>("lhs_batch"), + AggregateMember>("lhs_contract"), + AggregateMember>("rhs_batch"), + AggregateMember>("rhs_contract")); + +} // namespace runtime +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_SUPPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk.h new file mode 100644 index 0000000000000000000000000000000000000000..ea669e903dd6f0f5cc4eb56f8588c4f3e23f2808 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk.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_SERVICE_GPU_RUNTIME_TOPK_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla::gpu { + +// Registers XLA Gpu runtime TopK custom calls. +void RegisterTopkCustomCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel.cu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel.cu.h new file mode 100644 index 0000000000000000000000000000000000000000..908401c9979af87e133cae929071366ef9e23c18 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel.cu.h @@ -0,0 +1,280 @@ +/* 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_SERVICE_GPU_RUNTIME_TOPK_KERNEL_CU_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_CU_H_ + +// This file contains bespoke and optimized implementation for TopK shapes. When +// adding support for new shapes/dtypes, you also need to modify the rewritter +// on topk_specializer.cc for these changes to be picked up. + +#include +#include +#include + +#include "xla/service/gpu/runtime/topk_kernel_common.h" + +namespace xla::gpu { + +// Default implementation for KV holder. Useful for testing while adding support +// for a new type, but generally bitpacking those values is more efficient. See +// implementations below. +template +struct Descending { + class KVT { + public: + __device__ KVT() = default; + __device__ KVT& operator=(const KVT&) = default; + __device__ KVT& operator=(KVT&&) = default; + __device__ KVT(const KVT&) = default; + __device__ KVT(KVT&&) = default; + + __device__ KVT(T k, V v) : k_(k), v_(v) {} + __forceinline__ __device__ void Write(T* key, uint32_t* value) const { + *key = k_; + *value = v_; + } + + __device__ __forceinline__ KVT ShuffleDown(int offset) const { + unsigned FULL_MASK = 0xffffffff; + // The static casts here are necessary because some types will be + // broadened (e.g. bfloat16 -> f32), so we need to narrow them back after + // the shuffle. + return KVT(static_cast(__shfl_down_sync(FULL_MASK, k_, offset)), + static_cast(__shfl_down_sync(FULL_MASK, v_, offset))); + } + + private: + T k_; + V v_; + friend class Descending; + }; + + __device__ __forceinline__ static constexpr bool Gt(const KVT& lhs, + const KVT& rhs) { + return lhs.k_ == rhs.k_ ? lhs.v_ < rhs.v_ : lhs.k_ > rhs.k_; + } +}; + +// ----------------------------------------------------------------------------- +// More efficient implementation of Descending. +// ----------------------------------------------------------------------------- + +// Strided indexing. +__device__ __forceinline__ int Idx(int i) { + return blockDim.x * i + threadIdx.x; +} + +// TopK implements a faster TopK for K < 16. +// +// To compute the final largest K elements, we shard the data threads and each +// of them computes the top k elements for the data in its slice. When all lanes +// in a warp are done with their TopK, we merge all the lane-local topks into +// lane 0 using warp-local reductions. The lane-local topk is computed at +// PerWarpTopK() and the warp reduction is computed in Reduce(). The warp-local +// results are stored in shared memory. +// +// Once all warps are done, we load all previously produced results into a +// single warp and repeat the reduction described above. This is implemented in +// MergeTopKs() and we reuse the Reduce() implementation described above. On +// MergeTopKs we also write the final results to the user-provided buffer. +// +// === Detailed Design +// +// The high level goals of this implementations are: +// - Low latency for small N (i.e. kilobytes). +// - High throughput for large N and/or large batch. +// +// Non-goals: +// - K > 32. Register pressure will be too high. +// - Sharding over multiple SMs. As explained later, we can use TopK's +// structure to get this "for free". +// +// The core observation of this implementation is that reading/writing to main +// memory is the bottleneck in usual the Sort/TopK implementations and that for +// K<16 a linear scan with in-register data is faster than using a heap with +// shared memory, especially when K is a power of two. +// +// The heap for K=7 looks like: +// +// a0 +// a1 a2 +// a3 a4 a5 a6 +// +// When performing a push/pop, in the worst case scenario we need to compare it +// with the root, both of its children, and one of the two subtrees. This means +// that using a heap for K=7 only save us 2/7 comparions. Additionally, if the +// tree were unbalanced(e.g. K=8), we would not be able to unroll this +// computation. +// +// If we're using linear insertion, the worst case results in the full K +// comparisons comparisons, but with care all of those values can be kept in +// registers, replacing somewhat load/store instructions with movs. This +// performance are more than enough to surpass the heap. +// +// We split the data evenly over T (<=1024) threads, and use the algorithm above +// to maintain a sorted list of K elements in registers and perform linear +// insertions on every new element. Once a warp is done with their local slice, +// we reduce the slice-local data using shfl and the insertion described above, +// by adding the other lane's TopK results to the local lane. Once the warp is +// done, lane 0 writes its results to shared memory. This step has complexity: +// theta(k * slice_size + k^2 * log2(k)) +// +// On a second pass, we use a single warp to consume the results of the previous +// step and merge them into a final topk, using an analogous algorithm to what +// has been previously described. Complexity of this stage is: +// theta(k^2 * log2(k)). +// +// This algorithm only uses a single block per batch dimension, but for large N, +// we can split the input into B batches of size N/B, calculate each of their +// topks and then compute a final topk, fixing the indices in the process. +// +// Future improvements: +// - Use optimal sort/merge networks to reduce the complexity the algorithm and +// allow better scaling past K=16. This is fairly tricky to implement +// efficiently, so it was let out of v1. +// +template class Traits = Descending> +class TopK { + public: + using Trait = Traits; + using KVT = typename Trait::KVT; + + __device__ TopK(void* buffer, int num_outputs) + : buffer_(reinterpret_cast(buffer)), num_outputs_(num_outputs) {} + + __device__ void Run(KT* key, int n, KT* keys, uint32_t* values) { + PerWarpTopK(key, n); + MergeTopKs(keys, values); + } + + private: + // Compute a per-warp topk of a slice of data. + __device__ void PerWarpTopK(KT* key, int n) { + KVT tmp[K]; + // TODO(doak): Use bitonic sort. +#pragma unroll + for (int i = 0; i < K; i++) tmp[i] = KVT(key[Idx(i)], Idx(i)); +#pragma unroll + for (int i = 0; i < K; i++) { +#pragma unroll + for (int j = i + 1; j < K; j++) { + KVT ti = tmp[i]; + KVT tj = tmp[j]; + bool cmp = Trait::Gt(ti, tj); + tmp[i] = cmp ? ti : tj; + tmp[j] = cmp ? tj : ti; + } + } + + for (int idx = K; idx < n; idx++) { + KVT kv(key[Idx(idx)], Idx(idx)); + Push(tmp, kv); + } + + Reduce(tmp, 32); + + if (threadIdx.x % 32 != 0) return; + int warp_id = threadIdx.x / 32; + for (int i = 0; i < K; i++) { + buffer_[i * 32 + warp_id] = tmp[i]; + } + } + + // Merge the per-warp topks into a single topk. The final data is written to + // `keys` and `values` + __device__ void MergeTopKs(KT* keys, uint32_t* values) { + KVT tmp[K]; + // We only use one warp for this step. + if (threadIdx.x / 32 != 0) return; + __syncthreads(); +#pragma unroll + for (int i = 0; i < K; i++) tmp[i] = buffer_[i * 32 + threadIdx.x]; + Reduce(tmp, blockDim.x / 32); + if (threadIdx.x != 0) return; + for (int i = 0; i < num_outputs_; ++i) { + tmp[i].Write(&keys[i], &values[i]); + } + } + + // Merge `tmp` (a reverse-sorted array) from (0, `num_lanes`) lanes. The + // resulting array is stored in the tmp array of lane 0. For all other lanes, + // `tmp` is unspecified after this function is called. + __device__ __forceinline__ void Reduce(KVT tmp[K], int num_lanes) { + int lane_id = threadIdx.x % 32; + for (int offset = num_lanes / 2; offset > 0; offset /= 2) { +#pragma unroll + for (int i = 0; i < K; i++) { + KVT kv = tmp[i].ShuffleDown(offset); + if (lane_id >= offset) continue; + Push(tmp, kv); + } + } + } + + // Given a K-array of previously reverse-sorted KVTs, add kv to to it and + // remove the smallest element of the resulting array. Preserves the sorted + // order of `tmp`. + static __device__ __forceinline__ bool Push(KVT tmp[K], const KVT& kv) { + if (Trait::Gt(tmp[K - 1], kv)) return false; + tmp[K - 1] = kv; + if constexpr (K >= 2) { +#pragma unroll + for (int i = K - 2; i >= 0; --i) { + if (Trait::Gt(tmp[i], kv)) break; + // Swap + KVT t = tmp[i]; + tmp[i] = tmp[i + 1]; + tmp[i + 1] = t; + } + } + return true; + } + + int source_ = 0; + KVT* buffer_; + int num_outputs_; +}; + +// This shared memory buffer needs to be declared outside of the templated +// Run(), as otherwise it would generate name conflicts from the multiple +// instantiations of Run() from the multiple monomorphizations of Run(). +extern __device__ __shared__ int shmem[]; + +template +__launch_bounds__(kTopKMaxThreadsPerBlock, 1) __global__ + void Run(KT* data, int n, KT* result, uint32_t* result_idxs, int k) { + TopK top_k(shmem, k); + int slice_size = n / blockDim.x; + if (threadIdx.x < n % blockDim.x) { + slice_size++; + } + top_k.Run(&data[n * blockIdx.x], slice_size, &result[k * blockIdx.x], + &result_idxs[k * blockIdx.x]); +} + +template +void* GetTopKKernelForK(int n) { + // TODO(doak): Switch to uint32_t if we don't have an efficient + // implemementation for uint16_t. + return n < std::numeric_limits::max() + ? reinterpret_cast(&Run) + : reinterpret_cast(&Run); +} + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_CU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6afd56d35fe9d6c4788781d8776879fe69dc0e7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel.h @@ -0,0 +1,43 @@ +/* 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_SERVICE_GPU_RUNTIME_TOPK_KERNEL_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_H_ + +#include +#include + +#include "absl/status/status.h" +#include "xla/stream_executor/gpu/gpu_stream.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/platform.h" +#include "xla/xla_data.pb.h" + +namespace xla::gpu { + +// Input: [batch_size, num_elements]dtype +// Output: +// - top_elements: [batch_size, k] dtype +// - top_indices: [batch_size, k] u32 +// Where `top_elements` contains the largest elements of the input, and +// `top_indices` their original indices. +absl::Status RunTopk(::tensorflow::se::gpu::GpuStreamHandle stream, + PrimitiveType dtype, void* data, size_t num_elements, + void* top_elements, uint32_t* top_indices, size_t k, + size_t batch_size); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel_common.h new file mode 100644 index 0000000000000000000000000000000000000000..a805b4507aa09c7df2124e22ec9e311f44a3eea9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/topk_kernel_common.h @@ -0,0 +1,34 @@ +/* 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_SERVICE_GPU_RUNTIME_TOPK_KERNEL_COMMON_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_COMMON_H_ + +// Contains shared declarations between topk_kernel.cc and topk_kernel.cu.cc +// but avoids including ABSL, etc. which some CUDA compilers cannot +// handle. + +namespace xla::gpu { + +// We perform 2 32-way reductions, which means the largest number of threads per +// block we support is 1024. +static constexpr size_t kTopKMaxThreadsPerBlock = 1024; + +template +void* GetTopKKernelForK(int n); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/tracing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/tracing.h new file mode 100644 index 0000000000000000000000000000000000000000..7f5efe48accac438642b8074e0a55e7e34c5a9d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/tracing.h @@ -0,0 +1,34 @@ +/* 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_SERVICE_GPU_RUNTIME_TRACING_H_ +#define XLA_SERVICE_GPU_RUNTIME_TRACING_H_ + +#include + +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/type_id.h" + +namespace xla { +namespace gpu { + +void RegisterTracingTypeIdNames(runtime::TypeIDNameRegistry& registry); + +void RegisterTracingCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_TRACING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/triangular_solve.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/triangular_solve.h new file mode 100644 index 0000000000000000000000000000000000000000..947633ed2d0793eb153321e6d69e12a3c43a41f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime/triangular_solve.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_SERVICE_GPU_RUNTIME_TRIANGULAR_SOLVE_H_ +#define XLA_SERVICE_GPU_RUNTIME_TRIANGULAR_SOLVE_H_ + +#include + +#include "xla/runtime/custom_call.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +using runtime::CustomCall; + +struct TriangularSolve { + // Adaptor from XlaCustomCall API to properly typed TriangularSolve handler. + static absl::Status run(const ServiceExecutableRunOptions* run_options, + const DebugOptions* debug_options, + CustomCall::RemainingArgs args, + std::string_view backend_config); + + absl::Status operator()(const ServiceExecutableRunOptions* run_options, + const DebugOptions* debug_options, + runtime::StridedMemrefView a, + runtime::StridedMemrefView b, + runtime::StridedMemrefView result, + runtime::FlatMemrefView temp, bool left_side, + bool lower, bool unit_diagonal, + TriangularSolveOptions::Transpose transpose_a) const; + + static TriangularSolve Handler() { return TriangularSolve(); } +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_TRIANGULAR_SOLVE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime2/executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime2/executable.h new file mode 100644 index 0000000000000000000000000000000000000000..ac61847680c07bd7be659b3c5a4bf2b1da0e6147 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime2/executable.h @@ -0,0 +1,176 @@ +/* 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_SERVICE_GPU_RUNTIME2_EXECUTABLE_H_ +#define XLA_SERVICE_GPU_RUNTIME2_EXECUTABLE_H_ + +#include +#include +#include +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/status.h" +#include "xla/statusor.h" + +//===----------------------------------------------------------------------===// +// TODO(ezhulenev): We currently do not build with experimental XLA:GPU runtime +// in open source because we do not have bazel dependency from XLA to IREE. +#if XLA_DISABLE_GPU2_RUNTIME +//===----------------------------------------------------------------------===// + +namespace xla::gpu { +struct Gpu2RuntimeProgram { + Gpu2RuntimeProgram(std::unique_ptr, + mlir::OwningOpRef, std::string, + std::vector, DebugOptions) {} +}; + +struct Gpu2RuntimeExecutable { + static StatusOr> Create( + std::unique_ptr, std::string_view, + const std::vector&) { + return absl::UnimplementedError( + "Experimental XLA:GPU runtime is not supported in OSS build"); + } + + Status Execute(const ServiceExecutableRunOptions* run_options, + const BufferAllocations& buffer_allocations, + const BufferAllocation* temp_alloc) { + return absl::UnimplementedError( + "Experimental XLA:GPU runtime is not supported in OSS build"); + } +}; + +} // namespace xla::gpu + +//===----------------------------------------------------------------------===// +#else // !XLA_DISABLE_GPU2_RUNTIME +//===----------------------------------------------------------------------===// + +#include +#include + +#include "third_party/iree/runtime/src/iree/vm/api.h" // IWYU pragma: keep +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/runtime2/compiler.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Forward declare. +struct HalDevice; + +// XLA:GPU program lowered to the IREE input dialects. XLA:GPU runtime +// executable jit-compiles this program to an executable artifact (via lowering +// to IREE VM executable). +// +// Top level module has a single HAL executable source that contains all device +// kernels for an XLA module. After lowering from LMHLO executable source is +// just a placeholder; it gets updated with a real device kernels source only +// before we pass IR to IREE compiler (see Gpu2RuntimeExecutable below), +// because in the XLA compilation pipeline backend compiler runs last. +// +// We have this program as an intermediate step between lowering from LMHLO to +// VM executable to be able to introspect the compilation process. Once we have +// this program, the Xla gpu compiler job is done, and lowering to IREE VM is +// the responsibility of IREE compiler. +struct Gpu2RuntimeProgram { + Gpu2RuntimeProgram(std::unique_ptr ctx, + mlir::OwningOpRef module, + std::string entry_point, std::vector buffer_sizes, + DebugOptions debug_options) + : ctx(std::move(ctx)), + module(std::move(module)), + entry_point(std::move(entry_point)), + buffer_sizes(std::move(buffer_sizes)), + debug_options(std::move(debug_options)) {} + + std::unique_ptr ctx; + mlir::OwningOpRef module; + std::string entry_point; + std::vector buffer_sizes; + DebugOptions debug_options; +}; + +// Gpu runtime executable encapsulates the Xla runtime executable compiled from +// an Xla program and owns all the state required for running it (e.g. it owns +// various caches required for performance). +class Gpu2RuntimeExecutable { + public: + using Bytecode = RuntimeCompiler::Bytecode; + + // Creates Gpu2RuntimeExecutable from the XLA:GPU program. + static StatusOr> Create( + std::unique_ptr program, std::string_view asm_text, + const std::vector& binary); + + ~Gpu2RuntimeExecutable(); + + // Executes entry function with the given buffer arguments. + Status Execute(const ServiceExecutableRunOptions* run_options, + const BufferAllocations& buffer_allocations, + const BufferAllocation* temp_alloc); + + private: + Gpu2RuntimeExecutable(std::string module_name, int32_t module_id, + std::unique_ptr device, + std::unique_ptr bytecode, + std::vector buffer_sizes, + DebugOptions debug_options, std::string_view asm_text, + absl::Span binary, + iree::vm::ref context, + iree::vm::ref instance, + std::unique_ptr> modules, + iree_vm_function_t function); + + // Module name and unique id of the corresponding HLO module. + std::string module_name_; + int32_t module_id_; + + // TODO(ezhulenev): Devices should be created lazily for each StreamExecutor + // and share underlying resources. For now we create a CUDA driver and CUDA + // HAL device for each executable. And we assume that we have just once GPU + // attached to the host, and always run on device with ordinal 0. + std::unique_ptr device_; + + std::unique_ptr bytecode_; + + std::vector buffer_sizes_; + const DebugOptions debug_options_; + + std::string_view asm_text_; + absl::Span binary_; + + // TODO(ezhulenev): VM context and instance should be shared between multiple + // executables. Also HAL module should be loaded just once. This has to be + // fixed together with efficient device sharing, because HAL VM module + // requires HAL device for loading. + iree::vm::ref context_; + iree::vm::ref instance_; + std::unique_ptr> modules_; + iree_vm_function_t function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // !XLA_DISABLE_GPU2_RUNTIME +#endif // XLA_SERVICE_GPU_RUNTIME2_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime3/cholesky_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime3/cholesky_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..f226a25f7e4885fd32462852c9015f697d09217c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime3/cholesky_thunk.h @@ -0,0 +1,83 @@ +/* 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_SERVICE_GPU_RUNTIME3_CHOLESKY_THUNK_H_ +#define XLA_SERVICE_GPU_RUNTIME3_CHOLESKY_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/cusolver_context.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a Cholesky +// decomposition (LAPACK potrf). It is generated by IrEmitter. +// +// As an implementation detail, we may run potrf (potentially in a loop, if +// batch_size >1), or potrfBatched. +// +// Thread-compatible. +class CholeskyThunk : public Thunk { + public: + CholeskyThunk(ThunkInfo thunk_info, const CholeskyOptions& options, + se::GpuAsmOpts asm_opts, BufferAllocation::Slice a_buffer, + BufferAllocation::Slice workspace_buffer, + BufferAllocation::Slice info_buffer, PrimitiveType type, + int64_t batch_size, int64_t n); + + CholeskyThunk(const CholeskyThunk&) = delete; + CholeskyThunk& operator=(const CholeskyThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + se::GpuAsmOpts asm_opts_; + se::blas::UpperLower uplo_; + + const BufferAllocation::Slice a_buffer_; + const BufferAllocation::Slice workspace_buffer_; + const BufferAllocation::Slice info_buffer_; + + const PrimitiveType type_; + const int64_t batch_size_; + const int64_t n_; +}; + +struct CholeskyParams { + int64_t n; + int64_t batch_size; + se::blas::UpperLower uplo; + se::DeviceMemoryBase a_buffer; + se::DeviceMemoryBase workspace_buffer; + se::DeviceMemoryBase info_buffer; +}; +Status RunCholesky(const se::GpuAsmOpts& asm_opts, PrimitiveType type, + CholeskyParams* params, se::Stream* stream); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME3_CHOLESKY_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime_intrinsics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime_intrinsics.h new file mode 100644 index 0000000000000000000000000000000000000000..d73aced0e2a1fc58d7e83e7f82ab73ed2406d2c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/runtime_intrinsics.h @@ -0,0 +1,28 @@ +/* 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_SERVICE_GPU_RUNTIME_INTRINSICS_H_ +#define XLA_SERVICE_GPU_RUNTIME_INTRINSICS_H_ + +#include "absl/strings/string_view.h" + +namespace xla { + +inline constexpr absl::string_view kXlaGpuAssertCustomCallTag = + "__xla_gpu_assert"; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_INTRINSICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/scatter_slice_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/scatter_slice_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..374498fc31c5cd3d1067662c4db4f6c9432d03c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/scatter_slice_simplifier.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 XLA_SERVICE_GPU_SCATTER_SLICE_SIMPLIFIER_H_ +#define XLA_SERVICE_GPU_SCATTER_SLICE_SIMPLIFIER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Replaces scatters followed by truncation slices with a new scatter using +// a different output shape, and the slices are eliminated. +// +// (a) Single output (b) Multiple outputs (c) Elementwise users +// +// T[N+1] scatter (T1, T2) scatter T scatter T constant +// v v v v v +// T[N] slice T1 gte T2 gte T maximum +// v v v +// T1 slice T2 slice T slice +// +// This pattern is used when the last element of the scatter output is intended +// to accumulate updates from the input elements that should be ignored. +// This is slow if there are many indices mapped to the last output index and +// the scatter is implemented using atomics, so everything collides on that one +// memory location. +// As OOB scatter indices are dropped by the GPU implementation, we can remove +// the slice step entirely and avoid the memory congestion in the scatter step. + +class ScatterSliceSimplifier : public HloModulePass { + public: + absl::string_view name() const override { return "scatter-slice-simplifier"; } + + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_SCATTER_SLICE_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/sequential_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/sequential_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..b674a5e24e7035b3e96138bcde063782dd8785e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/sequential_thunk.h @@ -0,0 +1,54 @@ +/* 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_SERVICE_GPU_SEQUENTIAL_THUNK_H_ +#define XLA_SERVICE_GPU_SEQUENTIAL_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that wraps a list of sub-thunks. Executing this thunk executes all +// the sub-thunks sequentially. This is useful to implement instructions that +// require multiple kernel launches or library calls. +class SequentialThunk : public Thunk { + public: + SequentialThunk(ThunkInfo thunk_info, ThunkSequence thunks); + SequentialThunk(const SequentialThunk&) = delete; + SequentialThunk& operator=(const SequentialThunk&) = delete; + + ThunkSequence& thunks() { return thunks_; } + const ThunkSequence& thunks() const { return thunks_; } + std::string ToStringExtra(int indent) const override; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + // The list of sub-thunks. + ThunkSequence thunks_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_SEQUENTIAL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/softmax_rewriter_triton.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/softmax_rewriter_triton.h new file mode 100644 index 0000000000000000000000000000000000000000..fd131f8336d75483bdcc1f0506c453db9681153b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/softmax_rewriter_triton.h @@ -0,0 +1,70 @@ +/* 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_SERVICE_GPU_SOFTMAX_REWRITER_TRITON_H_ +#define XLA_SERVICE_GPU_SOFTMAX_REWRITER_TRITON_H_ + +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +struct DiamondChainDescriptor { + HloInstruction* root = nullptr; + HloInstruction* producer = nullptr; +}; + +// Rewrite compatible Softmax into a custom fusion region to be code-generated +// with the Triton-based Softmax emitter. +class SoftmaxRewriterTriton : public HloModulePass { + public: + explicit SoftmaxRewriterTriton(se::GpuComputeCapability gpu_version) + : gpu_version_(gpu_version) {} + absl::string_view name() const override { return "triton-softmax-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Finds and returns all the fusible diamond chains in the module. The + // resulting vector is sorted according to a post-order matching (i.e. within + // the same computation, producer diamonds appear before consumer diamonds). + std::vector FindAllFusibleDiamondChains( + HloModule& module, + const absl::flat_hash_set& execution_threads) const; + + // Constructs a Softmax fusion containing all the instructions between the + // root and the producer of a diamond chain. The producer is excluded from the + // fusion. + Status FuseDiamondChain(const DiamondChainDescriptor& diamond_chain); + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_SOFTMAX_REWRITER_TRITON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/split_k_gemm_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/split_k_gemm_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..436247be2a4b0b76835829eb1b054e249e4d6a7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/split_k_gemm_rewriter.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_GPU_SPLIT_K_GEMM_REWRITER_H_ +#define XLA_SERVICE_GPU_SPLIT_K_GEMM_REWRITER_H_ + +#include + +#include "absl/types/span.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/status.h" + +namespace xla { +namespace gpu { + +// Is there a non-empty suffix "s" of span such that product(s) % divisor = 0 +// and for all t != s non-empty suffixes of s: d % product(t) = 0? +bool HasDivisibleSuffixAllowingSplit(absl::Span span, + int64_t divisor); + +// Apply split K configuration from the tiling to the fusion instruction: +// in addition to MakeDotComputationSplitKBatch on its computation add the +// necessary reduction after it. +Status MakeDotSplitKBatch(HloInstruction* dot_fusion, + const AutotuneResult::TritonGemmKey& tiling); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_SPLIT_K_GEMM_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/stream_executor_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/stream_executor_util.h new file mode 100644 index 0000000000000000000000000000000000000000..4e291b5e9a04cc7b4398a63f5e679e445feab2f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/stream_executor_util.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_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_ +#define XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/autotuning.pb.h" +#include "xla/layout.h" +#include "xla/service/gpu/cublas_cudnn.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/hlo_module_config.h" +#include "xla/statusor.h" +#include "xla/stream_executor/kernel_spec.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +// Helper functions for interacting with StreamExecutor. + +namespace xla { +namespace gpu { + +// Returns (input, filter, output) XLA Layout protos given the StreamExecutor +// layouts. +StatusOr> +StreamExecutorConvLayoutsToXlaLayouts(const ConvolutionDimensionNumbers& dnums, + se::dnn::DataLayout input, + se::dnn::FilterLayout filter, + se::dnn::DataLayout output); + +// Returns (input, filter, output) StreamExecutor layouts given the XLA layouts. +StatusOr< + std::tuple> +XlaConvShapesToStreamExecutorLayouts(const ConvolutionDimensionNumbers& dnums, + const Shape& input, const Shape& filter, + const Shape& output); + +// Finds the VECT_C dimension in input/filter/output, if present. +// +// A cudnn convolution may have layout NCHW_VECT_C, which means instead of +// [N,C,H,W], the layout is [N,C/k,H,W,k] for some k (usually 4 or 32). +// +// ConvolutionDimensionNumbers doesn't explicitly store which is the `k` +// dimension, because only cudnn convolutions have this feature; it's not +// applicable elsewhere. We find it by finding a dimension in the +// input/filter/output shape that is *not* in dnums. +std::tuple, std::optional, + std::optional> +FindVectorizedFeatureDims(const ConvolutionDimensionNumbers& dnums, + const Shape& input, const Shape& filter, + const Shape& output); + +// Generates and returns a unique lock per the provided executor. +// Guarantees that blocks of code running for the same provided +// executor will not be running concurrently if they lock the returned mutex. +// +// This is used to prevent other XLA instances from trying to autotune on a +// device while another thread is using it. +absl::Mutex& GetGpuMutex(const se::StreamExecutor* stream_exec); + +// Creates a kernel with a provided name, based from provided PTX in ptx. +// The kernel should be executed using the provided executor. +// The argument cubin_data represents compiled PTX and may be left empty. +// +// The canonical storage for both ptx and cubin_data should outlive +// the lifetime of the kernel. +StatusOr> CreateKernel( + absl::string_view kernel_name, uint64_t num_args, absl::string_view ptx, + absl::Span cubin_data, se::StreamExecutor* stream_exec, + uint32_t shared_mem_bytes = 0); + +// Runs loaded kernel on the stream with the provided arguments. +Status ExecuteKernelOnStream(const se::KernelBase& kernel, + absl::Span args, + const LaunchDimensions& dims, se::Stream* stream); + +// Initializes `buffer` with random data on `stream`. +// `rng_state` is an inout parameter for the pseudorandom generator state. +// `buffer_type` determines what buffer would be filled out with. +// +// Precondition: `buffer_type` is a floating point type, `rng_state` needs to be +// initialized to zero on the first use. +void InitializeBuffer(se::Stream* stream, PrimitiveType buffer_type, + int64_t* rng_state, se::DeviceMemoryBase buffer); + +StatusOr GetDNNConvKindFromCudnnConvKind( + CudnnConvKind kind); + +StatusOr GetDNNFusedMHAKindFromCudnnfMHAKind( + CudnnfMHAKind kind); + +StatusOr GetDNNDataTypeFromPrimitiveType(PrimitiveType type); + +// Returns result with the smallest time which has not failed. +// If deterministic output is requested, returns first (not failing) result. +StatusOr PickBestResult( + absl::Span profile_results, + std::optional instr_str, + HloModuleConfig hlo_module_config); + +// Returns whether determinism is required. +bool RequireDeterminism(const HloModuleConfig& config); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/target_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/target_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..92f31a6c13506806f9a11b60442ff238237e9ae1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/target_constants.h @@ -0,0 +1,60 @@ +/* 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_SERVICE_GPU_TARGET_CONSTANTS_H_ +#define XLA_SERVICE_GPU_TARGET_CONSTANTS_H_ + +namespace xla { +namespace gpu { + +namespace nvptx { +// The triple that represents our target. +inline const char* TargetTriple() { + static constexpr char kTargetTriple[] = "nvptx64-nvidia-cuda"; + return kTargetTriple; +} + +// The data layout of the emitted module. Copied from computeDataLayout in +// NVPTXTargetMachine.cpp. +inline const char* DataLayout() { + static constexpr char kDataLayout[] = + "e-i64:64-i128:128-v16:16-v32:32-n16:32:64"; + return kDataLayout; +} +} // namespace nvptx + +namespace amdgpu { + +// The triple that represents our target on LLVM AMDGPU backend. +inline const char* TargetTriple() { + static constexpr char kTargetTriple[] = "amdgcn-amd-amdhsa"; + return kTargetTriple; +} + +// The data layout of the emitted module. +inline const char* DataLayout() { + static constexpr char kDataLayout[] = + "e-p:64:64-p1:64:64-p2:64:64-p3:32:32-p4:32:32-p5:32:32" + "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" + "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-A5"; + return kDataLayout; +} + +} // namespace amdgpu + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TARGET_CONSTANTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/target_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/target_util.h new file mode 100644 index 0000000000000000000000000000000000000000..19b00307b3fea1e68cce82acb5e72df0c16ec8d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/target_util.h @@ -0,0 +1,97 @@ +/* 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_SERVICE_GPU_TARGET_UTIL_H_ +#define XLA_SERVICE_GPU_TARGET_UTIL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/Module.h" +#include "llvm/TargetParser/Triple.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// Enumeration to get target specific intrinsics. +enum class TargetIntrinsicID { + kThreadIdx = 0, + kThreadIdy, + kThreadIdz, + kBlockIdx, + kBlockIdy, + kBlockIdz, + kBarrierId, + kBlockDimx, + kBlockDimy, + kBlockDimz, + kGroupBarrierId, +}; + +// Enumeration to get target specific device math function. +enum class TargetDeviceFunctionID { + kAtan2 = 0, + kCbrt, + kCos, + kExp, + kExpm1, + kFmod, + kHypot, + kLog, + kLog1p, + kPow, + kRsqrt, + kSin, + kSqrt, + kTan, + kTanh, +}; + +// HLO opcode -> TargetDeviceFunctionID mapping. +StatusOr GetTargetDeviceFunctionID(HloOpcode); + +// Emits IR to call a device function named "callee_name" on the given +// operand. Returns the IR value that represents the return value. +llvm::CallInst* EmitDeviceFunctionCall( + const std::string& callee_name, absl::Span operands, + absl::Span input_type, PrimitiveType output_type, + const llvm::AttrBuilder& attributes, llvm::IRBuilder<>* b, + absl::string_view name = ""); + +// Emits a call to the specified target intrinsic with the given operands. +// Overloaded intrinsics (for example, "minnum") must include a type +// in overloaded_types for each overloaded type. Typically, overloaded +// intrinsics have only a single overloaded type. +llvm::CallInst* EmitCallToTargetIntrinsic( + TargetIntrinsicID intrinsic_id, absl::Span operands, + absl::Span overloaded_types, llvm::IRBuilder<>* b); + +// Annotate the kernel as GPU kernel according to the GPU target. +void AnnotateFunctionAsGpuKernel(llvm::Module* module, llvm::Function* func, + llvm::IRBuilder<>* b); + +std::string ObtainDeviceFunctionName(TargetDeviceFunctionID func_id, + PrimitiveType output_type, + llvm::Triple target_triple); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TARGET_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..2bea9efc004b0058de09dfe1755bd69345e66094 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/thunk.h @@ -0,0 +1,200 @@ +/* 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_SERVICE_GPU_THUNK_H_ +#define XLA_SERVICE_GPU_THUNK_H_ + +#include +#include +#include +#include +#include +#include + +#include "mlir/IR/Operation.h" // from @llvm-project +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/gpu_executable_run_options.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +class GpuExecutable; + +enum AsyncStreamKind { + kAsyncStreamCollective = 0, // Stream for asynchronous collective ops. + kAsyncStreamP2P = 1, // Stream for P2P Send and Recv ops. +}; +constexpr static int64_t kAsyncStreamTotal = kAsyncStreamP2P + 1; +// Assigns a unique ID to a stream for asynchronous or synchronous execution. +// These IDs can be used, for example, to look up the NCCL communicator. +inline uint64_t GetStreamId( + bool is_async, AsyncStreamKind stream_kind = kAsyncStreamCollective) { + return is_async ? stream_kind + 1 : 0; +} + +// Thunk acts as the bridge between IrEmitter and GpuExecutable. It stores the +// metadata IrEmitter generates for GpuExecutable to invoke an HloInstruction. +// +// Thunk provides the Initialize and ExecuteOnStream interface for GpuExecutable +// to initialize and execute the invocation respectively. Its subclasses are +// supposed to override these interfaces to launch a generated kernel or call an +// external library function (such as operations in cuBLAS). +// +// This is thread-compatible. +class Thunk { + public: + enum Kind { + kCholesky, + kConditional, + kConvolution, + kConvolutionReorder, + kCopy, + kCublasLtMatmul, + kCustomCall, + kFft, + kFor, + kGemm, + kInfeed, + kKernel, + kMemset32BitValue, + kMemzero, + kNcclAllGather, + kNcclAllGatherStart, + kNcclAllGatherDone, + kNcclAllReduce, + kNcclAllReduceStart, + kNcclAllReduceDone, + kNcclCollectivePermute, + kNcclCollectivePermuteStart, + kNcclCollectivePermuteDone, + kNcclReduceScatter, + kNcclReduceScatterStart, + kNcclReduceScatterDone, + kNcclAllToAll, + kNcclAllToAllStart, + kNcclAllToAllDone, + kNcclSend, + kNcclRecv, + kOutfeed, + kReplicaId, + kPartitionId, + kSequential, + kTriangularSolve, + kWhile, + kFusedMHA + }; + + struct ThunkInfo { + explicit ThunkInfo(mlir::Operation* op) : op(op) {} + std::optional profile_index; + std::string profile_annotation; + mlir::Operation* op; + + static ThunkInfo WithProfileAnnotation(mlir::Operation* op); + }; + + // The hlo_instruction argument is meant to be the instruction this thunk was + // generated from, but Thunk never uses this argument other than to save it + // to Thunk::hlo_instruction, so it can be null. + Thunk(Kind kind, ThunkInfo thunk_info) + : kind_(kind), + profile_index_(thunk_info.profile_index), + profile_annotation_(thunk_info.profile_annotation), + op_(thunk_info.op) {} + virtual ~Thunk() = default; + Thunk(const Thunk&) = delete; + Thunk& operator=(const Thunk&) = delete; + + virtual std::string ToStringExtra(int indent) const { return ""; } + Kind kind() const { return kind_; } + std::string profile_annotation() const { return profile_annotation_; } + // Only valid during compilation, i.e., lowering thunks to kernel-launch + // related XLA runtime custom calls). nullptr at runtime. MLIR codegen will + // cease the practice of lowering thunks to XLA runtime custom calls. + mlir::Operation* op() { return op_; } + + // Prepares the thunk for execution on the given StreamExecutor. + // + // This may be called multiple times. Its main purpose is to give us a chance + // to do initialization outside of ExecuteOnStream() so that the + // time spent initializing doesn't count towards our execution profile. + virtual Status Initialize(const GpuExecutable& /*executable*/, + se::StreamExecutor* /*executor*/) { + return OkStatus(); + } + + // Parameters passed to ExecuteOnStream. Encapsulated in a struct so that + // when we add something we don't have to change every subclass of Thunk. + struct ExecuteParams { + ExecuteParams(const ServiceExecutableRunOptions& run_options, + const BufferAllocations& buffer_allocations, + se::Stream* stream, + absl::Span async_streams); + + const BufferAllocations* buffer_allocations; // never null + se::Stream* stream; + absl::InlinedVector async_comms_streams; + NcclExecuteParams nccl_params; + }; + + // Execute the kernel for the thunk on the given stream. This method must be + // called after Initialize and can be called multiple times over Thunk's + // lifetime. + // + // Precondition: Initialize(stream->parent()) has been called. + virtual Status ExecuteOnStream(const ExecuteParams& params) = 0; + + // Clears metadata that is only valid during compile time. + virtual void ClearCompileTimeInfo() { op_ = nullptr; } + + static absl::string_view KindToString(Thunk::Kind kind); + + protected: + std::optional profile_index() const { return profile_index_; } + + private: + Kind kind_; + std::optional profile_index_; + std::string profile_annotation_; + mlir::Operation* op_; +}; + +// A sequence of thunks. +class ThunkSequence : public std::vector> { + public: + std::string ToString(int indent = 0, + std::function + get_thunk_annotation = nullptr) const; +}; + +std::ostream& operator<<(std::ostream& os, Thunk::Kind kind); + +// A struct that defines a shaped slice, i.e., a BufferAllocation::Slice and its +// shape. +struct ShapedSlice { + BufferAllocation::Slice slice; + Shape shape; +}; + +// Returns if the thunk implements a reduction collective (all-reduce or +// reduce-scatter). +bool IsReductionCollective(Thunk::Kind kind); +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/topk_specializer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/topk_specializer.h new file mode 100644 index 0000000000000000000000000000000000000000..c2c02cfe1864fee6bc6fff9449c818a122d4e9f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/topk_specializer.h @@ -0,0 +1,43 @@ +/* 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_SERVICE_GPU_TOPK_SPECIALIZER_H_ +#define XLA_SERVICE_GPU_TOPK_SPECIALIZER_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/executable_run_options.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "tsl/platform/statusor.h" + +namespace xla::gpu { + +// This pass transforms eligible TopK CustomCall into a call to be executed by +// runtime/topk.cc. +class TopkSpecializer : public HloModulePass { + public: + absl::string_view name() const override { return "topk-specializer"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_TOPK_SPECIALIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/topk_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/topk_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..ac177d10151ec94cce7e11dfbb9d4522cf2ddcd5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/topk_splitter.h @@ -0,0 +1,55 @@ +/* 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_SERVICE_GPU_TOPK_SPLITTER_H_ +#define XLA_SERVICE_GPU_TOPK_SPLITTER_H_ + +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "tsl/platform/statusor.h" + +namespace xla { +namespace gpu { + +// Splits large TopK into batches of smaller TopKs, followed by sorting and +// slicing the results of those smaller topks. We consider TopKs to be 'large' +// the last dimension of the TopK is larger than `split_threshold`. +class TopKSplitter : public HloModulePass { + public: + explicit TopKSplitter(size_t split_threshold = 1024 * 1024) + : split_threshold_(split_threshold) {} + absl::string_view name() const override { return "topk-splitter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const size_t split_threshold_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TOPK_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/tree_reduction_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/tree_reduction_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..5c3e8d9bf73116122e4d28dfd862d1fcc430e6de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/tree_reduction_rewriter.h @@ -0,0 +1,99 @@ +/* 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_SERVICE_GPU_TREE_REDUCTION_REWRITER_H_ +#define XLA_SERVICE_GPU_TREE_REDUCTION_REWRITER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Rewrites reductions in a way they can be implemented without atomics. +// +// Rule application: rewrite a single HLO reduce operation into two. +// +// Case 1: Row reduction, batched dimension is present, larger than +// Z-tiling size. +// ----------------------------------------------------------------- +// +// Rewriting: +// +// f32[B] out = reduce(f32[A, B, C] input, dimensions={0, 2}) +// +// Into: +// +// f32[A, B] tmp = reduce(f32[A, B, C] input, dimensions={2}) +// f32[B] out = reduce(f32[A, B] tmp, dimensions={0}) +// +// Case 2: Row reduction +// ------------------------------------------------------------------ +// +// Let M be the thread tiling multiplied by the warp size. +// We go from (assuming C > M): +// +// f32[B] out = reduce(f32[A, B, C] input, dimensions={0, 2}) +// +// to: +// +// f32[A, B, P] padded = pad(input) // Let P = ceil(C/M) * M. +// f32[A, B, Q, M] reshaped = bitcast(padded) // Let Q = ceil(C/M) +// f32[B, Q] inner_reduce = reduce(reshaped, dimensions={0, 3}) +// f32[B] outer_reduce = reduce(inner_reduce, dimensions={1}) +// +// Case 3: Column reduction +// ------------------------------------------------------------------- +// +// Let T be the tiling size for the column reduction. +// +// We go from (assuming B > T): +// +// f32[A, C] out = reduce(f32[A, B, C] input, dimensions={1}) +// +// to: +// +// f32[A, P, C] padded = pad(input) // Let P = ceil(B/T) * T. +// f32[A, Q, T, C] reshaped = bitcast(padded) // Let Q = ceil(B/T) +// f32[A, Q, C] inner_reduce = reduce(reshaped, dimensions={2}) +// f32[A, C] outer_reduce = reduce(inner_reduce, dimensions={1}) +// +class GpuTreeReductionRewriter : public HloModulePass { + public: + explicit GpuTreeReductionRewriter(se::GpuComputeCapability gpu_version) + : gpu_version_(gpu_version) {} + + ~GpuTreeReductionRewriter() override = default; + absl::string_view name() const override { + return "gpu-tree-reduction-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_TREE_REDUCTION_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triangular_solve_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triangular_solve_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..7e1e2e0c69538f3f43373ca6cf92ac12eb9e33b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triangular_solve_rewriter.h @@ -0,0 +1,59 @@ +/* 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_SERVICE_GPU_TRIANGULAR_SOLVE_REWRITER_H_ +#define XLA_SERVICE_GPU_TRIANGULAR_SOLVE_REWRITER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Rewrites HLO TriangularSolve ops into a custom-call. +// +// The motivation for this is that we need to add temp memory to batched +// triangular-solve ops in order to call cublas trsmBatched. We rewrite batch 1 +// ops as well so that we have fewer codepaths to worry about in the backend. +// +// cublas trsmBatched takes arrays in GPU memory of pointers to the inputs and +// outputs, `a` and `b`. In XLA the inputs/outputs are always contiguous, but +// we still have to materialize out these arrays. +// +// We use the same trick as for cudnn convolutions: This custom-call returns a +// tuple (actual-result, temp-memory). In this our case the temp buffer always +// has size 2 * sizeof(void*) * batch_size, because we need two arrays of +// pointers. +// +// The custom-call has a backend-config equal to the TriangularSolveOptions +// object. +class TriangularSolveRewriter : public HloModulePass { + public: + absl::string_view name() const override { + return "triangular-solve-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TRIANGULAR_SOLVE_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triangular_solve_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triangular_solve_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..bb1a692ed83678a905a87778063d909687287bae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triangular_solve_thunk.h @@ -0,0 +1,88 @@ +/* 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_SERVICE_GPU_TRIANGULAR_SOLVE_THUNK_H_ +#define XLA_SERVICE_GPU_TRIANGULAR_SOLVE_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a triangular +// solve (BlasTrsm). It is generated by IrEmitter. +// +// Thread-compatible. +class TriangularSolveThunk : public Thunk { + public: + TriangularSolveThunk(ThunkInfo thunk_info, + const TriangularSolveOptions& options, + se::GpuAsmOpts asm_opts, + const BufferAllocation::Slice& a_buffer, + const BufferAllocation::Slice& b_buffer, + const BufferAllocation::Slice& temp_buffer, + PrimitiveType type, int64_t batch_size, int64_t m, + int64_t n, int64_t a_batch_stride, + int64_t b_batch_stride); + + TriangularSolveThunk(const TriangularSolveThunk&) = delete; + TriangularSolveThunk& operator=(const TriangularSolveThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + se::GpuAsmOpts asm_opts_; + const se::blas::UpperLower uplo_; + const se::blas::Side side_; + const se::blas::Diagonal unit_diagonal_; + se::blas::Transpose transpose_a_; + + const BufferAllocation::Slice a_buffer_; + const BufferAllocation::Slice b_buffer_; + const BufferAllocation::Slice temp_buffer_; + + const PrimitiveType type_; + const int64_t batch_size_; + const int64_t m_; + const int64_t n_; + const int64_t a_batch_stride_; + const int64_t b_batch_stride_; +}; + +Status RunTriangularSolve(se::DeviceMemoryBase a_data, + se::DeviceMemoryBase b_data, + se::DeviceMemoryBase temp_data, + se::GpuAsmOpts asm_opts, se::blas::UpperLower uplo, + se::blas::Side side, se::blas::Diagonal unit_diagonal, + se::blas::Transpose transpose_a, PrimitiveType type, + int64_t batch_size, int64_t m, int64_t n, + int64_t a_batch_stride, int64_t b_batch_stride, + se::Stream* stream); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TRIANGULAR_SOLVE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triton_autotuner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triton_autotuner.h new file mode 100644 index 0000000000000000000000000000000000000000..bff2f170e6e7b20c32a6aa4976503f5d927dd1e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/triton_autotuner.h @@ -0,0 +1,64 @@ +/* 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_SERVICE_GPU_TRITON_AUTOTUNER_H_ +#define XLA_SERVICE_GPU_TRITON_AUTOTUNER_H_ + +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" +#include "tsl/platform/threadpool.h" + +namespace xla { +namespace gpu { + +// Find best tiling configuration for each triton fusion outlined. +class TritonAutotuner : public HloModulePass { + public: + explicit TritonAutotuner(const AutotuneConfig& config, + tsl::thread::ThreadPool* thread_pool) + : config_(config), thread_pool_(thread_pool) {} + + absl::string_view name() const override { return "triton-autotuner"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + AutotuneConfig config_; + tsl::thread::ThreadPool* thread_pool_; +}; + +// TODO(b/266210099): have a way to generate/load these dynamically. +// Returns a list of possible tilings for a GEMM performed in Triton. +std::vector GetPossibleMatmulAutotuneConfigs( + const HloDotInstruction& dot, se::CudaComputeCapability compute_capability, + const DebugOptions& debug_options, bool exhaustive_tiling_search = false); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TRITON_AUTOTUNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/variadic_op_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/variadic_op_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..bba95c0ae179d15d213b316eb509dd4dbef4f283 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/variadic_op_splitter.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_GPU_VARIADIC_OP_SPLITTER_H_ +#define XLA_SERVICE_GPU_VARIADIC_OP_SPLITTER_H_ + +#include "absl/strings/string_view.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Splits variadic ops with many operands into pieces such that we don't exceed +// the parameter space on the GPU. Currently only concatenate ops are split up. +class VariadicOpSplitter : public HloModulePass { + public: + absl::string_view name() const override { return "variadic-op-splitter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_VARIADIC_OP_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/while_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/while_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..a908885c1c33b4fc6b594dbbd4edb923f442c60e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/while_thunk.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_SERVICE_GPU_WHILE_THUNK_H_ +#define XLA_SERVICE_GPU_WHILE_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/sequential_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// WhileThunk implements the while instruction on GPU by invoking a thunk +// sequence for the while 'condition' computation, and (conditionally) another +// thunk sequence for the while 'body' computation. WhileThunk assumes that +// buffers for the following set of while-related instructions share the same +// allocation: +// init, condition.parameter, body.parameter, body.root, while.result +// WhileThunk synchronizes the stream to test the result of the 'condition' +// computation. +class WhileThunk : public Thunk { + public: + // Constructs a WhileThunk to compute while instruction 'hlo'. + WhileThunk(ThunkInfo thunk_info, + const BufferAllocation::Slice& condition_result_buffer_index, + std::unique_ptr condition_thunk_sequence, + std::unique_ptr body_thunk_sequence); + WhileThunk(const WhileThunk&) = delete; + WhileThunk& operator=(const WhileThunk&) = delete; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + SequentialThunk* condition_thunk_sequence() { + return condition_thunk_sequence_.get(); + } + SequentialThunk* body_thunk_sequence() { return body_thunk_sequence_.get(); } + + private: + const BufferAllocation::Slice condition_result_buffer_index_; + std::unique_ptr condition_thunk_sequence_; + std::unique_ptr body_thunk_sequence_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_WHILE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/xfeed_queue.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/xfeed_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..1cb8dec6d5f91c21c1518d2c6632eb620d8f7738 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/xfeed_queue.h @@ -0,0 +1,160 @@ +/* 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_SERVICE_GPU_XFEED_QUEUE_H_ +#define XLA_SERVICE_GPU_XFEED_QUEUE_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace gpu { + +// TODO(b/30467474) Once GPU outfeed implementation settles, consider +// folding back the cpu and gpu outfeed implementations into a generic +// one if possible. + +// Manages a thread-safe queue of buffers. +template +class XfeedQueue { + public: + // Adds a tree of buffers to the queue. The individual buffers correspond to + // the elements of a tuple and may be nullptr if the buffer is a tuple index + // buffer. + void EnqueueDestination(BufferType buffers) { + absl::MutexLock l(&mu_); + enqueued_buffers_.push_back(std::move(buffers)); + enqueue_cv_.Signal(); + + EnqueueHook(); + } + + // Blocks until the queue is non-empty, then returns the buffer at the head of + // the queue. + BufferType BlockingGetNextDestination() { + for (const auto& callback : before_get_next_dest_callbacks_) { + callback(); + } + + bool became_empty; + BufferType current_buffer; + { + absl::MutexLock l(&mu_); + while (enqueued_buffers_.empty()) { + enqueue_cv_.Wait(&mu_); + } + current_buffer = std::move(enqueued_buffers_.front()); + enqueued_buffers_.pop_front(); + DequeueHook(); + became_empty = enqueued_buffers_.empty(); + } + if (became_empty) { + for (const auto& callback : on_empty_callbacks_) { + callback(); + } + } + return current_buffer; + } + + void RegisterOnEmptyCallback(std::function callback) { + on_empty_callbacks_.push_back(std::move(callback)); + } + void RegisterBeforeGetNextDestinationCallback( + std::function callback) { + before_get_next_dest_callbacks_.push_back(std::move(callback)); + } + + virtual ~XfeedQueue() = default; + + protected: + virtual void DequeueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) {} + virtual void EnqueueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) {} + + absl::Mutex mu_; + + // The queue of trees of buffers. Buffer* queue contents are not owned. + std::deque enqueued_buffers_ ABSL_GUARDED_BY(mu_); + + private: + // Condition variable that is signaled every time a buffer is enqueued. + absl::CondVar enqueue_cv_; + + // List of callbacks which will be called when 'enqueued_buffers_' becomes + // empty. + std::vector> on_empty_callbacks_; + + // List of callbacks which will be called before BlockingGetNextDestination() + // is called. This lets you e.g. call EnqueueDestination() for each call to + // BlockingGetNextDestination(). + std::vector> before_get_next_dest_callbacks_; +}; + +// Like XfeedQueue but with a maximum capacity. Clients can call +// `BlockUntilEnqueueSlotAvailable` to block until there are fewer than +// `max_pending_xfeeds_` capacity pending infeed items. +// +// We introduce a separate `BlockUntilEnqueueSlotAvailable` (as opposed to +// overriding `EnqueueDestination` to block) because we want to block before we +// copy the buffer to GPU memory, in order to bound the memory consumption due +// to pending infeeds. +template +class BlockingXfeedQueue : public XfeedQueue { + public: + explicit BlockingXfeedQueue(int max_pending_xfeeds) + : max_pending_xfeeds_(max_pending_xfeeds) {} + + void BlockUntilEnqueueSlotAvailable() { + absl::MutexLock l{&this->mu_}; + while (pending_buffers_ + this->enqueued_buffers_.size() >= + max_pending_xfeeds_) { + VLOG(2) << "Capacity " + << (pending_buffers_ + this->enqueued_buffers_.size()) + << " >= max capacity " << max_pending_xfeeds_; + dequeue_cv_.Wait(&this->mu_); + } + + pending_buffers_++; + } + + protected: + void EnqueueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) override { + pending_buffers_--; + } + + void DequeueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) override { + dequeue_cv_.Signal(); + } + + private: + const int max_pending_xfeeds_; + + // Condition variable that is signaled every time a buffer is dequeued. + absl::CondVar dequeue_cv_; + + // Keeps track of the number of buffers reserved but not added to + // enqueued_buffers_. + int pending_buffers_ ABSL_GUARDED_BY(this->mu_) = 0; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_XFEED_QUEUE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/xla_executor_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/xla_executor_state.h new file mode 100644 index 0000000000000000000000000000000000000000..8714d0b24bb8125894795e7a50a77d14456007f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/gpu/xla_executor_state.h @@ -0,0 +1,64 @@ +/* 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_SERVICE_GPU_XLA_EXECUTOR_STATE_H_ +#define XLA_SERVICE_GPU_XLA_EXECUTOR_STATE_H_ + +#include + +#include "xla/service/gpu/infeed_manager.h" +#include "xla/service/gpu/outfeed_manager.h" + +// Defines XLA:GPU specific state that will be attached to the GpuExecutor. + +namespace xla { +namespace gpu { + +class GpuExecutorXLAState { + public: + explicit GpuExecutorXLAState(stream_executor::StreamExecutor *) {} + + InfeedManager *getOrCreateInfeedManager(stream_executor::StreamExecutor *se) { + absl::MutexLock l(&this->mu_); + if (!infeed_manager_) infeed_manager_ = std::make_unique(se); + return infeed_manager_.get(); + } + + OutfeedManager *getOrCreateOutfeedManager( + stream_executor::StreamExecutor *se) { + absl::MutexLock l(&this->mu_); + if (!outfeed_manager_) + outfeed_manager_ = std::make_unique(); + return outfeed_manager_.get(); + } + + private: + template + T *getOrCreate(stream_executor::StreamExecutor *se, std::unique_ptr &ptr) { + if (!ptr) { + ptr = std::make_unique(se); + } + return ptr.get(); + } + + absl::Mutex mu_; + std::unique_ptr infeed_manager_ ABSL_GUARDED_BY(mu_); + std::unique_ptr outfeed_manager_ ABSL_GUARDED_BY(mu_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_XLA_EXECUTOR_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/graphcycles/graphcycles.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/graphcycles/graphcycles.h new file mode 100644 index 0000000000000000000000000000000000000000..778ed446fba70fdf96b3a6c1aa4ecbdca4688f2e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/graphcycles/graphcycles.h @@ -0,0 +1,153 @@ +/* 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_SERVICE_GRAPHCYCLES_GRAPHCYCLES_H_ +#define XLA_SERVICE_GRAPHCYCLES_GRAPHCYCLES_H_ + +#include + +// GraphCycles detects the introduction of a cycle into a directed +// graph that is being built up incrementally. +// +// Nodes are identified by small integers. It is not possible to +// record multiple edges with the same (source, destination) pair; +// requests to add an edge where one already exists are silently +// ignored. +// +// It is also not possible to introduce a cycle; an attempt to insert +// an edge that would introduce a cycle fails and returns false. +// +// GraphCycles uses no internal locking; calls into it should be +// serialized externally. + +// Performance considerations: +// Works well on sparse graphs, poorly on dense graphs. +// Extra information is maintained incrementally to detect cycles quickly. +// InsertEdge() is very fast when the edge already exists, and reasonably fast +// otherwise. +// FindPath() is linear in the size of the graph. +// The current implementation uses O(|V|+|E|) space. + +#include + +#include "absl/types/span.h" + +namespace tensorflow { + +// NOTE!!! +// For now a copy of this is forked to net/plaque. If you +// find a bug or add a feature, please inform the owners of the +// net/plaque copy in case it should be integrated. +// NOTE!!! +class GraphCycles { + public: + GraphCycles(); + ~GraphCycles(); + + // Allocate an unused node id and return it. + // The new node has a null pointer for its node data. + // All node identifiers passed to other routines in this interface + // must have been allocated by NewNode() and not yet deallocated + // by RemoveNode(). + int32_t NewNode(); + + // Remove "node" from the graph, deleting all edges to and from it. + // After this call the identifier "node" it may no longer be used + // as an argument to any routine until it has been reallocated with + // NewNode(). + void RemoveNode(int32_t node); + + // Attempt to insert an edge from source_node to dest_node. If the + // edge would introduce a cycle, return false without making any + // changes. Otherwise add the edge and return true. + bool InsertEdge(int32_t source_node, int32_t dest_node); + + // Remove any edge that exists from source_node to dest_node. + void RemoveEdge(int32_t source_node, int32_t dest_node); + + // Return whether there is an edge directly from source_node to dest_node. + bool HasEdge(int32_t source_node, int32_t dest_node) const; + + // Contracts the edge from 'a' to node 'b', merging nodes 'a' and 'b'. One of + // the nodes is removed from the graph, and edges to/from it are added to + // the remaining one, which is returned. If contracting the edge would create + // a cycle, does nothing and return no value. + std::optional ContractEdge(int32_t a, int32_t b); + + // Return true if can contract edge, otherwise return false. + bool CanContractEdge(int32_t a, int32_t b); + + // Return whether dest_node is reachable from source_node + // by following edges. + bool IsReachable(int32_t source_node, int32_t dest_node) const; + + // A faster non-thread-safe version of IsReachable. + bool IsReachableNonConst(int32_t source_node, int32_t dest_node); + + // Return or set the node data for a node. This data is unused + // by the implementation. + void *GetNodeData(int32_t node) const; + void SetNodeData(int32_t node, void *data); + + // Find a path from "source" to "dest". If such a path exists, place the + // node IDs of the nodes on the path in the array path[], and return the + // number of nodes on the path. If the path is longer than max_path_len + // nodes, only the first max_path_len nodes are placed in path[]. The client + // should compare the return value with max_path_len" to see when this + // occurs. If no path exists, return 0. Any valid path stored in path[] + // will start with "source" and end with "dest". There is no guarantee that + // the path is the shortest, but no node will appear twice in the path, + // except the source and destination node if they are identical; therefore, + // the return value is at most one greater than the number of nodes in the + // graph. + int FindPath(int32_t source, int32_t dest, int max_path_len, + int32_t path[]) const; + + // Check internal invariants. Crashes on failure, returns true on success. + // Expensive: should only be called from graphcycles_test.cc. + bool CheckInvariants() const; + + // Warning: Do not use these if iterating over the span and modifying the + // GraphCycles at the same time. Instead use SuccessorsCopy/PredecessorsCopy. + absl::Span Successors(int32_t node) const; + absl::Span Predecessors(int32_t node) const; + + // Return a copy of the successors set. This is needed for code using the + // collection while modifying the GraphCycles. + std::vector SuccessorsCopy(int32_t node) const; + // Return a copy of the predecessors set. This is needed for code using the + // collection while modifying the GraphCycles. + std::vector PredecessorsCopy(int32_t node) const; + + // Returns all nodes in post order. + // + // If there is a path from X to Y then X appears after Y in the + // returned vector. + std::vector AllNodesInPostOrder() const; + + // Returns the graph in graphviz format. + std::string DebugString() const; + + // ---------------------------------------------------- + struct Rep; + + private: + Rep *rep_; // opaque representation + GraphCycles(const GraphCycles &) = delete; + GraphCycles &operator=(const GraphCycles &) = delete; +}; + +} // namespace tensorflow +#endif // XLA_SERVICE_GRAPHCYCLES_GRAPHCYCLES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/graphcycles/ordered_set.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/graphcycles/ordered_set.h new file mode 100644 index 0000000000000000000000000000000000000000..16258a395ae43028c06a73c94c56cb26926afaac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/graphcycles/ordered_set.h @@ -0,0 +1,85 @@ +/* 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_SERVICE_GRAPHCYCLES_ORDERED_SET_H_ +#define XLA_SERVICE_GRAPHCYCLES_ORDERED_SET_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "tsl/platform/logging.h" + +namespace tensorflow { +// This is a set data structure that provides a deterministic iteration order. +// The iteration order of elements only depends on the sequence of +// inserts/deletes, so as long as the inserts/deletes happen in the same +// sequence, the set will have the same iteration order. +// +// Assumes that T can be cheaply copied for simplicity. +template +class OrderedSet { + public: + // Inserts `value` into the ordered set. Returns true if the value was not + // present in the set before the insertion. + bool Insert(T value) { + bool new_insertion = + value_to_index_.insert({value, value_sequence_.size()}).second; + if (new_insertion) { + value_sequence_.push_back(value); + } + return new_insertion; + } + + // Removes `value` from the set. Assumes `value` is already present in the + // set. + void Erase(T value) { + auto it = value_to_index_.find(value); + DCHECK(it != value_to_index_.end()); + + // Since we don't want to move values around in `value_sequence_` we swap + // the value in the last position and with value to be deleted and then + // pop_back. + value_to_index_[value_sequence_.back()] = it->second; + std::swap(value_sequence_[it->second], value_sequence_.back()); + value_sequence_.pop_back(); + value_to_index_.erase(it); + } + + void Reserve(size_t new_size) { + value_to_index_.reserve(new_size); + value_sequence_.reserve(new_size); + } + + void Clear() { + value_to_index_.clear(); + value_sequence_.clear(); + } + + bool Contains(T value) const { return value_to_index_.contains(value); } + size_t Size() const { return value_sequence_.size(); } + + absl::Span GetSequence() const { return value_sequence_; } + + private: + // The stable order that we maintain through insertions and deletions. + std::vector value_sequence_; + + // Maps values to their indices in `value_sequence_`. + absl::flat_hash_map value_to_index_; +}; +} // namespace tensorflow + +#endif // XLA_SERVICE_GRAPHCYCLES_ORDERED_SET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/heap_simulator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/heap_simulator.h new file mode 100644 index 0000000000000000000000000000000000000000..14f80a135c805152404cb0f90f5d8c241210a2ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/heap_simulator.h @@ -0,0 +1,909 @@ +/* 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_SERVICE_HEAP_SIMULATOR_H_ +#define XLA_SERVICE_HEAP_SIMULATOR_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// TODO(b/210891274): Use btree_map after build issue in Windows is resolved. +#if defined(__GNUC__) || defined(__clang__) +#include "absl/container/btree_map.h" +#endif +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/functional/any_invocable.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_schedule.h" +#include "xla/hlo/utils/hlo_live_range.h" +#include "xla/service/buffer_value.h" +#include "xla/service/buffer_value_containers.h" +#include "xla/service/hlo.pb.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/memory_space_assignment/repacking.h" +#include "xla/service/tuple_points_to_analysis.h" +#include "xla/statusor.h" + +namespace xla { + +// Forward declare classes defined below. +template +class HeapAlgorithm; +template +class NoFragmentationStatsHeap; + +// HeapSimulator assigns buffer offsets by running a simulation of a regular +// memory heap with Alloc and Free calls. It only works for completely +// sequential instruction sequences. Unlike regular heaps, we have the +// advantage that the sequence of Alloc and Free calls is known up-front; we +// don't need to return the assignment of buffer offsets until the very end. +class HeapSimulator { + public: + // Chunk represents a contiguous piece of memory. Each BufferValue will be + // associated with a chunk in the assignment result. + struct Chunk { + static Chunk FromOffsetEnd(int64_t offset, int64_t end); + static Chunk FromOffsetSize(int64_t offset, int64_t size); + Chunk() : Chunk(-1, 0) {} + + std::string ToString() const; + + int64_t offset; + int64_t size; + + int64_t chunk_end() const { return offset + size; } + + bool OverlapsWith(Chunk other_chunk) const; + + bool operator==(const Chunk& other) const { + return offset == other.offset && size == other.size; + } + + private: + Chunk(int64_t offset, int64_t size) : offset(offset), size(size) {} + + friend std::ostream& operator<<(std::ostream& stream, const Chunk& chunk); + }; + + template + struct HeapResult { + // Returns the updated heap size if `chunk` is added to the heap. + int64_t UpdatedHeapSize(const Chunk& chunk) const { + return std::max(heap_size, chunk.chunk_end()); + } + + // The assignment of buffers to chunks. + absl::flat_hash_map chunk_map; + + // The total size in bytes of the heap, containing all assigned chunks. + int64_t heap_size = 0; + }; + // Result represents the result of the heap simulation. + template + struct Result { + // Heap results. + std::vector> heap_results; + + // The total size in bytes of the heaps. + // heap_size == sum([hr.heap_size for hr in heap_results]). + int64_t heap_size = 0; + + // The total size in bytes of heap fragmentation. + int64_t fragmentation_size = 0; + + // A trace of heap simulation events. + HeapSimulatorTrace debug_trace; + }; + + // The different options to be passed to the Run() APIs. + struct Options { + Options() + : may_reuse_operand_buffers(true), + alloc_constants(false), + buffers_to_assign(nullptr) {} + + // Whether a buffer about to be Free()-ed, can be recycled for a new born + // one, hence collapsing Free()+Alloc() calls (default true). + bool may_reuse_operand_buffers; + // Whether to issue Alloc() and Free() calls for constants (default false). + bool alloc_constants; + // If 'buffers_to_assign' is provided, only those buffers are assigned + // offsets, otherwise all buffers defined by the instructions are assigned. + const absl::flat_hash_set* buffers_to_assign; + }; + + // Returns the minimum memory required to compute an HLO module where all + // computations have been scheduled (represented by the given + // schedule), assuming no fragmentation. + static StatusOr MinimumMemoryForModule( + const HloSchedule& schedule, + const LogicalBuffer::SizeFunction& size_function); + + // Returns the minimum memory required to compute the given computation, + // assuming no fragmentation. + static StatusOr MinimumMemoryForComputation( + const HloComputation& computation, const HloInstructionSequence& sequence, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const absl::flat_hash_map* + memory_by_computation = nullptr); + + static StatusOr MinimumMemoryForComputation( + const HloComputation& computation, const HloInstructionSequence& sequence, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const HloSchedule* schedule); + + // Run the heap simulation with the given algorithm, assuming the given + // schedule, which must contain a topologically-consistent total + // ordering of all instructions within each computation. The result is invalid + // if instructions are not run in exactly this sequence. + // + // Running heap simulation on the whole module tends to save memory, compared + // to running on a per-computation basis, since we can re-use buffer space for + // called sub-computations. + // + static StatusOr> Run( + std::unique_ptr> algorithm, + const HloModule& module, const HloSchedule& schedule, + const HloAliasAnalysis& alias_analysis, + const BufferValue::SizeFunction& size_fn, + const Options& options = Options()); + + // Same as above, but runs on a single computation. The 'instruction_sequence' + // must contain a topologically-consistent total ordering of all instructions + // in the computation. The result is invalid if instructions are not run in + // exactly this sequence. + static StatusOr> Run( + std::unique_ptr> algorithm, + const HloComputation& computation, + const HloInstructionSequence& instruction_sequence, + const HloAliasAnalysis& alias_analysis, + const BufferValue::SizeFunction& size_fn, + const Options& options = Options(), + const absl::flat_hash_map* + memory_by_computation = nullptr); + + // Same as above, but runs on with a schedule that covers all nested + // computations. + static StatusOr> Run( + std::unique_ptr> algorithm, + const HloComputation& computation, + const HloInstructionSequence& instruction_sequence, + const HloAliasAnalysis& alias_analysis, + const BufferValue::SizeFunction& size_fn, const HloSchedule* schedule, + const Options& options = Options()); + + private: + // If 'schedule' is non-null, it is used to find kCall and kWhile + // sub-computations, and the heap simulation for those sub-computations will + // be run recursively. I.e. the simulation is run over the whole module. + HeapSimulator(std::unique_ptr> algorithm, + const BufferValue::SizeFunction& size_fn, + const Options& options, const HloSchedule* schedule = nullptr, + const absl::flat_hash_map* + memory_by_computation = nullptr); + ~HeapSimulator(); + + Status RunComputation(const HloComputation& computation, + const HloInstructionSequence& instruction_sequence, + const HloAliasAnalysis& alias_analysis, + HloLiveRange* live_range); + + bool IgnoreBuffer(const HloValue* buffer) const; + void Alloc(const HloValue* buffer, const HloInstruction* instruction); + void Free(const HloValue* buffer, const HloInstruction* instruction); + // ShareBuffer indicates that a new buffer is defined and it has to be the + // same address as the shared one. + void ShareBuffer(const HloValue* buffer, const HloValue* shared, + const HloInstruction* instruction); + + // Returns the size of the HloValue, which is the max size of the HloValues + // that are part of the HloBuffer. + int64_t GetBufferSize(const HloValue* buffer) const; + + // Returns true if: + // Two buffers belong to the same shared group. + // Eight of the buffer has no shared group assigned. + bool InSameSharedGroup(const HloValue* left, const HloValue* right); + Result Finish(); + + void FillDebugTrace(HeapSimulatorTrace::Event::Kind kind, + const HloValue* buffer, const HloInstruction* instruction, + const HloValue* share_with_canonical); + + // Counterintuitive: the algorithm_ itself can be a NoFragmentationStatsHeap, + // in which case we are calculating the same allocs/frees twice in the + // simulation. + const std::unique_ptr> + no_fragmentation_stats_; + const std::unique_ptr> algorithm_; + const BufferValue::SizeFunction size_fn_; + const Options options_; + // schedule_ is set by buffer assignment, and memory_by_computation_ is + // set by hlo scheduling. Then, in RunComputation, we check both in order to + // handle subcomputations. It would be good to unify the handling of + // subcomputations, but it's not clear how. + const HloSchedule* schedule_; + const absl::flat_hash_map* + memory_by_computation_; + + // Hold some sets for error-checking the sequence of Alloc and Free calls. + absl::flat_hash_set allocated_buffers_; + absl::flat_hash_set freed_buffers_; + + absl::flat_hash_map buffer_sizes_; + + // Debugging information filled in while the heap simulator runs. + HeapSimulatorTrace debug_trace_; +}; + +// Abstract base class describing a heap simulation algorithm that assigns +// offsets to buffers. A sequence of Alloc / Free calls will be made, with the +// same semantics as a regular memory heap. Finish will be called at the end to +// collect the simulation results. +template +class HeapAlgorithm { + public: + using Chunk = HeapSimulator::Chunk; + using Result = HeapSimulator::Result; + using HeapResult = HeapSimulator::HeapResult; + + virtual ~HeapAlgorithm() = default; + + // Alloc allocates a buffer of 'size' bytes. + virtual void Alloc(const BufferType* buffer, int64_t size) = 0; + + // Takes memory usage of subcomputations into account when calculating the + // memory usage of a computation. Currently, we don't handle buffer aliasing + // between computations entirely correctly. We are careful to not double count + // for the output buffers of whiles/conds/calls. But we don't take into + // account other aliases, such as for the while init. A more thorough solution + // would require something like BufferAssignment::BuildColocatedBufferSets. + // TODO(b/65835246): + // Since TuplePointsToAnalysis is being replaced with a module-aware alias + // analysis, it's not worth making major changes to HeapSimulator now. + virtual void AccountForSubcomputationMemory( + const HloInstruction* instruction, + // The total number of bytes allocated by instruction. + int64_t alloc_size_by_instruction, + const absl::flat_hash_map& + memory_by_computation) {} + + // Free de-allocates a previously allocated buffer. + virtual void Free(const BufferType* buffer, int64_t size) = 0; + + // Indicates that a buffer has to be collocated with another buffer. In + // addition to Alloc and Free, the heap simulator exposes a concept of buffer + // sharing. When ShareBuffer is called, instead of allocating new space for + // the buffer, it associates the buffer with a previously allocated (or + // shared) buffer. Each group of mutually-shared buffers points to a single + // SharedGroup instance, which is a shared control block. + virtual void ShareWith(const BufferType* buffer, const BufferType* share_with, + int64_t size) { + Alloc(buffer, size); + } + + // Finish collects the buffer offset assignment results. Finish may only be + // called once, after all Alloc and Free calls. + virtual Result Finish() = 0; +}; + +// NoFragmentationStatsHeap computes the heap size assuming no fragmentation; +// this is the absolute minimum size for a given instruction sequence. The +// result.chunk_map returned in Finish is always empty, since we only collect +// stats, and don't actually compute chunk assignments. +template +class NoFragmentationStatsHeap : public HeapAlgorithm { + public: + using Result = HeapSimulator::Result; + + NoFragmentationStatsHeap() = default; + ~NoFragmentationStatsHeap() override = default; + + void Alloc(const BufferType* buffer, int64_t size) override; + + void AccountForSubcomputationMemory( + const HloInstruction* instruction, int64_t alloc_size_by_instruction, + const absl::flat_hash_map& + memory_by_computation) override; + + void Free(const BufferType* buffer, int64_t size) override; + + Result Finish() override; + + private: + int64_t current_heap_size_ = 0; + int64_t max_heap_size_ = 0; +}; + +// Node in BufferIntervalTree that stores the alloc and free times of a buffer, +// and the chunk assigned to it. +struct BufferIntervalTreeNode { + // Alloc time. + int64_t start; + // Free time. + int64_t end; + // Maximum free time of all nodes in the subtree where this node is the root. + int64_t subtree_end; + // Allocated chunk for the buffer. + HeapSimulator::Chunk chunk; + // Left child. + BufferIntervalTreeNode* left; + // Right child. + BufferIntervalTreeNode* right; + // parent + BufferIntervalTreeNode* parent; +}; + +// An interval tree that can query buffers overlapping in time. +class BufferIntervalTree { + public: + using Chunk = HeapSimulator::Chunk; + // Adds a buffer to the interval tree, with the time interval and allocated + // chunk specified. + void Add(int64_t start, int64_t end, const Chunk& chunk); + + // Remove the interval from the tree. Returns true if the chunk is removed. + bool Remove(int64_t start, int64_t end, const Chunk& chunk); + + // Returns vector of allocated chunks that overlap with the given time + // interval. + std::vector ChunksOverlappingInTime(int64_t start, int64_t end) const; + + BufferIntervalTreeNode* GetRoot() { return root_; } + + private: + BufferIntervalTreeNode* root_ = nullptr; + std::list node_storage_; +}; + +// GlobalDecreasingSizeBestFitHeap collects the live intervals of all buffers, +// then allocates them in decreasing spatial or temporal size regardless of the +// alloc/free time. It internally tracks the allocated buffers and their live +// intervals; when allocating a buffer, it finds the best-fit free chunk during +// its live interval. +template +class GlobalDecreasingSizeBestFitHeap : public HeapAlgorithm { + public: + using HeapResult = HeapSimulator::HeapResult; + using Result = HeapSimulator::Result; + using Chunk = HeapSimulator::Chunk; + + // A mapping from a free chunk offset to the end of that chunk (exclusive). +#if defined(__GNUC__) || defined(__clang__) + using FreeChunks = absl::btree_map>; +#else + using FreeChunks = std::map>; +#endif + + enum Type { + kSpatial = 0, + kTemporal, + // Custom uses a custom BufferIntervalCompare function provided in the + // constructor. + kCustom + }; + + // BufferInterval stores a buffer's size and time interval. + struct BufferInterval { + // Convenience method for use with debugging and logging. + std::string ToString() const; + + const BufferType* buffer = nullptr; + int64_t size = -1; + // Alloc time of the buffer. + int64_t start = -1; + // Free time of the buffer. + int64_t end = -1; + + // Colocation buffers that need to be collocated with this one. + absl::InlinedVector colocations; + + // True if this buffer needs an allocation. False if it is collocated with + // other buffer. + bool need_allocation = false; + }; + + // Comparison function that is used to store buffer intervals. + using BufferIntervalCompare = + std::function; + + // SlicedBufferInterval is a wrapper around BufferInterval with parameters + // indicating whether the BufferInterval should be allocated in slices. (If + // NumSlices() is 1, the allocation will not be sliced.) This class is used as + // input to GlobalDecreasingSizeBestFitHeap::FindChunkCandidates(). + // + // For example, instead of allocating A in space and time as illustrated on + // the left, we may wish to allocate A0 and A1 overlapping in time, contiguous + // in memory, (as illustrated on the right). Doing so allows us to free up + // allocation space between [s,i], but we only have the full allocation for A + // from [i,e]. + // + // ^ + // s | +-----------+ s | +-----+ + // p | | | p | | A1 | + // a | | A | a | +-----+-----+ + // c | | | c | | A0 | + // e | +-----------+ e | +-----------+ + // --|-----------|-------> --|-----|-----|-------> + // s e time s i e time + class SlicedBufferInterval { + public: + // Factory constructors. + static const SlicedBufferInterval CreateConstInterval( + const BufferInterval& full_buffer_interval); + static SlicedBufferInterval CreateMutableInterval( + BufferInterval& full_buffer_interval); + + SlicedBufferInterval() = delete; + + // Updates the number of slices, and slice sizes. An empty + // slice_sizes_sorted_by_offset is treated the same as setting the number of + // slices to 1. Every time Slice() is called with a set of sizes > 1, it + // should be followed at some point by a call to UpdateSliceStartTimes, to + // update slice start times. Otherwise, the slice start times are + // meaningless. + // + // REQUIRES: + // - sum(slice_sizes_sorted_by_offset) == full_buffer_interval_.size + void Slice(absl::Span slice_sizes_sorted_by_offset); + + // Updates the times at which we will start each slice. However, we have not + // yet decided which slice size will correspond to which start time. + // + // Mutates mutable_full_buffer_interval_. + // + // REQUIRES: + // - The SlicedBufferInterval was constructed using CreateMutableInterval. + // - start_times.size() == NumSlices() + // - start_times should be set such that it is permissible for any slice + // size to map to any start time. + void UpdateSliceStartTimes(const std::vector& start_times); + + // Updates the free time for all the slices. + // + // Mutates mutable_full_buffer_interval_. + // + // REQUIRES: + // - The SlicedBufferInterval was constructed using CreateMutableInterval. + void UpdateEndTime(int64_t end_time); + + const BufferInterval& full_buffer_interval() const; + size_t num_slices() const { return slice_sizes_sorted_by_offset_.size(); } + const std::vector& SliceSizesSortedByOffset() const; + + // Returns a BufferInterval with the requirements to call + // GlobalDecreasingSizeBestFitHeap::MakeFreeChunks at the specified slice + // time. The requirements are: + // - At the latest slice time, we need a contiguous buffer that is big + // enough to fit all slices. In addition, that contiguous buffer will have + // the same colocation requirements as the full_buffer_interval(). + // - At other slice times, required chunks may be as small as the smallest + // slice. Furthermore, their colocation requirements are empty. + // - The logical start time of the interval at slice time i is the end time + // of the interval at slice time i-1. + const BufferInterval& IntervalForMakeFreeChunks(int64_t slice_time) const; + + // Convenience method for use with debugging and logging. + std::string ToString() const; + + private: + explicit SlicedBufferInterval( + const BufferInterval& full_buffer_interval, + BufferInterval* mutable_full_buffer_interval = nullptr); + + const BufferInterval& full_buffer_interval_; + BufferInterval* mutable_full_buffer_interval_ = nullptr; + std::vector slice_sizes_sorted_by_offset_; + // make_free_chunks_intervals are indexed by slice time. + std::vector make_free_chunks_intervals_; + }; + + // A class for finding locations to allocate a sliced allocation. A sliced + // allocation is an allocation of a buffer, in which slices of the buffer are + // allocated at different times, called slice times. Slice time is a logical + // time. For example, a requestor may ask for 15 Mib, allocated 5 MiB at a + // time, at 3 slices times t0, t1, and t2. + // + // The primary data structure inside this class is free_chunks_. free_chunks_ + // is a sorted map of the chunks of memory that are free at the latest + // requested slice time. For each memory offset within each of those chunks, + // we track the earliest slice time t, such that the memory offset is + // continuously free during [t, latest requested slice time]. + // + // For example, the following depiction of free_chunks_ indicates that + // at slice time t2, we have 2 free chunks, [5,15) and [20, 25). At slice time + // t1, the free chunk [5,15) is still free at [6,8) and [10,12). At slice time + // t0, the free chunk [5,15) is still free at [7,8). The free chunk [20, 25) + // is also free at slice times t0 and t1. (In the depicition, `x` indicates + // used space and ` ` indicates free space.) + // + // ^ + // t2 |xxxxx xxxxx xxxxxx + // t1 |xxxxxx xx xxxxxxxx xxxxxx + // t0 |xxxxxxx xxxxxxxxxxxx xxxxxx + // +!----|----!----|----!----|----!> + // space + class SlicedAllocationFinder { + public: + // The chunk at index i is the chunk that should be allocated at slice time + // i. + using ChunksSortedBySliceTime = std::vector; + + // A structure representing a piece of a free chunk that is continuously + // free in [piece.earliest_free_slice_time, LatestSliceTime()]. + struct FreeChunkPiece { + std::string ToString() const; + + int64_t earliest_free_slice_time; + Chunk dimensions; + }; + + // A sorted map (indexed by starting offset) describing how far back in + // slice time different pieces of a FreeChunkRoot are free. +#if defined(__GNUC__) || defined(__clang__) + using FreeChunkPieces = + absl::btree_map>; +#else + using FreeChunkPieces = + std::map>; +#endif + + // A free chunk that has been split into FreeChunkPieces. + struct FreeChunkRoot { + FreeChunkRoot(const Chunk& free_chunk, int64_t free_chunk_slice_time); + + std::string ToString() const; + + // Update pieces in accordance with the knowledge that free_chunk is + // free at free_chunk_slice_time. + // + // REQUIRES: + // - We must process all updates at free_chunk_slice_time x before + // processing those at free time x-1. + void Update(const Chunk& free_chunk, int64_t free_chunk_slice_time); + + Chunk chunk; + FreeChunkPieces pieces; + }; + + // A sorted map (indexed by starting offset) of FreeChunkRoots. +#if defined(__GNUC__) || defined(__clang__) + using FreeChunkRoots = + absl::btree_map>; +#else + using FreeChunkRoots = + std::map>; +#endif + + // A method that can be passed to the is_offset_allowed parameter for + // SlicedAllocationFinder() that permits placement at any offset. + static bool AllOffsetsAllowed(int64_t offset) { return true; } + + // Arguments: + // - free_chunks_per_slice_time[i]: Describes free chunks at slice time i. + // - sorted_slice_sizes: A sliced allocation request. In space, the i+1th + // slice immediately follows the ith slice. + // - max_colocation_size: The max size of any buffer that will be colocated + // with the fully allocated sliced allocation. + // - preferred_offset: The preferred starting offset for the fully allocated + // sliced allocation. + // - is_offset_allowed: Indicates if a the entire sliced allocation is + // allowed to be allocated at a given offset. + // + // REQUIRES: + // - sorted_slice_sizes.size() == free_chunks_per_slice_time.size() + // - any slice can be allocated at any slice time + // - alignment >= 1 + // + // In the future, if we want to restrict certain slices to be fetched at + // certain slice times (e.g., because certain slices don't represent enough + // real time to allocate a larger slice), we can take a lambda to indicate + // what is permitted. + SlicedAllocationFinder( + absl::Span free_chunks_per_slice_time, + std::vector sorted_slice_sizes, int64_t max_colocation_size, + int64_t preferred_offset, int64_t alignment, + absl::AnyInvocable is_offset_allowed = + &AllOffsetsAllowed); + + std::string FreeChunksToAsciiArt() const; + std::string ToString() const; + + // Finds a set of chunks in which to allocate the sliced allocation request. + // Returns a vector of chunks in which the ith element is the chunk that + // should be allocated at slice time i. If no such chunks can be found, an + // empty vector is returned. + // + // The returned vector will always be 1 larger than the initial request, + // with a chunk to represent any additional allocation needed for + // max_colocation_size_. This extra chunk will always come at the end of + // the returned vector and will be present even if its size is 0. + ChunksSortedBySliceTime Find() const; + + // Similar to Find(), but only checks placement at the specified offset. If + // the sliced allocation can not be placed at the specified offset, an + // empty vector is returned. + ChunksSortedBySliceTime FindForOffset(int64_t offset) const; + + private: + // The earliest slice time for the specified sliced allocation request. + int64_t EarliestSliceTime() const { return 0; } + + // The latest slice time for the specified sliced allocation request. + int64_t LatestSliceTime() const { return sorted_slice_sizes_.size() - 1; } + + // Returns ok if the given permutation of slice times results in an + // allocation of free space in root, at the specified offset. Otherwise, + // returns the reason such an allocation would not fit. + // + // permutation_of_slice_times[i] is the slice time that the ith slice + // (spatially) should be allocated. Such a slice has size + // sorted_slice_sizes_[i] and would be allocated at offset + + // sum(sorted_slice_sizes[j], for j in [0, i-1]). + Status DoesPermutationFit( + const std::vector& permutation_of_slice_times, + const FreeChunkRoot& root, int64_t offset) const; + + // Only DoesSlicedPermutationFit() should call this method directly. Other + // callers should call DoesSlicedPermutationFit(), which contains some + // wrapper VLOGGING. + Status DoesPermutationFitImpl( + const std::vector& permutation_of_slice_times, + const FreeChunkRoot& root, int64_t offset) const; + + // Same as Find() except only checks root, to see if it can hold the sliced + // allocation request. If only_try_this_offset is set, we only evaluate the + // specified offset, when trying to find a fit for the sliced allocation + // request. + ChunksSortedBySliceTime FindInRoot( + const FreeChunkRoot& root, + std::optional only_try_this_offset = std::nullopt) const; + + // Given a permutation of slice times (see DoesSlicedPermutationFit()), + // return a vector of chunks, in which the ith chunk should be allocated at + // slice time i, with size sorted_slice_sizes_[i] and at offset + + // sum(sorted_slice_sizes[j], for j in [0, i-1]). + // + // PermutationToChunks() does the additional job of adding a Chunk to the + // end of the result to account for an additional colocation space that + // need to be allocated. This Chunk is added, even if it is of size 0. + ChunksSortedBySliceTime PermutationToChunks( + const std::vector& permutation_of_slice_times, + int64_t offset) const; + + std::vector sorted_slice_sizes_; + int64_t slice_size_sum_; + int64_t max_colocation_size_; + int64_t preferred_offset_; + int64_t alignment_; + FreeChunkRoots free_chunks_; + absl::AnyInvocable is_offset_allowed_; + }; + + explicit GlobalDecreasingSizeBestFitHeap( + int64_t alignment, Type type = kSpatial, + BufferIntervalCompare buffer_interval_compare = nullptr); + ~GlobalDecreasingSizeBestFitHeap() override {} + + void Alloc(const BufferType* buffer, int64_t size) override; + void Free(const BufferType* buffer, int64_t size) override; + + void ShareWith(const BufferType* buffer, const BufferType* share_with, + int64_t size) override; + + Result Finish() override; + + // Return a BufferIntervalCompare function that sort by spatial size. We don't + // look at co-locates as they should have the same size. + static BufferIntervalCompare GetSpatialBufferIntervalCompare(); + + protected: + // Returns the buffer intervals sorted according to buffer_interval_compare_. + std::vector GetSortedBufferIntervals() const; + + // Compute free chunks as all memory - chunks that are allocated at some time + // during the lifetime of buffer_interval or during the lifetime of buffers + // that are colocated with buffer_interval. + // + // Imagine that we've already allocated three chunks : a, b and c. And now + // we want to allocate d. Since e is colocated with d, we have to allocate + // chunks for them together at the same address. To do this, we first gather + // all chunks that overlap with d and e on the time dimension, in this case + // the overlapped chunks are a and b (c doesn't overlap with either of d and + // e), then find create a new chunk that doesn't overlap with a and b on the + // space dimension. + // + // space + // ^ + // |+--d---+ +---e---+ + // | + // |+---+ +---------------+ +-------+ + // || | | | | | + // || | | | | | + // |+-a-+ +-------b-------+ +---c---+ + // ----------------------------------------> time + // + // MakeFreeChunks imposes the following additional constraints on its output: + // - The chunks in the result will start on alignment_ boundaries. + // - A free chunk will not be returned if it does not have enough space to fit + // max_colocation_size. + FreeChunks MakeFreeChunks(const BufferInterval& buffer_interval, + int64_t max_colocation_size) const; + + // These two methods below are exposed to other heap algorithms that inherit + // from this class. The Finish() method tries to find a candidate chunk for + // each BufferInterval, after calling GetSortedBufferIntervals. If a + // non-negative preferred_offset is provided, FindChunkCandidate attempts + // finding a chunk at this offset. The Finish() method can then call + // CommitChunk to associate the chunk with the BufferInterval, if the final + // heap size is within the limits. + Chunk FindChunkCandidate(const BufferInterval& buffer_interval, + int64_t preferred_offset = -1) const; + // FindChunkCandidates is the same as FindChunkCandidate, except it finds + // spatially contiguous chunks candidates for a sliced buffer interval. + // Returned chunk i should be copied at slice time i. + // + // Given the way that FindChunkCandidates and MakeFreeChunks interact, the + // following properties are guaranteed about colocations. + // - The returned spatially contiguous chunks have enough space for every + // colocation specified in sliced_buffer_interval. + // - The returned spatially contiguous chunks will be free for the entire + // lifetime of each colocation. If a colocation is sliced, the returned + // chunks will be free for the lifetime of the longest-lived slice. + std::vector FindChunkCandidates( + const SlicedBufferInterval& sliced_buffer_interval, + int64_t preferred_offset = -1) const; + // The following 3 methods are used to implement FindChunkCandidates. + int64_t GetMaxColocationSize(const BufferInterval& buffer_interval) const; + SlicedAllocationFinder CreateSlicedAllocationFinder( + const SlicedBufferInterval& sliced_interval, int64_t max_colocation_size, + int64_t preferred_offset, + absl::AnyInvocable is_offset_allowed = + &SlicedAllocationFinder::AllOffsetsAllowed) const; + std::vector PostProcessFindChunkCandidatesResult( + const SlicedBufferInterval& sliced_interval, + std::vector chunks) const; + + void CommitChunk(const BufferInterval& buffer_interval, Chunk chunk); + + // Adds the buffer and the chunk to the result chunk map. + virtual void AddToChunkMap(const BufferType* buffer, Chunk chunk); + + // Return a BufferIntervalCompare function that sorts by live ranges. A live + // range is defined by the range between the start of the first buffer and the + // end of the last co-located buffer. There could be "holes" in the live + // ranges of each co-located buffers, but in this heuristics we think they are + // contiguous. + BufferIntervalCompare GetTemporalBufferIntervalCompare() const; + + absl::flat_hash_map buffer_intervals_; + HeapResult result_; + BufferIntervalCompare buffer_interval_compare_; + BufferIntervalTree interval_tree_; + + private: + int64_t alignment_; + + // The current time represented as an integer. It increments by 1 at each + // Alloc or Free call. + int64_t current_time_ = 0; + + protected: + // Returns all transitive colocated buffers of this buffer interval. I.e., If + // a buffer A is colocated with B and B is colocated with C, this function + // returns all three of them. + absl::flat_hash_set GetTransitiveColocations( + const BufferInterval& interval) const; +}; + +// This class implements an algorithm that will produce multiple heaps, where +// each heap size is constrained by a given limit. Note that the constraint is +// soft, meaning that a valid heap result is generated even if there are some +// buffer sizes larger than the given constraint size. +// +// Pseudocode: +// while( `buffers` is not empty ) { +// create a new heap `h` +// for (each buffer `buf` in `buffers` in the size-decreasing order) { +// if (buf.size() is larger than the heap size limit && +// `h` is empty) { +// h.place(buf) +// buffers.remove(buf) +// } else if (placing `buf` into `h` does not violate size +// constraint) { +// h.place(buf) +// buffers.remove(buf) +// } +// } +// } +class ConstrainedGlobalDecreasingSizeBestFitHeap + : public GlobalDecreasingSizeBestFitHeap { + public: + explicit ConstrainedGlobalDecreasingSizeBestFitHeap( + uint64_t size_limit_per_heap, int64_t alignment, Type type = kSpatial, + BufferIntervalCompare buffer_interval_compare = nullptr) + : GlobalDecreasingSizeBestFitHeap(alignment, type, + buffer_interval_compare), + size_limit_per_heap_(size_limit_per_heap) {} + ~ConstrainedGlobalDecreasingSizeBestFitHeap() override {} + + Result Finish() override; + + private: + uint64_t size_limit_per_heap_; +}; + +// A heap algorithm that chooses the best results from other algorithms added to +// it. +template +class ChooseBestHeapAlgorithm : public HeapAlgorithm { + public: + using Result = HeapSimulator::Result; + + ChooseBestHeapAlgorithm( + std::unique_ptr>>> + algorithms) + : algorithms_(std::move(*algorithms)) {} + ~ChooseBestHeapAlgorithm() override {} + + void Alloc(const BufferType* buffer, int64_t size) override { + for (auto& algorithm : algorithms_) { + algorithm->Alloc(buffer, size); + } + } + + void ShareWith(const BufferType* buffer, const BufferType* share_with, + int64_t size) override { + for (auto& algorithm : algorithms_) { + algorithm->ShareWith(buffer, share_with, size); + } + } + + void Free(const BufferType* buffer, int64_t size) override { + for (auto& algorithm : algorithms_) { + algorithm->Free(buffer, size); + } + } + + Result Finish() override; + + private: + std::vector>> algorithms_; +}; + +extern template class GlobalDecreasingSizeBestFitHeap; +extern template class GlobalDecreasingSizeBestFitHeap< + memory_space_assignment::MemorySpaceAssignmentRepacker::AllocationBlock>; +extern template class ChooseBestHeapAlgorithm; + +} // namespace xla + +#endif // XLA_SERVICE_HEAP_SIMULATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..aa6e4c6b4cea9f35a178abc758600272bcab6c2e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo.pb.h @@ -0,0 +1,16444 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/hlo.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_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 "xla/xla_data.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fhlo_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fhlo_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fhlo_2eproto; +namespace xla { +class BufferAllocationProto; +struct BufferAllocationProtoDefaultTypeInternal; +extern BufferAllocationProtoDefaultTypeInternal _BufferAllocationProto_default_instance_; +class BufferAllocationProto_Assigned; +struct BufferAllocationProto_AssignedDefaultTypeInternal; +extern BufferAllocationProto_AssignedDefaultTypeInternal _BufferAllocationProto_Assigned_default_instance_; +class BufferAssignmentProto; +struct BufferAssignmentProtoDefaultTypeInternal; +extern BufferAssignmentProtoDefaultTypeInternal _BufferAssignmentProto_default_instance_; +class BufferAssignmentProto_BufferAlias; +struct BufferAssignmentProto_BufferAliasDefaultTypeInternal; +extern BufferAssignmentProto_BufferAliasDefaultTypeInternal _BufferAssignmentProto_BufferAlias_default_instance_; +class CrossProgramPrefetch; +struct CrossProgramPrefetchDefaultTypeInternal; +extern CrossProgramPrefetchDefaultTypeInternal _CrossProgramPrefetch_default_instance_; +class EntryFunctionAttributes; +struct EntryFunctionAttributesDefaultTypeInternal; +extern EntryFunctionAttributesDefaultTypeInternal _EntryFunctionAttributes_default_instance_; +class EntryFunctionAttributes_BufferParameterAttributes; +struct EntryFunctionAttributes_BufferParameterAttributesDefaultTypeInternal; +extern EntryFunctionAttributes_BufferParameterAttributesDefaultTypeInternal _EntryFunctionAttributes_BufferParameterAttributes_default_instance_; +class EntryFunctionAttributes_ShapeIndex; +struct EntryFunctionAttributes_ShapeIndexDefaultTypeInternal; +extern EntryFunctionAttributes_ShapeIndexDefaultTypeInternal _EntryFunctionAttributes_ShapeIndex_default_instance_; +class HeapSimulatorTrace; +struct HeapSimulatorTraceDefaultTypeInternal; +extern HeapSimulatorTraceDefaultTypeInternal _HeapSimulatorTrace_default_instance_; +class HeapSimulatorTrace_Event; +struct HeapSimulatorTrace_EventDefaultTypeInternal; +extern HeapSimulatorTrace_EventDefaultTypeInternal _HeapSimulatorTrace_Event_default_instance_; +class HloBufferDonorProto; +struct HloBufferDonorProtoDefaultTypeInternal; +extern HloBufferDonorProtoDefaultTypeInternal _HloBufferDonorProto_default_instance_; +class HloBufferDonorProto_BufferDonorEntryProto; +struct HloBufferDonorProto_BufferDonorEntryProtoDefaultTypeInternal; +extern HloBufferDonorProto_BufferDonorEntryProtoDefaultTypeInternal _HloBufferDonorProto_BufferDonorEntryProto_default_instance_; +class HloComputationProto; +struct HloComputationProtoDefaultTypeInternal; +extern HloComputationProtoDefaultTypeInternal _HloComputationProto_default_instance_; +class HloInputOutputAliasProto; +struct HloInputOutputAliasProtoDefaultTypeInternal; +extern HloInputOutputAliasProtoDefaultTypeInternal _HloInputOutputAliasProto_default_instance_; +class HloInputOutputAliasProto_AliasEntryProto; +struct HloInputOutputAliasProto_AliasEntryProtoDefaultTypeInternal; +extern HloInputOutputAliasProto_AliasEntryProtoDefaultTypeInternal _HloInputOutputAliasProto_AliasEntryProto_default_instance_; +class HloInstructionProto; +struct HloInstructionProtoDefaultTypeInternal; +extern HloInstructionProtoDefaultTypeInternal _HloInstructionProto_default_instance_; +class HloInstructionProto_SliceDimensions; +struct HloInstructionProto_SliceDimensionsDefaultTypeInternal; +extern HloInstructionProto_SliceDimensionsDefaultTypeInternal _HloInstructionProto_SliceDimensions_default_instance_; +class HloModuleGroupProto; +struct HloModuleGroupProtoDefaultTypeInternal; +extern HloModuleGroupProtoDefaultTypeInternal _HloModuleGroupProto_default_instance_; +class HloModuleMetadataProto; +struct HloModuleMetadataProtoDefaultTypeInternal; +extern HloModuleMetadataProtoDefaultTypeInternal _HloModuleMetadataProto_default_instance_; +class HloModuleProto; +struct HloModuleProtoDefaultTypeInternal; +extern HloModuleProtoDefaultTypeInternal _HloModuleProto_default_instance_; +class HloModuleProto_ProfileInfo; +struct HloModuleProto_ProfileInfoDefaultTypeInternal; +extern HloModuleProto_ProfileInfoDefaultTypeInternal _HloModuleProto_ProfileInfo_default_instance_; +class HloPassMetadata; +struct HloPassMetadataDefaultTypeInternal; +extern HloPassMetadataDefaultTypeInternal _HloPassMetadata_default_instance_; +class HloProto; +struct HloProtoDefaultTypeInternal; +extern HloProtoDefaultTypeInternal _HloProto_default_instance_; +class HloScheduleProto; +struct HloScheduleProtoDefaultTypeInternal; +extern HloScheduleProtoDefaultTypeInternal _HloScheduleProto_default_instance_; +class HloScheduleProto_InstructionSequence; +struct HloScheduleProto_InstructionSequenceDefaultTypeInternal; +extern HloScheduleProto_InstructionSequenceDefaultTypeInternal _HloScheduleProto_InstructionSequence_default_instance_; +class HloScheduleProto_SequencesEntry_DoNotUse; +struct HloScheduleProto_SequencesEntry_DoNotUseDefaultTypeInternal; +extern HloScheduleProto_SequencesEntry_DoNotUseDefaultTypeInternal _HloScheduleProto_SequencesEntry_DoNotUse_default_instance_; +class HloSnapshot; +struct HloSnapshotDefaultTypeInternal; +extern HloSnapshotDefaultTypeInternal _HloSnapshot_default_instance_; +class LogicalBufferProto; +struct LogicalBufferProtoDefaultTypeInternal; +extern LogicalBufferProtoDefaultTypeInternal _LogicalBufferProto_default_instance_; +class LogicalBufferProto_Location; +struct LogicalBufferProto_LocationDefaultTypeInternal; +extern LogicalBufferProto_LocationDefaultTypeInternal _LogicalBufferProto_Location_default_instance_; +class StackFrameIndexProto; +struct StackFrameIndexProtoDefaultTypeInternal; +extern StackFrameIndexProtoDefaultTypeInternal _StackFrameIndexProto_default_instance_; +class StackFrameIndexProto_FileLocation; +struct StackFrameIndexProto_FileLocationDefaultTypeInternal; +extern StackFrameIndexProto_FileLocationDefaultTypeInternal _StackFrameIndexProto_FileLocation_default_instance_; +class StackFrameIndexProto_StackFrame; +struct StackFrameIndexProto_StackFrameDefaultTypeInternal; +extern StackFrameIndexProto_StackFrameDefaultTypeInternal _StackFrameIndexProto_StackFrame_default_instance_; +class XlaRuntimeExecutableProto; +struct XlaRuntimeExecutableProtoDefaultTypeInternal; +extern XlaRuntimeExecutableProtoDefaultTypeInternal _XlaRuntimeExecutableProto_default_instance_; +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::BufferAllocationProto* Arena::CreateMaybeMessage<::xla::BufferAllocationProto>(Arena*); +template<> ::xla::BufferAllocationProto_Assigned* Arena::CreateMaybeMessage<::xla::BufferAllocationProto_Assigned>(Arena*); +template<> ::xla::BufferAssignmentProto* Arena::CreateMaybeMessage<::xla::BufferAssignmentProto>(Arena*); +template<> ::xla::BufferAssignmentProto_BufferAlias* Arena::CreateMaybeMessage<::xla::BufferAssignmentProto_BufferAlias>(Arena*); +template<> ::xla::CrossProgramPrefetch* Arena::CreateMaybeMessage<::xla::CrossProgramPrefetch>(Arena*); +template<> ::xla::EntryFunctionAttributes* Arena::CreateMaybeMessage<::xla::EntryFunctionAttributes>(Arena*); +template<> ::xla::EntryFunctionAttributes_BufferParameterAttributes* Arena::CreateMaybeMessage<::xla::EntryFunctionAttributes_BufferParameterAttributes>(Arena*); +template<> ::xla::EntryFunctionAttributes_ShapeIndex* Arena::CreateMaybeMessage<::xla::EntryFunctionAttributes_ShapeIndex>(Arena*); +template<> ::xla::HeapSimulatorTrace* Arena::CreateMaybeMessage<::xla::HeapSimulatorTrace>(Arena*); +template<> ::xla::HeapSimulatorTrace_Event* Arena::CreateMaybeMessage<::xla::HeapSimulatorTrace_Event>(Arena*); +template<> ::xla::HloBufferDonorProto* Arena::CreateMaybeMessage<::xla::HloBufferDonorProto>(Arena*); +template<> ::xla::HloBufferDonorProto_BufferDonorEntryProto* Arena::CreateMaybeMessage<::xla::HloBufferDonorProto_BufferDonorEntryProto>(Arena*); +template<> ::xla::HloComputationProto* Arena::CreateMaybeMessage<::xla::HloComputationProto>(Arena*); +template<> ::xla::HloInputOutputAliasProto* Arena::CreateMaybeMessage<::xla::HloInputOutputAliasProto>(Arena*); +template<> ::xla::HloInputOutputAliasProto_AliasEntryProto* Arena::CreateMaybeMessage<::xla::HloInputOutputAliasProto_AliasEntryProto>(Arena*); +template<> ::xla::HloInstructionProto* Arena::CreateMaybeMessage<::xla::HloInstructionProto>(Arena*); +template<> ::xla::HloInstructionProto_SliceDimensions* Arena::CreateMaybeMessage<::xla::HloInstructionProto_SliceDimensions>(Arena*); +template<> ::xla::HloModuleGroupProto* Arena::CreateMaybeMessage<::xla::HloModuleGroupProto>(Arena*); +template<> ::xla::HloModuleMetadataProto* Arena::CreateMaybeMessage<::xla::HloModuleMetadataProto>(Arena*); +template<> ::xla::HloModuleProto* Arena::CreateMaybeMessage<::xla::HloModuleProto>(Arena*); +template<> ::xla::HloModuleProto_ProfileInfo* Arena::CreateMaybeMessage<::xla::HloModuleProto_ProfileInfo>(Arena*); +template<> ::xla::HloPassMetadata* Arena::CreateMaybeMessage<::xla::HloPassMetadata>(Arena*); +template<> ::xla::HloProto* Arena::CreateMaybeMessage<::xla::HloProto>(Arena*); +template<> ::xla::HloScheduleProto* Arena::CreateMaybeMessage<::xla::HloScheduleProto>(Arena*); +template<> ::xla::HloScheduleProto_InstructionSequence* Arena::CreateMaybeMessage<::xla::HloScheduleProto_InstructionSequence>(Arena*); +template<> ::xla::HloScheduleProto_SequencesEntry_DoNotUse* Arena::CreateMaybeMessage<::xla::HloScheduleProto_SequencesEntry_DoNotUse>(Arena*); +template<> ::xla::HloSnapshot* Arena::CreateMaybeMessage<::xla::HloSnapshot>(Arena*); +template<> ::xla::LogicalBufferProto* Arena::CreateMaybeMessage<::xla::LogicalBufferProto>(Arena*); +template<> ::xla::LogicalBufferProto_Location* Arena::CreateMaybeMessage<::xla::LogicalBufferProto_Location>(Arena*); +template<> ::xla::StackFrameIndexProto* Arena::CreateMaybeMessage<::xla::StackFrameIndexProto>(Arena*); +template<> ::xla::StackFrameIndexProto_FileLocation* Arena::CreateMaybeMessage<::xla::StackFrameIndexProto_FileLocation>(Arena*); +template<> ::xla::StackFrameIndexProto_StackFrame* Arena::CreateMaybeMessage<::xla::StackFrameIndexProto_StackFrame>(Arena*); +template<> ::xla::XlaRuntimeExecutableProto* Arena::CreateMaybeMessage<::xla::XlaRuntimeExecutableProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { + +enum HloModuleProto_ProfileType : int { + HloModuleProto_ProfileType_INVALID = 0, + HloModuleProto_ProfileType_FLAG = 1, + HloModuleProto_ProfileType_FUSION = 2, + HloModuleProto_ProfileType_LAYOUT = 3, + HloModuleProto_ProfileType_DOT = 4, + HloModuleProto_ProfileType_HloModuleProto_ProfileType_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + HloModuleProto_ProfileType_HloModuleProto_ProfileType_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool HloModuleProto_ProfileType_IsValid(int value); +constexpr HloModuleProto_ProfileType HloModuleProto_ProfileType_ProfileType_MIN = HloModuleProto_ProfileType_INVALID; +constexpr HloModuleProto_ProfileType HloModuleProto_ProfileType_ProfileType_MAX = HloModuleProto_ProfileType_DOT; +constexpr int HloModuleProto_ProfileType_ProfileType_ARRAYSIZE = HloModuleProto_ProfileType_ProfileType_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* HloModuleProto_ProfileType_descriptor(); +template +inline const std::string& HloModuleProto_ProfileType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function HloModuleProto_ProfileType_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + HloModuleProto_ProfileType_descriptor(), enum_t_value); +} +inline bool HloModuleProto_ProfileType_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, HloModuleProto_ProfileType* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + HloModuleProto_ProfileType_descriptor(), name, value); +} +enum HeapSimulatorTrace_Event_Kind : int { + HeapSimulatorTrace_Event_Kind_ALLOC = 0, + HeapSimulatorTrace_Event_Kind_FREE = 1, + HeapSimulatorTrace_Event_Kind_SHARE_WITH = 2, + HeapSimulatorTrace_Event_Kind_HeapSimulatorTrace_Event_Kind_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + HeapSimulatorTrace_Event_Kind_HeapSimulatorTrace_Event_Kind_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool HeapSimulatorTrace_Event_Kind_IsValid(int value); +constexpr HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event_Kind_Kind_MIN = HeapSimulatorTrace_Event_Kind_ALLOC; +constexpr HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event_Kind_Kind_MAX = HeapSimulatorTrace_Event_Kind_SHARE_WITH; +constexpr int HeapSimulatorTrace_Event_Kind_Kind_ARRAYSIZE = HeapSimulatorTrace_Event_Kind_Kind_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* HeapSimulatorTrace_Event_Kind_descriptor(); +template +inline const std::string& HeapSimulatorTrace_Event_Kind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function HeapSimulatorTrace_Event_Kind_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + HeapSimulatorTrace_Event_Kind_descriptor(), enum_t_value); +} +inline bool HeapSimulatorTrace_Event_Kind_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, HeapSimulatorTrace_Event_Kind* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + HeapSimulatorTrace_Event_Kind_descriptor(), name, value); +} +enum CustomCallSchedule : int { + SCHEDULE_NONE = 0, + SCHEDULE_LATEST = 1, + SCHEDULE_EARLIEST = 2, + CustomCallSchedule_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + CustomCallSchedule_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool CustomCallSchedule_IsValid(int value); +constexpr CustomCallSchedule CustomCallSchedule_MIN = SCHEDULE_NONE; +constexpr CustomCallSchedule CustomCallSchedule_MAX = SCHEDULE_EARLIEST; +constexpr int CustomCallSchedule_ARRAYSIZE = CustomCallSchedule_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CustomCallSchedule_descriptor(); +template +inline const std::string& CustomCallSchedule_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CustomCallSchedule_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + CustomCallSchedule_descriptor(), enum_t_value); +} +inline bool CustomCallSchedule_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CustomCallSchedule* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + CustomCallSchedule_descriptor(), name, value); +} +enum CustomCallApiVersion : int { + API_VERSION_UNSPECIFIED = 0, + API_VERSION_ORIGINAL = 1, + API_VERSION_STATUS_RETURNING = 2, + API_VERSION_STATUS_RETURNING_UNIFIED = 3, + API_VERSION_TYPED_FFI = 4, + CustomCallApiVersion_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + CustomCallApiVersion_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool CustomCallApiVersion_IsValid(int value); +constexpr CustomCallApiVersion CustomCallApiVersion_MIN = API_VERSION_UNSPECIFIED; +constexpr CustomCallApiVersion CustomCallApiVersion_MAX = API_VERSION_TYPED_FFI; +constexpr int CustomCallApiVersion_ARRAYSIZE = CustomCallApiVersion_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CustomCallApiVersion_descriptor(); +template +inline const std::string& CustomCallApiVersion_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CustomCallApiVersion_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + CustomCallApiVersion_descriptor(), enum_t_value); +} +inline bool CustomCallApiVersion_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CustomCallApiVersion* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + CustomCallApiVersion_descriptor(), name, value); +} +enum Kind : int { + UNDEFINED_ALIAS = 0, + MAY_ALIAS = 1, + MUST_ALIAS = 2, + Kind_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + Kind_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool Kind_IsValid(int value); +constexpr Kind Kind_MIN = UNDEFINED_ALIAS; +constexpr Kind Kind_MAX = MUST_ALIAS; +constexpr int Kind_ARRAYSIZE = Kind_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Kind_descriptor(); +template +inline const std::string& Kind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Kind_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + Kind_descriptor(), enum_t_value); +} +inline bool Kind_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, Kind* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + Kind_descriptor(), name, value); +} +// =================================================================== + +class HloInstructionProto_SliceDimensions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloInstructionProto.SliceDimensions) */ { + public: + inline HloInstructionProto_SliceDimensions() : HloInstructionProto_SliceDimensions(nullptr) {} + ~HloInstructionProto_SliceDimensions() override; + explicit PROTOBUF_CONSTEXPR HloInstructionProto_SliceDimensions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInstructionProto_SliceDimensions(const HloInstructionProto_SliceDimensions& from); + HloInstructionProto_SliceDimensions(HloInstructionProto_SliceDimensions&& from) noexcept + : HloInstructionProto_SliceDimensions() { + *this = ::std::move(from); + } + + inline HloInstructionProto_SliceDimensions& operator=(const HloInstructionProto_SliceDimensions& from) { + CopyFrom(from); + return *this; + } + inline HloInstructionProto_SliceDimensions& operator=(HloInstructionProto_SliceDimensions&& 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 HloInstructionProto_SliceDimensions& default_instance() { + return *internal_default_instance(); + } + static inline const HloInstructionProto_SliceDimensions* internal_default_instance() { + return reinterpret_cast( + &_HloInstructionProto_SliceDimensions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(HloInstructionProto_SliceDimensions& a, HloInstructionProto_SliceDimensions& b) { + a.Swap(&b); + } + inline void Swap(HloInstructionProto_SliceDimensions* 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(HloInstructionProto_SliceDimensions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInstructionProto_SliceDimensions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInstructionProto_SliceDimensions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInstructionProto_SliceDimensions& from) { + HloInstructionProto_SliceDimensions::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(HloInstructionProto_SliceDimensions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloInstructionProto.SliceDimensions"; + } + protected: + explicit HloInstructionProto_SliceDimensions(::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 { + kStartFieldNumber = 1, + kLimitFieldNumber = 2, + kStrideFieldNumber = 3, + }; + // int64 start = 1; + void clear_start(); + int64_t start() const; + void set_start(int64_t value); + private: + int64_t _internal_start() const; + void _internal_set_start(int64_t value); + public: + + // int64 limit = 2; + void clear_limit(); + int64_t limit() const; + void set_limit(int64_t value); + private: + int64_t _internal_limit() const; + void _internal_set_limit(int64_t value); + public: + + // int64 stride = 3; + void clear_stride(); + int64_t stride() const; + void set_stride(int64_t value); + private: + int64_t _internal_stride() const; + void _internal_set_stride(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloInstructionProto.SliceDimensions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t start_; + int64_t limit_; + int64_t stride_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloInstructionProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloInstructionProto) */ { + public: + inline HloInstructionProto() : HloInstructionProto(nullptr) {} + ~HloInstructionProto() override; + explicit PROTOBUF_CONSTEXPR HloInstructionProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInstructionProto(const HloInstructionProto& from); + HloInstructionProto(HloInstructionProto&& from) noexcept + : HloInstructionProto() { + *this = ::std::move(from); + } + + inline HloInstructionProto& operator=(const HloInstructionProto& from) { + CopyFrom(from); + return *this; + } + inline HloInstructionProto& operator=(HloInstructionProto&& 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 HloInstructionProto& default_instance() { + return *internal_default_instance(); + } + enum OptionalCrossProgramPrefetchIndexCase { + kCrossProgramPrefetchIndex = 80, + OPTIONAL_CROSS_PROGRAM_PREFETCH_INDEX_NOT_SET = 0, + }; + + static inline const HloInstructionProto* internal_default_instance() { + return reinterpret_cast( + &_HloInstructionProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(HloInstructionProto& a, HloInstructionProto& b) { + a.Swap(&b); + } + inline void Swap(HloInstructionProto* 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(HloInstructionProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInstructionProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInstructionProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInstructionProto& from) { + HloInstructionProto::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(HloInstructionProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloInstructionProto"; + } + protected: + explicit HloInstructionProto(::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 HloInstructionProto_SliceDimensions SliceDimensions; + + // accessors ------------------------------------------------------- + + enum : int { + kDimensionsFieldNumber = 14, + kSliceDimensionsFieldNumber = 17, + kDynamicSliceSizesFieldNumber = 20, + kFftLengthFieldNumber = 32, + kGatherSliceSizesFieldNumber = 34, + kOperandIdsFieldNumber = 36, + kControlPredecessorIdsFieldNumber = 37, + kCalledComputationIdsFieldNumber = 38, + kReplicaGroupsFieldNumber = 49, + kSourceTargetPairsFieldNumber = 52, + kOperandShapesWithLayoutFieldNumber = 57, + kOutputOperandAliasingFieldNumber = 74, + kNameFieldNumber = 1, + kOpcodeFieldNumber = 2, + kFusionKindFieldNumber = 11, + kOutfeedConfigFieldNumber = 22, + kInfeedConfigFieldNumber = 27, + kCustomCallTargetFieldNumber = 28, + kBackendConfigFieldNumber = 43, + kComparisonDirectionFieldNumber = 63, + kComparisonTypeFieldNumber = 72, + kAsyncExecutionThreadFieldNumber = 79, + kShapeFieldNumber = 3, + kMetadataFieldNumber = 7, + kLiteralFieldNumber = 8, + kWindowFieldNumber = 15, + kConvolutionDimensionNumbersFieldNumber = 16, + kPaddingConfigFieldNumber = 21, + kOutfeedShapeFieldNumber = 29, + kDotDimensionNumbersFieldNumber = 30, + kGatherDimensionNumbersFieldNumber = 33, + kShardingFieldNumber = 40, + kScatterDimensionNumbersFieldNumber = 48, + kPrecisionConfigFieldNumber = 51, + kDomainEntryShardingFieldNumber = 54, + kDomainExitShardingFieldNumber = 55, + kTriangularSolveOptionsFieldNumber = 59, + kParameterReplicationFieldNumber = 61, + kCholeskyOptionsFieldNumber = 62, + kFrontendAttributesFieldNumber = 68, + kStatisticsVizFieldNumber = 82, + kParameterNumberFieldNumber = 9, + kTupleIndexFieldNumber = 13, + kExponentBitsFieldNumber = 18, + kMantissaBitsFieldNumber = 19, + kDistributionFieldNumber = 23, + kEpsilonFieldNumber = 24, + kFeatureIndexFieldNumber = 25, + kChannelIdFieldNumber = 26, + kIdFieldNumber = 35, + kAllReduceIdFieldNumber = 45, + kFeatureGroupCountFieldNumber = 50, + kFftTypeFieldNumber = 31, + kUseGlobalDeviceIdsFieldNumber = 71, + kIsHostTransferFieldNumber = 47, + kIsStableFieldNumber = 60, + kConstrainLayoutFieldNumber = 56, + kBatchGroupCountFieldNumber = 58, + kDeltaFieldNumber = 66, + kCustomCallHasSideEffectFieldNumber = 65, + kIndicesAreSortedFieldNumber = 67, + kUniqueIndicesFieldNumber = 69, + kIsCrossProgramPrefetchFieldNumber = 73, + kRngAlgorithmFieldNumber = 70, + kPaddingTypeFieldNumber = 75, + kCustomCallScheduleFieldNumber = 76, + kAsyncGroupIdFieldNumber = 78, + kKFieldNumber = 81, + kCustomCallApiVersionFieldNumber = 77, + kCrossProgramPrefetchIndexFieldNumber = 80, + }; + // repeated int64 dimensions = 14; + int dimensions_size() const; + private: + int _internal_dimensions_size() const; + public: + void clear_dimensions(); + private: + int64_t _internal_dimensions(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_dimensions() const; + void _internal_add_dimensions(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_dimensions(); + public: + int64_t dimensions(int index) const; + void set_dimensions(int index, int64_t value); + void add_dimensions(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + dimensions() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_dimensions(); + + // repeated .xla.HloInstructionProto.SliceDimensions slice_dimensions = 17; + int slice_dimensions_size() const; + private: + int _internal_slice_dimensions_size() const; + public: + void clear_slice_dimensions(); + ::xla::HloInstructionProto_SliceDimensions* mutable_slice_dimensions(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto_SliceDimensions >* + mutable_slice_dimensions(); + private: + const ::xla::HloInstructionProto_SliceDimensions& _internal_slice_dimensions(int index) const; + ::xla::HloInstructionProto_SliceDimensions* _internal_add_slice_dimensions(); + public: + const ::xla::HloInstructionProto_SliceDimensions& slice_dimensions(int index) const; + ::xla::HloInstructionProto_SliceDimensions* add_slice_dimensions(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto_SliceDimensions >& + slice_dimensions() const; + + // repeated int64 dynamic_slice_sizes = 20; + int dynamic_slice_sizes_size() const; + private: + int _internal_dynamic_slice_sizes_size() const; + public: + void clear_dynamic_slice_sizes(); + private: + int64_t _internal_dynamic_slice_sizes(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_dynamic_slice_sizes() const; + void _internal_add_dynamic_slice_sizes(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_dynamic_slice_sizes(); + public: + int64_t dynamic_slice_sizes(int index) const; + void set_dynamic_slice_sizes(int index, int64_t value); + void add_dynamic_slice_sizes(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + dynamic_slice_sizes() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_dynamic_slice_sizes(); + + // repeated int64 fft_length = 32; + int fft_length_size() const; + private: + int _internal_fft_length_size() const; + public: + void clear_fft_length(); + private: + int64_t _internal_fft_length(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_fft_length() const; + void _internal_add_fft_length(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_fft_length(); + public: + int64_t fft_length(int index) const; + void set_fft_length(int index, int64_t value); + void add_fft_length(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + fft_length() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_fft_length(); + + // repeated int64 gather_slice_sizes = 34; + int gather_slice_sizes_size() const; + private: + int _internal_gather_slice_sizes_size() const; + public: + void clear_gather_slice_sizes(); + private: + int64_t _internal_gather_slice_sizes(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_gather_slice_sizes() const; + void _internal_add_gather_slice_sizes(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_gather_slice_sizes(); + public: + int64_t gather_slice_sizes(int index) const; + void set_gather_slice_sizes(int index, int64_t value); + void add_gather_slice_sizes(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + gather_slice_sizes() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_gather_slice_sizes(); + + // repeated int64 operand_ids = 36; + int operand_ids_size() const; + private: + int _internal_operand_ids_size() const; + public: + void clear_operand_ids(); + private: + int64_t _internal_operand_ids(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_operand_ids() const; + void _internal_add_operand_ids(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_operand_ids(); + public: + int64_t operand_ids(int index) const; + void set_operand_ids(int index, int64_t value); + void add_operand_ids(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + operand_ids() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_operand_ids(); + + // repeated int64 control_predecessor_ids = 37; + int control_predecessor_ids_size() const; + private: + int _internal_control_predecessor_ids_size() const; + public: + void clear_control_predecessor_ids(); + private: + int64_t _internal_control_predecessor_ids(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_control_predecessor_ids() const; + void _internal_add_control_predecessor_ids(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_control_predecessor_ids(); + public: + int64_t control_predecessor_ids(int index) const; + void set_control_predecessor_ids(int index, int64_t value); + void add_control_predecessor_ids(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + control_predecessor_ids() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_control_predecessor_ids(); + + // repeated int64 called_computation_ids = 38; + int called_computation_ids_size() const; + private: + int _internal_called_computation_ids_size() const; + public: + void clear_called_computation_ids(); + private: + int64_t _internal_called_computation_ids(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_called_computation_ids() const; + void _internal_add_called_computation_ids(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_called_computation_ids(); + public: + int64_t called_computation_ids(int index) const; + void set_called_computation_ids(int index, int64_t value); + void add_called_computation_ids(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + called_computation_ids() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_called_computation_ids(); + + // repeated .xla.ReplicaGroup replica_groups = 49; + int replica_groups_size() const; + private: + int _internal_replica_groups_size() const; + public: + void clear_replica_groups(); + ::xla::ReplicaGroup* mutable_replica_groups(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ReplicaGroup >* + mutable_replica_groups(); + private: + const ::xla::ReplicaGroup& _internal_replica_groups(int index) const; + ::xla::ReplicaGroup* _internal_add_replica_groups(); + public: + const ::xla::ReplicaGroup& replica_groups(int index) const; + ::xla::ReplicaGroup* add_replica_groups(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ReplicaGroup >& + replica_groups() const; + + // repeated .xla.SourceTarget source_target_pairs = 52; + int source_target_pairs_size() const; + private: + int _internal_source_target_pairs_size() const; + public: + void clear_source_target_pairs(); + ::xla::SourceTarget* mutable_source_target_pairs(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::SourceTarget >* + mutable_source_target_pairs(); + private: + const ::xla::SourceTarget& _internal_source_target_pairs(int index) const; + ::xla::SourceTarget* _internal_add_source_target_pairs(); + public: + const ::xla::SourceTarget& source_target_pairs(int index) const; + ::xla::SourceTarget* add_source_target_pairs(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::SourceTarget >& + source_target_pairs() const; + + // repeated .xla.ShapeProto operand_shapes_with_layout = 57; + int operand_shapes_with_layout_size() const; + private: + int _internal_operand_shapes_with_layout_size() const; + public: + void clear_operand_shapes_with_layout(); + ::xla::ShapeProto* mutable_operand_shapes_with_layout(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >* + mutable_operand_shapes_with_layout(); + private: + const ::xla::ShapeProto& _internal_operand_shapes_with_layout(int index) const; + ::xla::ShapeProto* _internal_add_operand_shapes_with_layout(); + public: + const ::xla::ShapeProto& operand_shapes_with_layout(int index) const; + ::xla::ShapeProto* add_operand_shapes_with_layout(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >& + operand_shapes_with_layout() const; + + // repeated .xla.OutputOperandAliasing output_operand_aliasing = 74; + int output_operand_aliasing_size() const; + private: + int _internal_output_operand_aliasing_size() const; + public: + void clear_output_operand_aliasing(); + ::xla::OutputOperandAliasing* mutable_output_operand_aliasing(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OutputOperandAliasing >* + mutable_output_operand_aliasing(); + private: + const ::xla::OutputOperandAliasing& _internal_output_operand_aliasing(int index) const; + ::xla::OutputOperandAliasing* _internal_add_output_operand_aliasing(); + public: + const ::xla::OutputOperandAliasing& output_operand_aliasing(int index) const; + ::xla::OutputOperandAliasing* add_output_operand_aliasing(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OutputOperandAliasing >& + output_operand_aliasing() 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: + + // string opcode = 2; + void clear_opcode(); + const std::string& opcode() const; + template + void set_opcode(ArgT0&& arg0, ArgT... args); + std::string* mutable_opcode(); + PROTOBUF_NODISCARD std::string* release_opcode(); + void set_allocated_opcode(std::string* opcode); + private: + const std::string& _internal_opcode() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_opcode(const std::string& value); + std::string* _internal_mutable_opcode(); + public: + + // string fusion_kind = 11; + void clear_fusion_kind(); + const std::string& fusion_kind() const; + template + void set_fusion_kind(ArgT0&& arg0, ArgT... args); + std::string* mutable_fusion_kind(); + PROTOBUF_NODISCARD std::string* release_fusion_kind(); + void set_allocated_fusion_kind(std::string* fusion_kind); + private: + const std::string& _internal_fusion_kind() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_fusion_kind(const std::string& value); + std::string* _internal_mutable_fusion_kind(); + public: + + // bytes outfeed_config = 22; + void clear_outfeed_config(); + const std::string& outfeed_config() const; + template + void set_outfeed_config(ArgT0&& arg0, ArgT... args); + std::string* mutable_outfeed_config(); + PROTOBUF_NODISCARD std::string* release_outfeed_config(); + void set_allocated_outfeed_config(std::string* outfeed_config); + private: + const std::string& _internal_outfeed_config() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_outfeed_config(const std::string& value); + std::string* _internal_mutable_outfeed_config(); + public: + + // bytes infeed_config = 27; + void clear_infeed_config(); + const std::string& infeed_config() const; + template + void set_infeed_config(ArgT0&& arg0, ArgT... args); + std::string* mutable_infeed_config(); + PROTOBUF_NODISCARD std::string* release_infeed_config(); + void set_allocated_infeed_config(std::string* infeed_config); + private: + const std::string& _internal_infeed_config() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_infeed_config(const std::string& value); + std::string* _internal_mutable_infeed_config(); + public: + + // string custom_call_target = 28; + void clear_custom_call_target(); + const std::string& custom_call_target() const; + template + void set_custom_call_target(ArgT0&& arg0, ArgT... args); + std::string* mutable_custom_call_target(); + PROTOBUF_NODISCARD std::string* release_custom_call_target(); + void set_allocated_custom_call_target(std::string* custom_call_target); + private: + const std::string& _internal_custom_call_target() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_custom_call_target(const std::string& value); + std::string* _internal_mutable_custom_call_target(); + public: + + // bytes backend_config = 43; + void clear_backend_config(); + const std::string& backend_config() const; + template + void set_backend_config(ArgT0&& arg0, ArgT... args); + std::string* mutable_backend_config(); + PROTOBUF_NODISCARD std::string* release_backend_config(); + void set_allocated_backend_config(std::string* backend_config); + private: + const std::string& _internal_backend_config() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_backend_config(const std::string& value); + std::string* _internal_mutable_backend_config(); + public: + + // string comparison_direction = 63; + void clear_comparison_direction(); + const std::string& comparison_direction() const; + template + void set_comparison_direction(ArgT0&& arg0, ArgT... args); + std::string* mutable_comparison_direction(); + PROTOBUF_NODISCARD std::string* release_comparison_direction(); + void set_allocated_comparison_direction(std::string* comparison_direction); + private: + const std::string& _internal_comparison_direction() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_comparison_direction(const std::string& value); + std::string* _internal_mutable_comparison_direction(); + public: + + // string comparison_type = 72; + void clear_comparison_type(); + const std::string& comparison_type() const; + template + void set_comparison_type(ArgT0&& arg0, ArgT... args); + std::string* mutable_comparison_type(); + PROTOBUF_NODISCARD std::string* release_comparison_type(); + void set_allocated_comparison_type(std::string* comparison_type); + private: + const std::string& _internal_comparison_type() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_comparison_type(const std::string& value); + std::string* _internal_mutable_comparison_type(); + public: + + // string async_execution_thread = 79; + void clear_async_execution_thread(); + const std::string& async_execution_thread() const; + template + void set_async_execution_thread(ArgT0&& arg0, ArgT... args); + std::string* mutable_async_execution_thread(); + PROTOBUF_NODISCARD std::string* release_async_execution_thread(); + void set_allocated_async_execution_thread(std::string* async_execution_thread); + private: + const std::string& _internal_async_execution_thread() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_async_execution_thread(const std::string& value); + std::string* _internal_mutable_async_execution_thread(); + public: + + // .xla.ShapeProto shape = 3; + bool has_shape() const; + private: + bool _internal_has_shape() const; + public: + void clear_shape(); + const ::xla::ShapeProto& shape() const; + PROTOBUF_NODISCARD ::xla::ShapeProto* release_shape(); + ::xla::ShapeProto* mutable_shape(); + void set_allocated_shape(::xla::ShapeProto* shape); + private: + const ::xla::ShapeProto& _internal_shape() const; + ::xla::ShapeProto* _internal_mutable_shape(); + public: + void unsafe_arena_set_allocated_shape( + ::xla::ShapeProto* shape); + ::xla::ShapeProto* unsafe_arena_release_shape(); + + // .xla.OpMetadata metadata = 7; + bool has_metadata() const; + private: + bool _internal_has_metadata() const; + public: + void clear_metadata(); + const ::xla::OpMetadata& metadata() const; + PROTOBUF_NODISCARD ::xla::OpMetadata* release_metadata(); + ::xla::OpMetadata* mutable_metadata(); + void set_allocated_metadata(::xla::OpMetadata* metadata); + private: + const ::xla::OpMetadata& _internal_metadata() const; + ::xla::OpMetadata* _internal_mutable_metadata(); + public: + void unsafe_arena_set_allocated_metadata( + ::xla::OpMetadata* metadata); + ::xla::OpMetadata* unsafe_arena_release_metadata(); + + // .xla.LiteralProto literal = 8; + bool has_literal() const; + private: + bool _internal_has_literal() const; + public: + void clear_literal(); + const ::xla::LiteralProto& literal() const; + PROTOBUF_NODISCARD ::xla::LiteralProto* release_literal(); + ::xla::LiteralProto* mutable_literal(); + void set_allocated_literal(::xla::LiteralProto* literal); + private: + const ::xla::LiteralProto& _internal_literal() const; + ::xla::LiteralProto* _internal_mutable_literal(); + public: + void unsafe_arena_set_allocated_literal( + ::xla::LiteralProto* literal); + ::xla::LiteralProto* unsafe_arena_release_literal(); + + // .xla.Window window = 15; + bool has_window() const; + private: + bool _internal_has_window() const; + public: + void clear_window(); + const ::xla::Window& window() const; + PROTOBUF_NODISCARD ::xla::Window* release_window(); + ::xla::Window* mutable_window(); + void set_allocated_window(::xla::Window* window); + private: + const ::xla::Window& _internal_window() const; + ::xla::Window* _internal_mutable_window(); + public: + void unsafe_arena_set_allocated_window( + ::xla::Window* window); + ::xla::Window* unsafe_arena_release_window(); + + // .xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16; + bool has_convolution_dimension_numbers() const; + private: + bool _internal_has_convolution_dimension_numbers() const; + public: + void clear_convolution_dimension_numbers(); + const ::xla::ConvolutionDimensionNumbers& convolution_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::ConvolutionDimensionNumbers* release_convolution_dimension_numbers(); + ::xla::ConvolutionDimensionNumbers* mutable_convolution_dimension_numbers(); + void set_allocated_convolution_dimension_numbers(::xla::ConvolutionDimensionNumbers* convolution_dimension_numbers); + private: + const ::xla::ConvolutionDimensionNumbers& _internal_convolution_dimension_numbers() const; + ::xla::ConvolutionDimensionNumbers* _internal_mutable_convolution_dimension_numbers(); + public: + void unsafe_arena_set_allocated_convolution_dimension_numbers( + ::xla::ConvolutionDimensionNumbers* convolution_dimension_numbers); + ::xla::ConvolutionDimensionNumbers* unsafe_arena_release_convolution_dimension_numbers(); + + // .xla.PaddingConfig padding_config = 21; + bool has_padding_config() const; + private: + bool _internal_has_padding_config() const; + public: + void clear_padding_config(); + const ::xla::PaddingConfig& padding_config() const; + PROTOBUF_NODISCARD ::xla::PaddingConfig* release_padding_config(); + ::xla::PaddingConfig* mutable_padding_config(); + void set_allocated_padding_config(::xla::PaddingConfig* padding_config); + private: + const ::xla::PaddingConfig& _internal_padding_config() const; + ::xla::PaddingConfig* _internal_mutable_padding_config(); + public: + void unsafe_arena_set_allocated_padding_config( + ::xla::PaddingConfig* padding_config); + ::xla::PaddingConfig* unsafe_arena_release_padding_config(); + + // .xla.ShapeProto outfeed_shape = 29; + bool has_outfeed_shape() const; + private: + bool _internal_has_outfeed_shape() const; + public: + void clear_outfeed_shape(); + const ::xla::ShapeProto& outfeed_shape() const; + PROTOBUF_NODISCARD ::xla::ShapeProto* release_outfeed_shape(); + ::xla::ShapeProto* mutable_outfeed_shape(); + void set_allocated_outfeed_shape(::xla::ShapeProto* outfeed_shape); + private: + const ::xla::ShapeProto& _internal_outfeed_shape() const; + ::xla::ShapeProto* _internal_mutable_outfeed_shape(); + public: + void unsafe_arena_set_allocated_outfeed_shape( + ::xla::ShapeProto* outfeed_shape); + ::xla::ShapeProto* unsafe_arena_release_outfeed_shape(); + + // .xla.DotDimensionNumbers dot_dimension_numbers = 30; + bool has_dot_dimension_numbers() const; + private: + bool _internal_has_dot_dimension_numbers() const; + public: + void clear_dot_dimension_numbers(); + const ::xla::DotDimensionNumbers& dot_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::DotDimensionNumbers* release_dot_dimension_numbers(); + ::xla::DotDimensionNumbers* mutable_dot_dimension_numbers(); + void set_allocated_dot_dimension_numbers(::xla::DotDimensionNumbers* dot_dimension_numbers); + private: + const ::xla::DotDimensionNumbers& _internal_dot_dimension_numbers() const; + ::xla::DotDimensionNumbers* _internal_mutable_dot_dimension_numbers(); + public: + void unsafe_arena_set_allocated_dot_dimension_numbers( + ::xla::DotDimensionNumbers* dot_dimension_numbers); + ::xla::DotDimensionNumbers* unsafe_arena_release_dot_dimension_numbers(); + + // .xla.GatherDimensionNumbers gather_dimension_numbers = 33; + bool has_gather_dimension_numbers() const; + private: + bool _internal_has_gather_dimension_numbers() const; + public: + void clear_gather_dimension_numbers(); + const ::xla::GatherDimensionNumbers& gather_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::GatherDimensionNumbers* release_gather_dimension_numbers(); + ::xla::GatherDimensionNumbers* mutable_gather_dimension_numbers(); + void set_allocated_gather_dimension_numbers(::xla::GatherDimensionNumbers* gather_dimension_numbers); + private: + const ::xla::GatherDimensionNumbers& _internal_gather_dimension_numbers() const; + ::xla::GatherDimensionNumbers* _internal_mutable_gather_dimension_numbers(); + public: + void unsafe_arena_set_allocated_gather_dimension_numbers( + ::xla::GatherDimensionNumbers* gather_dimension_numbers); + ::xla::GatherDimensionNumbers* unsafe_arena_release_gather_dimension_numbers(); + + // .xla.OpSharding sharding = 40; + bool has_sharding() const; + private: + bool _internal_has_sharding() const; + public: + void clear_sharding(); + const ::xla::OpSharding& sharding() const; + PROTOBUF_NODISCARD ::xla::OpSharding* release_sharding(); + ::xla::OpSharding* mutable_sharding(); + void set_allocated_sharding(::xla::OpSharding* sharding); + private: + const ::xla::OpSharding& _internal_sharding() const; + ::xla::OpSharding* _internal_mutable_sharding(); + public: + void unsafe_arena_set_allocated_sharding( + ::xla::OpSharding* sharding); + ::xla::OpSharding* unsafe_arena_release_sharding(); + + // .xla.ScatterDimensionNumbers scatter_dimension_numbers = 48; + bool has_scatter_dimension_numbers() const; + private: + bool _internal_has_scatter_dimension_numbers() const; + public: + void clear_scatter_dimension_numbers(); + const ::xla::ScatterDimensionNumbers& scatter_dimension_numbers() const; + PROTOBUF_NODISCARD ::xla::ScatterDimensionNumbers* release_scatter_dimension_numbers(); + ::xla::ScatterDimensionNumbers* mutable_scatter_dimension_numbers(); + void set_allocated_scatter_dimension_numbers(::xla::ScatterDimensionNumbers* scatter_dimension_numbers); + private: + const ::xla::ScatterDimensionNumbers& _internal_scatter_dimension_numbers() const; + ::xla::ScatterDimensionNumbers* _internal_mutable_scatter_dimension_numbers(); + public: + void unsafe_arena_set_allocated_scatter_dimension_numbers( + ::xla::ScatterDimensionNumbers* scatter_dimension_numbers); + ::xla::ScatterDimensionNumbers* unsafe_arena_release_scatter_dimension_numbers(); + + // .xla.PrecisionConfig precision_config = 51; + bool has_precision_config() const; + private: + bool _internal_has_precision_config() const; + public: + void clear_precision_config(); + const ::xla::PrecisionConfig& precision_config() const; + PROTOBUF_NODISCARD ::xla::PrecisionConfig* release_precision_config(); + ::xla::PrecisionConfig* mutable_precision_config(); + void set_allocated_precision_config(::xla::PrecisionConfig* precision_config); + private: + const ::xla::PrecisionConfig& _internal_precision_config() const; + ::xla::PrecisionConfig* _internal_mutable_precision_config(); + public: + void unsafe_arena_set_allocated_precision_config( + ::xla::PrecisionConfig* precision_config); + ::xla::PrecisionConfig* unsafe_arena_release_precision_config(); + + // .xla.OpSharding domain_entry_sharding = 54; + bool has_domain_entry_sharding() const; + private: + bool _internal_has_domain_entry_sharding() const; + public: + void clear_domain_entry_sharding(); + const ::xla::OpSharding& domain_entry_sharding() const; + PROTOBUF_NODISCARD ::xla::OpSharding* release_domain_entry_sharding(); + ::xla::OpSharding* mutable_domain_entry_sharding(); + void set_allocated_domain_entry_sharding(::xla::OpSharding* domain_entry_sharding); + private: + const ::xla::OpSharding& _internal_domain_entry_sharding() const; + ::xla::OpSharding* _internal_mutable_domain_entry_sharding(); + public: + void unsafe_arena_set_allocated_domain_entry_sharding( + ::xla::OpSharding* domain_entry_sharding); + ::xla::OpSharding* unsafe_arena_release_domain_entry_sharding(); + + // .xla.OpSharding domain_exit_sharding = 55; + bool has_domain_exit_sharding() const; + private: + bool _internal_has_domain_exit_sharding() const; + public: + void clear_domain_exit_sharding(); + const ::xla::OpSharding& domain_exit_sharding() const; + PROTOBUF_NODISCARD ::xla::OpSharding* release_domain_exit_sharding(); + ::xla::OpSharding* mutable_domain_exit_sharding(); + void set_allocated_domain_exit_sharding(::xla::OpSharding* domain_exit_sharding); + private: + const ::xla::OpSharding& _internal_domain_exit_sharding() const; + ::xla::OpSharding* _internal_mutable_domain_exit_sharding(); + public: + void unsafe_arena_set_allocated_domain_exit_sharding( + ::xla::OpSharding* domain_exit_sharding); + ::xla::OpSharding* unsafe_arena_release_domain_exit_sharding(); + + // .xla.TriangularSolveOptions triangular_solve_options = 59; + bool has_triangular_solve_options() const; + private: + bool _internal_has_triangular_solve_options() const; + public: + void clear_triangular_solve_options(); + const ::xla::TriangularSolveOptions& triangular_solve_options() const; + PROTOBUF_NODISCARD ::xla::TriangularSolveOptions* release_triangular_solve_options(); + ::xla::TriangularSolveOptions* mutable_triangular_solve_options(); + void set_allocated_triangular_solve_options(::xla::TriangularSolveOptions* triangular_solve_options); + private: + const ::xla::TriangularSolveOptions& _internal_triangular_solve_options() const; + ::xla::TriangularSolveOptions* _internal_mutable_triangular_solve_options(); + public: + void unsafe_arena_set_allocated_triangular_solve_options( + ::xla::TriangularSolveOptions* triangular_solve_options); + ::xla::TriangularSolveOptions* unsafe_arena_release_triangular_solve_options(); + + // .xla.ParameterReplication parameter_replication = 61; + bool has_parameter_replication() const; + private: + bool _internal_has_parameter_replication() const; + public: + void clear_parameter_replication(); + const ::xla::ParameterReplication& parameter_replication() const; + PROTOBUF_NODISCARD ::xla::ParameterReplication* release_parameter_replication(); + ::xla::ParameterReplication* mutable_parameter_replication(); + void set_allocated_parameter_replication(::xla::ParameterReplication* parameter_replication); + private: + const ::xla::ParameterReplication& _internal_parameter_replication() const; + ::xla::ParameterReplication* _internal_mutable_parameter_replication(); + public: + void unsafe_arena_set_allocated_parameter_replication( + ::xla::ParameterReplication* parameter_replication); + ::xla::ParameterReplication* unsafe_arena_release_parameter_replication(); + + // .xla.CholeskyOptions cholesky_options = 62; + bool has_cholesky_options() const; + private: + bool _internal_has_cholesky_options() const; + public: + void clear_cholesky_options(); + const ::xla::CholeskyOptions& cholesky_options() const; + PROTOBUF_NODISCARD ::xla::CholeskyOptions* release_cholesky_options(); + ::xla::CholeskyOptions* mutable_cholesky_options(); + void set_allocated_cholesky_options(::xla::CholeskyOptions* cholesky_options); + private: + const ::xla::CholeskyOptions& _internal_cholesky_options() const; + ::xla::CholeskyOptions* _internal_mutable_cholesky_options(); + public: + void unsafe_arena_set_allocated_cholesky_options( + ::xla::CholeskyOptions* cholesky_options); + ::xla::CholeskyOptions* unsafe_arena_release_cholesky_options(); + + // .xla.FrontendAttributes frontend_attributes = 68; + bool has_frontend_attributes() const; + private: + bool _internal_has_frontend_attributes() const; + public: + void clear_frontend_attributes(); + const ::xla::FrontendAttributes& frontend_attributes() const; + PROTOBUF_NODISCARD ::xla::FrontendAttributes* release_frontend_attributes(); + ::xla::FrontendAttributes* mutable_frontend_attributes(); + void set_allocated_frontend_attributes(::xla::FrontendAttributes* frontend_attributes); + private: + const ::xla::FrontendAttributes& _internal_frontend_attributes() const; + ::xla::FrontendAttributes* _internal_mutable_frontend_attributes(); + public: + void unsafe_arena_set_allocated_frontend_attributes( + ::xla::FrontendAttributes* frontend_attributes); + ::xla::FrontendAttributes* unsafe_arena_release_frontend_attributes(); + + // .xla.StatisticsViz statistics_viz = 82; + bool has_statistics_viz() const; + private: + bool _internal_has_statistics_viz() const; + public: + void clear_statistics_viz(); + const ::xla::StatisticsViz& statistics_viz() const; + PROTOBUF_NODISCARD ::xla::StatisticsViz* release_statistics_viz(); + ::xla::StatisticsViz* mutable_statistics_viz(); + void set_allocated_statistics_viz(::xla::StatisticsViz* statistics_viz); + private: + const ::xla::StatisticsViz& _internal_statistics_viz() const; + ::xla::StatisticsViz* _internal_mutable_statistics_viz(); + public: + void unsafe_arena_set_allocated_statistics_viz( + ::xla::StatisticsViz* statistics_viz); + ::xla::StatisticsViz* unsafe_arena_release_statistics_viz(); + + // int64 parameter_number = 9; + void clear_parameter_number(); + int64_t parameter_number() const; + void set_parameter_number(int64_t value); + private: + int64_t _internal_parameter_number() const; + void _internal_set_parameter_number(int64_t value); + public: + + // int64 tuple_index = 13; + void clear_tuple_index(); + int64_t tuple_index() const; + void set_tuple_index(int64_t value); + private: + int64_t _internal_tuple_index() const; + void _internal_set_tuple_index(int64_t value); + public: + + // int32 exponent_bits = 18; + void clear_exponent_bits(); + int32_t exponent_bits() const; + void set_exponent_bits(int32_t value); + private: + int32_t _internal_exponent_bits() const; + void _internal_set_exponent_bits(int32_t value); + public: + + // int32 mantissa_bits = 19; + void clear_mantissa_bits(); + int32_t mantissa_bits() const; + void set_mantissa_bits(int32_t value); + private: + int32_t _internal_mantissa_bits() const; + void _internal_set_mantissa_bits(int32_t value); + public: + + // .xla.RandomDistribution distribution = 23; + void clear_distribution(); + ::xla::RandomDistribution distribution() const; + void set_distribution(::xla::RandomDistribution value); + private: + ::xla::RandomDistribution _internal_distribution() const; + void _internal_set_distribution(::xla::RandomDistribution value); + public: + + // float epsilon = 24; + void clear_epsilon(); + float epsilon() const; + void set_epsilon(float value); + private: + float _internal_epsilon() const; + void _internal_set_epsilon(float value); + public: + + // int64 feature_index = 25; + void clear_feature_index(); + int64_t feature_index() const; + void set_feature_index(int64_t value); + private: + int64_t _internal_feature_index() const; + void _internal_set_feature_index(int64_t value); + public: + + // int64 channel_id = 26; + void clear_channel_id(); + int64_t channel_id() const; + void set_channel_id(int64_t value); + private: + int64_t _internal_channel_id() const; + void _internal_set_channel_id(int64_t value); + public: + + // int64 id = 35; + void clear_id(); + int64_t id() const; + void set_id(int64_t value); + private: + int64_t _internal_id() const; + void _internal_set_id(int64_t value); + public: + + // int64 all_reduce_id = 45 [deprecated = true]; + PROTOBUF_DEPRECATED void clear_all_reduce_id(); + PROTOBUF_DEPRECATED int64_t all_reduce_id() const; + PROTOBUF_DEPRECATED void set_all_reduce_id(int64_t value); + private: + int64_t _internal_all_reduce_id() const; + void _internal_set_all_reduce_id(int64_t value); + public: + + // int64 feature_group_count = 50; + void clear_feature_group_count(); + int64_t feature_group_count() const; + void set_feature_group_count(int64_t value); + private: + int64_t _internal_feature_group_count() const; + void _internal_set_feature_group_count(int64_t value); + public: + + // .xla.FftType fft_type = 31; + void clear_fft_type(); + ::xla::FftType fft_type() const; + void set_fft_type(::xla::FftType value); + private: + ::xla::FftType _internal_fft_type() const; + void _internal_set_fft_type(::xla::FftType value); + public: + + // bool use_global_device_ids = 71; + void clear_use_global_device_ids(); + bool use_global_device_ids() const; + void set_use_global_device_ids(bool value); + private: + bool _internal_use_global_device_ids() const; + void _internal_set_use_global_device_ids(bool value); + public: + + // bool is_host_transfer = 47; + void clear_is_host_transfer(); + bool is_host_transfer() const; + void set_is_host_transfer(bool value); + private: + bool _internal_is_host_transfer() const; + void _internal_set_is_host_transfer(bool value); + public: + + // bool is_stable = 60; + void clear_is_stable(); + bool is_stable() const; + void set_is_stable(bool value); + private: + bool _internal_is_stable() const; + void _internal_set_is_stable(bool value); + public: + + // bool constrain_layout = 56; + void clear_constrain_layout(); + bool constrain_layout() const; + void set_constrain_layout(bool value); + private: + bool _internal_constrain_layout() const; + void _internal_set_constrain_layout(bool value); + public: + + // int64 batch_group_count = 58; + void clear_batch_group_count(); + int64_t batch_group_count() const; + void set_batch_group_count(int64_t value); + private: + int64_t _internal_batch_group_count() const; + void _internal_set_batch_group_count(int64_t value); + public: + + // int64 delta = 66; + void clear_delta(); + int64_t delta() const; + void set_delta(int64_t value); + private: + int64_t _internal_delta() const; + void _internal_set_delta(int64_t value); + public: + + // bool custom_call_has_side_effect = 65; + void clear_custom_call_has_side_effect(); + bool custom_call_has_side_effect() const; + void set_custom_call_has_side_effect(bool value); + private: + bool _internal_custom_call_has_side_effect() const; + void _internal_set_custom_call_has_side_effect(bool value); + public: + + // bool indices_are_sorted = 67; + void clear_indices_are_sorted(); + bool indices_are_sorted() const; + void set_indices_are_sorted(bool value); + private: + bool _internal_indices_are_sorted() const; + void _internal_set_indices_are_sorted(bool value); + public: + + // bool unique_indices = 69; + void clear_unique_indices(); + bool unique_indices() const; + void set_unique_indices(bool value); + private: + bool _internal_unique_indices() const; + void _internal_set_unique_indices(bool value); + public: + + // bool is_cross_program_prefetch = 73 [deprecated = true]; + PROTOBUF_DEPRECATED void clear_is_cross_program_prefetch(); + PROTOBUF_DEPRECATED bool is_cross_program_prefetch() const; + PROTOBUF_DEPRECATED void set_is_cross_program_prefetch(bool value); + private: + bool _internal_is_cross_program_prefetch() const; + void _internal_set_is_cross_program_prefetch(bool value); + public: + + // .xla.RandomAlgorithm rng_algorithm = 70; + void clear_rng_algorithm(); + ::xla::RandomAlgorithm rng_algorithm() const; + void set_rng_algorithm(::xla::RandomAlgorithm value); + private: + ::xla::RandomAlgorithm _internal_rng_algorithm() const; + void _internal_set_rng_algorithm(::xla::RandomAlgorithm value); + public: + + // .xla.PaddingType padding_type = 75; + void clear_padding_type(); + ::xla::PaddingType padding_type() const; + void set_padding_type(::xla::PaddingType value); + private: + ::xla::PaddingType _internal_padding_type() const; + void _internal_set_padding_type(::xla::PaddingType value); + public: + + // .xla.CustomCallSchedule custom_call_schedule = 76; + void clear_custom_call_schedule(); + ::xla::CustomCallSchedule custom_call_schedule() const; + void set_custom_call_schedule(::xla::CustomCallSchedule value); + private: + ::xla::CustomCallSchedule _internal_custom_call_schedule() const; + void _internal_set_custom_call_schedule(::xla::CustomCallSchedule value); + public: + + // int64 async_group_id = 78; + void clear_async_group_id(); + int64_t async_group_id() const; + void set_async_group_id(int64_t value); + private: + int64_t _internal_async_group_id() const; + void _internal_set_async_group_id(int64_t value); + public: + + // int64 k = 81; + void clear_k(); + int64_t k() const; + void set_k(int64_t value); + private: + int64_t _internal_k() const; + void _internal_set_k(int64_t value); + public: + + // .xla.CustomCallApiVersion custom_call_api_version = 77; + void clear_custom_call_api_version(); + ::xla::CustomCallApiVersion custom_call_api_version() const; + void set_custom_call_api_version(::xla::CustomCallApiVersion value); + private: + ::xla::CustomCallApiVersion _internal_custom_call_api_version() const; + void _internal_set_custom_call_api_version(::xla::CustomCallApiVersion value); + public: + + // int32 cross_program_prefetch_index = 80; + bool has_cross_program_prefetch_index() const; + private: + bool _internal_has_cross_program_prefetch_index() const; + public: + void clear_cross_program_prefetch_index(); + int32_t cross_program_prefetch_index() const; + void set_cross_program_prefetch_index(int32_t value); + private: + int32_t _internal_cross_program_prefetch_index() const; + void _internal_set_cross_program_prefetch_index(int32_t value); + public: + + void clear_optional_cross_program_prefetch_index(); + OptionalCrossProgramPrefetchIndexCase optional_cross_program_prefetch_index_case() const; + // @@protoc_insertion_point(class_scope:xla.HloInstructionProto) + private: + class _Internal; + void set_has_cross_program_prefetch_index(); + + inline bool has_optional_cross_program_prefetch_index() const; + inline void clear_has_optional_cross_program_prefetch_index(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > dimensions_; + mutable std::atomic _dimensions_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto_SliceDimensions > slice_dimensions_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > dynamic_slice_sizes_; + mutable std::atomic _dynamic_slice_sizes_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > fft_length_; + mutable std::atomic _fft_length_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > gather_slice_sizes_; + mutable std::atomic _gather_slice_sizes_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > operand_ids_; + mutable std::atomic _operand_ids_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > control_predecessor_ids_; + mutable std::atomic _control_predecessor_ids_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > called_computation_ids_; + mutable std::atomic _called_computation_ids_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ReplicaGroup > replica_groups_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::SourceTarget > source_target_pairs_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto > operand_shapes_with_layout_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OutputOperandAliasing > output_operand_aliasing_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr opcode_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr fusion_kind_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr outfeed_config_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr infeed_config_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr custom_call_target_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr backend_config_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr comparison_direction_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr comparison_type_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr async_execution_thread_; + ::xla::ShapeProto* shape_; + ::xla::OpMetadata* metadata_; + ::xla::LiteralProto* literal_; + ::xla::Window* window_; + ::xla::ConvolutionDimensionNumbers* convolution_dimension_numbers_; + ::xla::PaddingConfig* padding_config_; + ::xla::ShapeProto* outfeed_shape_; + ::xla::DotDimensionNumbers* dot_dimension_numbers_; + ::xla::GatherDimensionNumbers* gather_dimension_numbers_; + ::xla::OpSharding* sharding_; + ::xla::ScatterDimensionNumbers* scatter_dimension_numbers_; + ::xla::PrecisionConfig* precision_config_; + ::xla::OpSharding* domain_entry_sharding_; + ::xla::OpSharding* domain_exit_sharding_; + ::xla::TriangularSolveOptions* triangular_solve_options_; + ::xla::ParameterReplication* parameter_replication_; + ::xla::CholeskyOptions* cholesky_options_; + ::xla::FrontendAttributes* frontend_attributes_; + ::xla::StatisticsViz* statistics_viz_; + int64_t parameter_number_; + int64_t tuple_index_; + int32_t exponent_bits_; + int32_t mantissa_bits_; + int distribution_; + float epsilon_; + int64_t feature_index_; + int64_t channel_id_; + int64_t id_; + int64_t all_reduce_id_; + int64_t feature_group_count_; + int fft_type_; + bool use_global_device_ids_; + bool is_host_transfer_; + bool is_stable_; + bool constrain_layout_; + int64_t batch_group_count_; + int64_t delta_; + bool custom_call_has_side_effect_; + bool indices_are_sorted_; + bool unique_indices_; + bool is_cross_program_prefetch_; + int rng_algorithm_; + int padding_type_; + int custom_call_schedule_; + int64_t async_group_id_; + int64_t k_; + int custom_call_api_version_; + union OptionalCrossProgramPrefetchIndexUnion { + constexpr OptionalCrossProgramPrefetchIndexUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int32_t cross_program_prefetch_index_; + } optional_cross_program_prefetch_index_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloComputationProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloComputationProto) */ { + public: + inline HloComputationProto() : HloComputationProto(nullptr) {} + ~HloComputationProto() override; + explicit PROTOBUF_CONSTEXPR HloComputationProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloComputationProto(const HloComputationProto& from); + HloComputationProto(HloComputationProto&& from) noexcept + : HloComputationProto() { + *this = ::std::move(from); + } + + inline HloComputationProto& operator=(const HloComputationProto& from) { + CopyFrom(from); + return *this; + } + inline HloComputationProto& operator=(HloComputationProto&& 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 HloComputationProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloComputationProto* internal_default_instance() { + return reinterpret_cast( + &_HloComputationProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(HloComputationProto& a, HloComputationProto& b) { + a.Swap(&b); + } + inline void Swap(HloComputationProto* 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(HloComputationProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloComputationProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloComputationProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloComputationProto& from) { + HloComputationProto::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(HloComputationProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloComputationProto"; + } + protected: + explicit HloComputationProto(::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 { + kInstructionsFieldNumber = 2, + kNameFieldNumber = 1, + kExecutionThreadFieldNumber = 8, + kProgramShapeFieldNumber = 4, + kIdFieldNumber = 5, + kRootIdFieldNumber = 6, + kIsFusionComputationFieldNumber = 7, + }; + // repeated .xla.HloInstructionProto instructions = 2; + int instructions_size() const; + private: + int _internal_instructions_size() const; + public: + void clear_instructions(); + ::xla::HloInstructionProto* mutable_instructions(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto >* + mutable_instructions(); + private: + const ::xla::HloInstructionProto& _internal_instructions(int index) const; + ::xla::HloInstructionProto* _internal_add_instructions(); + public: + const ::xla::HloInstructionProto& instructions(int index) const; + ::xla::HloInstructionProto* add_instructions(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto >& + instructions() 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: + + // string execution_thread = 8; + void clear_execution_thread(); + const std::string& execution_thread() const; + template + void set_execution_thread(ArgT0&& arg0, ArgT... args); + std::string* mutable_execution_thread(); + PROTOBUF_NODISCARD std::string* release_execution_thread(); + void set_allocated_execution_thread(std::string* execution_thread); + private: + const std::string& _internal_execution_thread() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_execution_thread(const std::string& value); + std::string* _internal_mutable_execution_thread(); + public: + + // .xla.ProgramShapeProto program_shape = 4; + bool has_program_shape() const; + private: + bool _internal_has_program_shape() const; + public: + void clear_program_shape(); + const ::xla::ProgramShapeProto& program_shape() const; + PROTOBUF_NODISCARD ::xla::ProgramShapeProto* release_program_shape(); + ::xla::ProgramShapeProto* mutable_program_shape(); + void set_allocated_program_shape(::xla::ProgramShapeProto* program_shape); + private: + const ::xla::ProgramShapeProto& _internal_program_shape() const; + ::xla::ProgramShapeProto* _internal_mutable_program_shape(); + public: + void unsafe_arena_set_allocated_program_shape( + ::xla::ProgramShapeProto* program_shape); + ::xla::ProgramShapeProto* unsafe_arena_release_program_shape(); + + // int64 id = 5; + void clear_id(); + int64_t id() const; + void set_id(int64_t value); + private: + int64_t _internal_id() const; + void _internal_set_id(int64_t value); + public: + + // int64 root_id = 6; + void clear_root_id(); + int64_t root_id() const; + void set_root_id(int64_t value); + private: + int64_t _internal_root_id() const; + void _internal_set_root_id(int64_t value); + public: + + // bool is_fusion_computation = 7; + void clear_is_fusion_computation(); + bool is_fusion_computation() const; + void set_is_fusion_computation(bool value); + private: + bool _internal_is_fusion_computation() const; + void _internal_set_is_fusion_computation(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloComputationProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto > instructions_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr execution_thread_; + ::xla::ProgramShapeProto* program_shape_; + int64_t id_; + int64_t root_id_; + bool is_fusion_computation_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloScheduleProto_InstructionSequence final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloScheduleProto.InstructionSequence) */ { + public: + inline HloScheduleProto_InstructionSequence() : HloScheduleProto_InstructionSequence(nullptr) {} + ~HloScheduleProto_InstructionSequence() override; + explicit PROTOBUF_CONSTEXPR HloScheduleProto_InstructionSequence(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloScheduleProto_InstructionSequence(const HloScheduleProto_InstructionSequence& from); + HloScheduleProto_InstructionSequence(HloScheduleProto_InstructionSequence&& from) noexcept + : HloScheduleProto_InstructionSequence() { + *this = ::std::move(from); + } + + inline HloScheduleProto_InstructionSequence& operator=(const HloScheduleProto_InstructionSequence& from) { + CopyFrom(from); + return *this; + } + inline HloScheduleProto_InstructionSequence& operator=(HloScheduleProto_InstructionSequence&& 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 HloScheduleProto_InstructionSequence& default_instance() { + return *internal_default_instance(); + } + static inline const HloScheduleProto_InstructionSequence* internal_default_instance() { + return reinterpret_cast( + &_HloScheduleProto_InstructionSequence_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(HloScheduleProto_InstructionSequence& a, HloScheduleProto_InstructionSequence& b) { + a.Swap(&b); + } + inline void Swap(HloScheduleProto_InstructionSequence* 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(HloScheduleProto_InstructionSequence* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloScheduleProto_InstructionSequence* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloScheduleProto_InstructionSequence& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloScheduleProto_InstructionSequence& from) { + HloScheduleProto_InstructionSequence::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(HloScheduleProto_InstructionSequence* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloScheduleProto.InstructionSequence"; + } + protected: + explicit HloScheduleProto_InstructionSequence(::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 { + kInstructionIdsFieldNumber = 1, + }; + // repeated int64 instruction_ids = 1; + int instruction_ids_size() const; + private: + int _internal_instruction_ids_size() const; + public: + void clear_instruction_ids(); + private: + int64_t _internal_instruction_ids(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_instruction_ids() const; + void _internal_add_instruction_ids(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_instruction_ids(); + public: + int64_t instruction_ids(int index) const; + void set_instruction_ids(int index, int64_t value); + void add_instruction_ids(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + instruction_ids() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_instruction_ids(); + + // @@protoc_insertion_point(class_scope:xla.HloScheduleProto.InstructionSequence) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > instruction_ids_; + mutable std::atomic _instruction_ids_cached_byte_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloScheduleProto_SequencesEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + HloScheduleProto_SequencesEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR HloScheduleProto_SequencesEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit HloScheduleProto_SequencesEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const HloScheduleProto_SequencesEntry_DoNotUse& other); + static const HloScheduleProto_SequencesEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_HloScheduleProto_SequencesEntry_DoNotUse_default_instance_); } + static bool ValidateKey(void*) { return true; } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; + +// ------------------------------------------------------------------- + +class HloScheduleProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloScheduleProto) */ { + public: + inline HloScheduleProto() : HloScheduleProto(nullptr) {} + ~HloScheduleProto() override; + explicit PROTOBUF_CONSTEXPR HloScheduleProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloScheduleProto(const HloScheduleProto& from); + HloScheduleProto(HloScheduleProto&& from) noexcept + : HloScheduleProto() { + *this = ::std::move(from); + } + + inline HloScheduleProto& operator=(const HloScheduleProto& from) { + CopyFrom(from); + return *this; + } + inline HloScheduleProto& operator=(HloScheduleProto&& 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 HloScheduleProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloScheduleProto* internal_default_instance() { + return reinterpret_cast( + &_HloScheduleProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 5; + + friend void swap(HloScheduleProto& a, HloScheduleProto& b) { + a.Swap(&b); + } + inline void Swap(HloScheduleProto* 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(HloScheduleProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloScheduleProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloScheduleProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloScheduleProto& from) { + HloScheduleProto::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(HloScheduleProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloScheduleProto"; + } + protected: + explicit HloScheduleProto(::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 ---------------------------------------------------- + + typedef HloScheduleProto_InstructionSequence InstructionSequence; + + // accessors ------------------------------------------------------- + + enum : int { + kSequencesFieldNumber = 1, + }; + // map sequences = 1; + int sequences_size() const; + private: + int _internal_sequences_size() const; + public: + void clear_sequences(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >& + _internal_sequences() const; + ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >* + _internal_mutable_sequences(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >& + sequences() const; + ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >* + mutable_sequences(); + + // @@protoc_insertion_point(class_scope:xla.HloScheduleProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + HloScheduleProto_SequencesEntry_DoNotUse, + int64_t, ::xla::HloScheduleProto_InstructionSequence, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> sequences_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloInputOutputAliasProto_AliasEntryProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloInputOutputAliasProto.AliasEntryProto) */ { + public: + inline HloInputOutputAliasProto_AliasEntryProto() : HloInputOutputAliasProto_AliasEntryProto(nullptr) {} + ~HloInputOutputAliasProto_AliasEntryProto() override; + explicit PROTOBUF_CONSTEXPR HloInputOutputAliasProto_AliasEntryProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInputOutputAliasProto_AliasEntryProto(const HloInputOutputAliasProto_AliasEntryProto& from); + HloInputOutputAliasProto_AliasEntryProto(HloInputOutputAliasProto_AliasEntryProto&& from) noexcept + : HloInputOutputAliasProto_AliasEntryProto() { + *this = ::std::move(from); + } + + inline HloInputOutputAliasProto_AliasEntryProto& operator=(const HloInputOutputAliasProto_AliasEntryProto& from) { + CopyFrom(from); + return *this; + } + inline HloInputOutputAliasProto_AliasEntryProto& operator=(HloInputOutputAliasProto_AliasEntryProto&& 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 HloInputOutputAliasProto_AliasEntryProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloInputOutputAliasProto_AliasEntryProto* internal_default_instance() { + return reinterpret_cast( + &_HloInputOutputAliasProto_AliasEntryProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 6; + + friend void swap(HloInputOutputAliasProto_AliasEntryProto& a, HloInputOutputAliasProto_AliasEntryProto& b) { + a.Swap(&b); + } + inline void Swap(HloInputOutputAliasProto_AliasEntryProto* 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(HloInputOutputAliasProto_AliasEntryProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInputOutputAliasProto_AliasEntryProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInputOutputAliasProto_AliasEntryProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInputOutputAliasProto_AliasEntryProto& from) { + HloInputOutputAliasProto_AliasEntryProto::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(HloInputOutputAliasProto_AliasEntryProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloInputOutputAliasProto.AliasEntryProto"; + } + protected: + explicit HloInputOutputAliasProto_AliasEntryProto(::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 { + kOutputShapeIndexFieldNumber = 1, + kParameterShapeIndexFieldNumber = 3, + kParameterNumberFieldNumber = 2, + kKindFieldNumber = 4, + }; + // repeated int64 output_shape_index = 1; + int output_shape_index_size() const; + private: + int _internal_output_shape_index_size() const; + public: + void clear_output_shape_index(); + private: + int64_t _internal_output_shape_index(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_output_shape_index() const; + void _internal_add_output_shape_index(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_output_shape_index(); + public: + int64_t output_shape_index(int index) const; + void set_output_shape_index(int index, int64_t value); + void add_output_shape_index(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + output_shape_index() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_output_shape_index(); + + // repeated int64 parameter_shape_index = 3; + int parameter_shape_index_size() const; + private: + int _internal_parameter_shape_index_size() const; + public: + void clear_parameter_shape_index(); + private: + int64_t _internal_parameter_shape_index(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_parameter_shape_index() const; + void _internal_add_parameter_shape_index(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_parameter_shape_index(); + public: + int64_t parameter_shape_index(int index) const; + void set_parameter_shape_index(int index, int64_t value); + void add_parameter_shape_index(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + parameter_shape_index() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_parameter_shape_index(); + + // int64 parameter_number = 2; + void clear_parameter_number(); + int64_t parameter_number() const; + void set_parameter_number(int64_t value); + private: + int64_t _internal_parameter_number() const; + void _internal_set_parameter_number(int64_t value); + public: + + // .xla.Kind kind = 4; + void clear_kind(); + ::xla::Kind kind() const; + void set_kind(::xla::Kind value); + private: + ::xla::Kind _internal_kind() const; + void _internal_set_kind(::xla::Kind value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloInputOutputAliasProto.AliasEntryProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > output_shape_index_; + mutable std::atomic _output_shape_index_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > parameter_shape_index_; + mutable std::atomic _parameter_shape_index_cached_byte_size_; + int64_t parameter_number_; + int kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloInputOutputAliasProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloInputOutputAliasProto) */ { + public: + inline HloInputOutputAliasProto() : HloInputOutputAliasProto(nullptr) {} + ~HloInputOutputAliasProto() override; + explicit PROTOBUF_CONSTEXPR HloInputOutputAliasProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInputOutputAliasProto(const HloInputOutputAliasProto& from); + HloInputOutputAliasProto(HloInputOutputAliasProto&& from) noexcept + : HloInputOutputAliasProto() { + *this = ::std::move(from); + } + + inline HloInputOutputAliasProto& operator=(const HloInputOutputAliasProto& from) { + CopyFrom(from); + return *this; + } + inline HloInputOutputAliasProto& operator=(HloInputOutputAliasProto&& 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 HloInputOutputAliasProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloInputOutputAliasProto* internal_default_instance() { + return reinterpret_cast( + &_HloInputOutputAliasProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 7; + + friend void swap(HloInputOutputAliasProto& a, HloInputOutputAliasProto& b) { + a.Swap(&b); + } + inline void Swap(HloInputOutputAliasProto* 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(HloInputOutputAliasProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInputOutputAliasProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInputOutputAliasProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInputOutputAliasProto& from) { + HloInputOutputAliasProto::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(HloInputOutputAliasProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloInputOutputAliasProto"; + } + protected: + explicit HloInputOutputAliasProto(::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 HloInputOutputAliasProto_AliasEntryProto AliasEntryProto; + + // accessors ------------------------------------------------------- + + enum : int { + kEntriesFieldNumber = 1, + }; + // repeated .xla.HloInputOutputAliasProto.AliasEntryProto entries = 1; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + ::xla::HloInputOutputAliasProto_AliasEntryProto* mutable_entries(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInputOutputAliasProto_AliasEntryProto >* + mutable_entries(); + private: + const ::xla::HloInputOutputAliasProto_AliasEntryProto& _internal_entries(int index) const; + ::xla::HloInputOutputAliasProto_AliasEntryProto* _internal_add_entries(); + public: + const ::xla::HloInputOutputAliasProto_AliasEntryProto& entries(int index) const; + ::xla::HloInputOutputAliasProto_AliasEntryProto* add_entries(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInputOutputAliasProto_AliasEntryProto >& + entries() const; + + // @@protoc_insertion_point(class_scope:xla.HloInputOutputAliasProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInputOutputAliasProto_AliasEntryProto > entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloBufferDonorProto_BufferDonorEntryProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloBufferDonorProto.BufferDonorEntryProto) */ { + public: + inline HloBufferDonorProto_BufferDonorEntryProto() : HloBufferDonorProto_BufferDonorEntryProto(nullptr) {} + ~HloBufferDonorProto_BufferDonorEntryProto() override; + explicit PROTOBUF_CONSTEXPR HloBufferDonorProto_BufferDonorEntryProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloBufferDonorProto_BufferDonorEntryProto(const HloBufferDonorProto_BufferDonorEntryProto& from); + HloBufferDonorProto_BufferDonorEntryProto(HloBufferDonorProto_BufferDonorEntryProto&& from) noexcept + : HloBufferDonorProto_BufferDonorEntryProto() { + *this = ::std::move(from); + } + + inline HloBufferDonorProto_BufferDonorEntryProto& operator=(const HloBufferDonorProto_BufferDonorEntryProto& from) { + CopyFrom(from); + return *this; + } + inline HloBufferDonorProto_BufferDonorEntryProto& operator=(HloBufferDonorProto_BufferDonorEntryProto&& 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 HloBufferDonorProto_BufferDonorEntryProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloBufferDonorProto_BufferDonorEntryProto* internal_default_instance() { + return reinterpret_cast( + &_HloBufferDonorProto_BufferDonorEntryProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 8; + + friend void swap(HloBufferDonorProto_BufferDonorEntryProto& a, HloBufferDonorProto_BufferDonorEntryProto& b) { + a.Swap(&b); + } + inline void Swap(HloBufferDonorProto_BufferDonorEntryProto* 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(HloBufferDonorProto_BufferDonorEntryProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloBufferDonorProto_BufferDonorEntryProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloBufferDonorProto_BufferDonorEntryProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloBufferDonorProto_BufferDonorEntryProto& from) { + HloBufferDonorProto_BufferDonorEntryProto::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(HloBufferDonorProto_BufferDonorEntryProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloBufferDonorProto.BufferDonorEntryProto"; + } + protected: + explicit HloBufferDonorProto_BufferDonorEntryProto(::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 { + kParameterShapeIndexFieldNumber = 2, + kParameterNumberFieldNumber = 1, + }; + // repeated int64 parameter_shape_index = 2; + int parameter_shape_index_size() const; + private: + int _internal_parameter_shape_index_size() const; + public: + void clear_parameter_shape_index(); + private: + int64_t _internal_parameter_shape_index(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_parameter_shape_index() const; + void _internal_add_parameter_shape_index(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_parameter_shape_index(); + public: + int64_t parameter_shape_index(int index) const; + void set_parameter_shape_index(int index, int64_t value); + void add_parameter_shape_index(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + parameter_shape_index() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_parameter_shape_index(); + + // int64 parameter_number = 1; + void clear_parameter_number(); + int64_t parameter_number() const; + void set_parameter_number(int64_t value); + private: + int64_t _internal_parameter_number() const; + void _internal_set_parameter_number(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloBufferDonorProto.BufferDonorEntryProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > parameter_shape_index_; + mutable std::atomic _parameter_shape_index_cached_byte_size_; + int64_t parameter_number_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloBufferDonorProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloBufferDonorProto) */ { + public: + inline HloBufferDonorProto() : HloBufferDonorProto(nullptr) {} + ~HloBufferDonorProto() override; + explicit PROTOBUF_CONSTEXPR HloBufferDonorProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloBufferDonorProto(const HloBufferDonorProto& from); + HloBufferDonorProto(HloBufferDonorProto&& from) noexcept + : HloBufferDonorProto() { + *this = ::std::move(from); + } + + inline HloBufferDonorProto& operator=(const HloBufferDonorProto& from) { + CopyFrom(from); + return *this; + } + inline HloBufferDonorProto& operator=(HloBufferDonorProto&& 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 HloBufferDonorProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloBufferDonorProto* internal_default_instance() { + return reinterpret_cast( + &_HloBufferDonorProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 9; + + friend void swap(HloBufferDonorProto& a, HloBufferDonorProto& b) { + a.Swap(&b); + } + inline void Swap(HloBufferDonorProto* 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(HloBufferDonorProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloBufferDonorProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloBufferDonorProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloBufferDonorProto& from) { + HloBufferDonorProto::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(HloBufferDonorProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloBufferDonorProto"; + } + protected: + explicit HloBufferDonorProto(::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 HloBufferDonorProto_BufferDonorEntryProto BufferDonorEntryProto; + + // accessors ------------------------------------------------------- + + enum : int { + kEntriesFieldNumber = 1, + }; + // repeated .xla.HloBufferDonorProto.BufferDonorEntryProto entries = 1; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + ::xla::HloBufferDonorProto_BufferDonorEntryProto* mutable_entries(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloBufferDonorProto_BufferDonorEntryProto >* + mutable_entries(); + private: + const ::xla::HloBufferDonorProto_BufferDonorEntryProto& _internal_entries(int index) const; + ::xla::HloBufferDonorProto_BufferDonorEntryProto* _internal_add_entries(); + public: + const ::xla::HloBufferDonorProto_BufferDonorEntryProto& entries(int index) const; + ::xla::HloBufferDonorProto_BufferDonorEntryProto* add_entries(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloBufferDonorProto_BufferDonorEntryProto >& + entries() const; + + // @@protoc_insertion_point(class_scope:xla.HloBufferDonorProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloBufferDonorProto_BufferDonorEntryProto > entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class CrossProgramPrefetch final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.CrossProgramPrefetch) */ { + public: + inline CrossProgramPrefetch() : CrossProgramPrefetch(nullptr) {} + ~CrossProgramPrefetch() override; + explicit PROTOBUF_CONSTEXPR CrossProgramPrefetch(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CrossProgramPrefetch(const CrossProgramPrefetch& from); + CrossProgramPrefetch(CrossProgramPrefetch&& from) noexcept + : CrossProgramPrefetch() { + *this = ::std::move(from); + } + + inline CrossProgramPrefetch& operator=(const CrossProgramPrefetch& from) { + CopyFrom(from); + return *this; + } + inline CrossProgramPrefetch& operator=(CrossProgramPrefetch&& 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 CrossProgramPrefetch& default_instance() { + return *internal_default_instance(); + } + static inline const CrossProgramPrefetch* internal_default_instance() { + return reinterpret_cast( + &_CrossProgramPrefetch_default_instance_); + } + static constexpr int kIndexInFileMessages = + 10; + + friend void swap(CrossProgramPrefetch& a, CrossProgramPrefetch& b) { + a.Swap(&b); + } + inline void Swap(CrossProgramPrefetch* 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(CrossProgramPrefetch* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CrossProgramPrefetch* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CrossProgramPrefetch& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CrossProgramPrefetch& from) { + CrossProgramPrefetch::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(CrossProgramPrefetch* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.CrossProgramPrefetch"; + } + protected: + explicit CrossProgramPrefetch(::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 { + kIndexFieldNumber = 2, + kParameterFieldNumber = 1, + kOffsetFieldNumber = 3, + }; + // repeated int64 index = 2; + int index_size() const; + private: + int _internal_index_size() const; + public: + void clear_index(); + private: + int64_t _internal_index(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_index() const; + void _internal_add_index(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_index(); + public: + int64_t index(int index) const; + void set_index(int index, int64_t value); + void add_index(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + index() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_index(); + + // int64 parameter = 1; + void clear_parameter(); + int64_t parameter() const; + void set_parameter(int64_t value); + private: + int64_t _internal_parameter() const; + void _internal_set_parameter(int64_t value); + public: + + // int64 offset = 3; + void clear_offset(); + int64_t offset() const; + void set_offset(int64_t value); + private: + int64_t _internal_offset() const; + void _internal_set_offset(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.CrossProgramPrefetch) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > index_; + mutable std::atomic _index_cached_byte_size_; + int64_t parameter_; + int64_t offset_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class StackFrameIndexProto_FileLocation final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.StackFrameIndexProto.FileLocation) */ { + public: + inline StackFrameIndexProto_FileLocation() : StackFrameIndexProto_FileLocation(nullptr) {} + ~StackFrameIndexProto_FileLocation() override; + explicit PROTOBUF_CONSTEXPR StackFrameIndexProto_FileLocation(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + StackFrameIndexProto_FileLocation(const StackFrameIndexProto_FileLocation& from); + StackFrameIndexProto_FileLocation(StackFrameIndexProto_FileLocation&& from) noexcept + : StackFrameIndexProto_FileLocation() { + *this = ::std::move(from); + } + + inline StackFrameIndexProto_FileLocation& operator=(const StackFrameIndexProto_FileLocation& from) { + CopyFrom(from); + return *this; + } + inline StackFrameIndexProto_FileLocation& operator=(StackFrameIndexProto_FileLocation&& 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 StackFrameIndexProto_FileLocation& default_instance() { + return *internal_default_instance(); + } + static inline const StackFrameIndexProto_FileLocation* internal_default_instance() { + return reinterpret_cast( + &_StackFrameIndexProto_FileLocation_default_instance_); + } + static constexpr int kIndexInFileMessages = + 11; + + friend void swap(StackFrameIndexProto_FileLocation& a, StackFrameIndexProto_FileLocation& b) { + a.Swap(&b); + } + inline void Swap(StackFrameIndexProto_FileLocation* 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(StackFrameIndexProto_FileLocation* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + StackFrameIndexProto_FileLocation* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const StackFrameIndexProto_FileLocation& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const StackFrameIndexProto_FileLocation& from) { + StackFrameIndexProto_FileLocation::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(StackFrameIndexProto_FileLocation* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.StackFrameIndexProto.FileLocation"; + } + protected: + explicit StackFrameIndexProto_FileLocation(::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 { + kFileNameIdFieldNumber = 1, + kFunctionNameIdFieldNumber = 2, + kLineFieldNumber = 3, + kColumnFieldNumber = 4, + }; + // int32 file_name_id = 1; + void clear_file_name_id(); + int32_t file_name_id() const; + void set_file_name_id(int32_t value); + private: + int32_t _internal_file_name_id() const; + void _internal_set_file_name_id(int32_t value); + public: + + // int32 function_name_id = 2; + void clear_function_name_id(); + int32_t function_name_id() const; + void set_function_name_id(int32_t value); + private: + int32_t _internal_function_name_id() const; + void _internal_set_function_name_id(int32_t value); + public: + + // int32 line = 3; + void clear_line(); + int32_t line() const; + void set_line(int32_t value); + private: + int32_t _internal_line() const; + void _internal_set_line(int32_t value); + public: + + // int32 column = 4; + void clear_column(); + int32_t column() const; + void set_column(int32_t value); + private: + int32_t _internal_column() const; + void _internal_set_column(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.StackFrameIndexProto.FileLocation) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t file_name_id_; + int32_t function_name_id_; + int32_t line_; + int32_t column_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class StackFrameIndexProto_StackFrame final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.StackFrameIndexProto.StackFrame) */ { + public: + inline StackFrameIndexProto_StackFrame() : StackFrameIndexProto_StackFrame(nullptr) {} + ~StackFrameIndexProto_StackFrame() override; + explicit PROTOBUF_CONSTEXPR StackFrameIndexProto_StackFrame(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + StackFrameIndexProto_StackFrame(const StackFrameIndexProto_StackFrame& from); + StackFrameIndexProto_StackFrame(StackFrameIndexProto_StackFrame&& from) noexcept + : StackFrameIndexProto_StackFrame() { + *this = ::std::move(from); + } + + inline StackFrameIndexProto_StackFrame& operator=(const StackFrameIndexProto_StackFrame& from) { + CopyFrom(from); + return *this; + } + inline StackFrameIndexProto_StackFrame& operator=(StackFrameIndexProto_StackFrame&& 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 StackFrameIndexProto_StackFrame& default_instance() { + return *internal_default_instance(); + } + static inline const StackFrameIndexProto_StackFrame* internal_default_instance() { + return reinterpret_cast( + &_StackFrameIndexProto_StackFrame_default_instance_); + } + static constexpr int kIndexInFileMessages = + 12; + + friend void swap(StackFrameIndexProto_StackFrame& a, StackFrameIndexProto_StackFrame& b) { + a.Swap(&b); + } + inline void Swap(StackFrameIndexProto_StackFrame* 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(StackFrameIndexProto_StackFrame* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + StackFrameIndexProto_StackFrame* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const StackFrameIndexProto_StackFrame& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const StackFrameIndexProto_StackFrame& from) { + StackFrameIndexProto_StackFrame::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(StackFrameIndexProto_StackFrame* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.StackFrameIndexProto.StackFrame"; + } + protected: + explicit StackFrameIndexProto_StackFrame(::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 { + kFileLocationIdFieldNumber = 1, + kParentFrameIdFieldNumber = 2, + }; + // int32 file_location_id = 1; + void clear_file_location_id(); + int32_t file_location_id() const; + void set_file_location_id(int32_t value); + private: + int32_t _internal_file_location_id() const; + void _internal_set_file_location_id(int32_t value); + public: + + // int32 parent_frame_id = 2; + void clear_parent_frame_id(); + int32_t parent_frame_id() const; + void set_parent_frame_id(int32_t value); + private: + int32_t _internal_parent_frame_id() const; + void _internal_set_parent_frame_id(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.StackFrameIndexProto.StackFrame) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t file_location_id_; + int32_t parent_frame_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class StackFrameIndexProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.StackFrameIndexProto) */ { + public: + inline StackFrameIndexProto() : StackFrameIndexProto(nullptr) {} + ~StackFrameIndexProto() override; + explicit PROTOBUF_CONSTEXPR StackFrameIndexProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + StackFrameIndexProto(const StackFrameIndexProto& from); + StackFrameIndexProto(StackFrameIndexProto&& from) noexcept + : StackFrameIndexProto() { + *this = ::std::move(from); + } + + inline StackFrameIndexProto& operator=(const StackFrameIndexProto& from) { + CopyFrom(from); + return *this; + } + inline StackFrameIndexProto& operator=(StackFrameIndexProto&& 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 StackFrameIndexProto& default_instance() { + return *internal_default_instance(); + } + static inline const StackFrameIndexProto* internal_default_instance() { + return reinterpret_cast( + &_StackFrameIndexProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 13; + + friend void swap(StackFrameIndexProto& a, StackFrameIndexProto& b) { + a.Swap(&b); + } + inline void Swap(StackFrameIndexProto* 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(StackFrameIndexProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + StackFrameIndexProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const StackFrameIndexProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const StackFrameIndexProto& from) { + StackFrameIndexProto::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(StackFrameIndexProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.StackFrameIndexProto"; + } + protected: + explicit StackFrameIndexProto(::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 StackFrameIndexProto_FileLocation FileLocation; + typedef StackFrameIndexProto_StackFrame StackFrame; + + // accessors ------------------------------------------------------- + + enum : int { + kFileNamesFieldNumber = 1, + kFunctionNamesFieldNumber = 2, + kFileLocationsFieldNumber = 3, + kStackFramesFieldNumber = 4, + }; + // repeated string file_names = 1; + int file_names_size() const; + private: + int _internal_file_names_size() const; + public: + void clear_file_names(); + const std::string& file_names(int index) const; + std::string* mutable_file_names(int index); + void set_file_names(int index, const std::string& value); + void set_file_names(int index, std::string&& value); + void set_file_names(int index, const char* value); + void set_file_names(int index, const char* value, size_t size); + std::string* add_file_names(); + void add_file_names(const std::string& value); + void add_file_names(std::string&& value); + void add_file_names(const char* value); + void add_file_names(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& file_names() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_file_names(); + private: + const std::string& _internal_file_names(int index) const; + std::string* _internal_add_file_names(); + public: + + // repeated string function_names = 2; + int function_names_size() const; + private: + int _internal_function_names_size() const; + public: + void clear_function_names(); + const std::string& function_names(int index) const; + std::string* mutable_function_names(int index); + void set_function_names(int index, const std::string& value); + void set_function_names(int index, std::string&& value); + void set_function_names(int index, const char* value); + void set_function_names(int index, const char* value, size_t size); + std::string* add_function_names(); + void add_function_names(const std::string& value); + void add_function_names(std::string&& value); + void add_function_names(const char* value); + void add_function_names(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& function_names() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_function_names(); + private: + const std::string& _internal_function_names(int index) const; + std::string* _internal_add_function_names(); + public: + + // repeated .xla.StackFrameIndexProto.FileLocation file_locations = 3; + int file_locations_size() const; + private: + int _internal_file_locations_size() const; + public: + void clear_file_locations(); + ::xla::StackFrameIndexProto_FileLocation* mutable_file_locations(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_FileLocation >* + mutable_file_locations(); + private: + const ::xla::StackFrameIndexProto_FileLocation& _internal_file_locations(int index) const; + ::xla::StackFrameIndexProto_FileLocation* _internal_add_file_locations(); + public: + const ::xla::StackFrameIndexProto_FileLocation& file_locations(int index) const; + ::xla::StackFrameIndexProto_FileLocation* add_file_locations(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_FileLocation >& + file_locations() const; + + // repeated .xla.StackFrameIndexProto.StackFrame stack_frames = 4; + int stack_frames_size() const; + private: + int _internal_stack_frames_size() const; + public: + void clear_stack_frames(); + ::xla::StackFrameIndexProto_StackFrame* mutable_stack_frames(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_StackFrame >* + mutable_stack_frames(); + private: + const ::xla::StackFrameIndexProto_StackFrame& _internal_stack_frames(int index) const; + ::xla::StackFrameIndexProto_StackFrame* _internal_add_stack_frames(); + public: + const ::xla::StackFrameIndexProto_StackFrame& stack_frames(int index) const; + ::xla::StackFrameIndexProto_StackFrame* add_stack_frames(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_StackFrame >& + stack_frames() const; + + // @@protoc_insertion_point(class_scope:xla.StackFrameIndexProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField file_names_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField function_names_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_FileLocation > file_locations_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_StackFrame > stack_frames_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloModuleProto_ProfileInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloModuleProto.ProfileInfo) */ { + public: + inline HloModuleProto_ProfileInfo() : HloModuleProto_ProfileInfo(nullptr) {} + ~HloModuleProto_ProfileInfo() override; + explicit PROTOBUF_CONSTEXPR HloModuleProto_ProfileInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloModuleProto_ProfileInfo(const HloModuleProto_ProfileInfo& from); + HloModuleProto_ProfileInfo(HloModuleProto_ProfileInfo&& from) noexcept + : HloModuleProto_ProfileInfo() { + *this = ::std::move(from); + } + + inline HloModuleProto_ProfileInfo& operator=(const HloModuleProto_ProfileInfo& from) { + CopyFrom(from); + return *this; + } + inline HloModuleProto_ProfileInfo& operator=(HloModuleProto_ProfileInfo&& 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 HloModuleProto_ProfileInfo& default_instance() { + return *internal_default_instance(); + } + static inline const HloModuleProto_ProfileInfo* internal_default_instance() { + return reinterpret_cast( + &_HloModuleProto_ProfileInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 14; + + friend void swap(HloModuleProto_ProfileInfo& a, HloModuleProto_ProfileInfo& b) { + a.Swap(&b); + } + inline void Swap(HloModuleProto_ProfileInfo* 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(HloModuleProto_ProfileInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloModuleProto_ProfileInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloModuleProto_ProfileInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloModuleProto_ProfileInfo& from) { + HloModuleProto_ProfileInfo::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(HloModuleProto_ProfileInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloModuleProto.ProfileInfo"; + } + protected: + explicit HloModuleProto_ProfileInfo(::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 { + kRelativeSpeedupFieldNumber = 2, + kProfileTypeFieldNumber = 1, + kProfileSourceFieldNumber = 3, + kCompilationEventFieldNumber = 4, + }; + // double relative_speedup = 2; + void clear_relative_speedup(); + double relative_speedup() const; + void set_relative_speedup(double value); + private: + double _internal_relative_speedup() const; + void _internal_set_relative_speedup(double value); + public: + + // .xla.HloModuleProto.ProfileType profile_type = 1; + void clear_profile_type(); + ::xla::HloModuleProto_ProfileType profile_type() const; + void set_profile_type(::xla::HloModuleProto_ProfileType value); + private: + ::xla::HloModuleProto_ProfileType _internal_profile_type() const; + void _internal_set_profile_type(::xla::HloModuleProto_ProfileType value); + public: + + // .xla.ProfileSource profile_source = 3; + void clear_profile_source(); + ::xla::ProfileSource profile_source() const; + void set_profile_source(::xla::ProfileSource value); + private: + ::xla::ProfileSource _internal_profile_source() const; + void _internal_set_profile_source(::xla::ProfileSource value); + public: + + // .xla.CompilationEvent compilation_event = 4; + void clear_compilation_event(); + ::xla::CompilationEvent compilation_event() const; + void set_compilation_event(::xla::CompilationEvent value); + private: + ::xla::CompilationEvent _internal_compilation_event() const; + void _internal_set_compilation_event(::xla::CompilationEvent value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloModuleProto.ProfileInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + double relative_speedup_; + int profile_type_; + int profile_source_; + int compilation_event_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloModuleProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloModuleProto) */ { + public: + inline HloModuleProto() : HloModuleProto(nullptr) {} + ~HloModuleProto() override; + explicit PROTOBUF_CONSTEXPR HloModuleProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloModuleProto(const HloModuleProto& from); + HloModuleProto(HloModuleProto&& from) noexcept + : HloModuleProto() { + *this = ::std::move(from); + } + + inline HloModuleProto& operator=(const HloModuleProto& from) { + CopyFrom(from); + return *this; + } + inline HloModuleProto& operator=(HloModuleProto&& 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 HloModuleProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloModuleProto* internal_default_instance() { + return reinterpret_cast( + &_HloModuleProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 15; + + friend void swap(HloModuleProto& a, HloModuleProto& b) { + a.Swap(&b); + } + inline void Swap(HloModuleProto* 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(HloModuleProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloModuleProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloModuleProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloModuleProto& from) { + HloModuleProto::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(HloModuleProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloModuleProto"; + } + protected: + explicit HloModuleProto(::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 HloModuleProto_ProfileInfo ProfileInfo; + + typedef HloModuleProto_ProfileType ProfileType; + static constexpr ProfileType INVALID = + HloModuleProto_ProfileType_INVALID; + static constexpr ProfileType FLAG = + HloModuleProto_ProfileType_FLAG; + static constexpr ProfileType FUSION = + HloModuleProto_ProfileType_FUSION; + static constexpr ProfileType LAYOUT = + HloModuleProto_ProfileType_LAYOUT; + static constexpr ProfileType DOT = + HloModuleProto_ProfileType_DOT; + static inline bool ProfileType_IsValid(int value) { + return HloModuleProto_ProfileType_IsValid(value); + } + static constexpr ProfileType ProfileType_MIN = + HloModuleProto_ProfileType_ProfileType_MIN; + static constexpr ProfileType ProfileType_MAX = + HloModuleProto_ProfileType_ProfileType_MAX; + static constexpr int ProfileType_ARRAYSIZE = + HloModuleProto_ProfileType_ProfileType_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + ProfileType_descriptor() { + return HloModuleProto_ProfileType_descriptor(); + } + template + static inline const std::string& ProfileType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function ProfileType_Name."); + return HloModuleProto_ProfileType_Name(enum_t_value); + } + static inline bool ProfileType_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + ProfileType* value) { + return HloModuleProto_ProfileType_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kComputationsFieldNumber = 3, + kCrossProgramPrefetchesFieldNumber = 10, + kProfileInfoFieldNumber = 13, + kSpmdParametersShardingsFieldNumber = 14, + kNameFieldNumber = 1, + kEntryComputationNameFieldNumber = 2, + kHostProgramShapeFieldNumber = 4, + kScheduleFieldNumber = 7, + kInputOutputAliasFieldNumber = 8, + kSpmdOutputShardingFieldNumber = 12, + kDeviceAssignmentFieldNumber = 15, + kStackFrameIndexFieldNumber = 17, + kBufferDonorFieldNumber = 18, + kFrontendAttributesFieldNumber = 19, + kIdFieldNumber = 5, + kEntryComputationIdFieldNumber = 6, + kIsDynamicFieldNumber = 11, + kUseAutoSpmdPartitioningFieldNumber = 16, + }; + // repeated .xla.HloComputationProto computations = 3; + int computations_size() const; + private: + int _internal_computations_size() const; + public: + void clear_computations(); + ::xla::HloComputationProto* mutable_computations(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloComputationProto >* + mutable_computations(); + private: + const ::xla::HloComputationProto& _internal_computations(int index) const; + ::xla::HloComputationProto* _internal_add_computations(); + public: + const ::xla::HloComputationProto& computations(int index) const; + ::xla::HloComputationProto* add_computations(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloComputationProto >& + computations() const; + + // repeated .xla.CrossProgramPrefetch cross_program_prefetches = 10; + int cross_program_prefetches_size() const; + private: + int _internal_cross_program_prefetches_size() const; + public: + void clear_cross_program_prefetches(); + ::xla::CrossProgramPrefetch* mutable_cross_program_prefetches(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::CrossProgramPrefetch >* + mutable_cross_program_prefetches(); + private: + const ::xla::CrossProgramPrefetch& _internal_cross_program_prefetches(int index) const; + ::xla::CrossProgramPrefetch* _internal_add_cross_program_prefetches(); + public: + const ::xla::CrossProgramPrefetch& cross_program_prefetches(int index) const; + ::xla::CrossProgramPrefetch* add_cross_program_prefetches(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::CrossProgramPrefetch >& + cross_program_prefetches() const; + + // repeated .xla.HloModuleProto.ProfileInfo profile_info = 13; + int profile_info_size() const; + private: + int _internal_profile_info_size() const; + public: + void clear_profile_info(); + ::xla::HloModuleProto_ProfileInfo* mutable_profile_info(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto_ProfileInfo >* + mutable_profile_info(); + private: + const ::xla::HloModuleProto_ProfileInfo& _internal_profile_info(int index) const; + ::xla::HloModuleProto_ProfileInfo* _internal_add_profile_info(); + public: + const ::xla::HloModuleProto_ProfileInfo& profile_info(int index) const; + ::xla::HloModuleProto_ProfileInfo* add_profile_info(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto_ProfileInfo >& + profile_info() const; + + // repeated .xla.OpSharding spmd_parameters_shardings = 14; + int spmd_parameters_shardings_size() const; + private: + int _internal_spmd_parameters_shardings_size() const; + public: + void clear_spmd_parameters_shardings(); + ::xla::OpSharding* mutable_spmd_parameters_shardings(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OpSharding >* + mutable_spmd_parameters_shardings(); + private: + const ::xla::OpSharding& _internal_spmd_parameters_shardings(int index) const; + ::xla::OpSharding* _internal_add_spmd_parameters_shardings(); + public: + const ::xla::OpSharding& spmd_parameters_shardings(int index) const; + ::xla::OpSharding* add_spmd_parameters_shardings(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OpSharding >& + spmd_parameters_shardings() 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: + + // string entry_computation_name = 2; + void clear_entry_computation_name(); + const std::string& entry_computation_name() const; + template + void set_entry_computation_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_entry_computation_name(); + PROTOBUF_NODISCARD std::string* release_entry_computation_name(); + void set_allocated_entry_computation_name(std::string* entry_computation_name); + private: + const std::string& _internal_entry_computation_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_entry_computation_name(const std::string& value); + std::string* _internal_mutable_entry_computation_name(); + public: + + // .xla.ProgramShapeProto host_program_shape = 4; + bool has_host_program_shape() const; + private: + bool _internal_has_host_program_shape() const; + public: + void clear_host_program_shape(); + const ::xla::ProgramShapeProto& host_program_shape() const; + PROTOBUF_NODISCARD ::xla::ProgramShapeProto* release_host_program_shape(); + ::xla::ProgramShapeProto* mutable_host_program_shape(); + void set_allocated_host_program_shape(::xla::ProgramShapeProto* host_program_shape); + private: + const ::xla::ProgramShapeProto& _internal_host_program_shape() const; + ::xla::ProgramShapeProto* _internal_mutable_host_program_shape(); + public: + void unsafe_arena_set_allocated_host_program_shape( + ::xla::ProgramShapeProto* host_program_shape); + ::xla::ProgramShapeProto* unsafe_arena_release_host_program_shape(); + + // .xla.HloScheduleProto schedule = 7; + bool has_schedule() const; + private: + bool _internal_has_schedule() const; + public: + void clear_schedule(); + const ::xla::HloScheduleProto& schedule() const; + PROTOBUF_NODISCARD ::xla::HloScheduleProto* release_schedule(); + ::xla::HloScheduleProto* mutable_schedule(); + void set_allocated_schedule(::xla::HloScheduleProto* schedule); + private: + const ::xla::HloScheduleProto& _internal_schedule() const; + ::xla::HloScheduleProto* _internal_mutable_schedule(); + public: + void unsafe_arena_set_allocated_schedule( + ::xla::HloScheduleProto* schedule); + ::xla::HloScheduleProto* unsafe_arena_release_schedule(); + + // .xla.HloInputOutputAliasProto input_output_alias = 8; + bool has_input_output_alias() const; + private: + bool _internal_has_input_output_alias() const; + public: + void clear_input_output_alias(); + const ::xla::HloInputOutputAliasProto& input_output_alias() const; + PROTOBUF_NODISCARD ::xla::HloInputOutputAliasProto* release_input_output_alias(); + ::xla::HloInputOutputAliasProto* mutable_input_output_alias(); + void set_allocated_input_output_alias(::xla::HloInputOutputAliasProto* input_output_alias); + private: + const ::xla::HloInputOutputAliasProto& _internal_input_output_alias() const; + ::xla::HloInputOutputAliasProto* _internal_mutable_input_output_alias(); + public: + void unsafe_arena_set_allocated_input_output_alias( + ::xla::HloInputOutputAliasProto* input_output_alias); + ::xla::HloInputOutputAliasProto* unsafe_arena_release_input_output_alias(); + + // .xla.OpSharding spmd_output_sharding = 12; + bool has_spmd_output_sharding() const; + private: + bool _internal_has_spmd_output_sharding() const; + public: + void clear_spmd_output_sharding(); + const ::xla::OpSharding& spmd_output_sharding() const; + PROTOBUF_NODISCARD ::xla::OpSharding* release_spmd_output_sharding(); + ::xla::OpSharding* mutable_spmd_output_sharding(); + void set_allocated_spmd_output_sharding(::xla::OpSharding* spmd_output_sharding); + private: + const ::xla::OpSharding& _internal_spmd_output_sharding() const; + ::xla::OpSharding* _internal_mutable_spmd_output_sharding(); + public: + void unsafe_arena_set_allocated_spmd_output_sharding( + ::xla::OpSharding* spmd_output_sharding); + ::xla::OpSharding* unsafe_arena_release_spmd_output_sharding(); + + // .xla.DeviceAssignmentProto device_assignment = 15; + bool has_device_assignment() const; + private: + bool _internal_has_device_assignment() const; + public: + void clear_device_assignment(); + const ::xla::DeviceAssignmentProto& device_assignment() const; + PROTOBUF_NODISCARD ::xla::DeviceAssignmentProto* release_device_assignment(); + ::xla::DeviceAssignmentProto* mutable_device_assignment(); + void set_allocated_device_assignment(::xla::DeviceAssignmentProto* device_assignment); + private: + const ::xla::DeviceAssignmentProto& _internal_device_assignment() const; + ::xla::DeviceAssignmentProto* _internal_mutable_device_assignment(); + public: + void unsafe_arena_set_allocated_device_assignment( + ::xla::DeviceAssignmentProto* device_assignment); + ::xla::DeviceAssignmentProto* unsafe_arena_release_device_assignment(); + + // .xla.StackFrameIndexProto stack_frame_index = 17; + bool has_stack_frame_index() const; + private: + bool _internal_has_stack_frame_index() const; + public: + void clear_stack_frame_index(); + const ::xla::StackFrameIndexProto& stack_frame_index() const; + PROTOBUF_NODISCARD ::xla::StackFrameIndexProto* release_stack_frame_index(); + ::xla::StackFrameIndexProto* mutable_stack_frame_index(); + void set_allocated_stack_frame_index(::xla::StackFrameIndexProto* stack_frame_index); + private: + const ::xla::StackFrameIndexProto& _internal_stack_frame_index() const; + ::xla::StackFrameIndexProto* _internal_mutable_stack_frame_index(); + public: + void unsafe_arena_set_allocated_stack_frame_index( + ::xla::StackFrameIndexProto* stack_frame_index); + ::xla::StackFrameIndexProto* unsafe_arena_release_stack_frame_index(); + + // .xla.HloBufferDonorProto buffer_donor = 18; + bool has_buffer_donor() const; + private: + bool _internal_has_buffer_donor() const; + public: + void clear_buffer_donor(); + const ::xla::HloBufferDonorProto& buffer_donor() const; + PROTOBUF_NODISCARD ::xla::HloBufferDonorProto* release_buffer_donor(); + ::xla::HloBufferDonorProto* mutable_buffer_donor(); + void set_allocated_buffer_donor(::xla::HloBufferDonorProto* buffer_donor); + private: + const ::xla::HloBufferDonorProto& _internal_buffer_donor() const; + ::xla::HloBufferDonorProto* _internal_mutable_buffer_donor(); + public: + void unsafe_arena_set_allocated_buffer_donor( + ::xla::HloBufferDonorProto* buffer_donor); + ::xla::HloBufferDonorProto* unsafe_arena_release_buffer_donor(); + + // .xla.FrontendAttributes frontend_attributes = 19; + bool has_frontend_attributes() const; + private: + bool _internal_has_frontend_attributes() const; + public: + void clear_frontend_attributes(); + const ::xla::FrontendAttributes& frontend_attributes() const; + PROTOBUF_NODISCARD ::xla::FrontendAttributes* release_frontend_attributes(); + ::xla::FrontendAttributes* mutable_frontend_attributes(); + void set_allocated_frontend_attributes(::xla::FrontendAttributes* frontend_attributes); + private: + const ::xla::FrontendAttributes& _internal_frontend_attributes() const; + ::xla::FrontendAttributes* _internal_mutable_frontend_attributes(); + public: + void unsafe_arena_set_allocated_frontend_attributes( + ::xla::FrontendAttributes* frontend_attributes); + ::xla::FrontendAttributes* unsafe_arena_release_frontend_attributes(); + + // int64 id = 5; + void clear_id(); + int64_t id() const; + void set_id(int64_t value); + private: + int64_t _internal_id() const; + void _internal_set_id(int64_t value); + public: + + // int64 entry_computation_id = 6; + void clear_entry_computation_id(); + int64_t entry_computation_id() const; + void set_entry_computation_id(int64_t value); + private: + int64_t _internal_entry_computation_id() const; + void _internal_set_entry_computation_id(int64_t value); + public: + + // bool is_dynamic = 11; + void clear_is_dynamic(); + bool is_dynamic() const; + void set_is_dynamic(bool value); + private: + bool _internal_is_dynamic() const; + void _internal_set_is_dynamic(bool value); + public: + + // bool use_auto_spmd_partitioning = 16; + void clear_use_auto_spmd_partitioning(); + bool use_auto_spmd_partitioning() const; + void set_use_auto_spmd_partitioning(bool value); + private: + bool _internal_use_auto_spmd_partitioning() const; + void _internal_set_use_auto_spmd_partitioning(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloModuleProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloComputationProto > computations_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::CrossProgramPrefetch > cross_program_prefetches_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto_ProfileInfo > profile_info_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OpSharding > spmd_parameters_shardings_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr entry_computation_name_; + ::xla::ProgramShapeProto* host_program_shape_; + ::xla::HloScheduleProto* schedule_; + ::xla::HloInputOutputAliasProto* input_output_alias_; + ::xla::OpSharding* spmd_output_sharding_; + ::xla::DeviceAssignmentProto* device_assignment_; + ::xla::StackFrameIndexProto* stack_frame_index_; + ::xla::HloBufferDonorProto* buffer_donor_; + ::xla::FrontendAttributes* frontend_attributes_; + int64_t id_; + int64_t entry_computation_id_; + bool is_dynamic_; + bool use_auto_spmd_partitioning_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class LogicalBufferProto_Location final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.LogicalBufferProto.Location) */ { + public: + inline LogicalBufferProto_Location() : LogicalBufferProto_Location(nullptr) {} + ~LogicalBufferProto_Location() override; + explicit PROTOBUF_CONSTEXPR LogicalBufferProto_Location(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + LogicalBufferProto_Location(const LogicalBufferProto_Location& from); + LogicalBufferProto_Location(LogicalBufferProto_Location&& from) noexcept + : LogicalBufferProto_Location() { + *this = ::std::move(from); + } + + inline LogicalBufferProto_Location& operator=(const LogicalBufferProto_Location& from) { + CopyFrom(from); + return *this; + } + inline LogicalBufferProto_Location& operator=(LogicalBufferProto_Location&& 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 LogicalBufferProto_Location& default_instance() { + return *internal_default_instance(); + } + static inline const LogicalBufferProto_Location* internal_default_instance() { + return reinterpret_cast( + &_LogicalBufferProto_Location_default_instance_); + } + static constexpr int kIndexInFileMessages = + 16; + + friend void swap(LogicalBufferProto_Location& a, LogicalBufferProto_Location& b) { + a.Swap(&b); + } + inline void Swap(LogicalBufferProto_Location* 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(LogicalBufferProto_Location* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + LogicalBufferProto_Location* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const LogicalBufferProto_Location& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const LogicalBufferProto_Location& from) { + LogicalBufferProto_Location::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(LogicalBufferProto_Location* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.LogicalBufferProto.Location"; + } + protected: + explicit LogicalBufferProto_Location(::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 { + kShapeIndexFieldNumber = 3, + kInstructionNameFieldNumber = 2, + kInstructionIdFieldNumber = 4, + }; + // repeated int64 shape_index = 3; + int shape_index_size() const; + private: + int _internal_shape_index_size() const; + public: + void clear_shape_index(); + private: + int64_t _internal_shape_index(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_shape_index() const; + void _internal_add_shape_index(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_shape_index(); + public: + int64_t shape_index(int index) const; + void set_shape_index(int index, int64_t value); + void add_shape_index(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + shape_index() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_shape_index(); + + // string instruction_name = 2 [deprecated = true]; + PROTOBUF_DEPRECATED void clear_instruction_name(); + PROTOBUF_DEPRECATED const std::string& instruction_name() const; + template + PROTOBUF_DEPRECATED void set_instruction_name(ArgT0&& arg0, ArgT... args); + PROTOBUF_DEPRECATED std::string* mutable_instruction_name(); + PROTOBUF_NODISCARD PROTOBUF_DEPRECATED std::string* release_instruction_name(); + PROTOBUF_DEPRECATED void set_allocated_instruction_name(std::string* instruction_name); + private: + const std::string& _internal_instruction_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_instruction_name(const std::string& value); + std::string* _internal_mutable_instruction_name(); + public: + + // int64 instruction_id = 4; + void clear_instruction_id(); + int64_t instruction_id() const; + void set_instruction_id(int64_t value); + private: + int64_t _internal_instruction_id() const; + void _internal_set_instruction_id(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.LogicalBufferProto.Location) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > shape_index_; + mutable std::atomic _shape_index_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr instruction_name_; + int64_t instruction_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class LogicalBufferProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.LogicalBufferProto) */ { + public: + inline LogicalBufferProto() : LogicalBufferProto(nullptr) {} + ~LogicalBufferProto() override; + explicit PROTOBUF_CONSTEXPR LogicalBufferProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + LogicalBufferProto(const LogicalBufferProto& from); + LogicalBufferProto(LogicalBufferProto&& from) noexcept + : LogicalBufferProto() { + *this = ::std::move(from); + } + + inline LogicalBufferProto& operator=(const LogicalBufferProto& from) { + CopyFrom(from); + return *this; + } + inline LogicalBufferProto& operator=(LogicalBufferProto&& 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 LogicalBufferProto& default_instance() { + return *internal_default_instance(); + } + static inline const LogicalBufferProto* internal_default_instance() { + return reinterpret_cast( + &_LogicalBufferProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 17; + + friend void swap(LogicalBufferProto& a, LogicalBufferProto& b) { + a.Swap(&b); + } + inline void Swap(LogicalBufferProto* 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(LogicalBufferProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + LogicalBufferProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const LogicalBufferProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const LogicalBufferProto& from) { + LogicalBufferProto::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(LogicalBufferProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.LogicalBufferProto"; + } + protected: + explicit LogicalBufferProto(::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 LogicalBufferProto_Location Location; + + // accessors ------------------------------------------------------- + + enum : int { + kDefinedAtFieldNumber = 3, + kIdFieldNumber = 1, + kSizeFieldNumber = 2, + kColorFieldNumber = 4, + }; + // .xla.LogicalBufferProto.Location defined_at = 3; + bool has_defined_at() const; + private: + bool _internal_has_defined_at() const; + public: + void clear_defined_at(); + const ::xla::LogicalBufferProto_Location& defined_at() const; + PROTOBUF_NODISCARD ::xla::LogicalBufferProto_Location* release_defined_at(); + ::xla::LogicalBufferProto_Location* mutable_defined_at(); + void set_allocated_defined_at(::xla::LogicalBufferProto_Location* defined_at); + private: + const ::xla::LogicalBufferProto_Location& _internal_defined_at() const; + ::xla::LogicalBufferProto_Location* _internal_mutable_defined_at(); + public: + void unsafe_arena_set_allocated_defined_at( + ::xla::LogicalBufferProto_Location* defined_at); + ::xla::LogicalBufferProto_Location* unsafe_arena_release_defined_at(); + + // int64 id = 1; + void clear_id(); + int64_t id() const; + void set_id(int64_t value); + private: + int64_t _internal_id() const; + void _internal_set_id(int64_t value); + public: + + // int64 size = 2; + void clear_size(); + int64_t size() const; + void set_size(int64_t value); + private: + int64_t _internal_size() const; + void _internal_set_size(int64_t value); + public: + + // int64 color = 4; + void clear_color(); + int64_t color() const; + void set_color(int64_t value); + private: + int64_t _internal_color() const; + void _internal_set_color(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.LogicalBufferProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::LogicalBufferProto_Location* defined_at_; + int64_t id_; + int64_t size_; + int64_t color_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class BufferAllocationProto_Assigned final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.BufferAllocationProto.Assigned) */ { + public: + inline BufferAllocationProto_Assigned() : BufferAllocationProto_Assigned(nullptr) {} + ~BufferAllocationProto_Assigned() override; + explicit PROTOBUF_CONSTEXPR BufferAllocationProto_Assigned(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BufferAllocationProto_Assigned(const BufferAllocationProto_Assigned& from); + BufferAllocationProto_Assigned(BufferAllocationProto_Assigned&& from) noexcept + : BufferAllocationProto_Assigned() { + *this = ::std::move(from); + } + + inline BufferAllocationProto_Assigned& operator=(const BufferAllocationProto_Assigned& from) { + CopyFrom(from); + return *this; + } + inline BufferAllocationProto_Assigned& operator=(BufferAllocationProto_Assigned&& 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 BufferAllocationProto_Assigned& default_instance() { + return *internal_default_instance(); + } + static inline const BufferAllocationProto_Assigned* internal_default_instance() { + return reinterpret_cast( + &_BufferAllocationProto_Assigned_default_instance_); + } + static constexpr int kIndexInFileMessages = + 18; + + friend void swap(BufferAllocationProto_Assigned& a, BufferAllocationProto_Assigned& b) { + a.Swap(&b); + } + inline void Swap(BufferAllocationProto_Assigned* 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(BufferAllocationProto_Assigned* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BufferAllocationProto_Assigned* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BufferAllocationProto_Assigned& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BufferAllocationProto_Assigned& from) { + BufferAllocationProto_Assigned::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(BufferAllocationProto_Assigned* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.BufferAllocationProto.Assigned"; + } + protected: + explicit BufferAllocationProto_Assigned(::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 { + kLogicalBufferIdFieldNumber = 1, + kOffsetFieldNumber = 2, + kSizeFieldNumber = 3, + }; + // int64 logical_buffer_id = 1; + void clear_logical_buffer_id(); + int64_t logical_buffer_id() const; + void set_logical_buffer_id(int64_t value); + private: + int64_t _internal_logical_buffer_id() const; + void _internal_set_logical_buffer_id(int64_t value); + public: + + // int64 offset = 2; + void clear_offset(); + int64_t offset() const; + void set_offset(int64_t value); + private: + int64_t _internal_offset() const; + void _internal_set_offset(int64_t value); + public: + + // int64 size = 3; + void clear_size(); + int64_t size() const; + void set_size(int64_t value); + private: + int64_t _internal_size() const; + void _internal_set_size(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.BufferAllocationProto.Assigned) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t logical_buffer_id_; + int64_t offset_; + int64_t size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class BufferAllocationProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.BufferAllocationProto) */ { + public: + inline BufferAllocationProto() : BufferAllocationProto(nullptr) {} + ~BufferAllocationProto() override; + explicit PROTOBUF_CONSTEXPR BufferAllocationProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BufferAllocationProto(const BufferAllocationProto& from); + BufferAllocationProto(BufferAllocationProto&& from) noexcept + : BufferAllocationProto() { + *this = ::std::move(from); + } + + inline BufferAllocationProto& operator=(const BufferAllocationProto& from) { + CopyFrom(from); + return *this; + } + inline BufferAllocationProto& operator=(BufferAllocationProto&& 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 BufferAllocationProto& default_instance() { + return *internal_default_instance(); + } + static inline const BufferAllocationProto* internal_default_instance() { + return reinterpret_cast( + &_BufferAllocationProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 19; + + friend void swap(BufferAllocationProto& a, BufferAllocationProto& b) { + a.Swap(&b); + } + inline void Swap(BufferAllocationProto* 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(BufferAllocationProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BufferAllocationProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BufferAllocationProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BufferAllocationProto& from) { + BufferAllocationProto::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(BufferAllocationProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.BufferAllocationProto"; + } + protected: + explicit BufferAllocationProto(::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 BufferAllocationProto_Assigned Assigned; + + // accessors ------------------------------------------------------- + + enum : int { + kAssignedFieldNumber = 9, + kParameterShapeIndexFieldNumber = 10, + kIndexFieldNumber = 1, + kSizeFieldNumber = 2, + kParameterNumberFieldNumber = 6, + kMaybeLiveOutFieldNumber = 7, + kIsThreadLocalFieldNumber = 3, + kIsTupleFieldNumber = 11, + kIsEntryComputationParameterFieldNumber = 5, + kIsConstantFieldNumber = 12, + kColorFieldNumber = 8, + }; + // repeated .xla.BufferAllocationProto.Assigned assigned = 9; + int assigned_size() const; + private: + int _internal_assigned_size() const; + public: + void clear_assigned(); + ::xla::BufferAllocationProto_Assigned* mutable_assigned(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto_Assigned >* + mutable_assigned(); + private: + const ::xla::BufferAllocationProto_Assigned& _internal_assigned(int index) const; + ::xla::BufferAllocationProto_Assigned* _internal_add_assigned(); + public: + const ::xla::BufferAllocationProto_Assigned& assigned(int index) const; + ::xla::BufferAllocationProto_Assigned* add_assigned(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto_Assigned >& + assigned() const; + + // repeated int64 parameter_shape_index = 10; + int parameter_shape_index_size() const; + private: + int _internal_parameter_shape_index_size() const; + public: + void clear_parameter_shape_index(); + private: + int64_t _internal_parameter_shape_index(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_parameter_shape_index() const; + void _internal_add_parameter_shape_index(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_parameter_shape_index(); + public: + int64_t parameter_shape_index(int index) const; + void set_parameter_shape_index(int index, int64_t value); + void add_parameter_shape_index(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + parameter_shape_index() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_parameter_shape_index(); + + // int64 index = 1; + void clear_index(); + int64_t index() const; + void set_index(int64_t value); + private: + int64_t _internal_index() const; + void _internal_set_index(int64_t value); + public: + + // int64 size = 2; + void clear_size(); + int64_t size() const; + void set_size(int64_t value); + private: + int64_t _internal_size() const; + void _internal_set_size(int64_t value); + public: + + // int64 parameter_number = 6; + void clear_parameter_number(); + int64_t parameter_number() const; + void set_parameter_number(int64_t value); + private: + int64_t _internal_parameter_number() const; + void _internal_set_parameter_number(int64_t value); + public: + + // bool maybe_live_out = 7; + void clear_maybe_live_out(); + bool maybe_live_out() const; + void set_maybe_live_out(bool value); + private: + bool _internal_maybe_live_out() const; + void _internal_set_maybe_live_out(bool value); + public: + + // bool is_thread_local = 3; + void clear_is_thread_local(); + bool is_thread_local() const; + void set_is_thread_local(bool value); + private: + bool _internal_is_thread_local() const; + void _internal_set_is_thread_local(bool value); + public: + + // bool is_tuple = 11; + void clear_is_tuple(); + bool is_tuple() const; + void set_is_tuple(bool value); + private: + bool _internal_is_tuple() const; + void _internal_set_is_tuple(bool value); + public: + + // bool is_entry_computation_parameter = 5; + void clear_is_entry_computation_parameter(); + bool is_entry_computation_parameter() const; + void set_is_entry_computation_parameter(bool value); + private: + bool _internal_is_entry_computation_parameter() const; + void _internal_set_is_entry_computation_parameter(bool value); + public: + + // bool is_constant = 12; + void clear_is_constant(); + bool is_constant() const; + void set_is_constant(bool value); + private: + bool _internal_is_constant() const; + void _internal_set_is_constant(bool value); + public: + + // int64 color = 8; + void clear_color(); + int64_t color() const; + void set_color(int64_t value); + private: + int64_t _internal_color() const; + void _internal_set_color(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.BufferAllocationProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto_Assigned > assigned_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > parameter_shape_index_; + mutable std::atomic _parameter_shape_index_cached_byte_size_; + int64_t index_; + int64_t size_; + int64_t parameter_number_; + bool maybe_live_out_; + bool is_thread_local_; + bool is_tuple_; + bool is_entry_computation_parameter_; + bool is_constant_; + int64_t color_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HeapSimulatorTrace_Event final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HeapSimulatorTrace.Event) */ { + public: + inline HeapSimulatorTrace_Event() : HeapSimulatorTrace_Event(nullptr) {} + ~HeapSimulatorTrace_Event() override; + explicit PROTOBUF_CONSTEXPR HeapSimulatorTrace_Event(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HeapSimulatorTrace_Event(const HeapSimulatorTrace_Event& from); + HeapSimulatorTrace_Event(HeapSimulatorTrace_Event&& from) noexcept + : HeapSimulatorTrace_Event() { + *this = ::std::move(from); + } + + inline HeapSimulatorTrace_Event& operator=(const HeapSimulatorTrace_Event& from) { + CopyFrom(from); + return *this; + } + inline HeapSimulatorTrace_Event& operator=(HeapSimulatorTrace_Event&& 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 HeapSimulatorTrace_Event& default_instance() { + return *internal_default_instance(); + } + static inline const HeapSimulatorTrace_Event* internal_default_instance() { + return reinterpret_cast( + &_HeapSimulatorTrace_Event_default_instance_); + } + static constexpr int kIndexInFileMessages = + 20; + + friend void swap(HeapSimulatorTrace_Event& a, HeapSimulatorTrace_Event& b) { + a.Swap(&b); + } + inline void Swap(HeapSimulatorTrace_Event* 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(HeapSimulatorTrace_Event* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HeapSimulatorTrace_Event* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HeapSimulatorTrace_Event& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HeapSimulatorTrace_Event& from) { + HeapSimulatorTrace_Event::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(HeapSimulatorTrace_Event* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HeapSimulatorTrace.Event"; + } + protected: + explicit HeapSimulatorTrace_Event(::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 HeapSimulatorTrace_Event_Kind Kind; + static constexpr Kind ALLOC = + HeapSimulatorTrace_Event_Kind_ALLOC; + static constexpr Kind FREE = + HeapSimulatorTrace_Event_Kind_FREE; + static constexpr Kind SHARE_WITH = + HeapSimulatorTrace_Event_Kind_SHARE_WITH; + static inline bool Kind_IsValid(int value) { + return HeapSimulatorTrace_Event_Kind_IsValid(value); + } + static constexpr Kind Kind_MIN = + HeapSimulatorTrace_Event_Kind_Kind_MIN; + static constexpr Kind Kind_MAX = + HeapSimulatorTrace_Event_Kind_Kind_MAX; + static constexpr int Kind_ARRAYSIZE = + HeapSimulatorTrace_Event_Kind_Kind_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + Kind_descriptor() { + return HeapSimulatorTrace_Event_Kind_descriptor(); + } + template + static inline const std::string& Kind_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Kind_Name."); + return HeapSimulatorTrace_Event_Kind_Name(enum_t_value); + } + static inline bool Kind_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + Kind* value) { + return HeapSimulatorTrace_Event_Kind_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kComputationNameFieldNumber = 3, + kInstructionNameFieldNumber = 4, + kBufferIdFieldNumber = 2, + kShareWithCanonicalIdFieldNumber = 5, + kKindFieldNumber = 1, + }; + // string computation_name = 3; + void clear_computation_name(); + const std::string& computation_name() const; + template + void set_computation_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_computation_name(); + PROTOBUF_NODISCARD std::string* release_computation_name(); + void set_allocated_computation_name(std::string* computation_name); + private: + const std::string& _internal_computation_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_computation_name(const std::string& value); + std::string* _internal_mutable_computation_name(); + public: + + // string instruction_name = 4; + void clear_instruction_name(); + const std::string& instruction_name() const; + template + void set_instruction_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_instruction_name(); + PROTOBUF_NODISCARD std::string* release_instruction_name(); + void set_allocated_instruction_name(std::string* instruction_name); + private: + const std::string& _internal_instruction_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_instruction_name(const std::string& value); + std::string* _internal_mutable_instruction_name(); + public: + + // int64 buffer_id = 2; + void clear_buffer_id(); + int64_t buffer_id() const; + void set_buffer_id(int64_t value); + private: + int64_t _internal_buffer_id() const; + void _internal_set_buffer_id(int64_t value); + public: + + // int64 share_with_canonical_id = 5; + void clear_share_with_canonical_id(); + int64_t share_with_canonical_id() const; + void set_share_with_canonical_id(int64_t value); + private: + int64_t _internal_share_with_canonical_id() const; + void _internal_set_share_with_canonical_id(int64_t value); + public: + + // .xla.HeapSimulatorTrace.Event.Kind kind = 1; + void clear_kind(); + ::xla::HeapSimulatorTrace_Event_Kind kind() const; + void set_kind(::xla::HeapSimulatorTrace_Event_Kind value); + private: + ::xla::HeapSimulatorTrace_Event_Kind _internal_kind() const; + void _internal_set_kind(::xla::HeapSimulatorTrace_Event_Kind value); + public: + + // @@protoc_insertion_point(class_scope:xla.HeapSimulatorTrace.Event) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr computation_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr instruction_name_; + int64_t buffer_id_; + int64_t share_with_canonical_id_; + int kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HeapSimulatorTrace final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HeapSimulatorTrace) */ { + public: + inline HeapSimulatorTrace() : HeapSimulatorTrace(nullptr) {} + ~HeapSimulatorTrace() override; + explicit PROTOBUF_CONSTEXPR HeapSimulatorTrace(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HeapSimulatorTrace(const HeapSimulatorTrace& from); + HeapSimulatorTrace(HeapSimulatorTrace&& from) noexcept + : HeapSimulatorTrace() { + *this = ::std::move(from); + } + + inline HeapSimulatorTrace& operator=(const HeapSimulatorTrace& from) { + CopyFrom(from); + return *this; + } + inline HeapSimulatorTrace& operator=(HeapSimulatorTrace&& 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 HeapSimulatorTrace& default_instance() { + return *internal_default_instance(); + } + static inline const HeapSimulatorTrace* internal_default_instance() { + return reinterpret_cast( + &_HeapSimulatorTrace_default_instance_); + } + static constexpr int kIndexInFileMessages = + 21; + + friend void swap(HeapSimulatorTrace& a, HeapSimulatorTrace& b) { + a.Swap(&b); + } + inline void Swap(HeapSimulatorTrace* 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(HeapSimulatorTrace* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HeapSimulatorTrace* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HeapSimulatorTrace& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HeapSimulatorTrace& from) { + HeapSimulatorTrace::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(HeapSimulatorTrace* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HeapSimulatorTrace"; + } + protected: + explicit HeapSimulatorTrace(::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 HeapSimulatorTrace_Event Event; + + // accessors ------------------------------------------------------- + + enum : int { + kEventsFieldNumber = 1, + kBufferAllocationIndexFieldNumber = 3, + kWholeModuleSimulationFieldNumber = 2, + }; + // repeated .xla.HeapSimulatorTrace.Event events = 1; + int events_size() const; + private: + int _internal_events_size() const; + public: + void clear_events(); + ::xla::HeapSimulatorTrace_Event* mutable_events(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace_Event >* + mutable_events(); + private: + const ::xla::HeapSimulatorTrace_Event& _internal_events(int index) const; + ::xla::HeapSimulatorTrace_Event* _internal_add_events(); + public: + const ::xla::HeapSimulatorTrace_Event& events(int index) const; + ::xla::HeapSimulatorTrace_Event* add_events(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace_Event >& + events() const; + + // int64 buffer_allocation_index = 3; + void clear_buffer_allocation_index(); + int64_t buffer_allocation_index() const; + void set_buffer_allocation_index(int64_t value); + private: + int64_t _internal_buffer_allocation_index() const; + void _internal_set_buffer_allocation_index(int64_t value); + public: + + // bool whole_module_simulation = 2; + void clear_whole_module_simulation(); + bool whole_module_simulation() const; + void set_whole_module_simulation(bool value); + private: + bool _internal_whole_module_simulation() const; + void _internal_set_whole_module_simulation(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.HeapSimulatorTrace) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace_Event > events_; + int64_t buffer_allocation_index_; + bool whole_module_simulation_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloModuleGroupProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloModuleGroupProto) */ { + public: + inline HloModuleGroupProto() : HloModuleGroupProto(nullptr) {} + ~HloModuleGroupProto() override; + explicit PROTOBUF_CONSTEXPR HloModuleGroupProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloModuleGroupProto(const HloModuleGroupProto& from); + HloModuleGroupProto(HloModuleGroupProto&& from) noexcept + : HloModuleGroupProto() { + *this = ::std::move(from); + } + + inline HloModuleGroupProto& operator=(const HloModuleGroupProto& from) { + CopyFrom(from); + return *this; + } + inline HloModuleGroupProto& operator=(HloModuleGroupProto&& 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 HloModuleGroupProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloModuleGroupProto* internal_default_instance() { + return reinterpret_cast( + &_HloModuleGroupProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 22; + + friend void swap(HloModuleGroupProto& a, HloModuleGroupProto& b) { + a.Swap(&b); + } + inline void Swap(HloModuleGroupProto* 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(HloModuleGroupProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloModuleGroupProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloModuleGroupProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloModuleGroupProto& from) { + HloModuleGroupProto::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(HloModuleGroupProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloModuleGroupProto"; + } + protected: + explicit HloModuleGroupProto(::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 { + kHloModulesFieldNumber = 2, + kNameFieldNumber = 1, + }; + // repeated .xla.HloModuleProto hlo_modules = 2; + int hlo_modules_size() const; + private: + int _internal_hlo_modules_size() const; + public: + void clear_hlo_modules(); + ::xla::HloModuleProto* mutable_hlo_modules(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto >* + mutable_hlo_modules(); + private: + const ::xla::HloModuleProto& _internal_hlo_modules(int index) const; + ::xla::HloModuleProto* _internal_add_hlo_modules(); + public: + const ::xla::HloModuleProto& hlo_modules(int index) const; + ::xla::HloModuleProto* add_hlo_modules(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto >& + hlo_modules() 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: + + // @@protoc_insertion_point(class_scope:xla.HloModuleGroupProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto > hlo_modules_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class BufferAssignmentProto_BufferAlias final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.BufferAssignmentProto.BufferAlias) */ { + public: + inline BufferAssignmentProto_BufferAlias() : BufferAssignmentProto_BufferAlias(nullptr) {} + ~BufferAssignmentProto_BufferAlias() override; + explicit PROTOBUF_CONSTEXPR BufferAssignmentProto_BufferAlias(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BufferAssignmentProto_BufferAlias(const BufferAssignmentProto_BufferAlias& from); + BufferAssignmentProto_BufferAlias(BufferAssignmentProto_BufferAlias&& from) noexcept + : BufferAssignmentProto_BufferAlias() { + *this = ::std::move(from); + } + + inline BufferAssignmentProto_BufferAlias& operator=(const BufferAssignmentProto_BufferAlias& from) { + CopyFrom(from); + return *this; + } + inline BufferAssignmentProto_BufferAlias& operator=(BufferAssignmentProto_BufferAlias&& 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 BufferAssignmentProto_BufferAlias& default_instance() { + return *internal_default_instance(); + } + static inline const BufferAssignmentProto_BufferAlias* internal_default_instance() { + return reinterpret_cast( + &_BufferAssignmentProto_BufferAlias_default_instance_); + } + static constexpr int kIndexInFileMessages = + 23; + + friend void swap(BufferAssignmentProto_BufferAlias& a, BufferAssignmentProto_BufferAlias& b) { + a.Swap(&b); + } + inline void Swap(BufferAssignmentProto_BufferAlias* 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(BufferAssignmentProto_BufferAlias* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BufferAssignmentProto_BufferAlias* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BufferAssignmentProto_BufferAlias& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BufferAssignmentProto_BufferAlias& from) { + BufferAssignmentProto_BufferAlias::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(BufferAssignmentProto_BufferAlias* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.BufferAssignmentProto.BufferAlias"; + } + protected: + explicit BufferAssignmentProto_BufferAlias(::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 { + kLocationFieldNumber = 2, + kSourceBufferIdFieldNumber = 1, + }; + // .xla.LogicalBufferProto.Location location = 2; + bool has_location() const; + private: + bool _internal_has_location() const; + public: + void clear_location(); + const ::xla::LogicalBufferProto_Location& location() const; + PROTOBUF_NODISCARD ::xla::LogicalBufferProto_Location* release_location(); + ::xla::LogicalBufferProto_Location* mutable_location(); + void set_allocated_location(::xla::LogicalBufferProto_Location* location); + private: + const ::xla::LogicalBufferProto_Location& _internal_location() const; + ::xla::LogicalBufferProto_Location* _internal_mutable_location(); + public: + void unsafe_arena_set_allocated_location( + ::xla::LogicalBufferProto_Location* location); + ::xla::LogicalBufferProto_Location* unsafe_arena_release_location(); + + // int64 source_buffer_id = 1; + void clear_source_buffer_id(); + int64_t source_buffer_id() const; + void set_source_buffer_id(int64_t value); + private: + int64_t _internal_source_buffer_id() const; + void _internal_set_source_buffer_id(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.BufferAssignmentProto.BufferAlias) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::LogicalBufferProto_Location* location_; + int64_t source_buffer_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class BufferAssignmentProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.BufferAssignmentProto) */ { + public: + inline BufferAssignmentProto() : BufferAssignmentProto(nullptr) {} + ~BufferAssignmentProto() override; + explicit PROTOBUF_CONSTEXPR BufferAssignmentProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BufferAssignmentProto(const BufferAssignmentProto& from); + BufferAssignmentProto(BufferAssignmentProto&& from) noexcept + : BufferAssignmentProto() { + *this = ::std::move(from); + } + + inline BufferAssignmentProto& operator=(const BufferAssignmentProto& from) { + CopyFrom(from); + return *this; + } + inline BufferAssignmentProto& operator=(BufferAssignmentProto&& 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 BufferAssignmentProto& default_instance() { + return *internal_default_instance(); + } + static inline const BufferAssignmentProto* internal_default_instance() { + return reinterpret_cast( + &_BufferAssignmentProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 24; + + friend void swap(BufferAssignmentProto& a, BufferAssignmentProto& b) { + a.Swap(&b); + } + inline void Swap(BufferAssignmentProto* 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(BufferAssignmentProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BufferAssignmentProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BufferAssignmentProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BufferAssignmentProto& from) { + BufferAssignmentProto::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(BufferAssignmentProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.BufferAssignmentProto"; + } + protected: + explicit BufferAssignmentProto(::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 BufferAssignmentProto_BufferAlias BufferAlias; + + // accessors ------------------------------------------------------- + + enum : int { + kLogicalBuffersFieldNumber = 1, + kBufferAliasesFieldNumber = 2, + kBufferAllocationsFieldNumber = 3, + kHeapSimulatorTracesFieldNumber = 4, + }; + // repeated .xla.LogicalBufferProto logical_buffers = 1; + int logical_buffers_size() const; + private: + int _internal_logical_buffers_size() const; + public: + void clear_logical_buffers(); + ::xla::LogicalBufferProto* mutable_logical_buffers(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LogicalBufferProto >* + mutable_logical_buffers(); + private: + const ::xla::LogicalBufferProto& _internal_logical_buffers(int index) const; + ::xla::LogicalBufferProto* _internal_add_logical_buffers(); + public: + const ::xla::LogicalBufferProto& logical_buffers(int index) const; + ::xla::LogicalBufferProto* add_logical_buffers(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LogicalBufferProto >& + logical_buffers() const; + + // repeated .xla.BufferAssignmentProto.BufferAlias buffer_aliases = 2; + int buffer_aliases_size() const; + private: + int _internal_buffer_aliases_size() const; + public: + void clear_buffer_aliases(); + ::xla::BufferAssignmentProto_BufferAlias* mutable_buffer_aliases(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAssignmentProto_BufferAlias >* + mutable_buffer_aliases(); + private: + const ::xla::BufferAssignmentProto_BufferAlias& _internal_buffer_aliases(int index) const; + ::xla::BufferAssignmentProto_BufferAlias* _internal_add_buffer_aliases(); + public: + const ::xla::BufferAssignmentProto_BufferAlias& buffer_aliases(int index) const; + ::xla::BufferAssignmentProto_BufferAlias* add_buffer_aliases(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAssignmentProto_BufferAlias >& + buffer_aliases() const; + + // repeated .xla.BufferAllocationProto buffer_allocations = 3; + int buffer_allocations_size() const; + private: + int _internal_buffer_allocations_size() const; + public: + void clear_buffer_allocations(); + ::xla::BufferAllocationProto* mutable_buffer_allocations(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto >* + mutable_buffer_allocations(); + private: + const ::xla::BufferAllocationProto& _internal_buffer_allocations(int index) const; + ::xla::BufferAllocationProto* _internal_add_buffer_allocations(); + public: + const ::xla::BufferAllocationProto& buffer_allocations(int index) const; + ::xla::BufferAllocationProto* add_buffer_allocations(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto >& + buffer_allocations() const; + + // repeated .xla.HeapSimulatorTrace heap_simulator_traces = 4; + int heap_simulator_traces_size() const; + private: + int _internal_heap_simulator_traces_size() const; + public: + void clear_heap_simulator_traces(); + ::xla::HeapSimulatorTrace* mutable_heap_simulator_traces(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace >* + mutable_heap_simulator_traces(); + private: + const ::xla::HeapSimulatorTrace& _internal_heap_simulator_traces(int index) const; + ::xla::HeapSimulatorTrace* _internal_add_heap_simulator_traces(); + public: + const ::xla::HeapSimulatorTrace& heap_simulator_traces(int index) const; + ::xla::HeapSimulatorTrace* add_heap_simulator_traces(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace >& + heap_simulator_traces() const; + + // @@protoc_insertion_point(class_scope:xla.BufferAssignmentProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LogicalBufferProto > logical_buffers_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAssignmentProto_BufferAlias > buffer_aliases_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto > buffer_allocations_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace > heap_simulator_traces_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloProto) */ { + public: + inline HloProto() : HloProto(nullptr) {} + ~HloProto() override; + explicit PROTOBUF_CONSTEXPR HloProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloProto(const HloProto& from); + HloProto(HloProto&& from) noexcept + : HloProto() { + *this = ::std::move(from); + } + + inline HloProto& operator=(const HloProto& from) { + CopyFrom(from); + return *this; + } + inline HloProto& operator=(HloProto&& 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 HloProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloProto* internal_default_instance() { + return reinterpret_cast( + &_HloProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 25; + + friend void swap(HloProto& a, HloProto& b) { + a.Swap(&b); + } + inline void Swap(HloProto* 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(HloProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloProto& from) { + HloProto::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(HloProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloProto"; + } + protected: + explicit HloProto(::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 { + kHloModuleFieldNumber = 1, + kBufferAssignmentFieldNumber = 3, + }; + // .xla.HloModuleProto hlo_module = 1; + bool has_hlo_module() const; + private: + bool _internal_has_hlo_module() const; + public: + void clear_hlo_module(); + const ::xla::HloModuleProto& hlo_module() const; + PROTOBUF_NODISCARD ::xla::HloModuleProto* release_hlo_module(); + ::xla::HloModuleProto* mutable_hlo_module(); + void set_allocated_hlo_module(::xla::HloModuleProto* hlo_module); + private: + const ::xla::HloModuleProto& _internal_hlo_module() const; + ::xla::HloModuleProto* _internal_mutable_hlo_module(); + public: + void unsafe_arena_set_allocated_hlo_module( + ::xla::HloModuleProto* hlo_module); + ::xla::HloModuleProto* unsafe_arena_release_hlo_module(); + + // .xla.BufferAssignmentProto buffer_assignment = 3; + bool has_buffer_assignment() const; + private: + bool _internal_has_buffer_assignment() const; + public: + void clear_buffer_assignment(); + const ::xla::BufferAssignmentProto& buffer_assignment() const; + PROTOBUF_NODISCARD ::xla::BufferAssignmentProto* release_buffer_assignment(); + ::xla::BufferAssignmentProto* mutable_buffer_assignment(); + void set_allocated_buffer_assignment(::xla::BufferAssignmentProto* buffer_assignment); + private: + const ::xla::BufferAssignmentProto& _internal_buffer_assignment() const; + ::xla::BufferAssignmentProto* _internal_mutable_buffer_assignment(); + public: + void unsafe_arena_set_allocated_buffer_assignment( + ::xla::BufferAssignmentProto* buffer_assignment); + ::xla::BufferAssignmentProto* unsafe_arena_release_buffer_assignment(); + + // @@protoc_insertion_point(class_scope:xla.HloProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::HloModuleProto* hlo_module_; + ::xla::BufferAssignmentProto* buffer_assignment_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloSnapshot final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloSnapshot) */ { + public: + inline HloSnapshot() : HloSnapshot(nullptr) {} + ~HloSnapshot() override; + explicit PROTOBUF_CONSTEXPR HloSnapshot(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloSnapshot(const HloSnapshot& from); + HloSnapshot(HloSnapshot&& from) noexcept + : HloSnapshot() { + *this = ::std::move(from); + } + + inline HloSnapshot& operator=(const HloSnapshot& from) { + CopyFrom(from); + return *this; + } + inline HloSnapshot& operator=(HloSnapshot&& 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 HloSnapshot& default_instance() { + return *internal_default_instance(); + } + static inline const HloSnapshot* internal_default_instance() { + return reinterpret_cast( + &_HloSnapshot_default_instance_); + } + static constexpr int kIndexInFileMessages = + 26; + + friend void swap(HloSnapshot& a, HloSnapshot& b) { + a.Swap(&b); + } + inline void Swap(HloSnapshot* 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(HloSnapshot* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloSnapshot* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloSnapshot& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloSnapshot& from) { + HloSnapshot::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(HloSnapshot* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloSnapshot"; + } + protected: + explicit HloSnapshot(::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 { + kArgumentsFieldNumber = 2, + kExecutionPlatformFieldNumber = 4, + kHloFieldNumber = 1, + kResultFieldNumber = 3, + }; + // repeated .xla.LiteralProto arguments = 2; + int arguments_size() const; + private: + int _internal_arguments_size() const; + public: + void clear_arguments(); + ::xla::LiteralProto* mutable_arguments(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LiteralProto >* + mutable_arguments(); + private: + const ::xla::LiteralProto& _internal_arguments(int index) const; + ::xla::LiteralProto* _internal_add_arguments(); + public: + const ::xla::LiteralProto& arguments(int index) const; + ::xla::LiteralProto* add_arguments(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LiteralProto >& + arguments() const; + + // string execution_platform = 4; + void clear_execution_platform(); + const std::string& execution_platform() const; + template + void set_execution_platform(ArgT0&& arg0, ArgT... args); + std::string* mutable_execution_platform(); + PROTOBUF_NODISCARD std::string* release_execution_platform(); + void set_allocated_execution_platform(std::string* execution_platform); + private: + const std::string& _internal_execution_platform() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_execution_platform(const std::string& value); + std::string* _internal_mutable_execution_platform(); + public: + + // .xla.HloProto hlo = 1; + bool has_hlo() const; + private: + bool _internal_has_hlo() const; + public: + void clear_hlo(); + const ::xla::HloProto& hlo() const; + PROTOBUF_NODISCARD ::xla::HloProto* release_hlo(); + ::xla::HloProto* mutable_hlo(); + void set_allocated_hlo(::xla::HloProto* hlo); + private: + const ::xla::HloProto& _internal_hlo() const; + ::xla::HloProto* _internal_mutable_hlo(); + public: + void unsafe_arena_set_allocated_hlo( + ::xla::HloProto* hlo); + ::xla::HloProto* unsafe_arena_release_hlo(); + + // .xla.LiteralProto result = 3; + bool has_result() const; + private: + bool _internal_has_result() const; + public: + void clear_result(); + const ::xla::LiteralProto& result() const; + PROTOBUF_NODISCARD ::xla::LiteralProto* release_result(); + ::xla::LiteralProto* mutable_result(); + void set_allocated_result(::xla::LiteralProto* result); + private: + const ::xla::LiteralProto& _internal_result() const; + ::xla::LiteralProto* _internal_mutable_result(); + public: + void unsafe_arena_set_allocated_result( + ::xla::LiteralProto* result); + ::xla::LiteralProto* unsafe_arena_release_result(); + + // @@protoc_insertion_point(class_scope:xla.HloSnapshot) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LiteralProto > arguments_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr execution_platform_; + ::xla::HloProto* hlo_; + ::xla::LiteralProto* result_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloModuleMetadataProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloModuleMetadataProto) */ { + public: + inline HloModuleMetadataProto() : HloModuleMetadataProto(nullptr) {} + ~HloModuleMetadataProto() override; + explicit PROTOBUF_CONSTEXPR HloModuleMetadataProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloModuleMetadataProto(const HloModuleMetadataProto& from); + HloModuleMetadataProto(HloModuleMetadataProto&& from) noexcept + : HloModuleMetadataProto() { + *this = ::std::move(from); + } + + inline HloModuleMetadataProto& operator=(const HloModuleMetadataProto& from) { + CopyFrom(from); + return *this; + } + inline HloModuleMetadataProto& operator=(HloModuleMetadataProto&& 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 HloModuleMetadataProto& default_instance() { + return *internal_default_instance(); + } + static inline const HloModuleMetadataProto* internal_default_instance() { + return reinterpret_cast( + &_HloModuleMetadataProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 27; + + friend void swap(HloModuleMetadataProto& a, HloModuleMetadataProto& b) { + a.Swap(&b); + } + inline void Swap(HloModuleMetadataProto* 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(HloModuleMetadataProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloModuleMetadataProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloModuleMetadataProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloModuleMetadataProto& from) { + HloModuleMetadataProto::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(HloModuleMetadataProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloModuleMetadataProto"; + } + protected: + explicit HloModuleMetadataProto(::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 { + kPartitionedModuleIdsFieldNumber = 4, + kPassMetadataFieldNumber = 5, + kModuleGroupNameFieldNumber = 2, + kCanonicalModuleIdFieldNumber = 1, + kOriginalModuleIdFieldNumber = 3, + }; + // repeated int64 partitioned_module_ids = 4; + int partitioned_module_ids_size() const; + private: + int _internal_partitioned_module_ids_size() const; + public: + void clear_partitioned_module_ids(); + private: + int64_t _internal_partitioned_module_ids(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_partitioned_module_ids() const; + void _internal_add_partitioned_module_ids(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_partitioned_module_ids(); + public: + int64_t partitioned_module_ids(int index) const; + void set_partitioned_module_ids(int index, int64_t value); + void add_partitioned_module_ids(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + partitioned_module_ids() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_partitioned_module_ids(); + + // repeated .xla.HloPassMetadata pass_metadata = 5; + int pass_metadata_size() const; + private: + int _internal_pass_metadata_size() const; + public: + void clear_pass_metadata(); + ::xla::HloPassMetadata* mutable_pass_metadata(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloPassMetadata >* + mutable_pass_metadata(); + private: + const ::xla::HloPassMetadata& _internal_pass_metadata(int index) const; + ::xla::HloPassMetadata* _internal_add_pass_metadata(); + public: + const ::xla::HloPassMetadata& pass_metadata(int index) const; + ::xla::HloPassMetadata* add_pass_metadata(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloPassMetadata >& + pass_metadata() const; + + // string module_group_name = 2; + void clear_module_group_name(); + const std::string& module_group_name() const; + template + void set_module_group_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_module_group_name(); + PROTOBUF_NODISCARD std::string* release_module_group_name(); + void set_allocated_module_group_name(std::string* module_group_name); + private: + const std::string& _internal_module_group_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_module_group_name(const std::string& value); + std::string* _internal_mutable_module_group_name(); + public: + + // int64 canonical_module_id = 1; + void clear_canonical_module_id(); + int64_t canonical_module_id() const; + void set_canonical_module_id(int64_t value); + private: + int64_t _internal_canonical_module_id() const; + void _internal_set_canonical_module_id(int64_t value); + public: + + // int64 original_module_id = 3; + void clear_original_module_id(); + int64_t original_module_id() const; + void set_original_module_id(int64_t value); + private: + int64_t _internal_original_module_id() const; + void _internal_set_original_module_id(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloModuleMetadataProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > partitioned_module_ids_; + mutable std::atomic _partitioned_module_ids_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloPassMetadata > pass_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr module_group_name_; + int64_t canonical_module_id_; + int64_t original_module_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class HloPassMetadata final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloPassMetadata) */ { + public: + inline HloPassMetadata() : HloPassMetadata(nullptr) {} + ~HloPassMetadata() override; + explicit PROTOBUF_CONSTEXPR HloPassMetadata(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloPassMetadata(const HloPassMetadata& from); + HloPassMetadata(HloPassMetadata&& from) noexcept + : HloPassMetadata() { + *this = ::std::move(from); + } + + inline HloPassMetadata& operator=(const HloPassMetadata& from) { + CopyFrom(from); + return *this; + } + inline HloPassMetadata& operator=(HloPassMetadata&& 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 HloPassMetadata& default_instance() { + return *internal_default_instance(); + } + static inline const HloPassMetadata* internal_default_instance() { + return reinterpret_cast( + &_HloPassMetadata_default_instance_); + } + static constexpr int kIndexInFileMessages = + 28; + + friend void swap(HloPassMetadata& a, HloPassMetadata& b) { + a.Swap(&b); + } + inline void Swap(HloPassMetadata* 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(HloPassMetadata* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloPassMetadata* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloPassMetadata& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloPassMetadata& from) { + HloPassMetadata::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(HloPassMetadata* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloPassMetadata"; + } + protected: + explicit HloPassMetadata(::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 { + kDumpFilenamesFieldNumber = 4, + kModuleGroupModuleIdsFieldNumber = 7, + kPassNameFieldNumber = 2, + kPipelineNameFieldNumber = 3, + kPassIdFieldNumber = 1, + kModuleIdFieldNumber = 6, + kStartTimestampUsecFieldNumber = 8, + kEndTimestampUsecFieldNumber = 9, + kModuleChangedFieldNumber = 5, + }; + // repeated string dump_filenames = 4; + int dump_filenames_size() const; + private: + int _internal_dump_filenames_size() const; + public: + void clear_dump_filenames(); + const std::string& dump_filenames(int index) const; + std::string* mutable_dump_filenames(int index); + void set_dump_filenames(int index, const std::string& value); + void set_dump_filenames(int index, std::string&& value); + void set_dump_filenames(int index, const char* value); + void set_dump_filenames(int index, const char* value, size_t size); + std::string* add_dump_filenames(); + void add_dump_filenames(const std::string& value); + void add_dump_filenames(std::string&& value); + void add_dump_filenames(const char* value); + void add_dump_filenames(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& dump_filenames() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_dump_filenames(); + private: + const std::string& _internal_dump_filenames(int index) const; + std::string* _internal_add_dump_filenames(); + public: + + // repeated int64 module_group_module_ids = 7; + int module_group_module_ids_size() const; + private: + int _internal_module_group_module_ids_size() const; + public: + void clear_module_group_module_ids(); + private: + int64_t _internal_module_group_module_ids(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_module_group_module_ids() const; + void _internal_add_module_group_module_ids(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_module_group_module_ids(); + public: + int64_t module_group_module_ids(int index) const; + void set_module_group_module_ids(int index, int64_t value); + void add_module_group_module_ids(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + module_group_module_ids() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_module_group_module_ids(); + + // string pass_name = 2; + void clear_pass_name(); + const std::string& pass_name() const; + template + void set_pass_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_pass_name(); + PROTOBUF_NODISCARD std::string* release_pass_name(); + void set_allocated_pass_name(std::string* pass_name); + private: + const std::string& _internal_pass_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_pass_name(const std::string& value); + std::string* _internal_mutable_pass_name(); + public: + + // string pipeline_name = 3; + void clear_pipeline_name(); + const std::string& pipeline_name() const; + template + void set_pipeline_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_pipeline_name(); + PROTOBUF_NODISCARD std::string* release_pipeline_name(); + void set_allocated_pipeline_name(std::string* pipeline_name); + private: + const std::string& _internal_pipeline_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_pipeline_name(const std::string& value); + std::string* _internal_mutable_pipeline_name(); + public: + + // int64 pass_id = 1; + void clear_pass_id(); + int64_t pass_id() const; + void set_pass_id(int64_t value); + private: + int64_t _internal_pass_id() const; + void _internal_set_pass_id(int64_t value); + public: + + // int64 module_id = 6; + void clear_module_id(); + int64_t module_id() const; + void set_module_id(int64_t value); + private: + int64_t _internal_module_id() const; + void _internal_set_module_id(int64_t value); + public: + + // int64 start_timestamp_usec = 8; + void clear_start_timestamp_usec(); + int64_t start_timestamp_usec() const; + void set_start_timestamp_usec(int64_t value); + private: + int64_t _internal_start_timestamp_usec() const; + void _internal_set_start_timestamp_usec(int64_t value); + public: + + // int64 end_timestamp_usec = 9; + void clear_end_timestamp_usec(); + int64_t end_timestamp_usec() const; + void set_end_timestamp_usec(int64_t value); + private: + int64_t _internal_end_timestamp_usec() const; + void _internal_set_end_timestamp_usec(int64_t value); + public: + + // bool module_changed = 5; + void clear_module_changed(); + bool module_changed() const; + void set_module_changed(bool value); + private: + bool _internal_module_changed() const; + void _internal_set_module_changed(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloPassMetadata) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField dump_filenames_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > module_group_module_ids_; + mutable std::atomic _module_group_module_ids_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr pass_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr pipeline_name_; + int64_t pass_id_; + int64_t module_id_; + int64_t start_timestamp_usec_; + int64_t end_timestamp_usec_; + bool module_changed_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class EntryFunctionAttributes_ShapeIndex final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.EntryFunctionAttributes.ShapeIndex) */ { + public: + inline EntryFunctionAttributes_ShapeIndex() : EntryFunctionAttributes_ShapeIndex(nullptr) {} + ~EntryFunctionAttributes_ShapeIndex() override; + explicit PROTOBUF_CONSTEXPR EntryFunctionAttributes_ShapeIndex(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EntryFunctionAttributes_ShapeIndex(const EntryFunctionAttributes_ShapeIndex& from); + EntryFunctionAttributes_ShapeIndex(EntryFunctionAttributes_ShapeIndex&& from) noexcept + : EntryFunctionAttributes_ShapeIndex() { + *this = ::std::move(from); + } + + inline EntryFunctionAttributes_ShapeIndex& operator=(const EntryFunctionAttributes_ShapeIndex& from) { + CopyFrom(from); + return *this; + } + inline EntryFunctionAttributes_ShapeIndex& operator=(EntryFunctionAttributes_ShapeIndex&& 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 EntryFunctionAttributes_ShapeIndex& default_instance() { + return *internal_default_instance(); + } + static inline const EntryFunctionAttributes_ShapeIndex* internal_default_instance() { + return reinterpret_cast( + &_EntryFunctionAttributes_ShapeIndex_default_instance_); + } + static constexpr int kIndexInFileMessages = + 29; + + friend void swap(EntryFunctionAttributes_ShapeIndex& a, EntryFunctionAttributes_ShapeIndex& b) { + a.Swap(&b); + } + inline void Swap(EntryFunctionAttributes_ShapeIndex* 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(EntryFunctionAttributes_ShapeIndex* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EntryFunctionAttributes_ShapeIndex* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EntryFunctionAttributes_ShapeIndex& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const EntryFunctionAttributes_ShapeIndex& from) { + EntryFunctionAttributes_ShapeIndex::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(EntryFunctionAttributes_ShapeIndex* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.EntryFunctionAttributes.ShapeIndex"; + } + protected: + explicit EntryFunctionAttributes_ShapeIndex(::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 { + kIndicesFieldNumber = 1, + }; + // repeated int64 indices = 1; + int indices_size() const; + private: + int _internal_indices_size() const; + public: + void clear_indices(); + private: + int64_t _internal_indices(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_indices() const; + void _internal_add_indices(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_indices(); + public: + int64_t indices(int index) const; + void set_indices(int index, int64_t value); + void add_indices(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + indices() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_indices(); + + // @@protoc_insertion_point(class_scope:xla.EntryFunctionAttributes.ShapeIndex) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > indices_; + mutable std::atomic _indices_cached_byte_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class EntryFunctionAttributes_BufferParameterAttributes final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.EntryFunctionAttributes.BufferParameterAttributes) */ { + public: + inline EntryFunctionAttributes_BufferParameterAttributes() : EntryFunctionAttributes_BufferParameterAttributes(nullptr) {} + ~EntryFunctionAttributes_BufferParameterAttributes() override; + explicit PROTOBUF_CONSTEXPR EntryFunctionAttributes_BufferParameterAttributes(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EntryFunctionAttributes_BufferParameterAttributes(const EntryFunctionAttributes_BufferParameterAttributes& from); + EntryFunctionAttributes_BufferParameterAttributes(EntryFunctionAttributes_BufferParameterAttributes&& from) noexcept + : EntryFunctionAttributes_BufferParameterAttributes() { + *this = ::std::move(from); + } + + inline EntryFunctionAttributes_BufferParameterAttributes& operator=(const EntryFunctionAttributes_BufferParameterAttributes& from) { + CopyFrom(from); + return *this; + } + inline EntryFunctionAttributes_BufferParameterAttributes& operator=(EntryFunctionAttributes_BufferParameterAttributes&& 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 EntryFunctionAttributes_BufferParameterAttributes& default_instance() { + return *internal_default_instance(); + } + static inline const EntryFunctionAttributes_BufferParameterAttributes* internal_default_instance() { + return reinterpret_cast( + &_EntryFunctionAttributes_BufferParameterAttributes_default_instance_); + } + static constexpr int kIndexInFileMessages = + 30; + + friend void swap(EntryFunctionAttributes_BufferParameterAttributes& a, EntryFunctionAttributes_BufferParameterAttributes& b) { + a.Swap(&b); + } + inline void Swap(EntryFunctionAttributes_BufferParameterAttributes* 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(EntryFunctionAttributes_BufferParameterAttributes* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EntryFunctionAttributes_BufferParameterAttributes* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EntryFunctionAttributes_BufferParameterAttributes& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const EntryFunctionAttributes_BufferParameterAttributes& from) { + EntryFunctionAttributes_BufferParameterAttributes::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(EntryFunctionAttributes_BufferParameterAttributes* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.EntryFunctionAttributes.BufferParameterAttributes"; + } + protected: + explicit EntryFunctionAttributes_BufferParameterAttributes(::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 { + kLmhloConstantNameFieldNumber = 3, + kLmhloParamShapeIndexFieldNumber = 2, + kLmhloOutputIndexFieldNumber = 5, + kLmhloParamsFieldNumber = 1, + kLmhloParamsPresentFieldNumber = 6, + kLmhloMustAliasFieldNumber = 4, + }; + // string lmhlo_constant_name = 3; + void clear_lmhlo_constant_name(); + const std::string& lmhlo_constant_name() const; + template + void set_lmhlo_constant_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_lmhlo_constant_name(); + PROTOBUF_NODISCARD std::string* release_lmhlo_constant_name(); + void set_allocated_lmhlo_constant_name(std::string* lmhlo_constant_name); + private: + const std::string& _internal_lmhlo_constant_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_lmhlo_constant_name(const std::string& value); + std::string* _internal_mutable_lmhlo_constant_name(); + public: + + // .xla.EntryFunctionAttributes.ShapeIndex lmhlo_param_shape_index = 2; + bool has_lmhlo_param_shape_index() const; + private: + bool _internal_has_lmhlo_param_shape_index() const; + public: + void clear_lmhlo_param_shape_index(); + const ::xla::EntryFunctionAttributes_ShapeIndex& lmhlo_param_shape_index() const; + PROTOBUF_NODISCARD ::xla::EntryFunctionAttributes_ShapeIndex* release_lmhlo_param_shape_index(); + ::xla::EntryFunctionAttributes_ShapeIndex* mutable_lmhlo_param_shape_index(); + void set_allocated_lmhlo_param_shape_index(::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_param_shape_index); + private: + const ::xla::EntryFunctionAttributes_ShapeIndex& _internal_lmhlo_param_shape_index() const; + ::xla::EntryFunctionAttributes_ShapeIndex* _internal_mutable_lmhlo_param_shape_index(); + public: + void unsafe_arena_set_allocated_lmhlo_param_shape_index( + ::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_param_shape_index); + ::xla::EntryFunctionAttributes_ShapeIndex* unsafe_arena_release_lmhlo_param_shape_index(); + + // .xla.EntryFunctionAttributes.ShapeIndex lmhlo_output_index = 5; + bool has_lmhlo_output_index() const; + private: + bool _internal_has_lmhlo_output_index() const; + public: + void clear_lmhlo_output_index(); + const ::xla::EntryFunctionAttributes_ShapeIndex& lmhlo_output_index() const; + PROTOBUF_NODISCARD ::xla::EntryFunctionAttributes_ShapeIndex* release_lmhlo_output_index(); + ::xla::EntryFunctionAttributes_ShapeIndex* mutable_lmhlo_output_index(); + void set_allocated_lmhlo_output_index(::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_output_index); + private: + const ::xla::EntryFunctionAttributes_ShapeIndex& _internal_lmhlo_output_index() const; + ::xla::EntryFunctionAttributes_ShapeIndex* _internal_mutable_lmhlo_output_index(); + public: + void unsafe_arena_set_allocated_lmhlo_output_index( + ::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_output_index); + ::xla::EntryFunctionAttributes_ShapeIndex* unsafe_arena_release_lmhlo_output_index(); + + // int64 lmhlo_params = 1; + void clear_lmhlo_params(); + int64_t lmhlo_params() const; + void set_lmhlo_params(int64_t value); + private: + int64_t _internal_lmhlo_params() const; + void _internal_set_lmhlo_params(int64_t value); + public: + + // bool lmhlo_params_present = 6; + void clear_lmhlo_params_present(); + bool lmhlo_params_present() const; + void set_lmhlo_params_present(bool value); + private: + bool _internal_lmhlo_params_present() const; + void _internal_set_lmhlo_params_present(bool value); + public: + + // bool lmhlo_must_alias = 4; + void clear_lmhlo_must_alias(); + bool lmhlo_must_alias() const; + void set_lmhlo_must_alias(bool value); + private: + bool _internal_lmhlo_must_alias() const; + void _internal_set_lmhlo_must_alias(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.EntryFunctionAttributes.BufferParameterAttributes) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr lmhlo_constant_name_; + ::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_param_shape_index_; + ::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_output_index_; + int64_t lmhlo_params_; + bool lmhlo_params_present_; + bool lmhlo_must_alias_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class EntryFunctionAttributes final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.EntryFunctionAttributes) */ { + public: + inline EntryFunctionAttributes() : EntryFunctionAttributes(nullptr) {} + ~EntryFunctionAttributes() override; + explicit PROTOBUF_CONSTEXPR EntryFunctionAttributes(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EntryFunctionAttributes(const EntryFunctionAttributes& from); + EntryFunctionAttributes(EntryFunctionAttributes&& from) noexcept + : EntryFunctionAttributes() { + *this = ::std::move(from); + } + + inline EntryFunctionAttributes& operator=(const EntryFunctionAttributes& from) { + CopyFrom(from); + return *this; + } + inline EntryFunctionAttributes& operator=(EntryFunctionAttributes&& 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 EntryFunctionAttributes& default_instance() { + return *internal_default_instance(); + } + static inline const EntryFunctionAttributes* internal_default_instance() { + return reinterpret_cast( + &_EntryFunctionAttributes_default_instance_); + } + static constexpr int kIndexInFileMessages = + 31; + + friend void swap(EntryFunctionAttributes& a, EntryFunctionAttributes& b) { + a.Swap(&b); + } + inline void Swap(EntryFunctionAttributes* 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(EntryFunctionAttributes* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EntryFunctionAttributes* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EntryFunctionAttributes& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const EntryFunctionAttributes& from) { + EntryFunctionAttributes::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(EntryFunctionAttributes* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.EntryFunctionAttributes"; + } + protected: + explicit EntryFunctionAttributes(::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 EntryFunctionAttributes_ShapeIndex ShapeIndex; + typedef EntryFunctionAttributes_BufferParameterAttributes BufferParameterAttributes; + + // accessors ------------------------------------------------------- + + enum : int { + kBuffersFieldNumber = 1, + kResultXlaShapeFieldNumber = 2, + }; + // repeated .xla.EntryFunctionAttributes.BufferParameterAttributes buffers = 1; + int buffers_size() const; + private: + int _internal_buffers_size() const; + public: + void clear_buffers(); + ::xla::EntryFunctionAttributes_BufferParameterAttributes* mutable_buffers(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::EntryFunctionAttributes_BufferParameterAttributes >* + mutable_buffers(); + private: + const ::xla::EntryFunctionAttributes_BufferParameterAttributes& _internal_buffers(int index) const; + ::xla::EntryFunctionAttributes_BufferParameterAttributes* _internal_add_buffers(); + public: + const ::xla::EntryFunctionAttributes_BufferParameterAttributes& buffers(int index) const; + ::xla::EntryFunctionAttributes_BufferParameterAttributes* add_buffers(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::EntryFunctionAttributes_BufferParameterAttributes >& + buffers() const; + + // string result_xla_shape = 2; + void clear_result_xla_shape(); + const std::string& result_xla_shape() const; + template + void set_result_xla_shape(ArgT0&& arg0, ArgT... args); + std::string* mutable_result_xla_shape(); + PROTOBUF_NODISCARD std::string* release_result_xla_shape(); + void set_allocated_result_xla_shape(std::string* result_xla_shape); + private: + const std::string& _internal_result_xla_shape() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_result_xla_shape(const std::string& value); + std::string* _internal_mutable_result_xla_shape(); + public: + + // @@protoc_insertion_point(class_scope:xla.EntryFunctionAttributes) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::EntryFunctionAttributes_BufferParameterAttributes > buffers_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr result_xla_shape_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// ------------------------------------------------------------------- + +class XlaRuntimeExecutableProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.XlaRuntimeExecutableProto) */ { + public: + inline XlaRuntimeExecutableProto() : XlaRuntimeExecutableProto(nullptr) {} + ~XlaRuntimeExecutableProto() override; + explicit PROTOBUF_CONSTEXPR XlaRuntimeExecutableProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaRuntimeExecutableProto(const XlaRuntimeExecutableProto& from); + XlaRuntimeExecutableProto(XlaRuntimeExecutableProto&& from) noexcept + : XlaRuntimeExecutableProto() { + *this = ::std::move(from); + } + + inline XlaRuntimeExecutableProto& operator=(const XlaRuntimeExecutableProto& from) { + CopyFrom(from); + return *this; + } + inline XlaRuntimeExecutableProto& operator=(XlaRuntimeExecutableProto&& 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 XlaRuntimeExecutableProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaRuntimeExecutableProto* internal_default_instance() { + return reinterpret_cast( + &_XlaRuntimeExecutableProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 32; + + friend void swap(XlaRuntimeExecutableProto& a, XlaRuntimeExecutableProto& b) { + a.Swap(&b); + } + inline void Swap(XlaRuntimeExecutableProto* 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(XlaRuntimeExecutableProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaRuntimeExecutableProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaRuntimeExecutableProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaRuntimeExecutableProto& from) { + XlaRuntimeExecutableProto::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(XlaRuntimeExecutableProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.XlaRuntimeExecutableProto"; + } + protected: + explicit XlaRuntimeExecutableProto(::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 { + kObjFileFieldNumber = 3, + kMlirModuleFieldNumber = 4, + kHloModuleProtoFieldNumber = 1, + }; + // bytes obj_file = 3; + void clear_obj_file(); + const std::string& obj_file() const; + template + void set_obj_file(ArgT0&& arg0, ArgT... args); + std::string* mutable_obj_file(); + PROTOBUF_NODISCARD std::string* release_obj_file(); + void set_allocated_obj_file(std::string* obj_file); + private: + const std::string& _internal_obj_file() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_obj_file(const std::string& value); + std::string* _internal_mutable_obj_file(); + public: + + // string mlir_module = 4; + void clear_mlir_module(); + const std::string& mlir_module() const; + template + void set_mlir_module(ArgT0&& arg0, ArgT... args); + std::string* mutable_mlir_module(); + PROTOBUF_NODISCARD std::string* release_mlir_module(); + void set_allocated_mlir_module(std::string* mlir_module); + private: + const std::string& _internal_mlir_module() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_mlir_module(const std::string& value); + std::string* _internal_mutable_mlir_module(); + public: + + // .xla.HloModuleProto hlo_module_proto = 1; + bool has_hlo_module_proto() const; + private: + bool _internal_has_hlo_module_proto() const; + public: + void clear_hlo_module_proto(); + const ::xla::HloModuleProto& hlo_module_proto() const; + PROTOBUF_NODISCARD ::xla::HloModuleProto* release_hlo_module_proto(); + ::xla::HloModuleProto* mutable_hlo_module_proto(); + void set_allocated_hlo_module_proto(::xla::HloModuleProto* hlo_module_proto); + private: + const ::xla::HloModuleProto& _internal_hlo_module_proto() const; + ::xla::HloModuleProto* _internal_mutable_hlo_module_proto(); + public: + void unsafe_arena_set_allocated_hlo_module_proto( + ::xla::HloModuleProto* hlo_module_proto); + ::xla::HloModuleProto* unsafe_arena_release_hlo_module_proto(); + + // @@protoc_insertion_point(class_scope:xla.XlaRuntimeExecutableProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr obj_file_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr mlir_module_; + ::xla::HloModuleProto* hlo_module_proto_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// HloInstructionProto_SliceDimensions + +// int64 start = 1; +inline void HloInstructionProto_SliceDimensions::clear_start() { + _impl_.start_ = int64_t{0}; +} +inline int64_t HloInstructionProto_SliceDimensions::_internal_start() const { + return _impl_.start_; +} +inline int64_t HloInstructionProto_SliceDimensions::start() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.SliceDimensions.start) + return _internal_start(); +} +inline void HloInstructionProto_SliceDimensions::_internal_set_start(int64_t value) { + + _impl_.start_ = value; +} +inline void HloInstructionProto_SliceDimensions::set_start(int64_t value) { + _internal_set_start(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.SliceDimensions.start) +} + +// int64 limit = 2; +inline void HloInstructionProto_SliceDimensions::clear_limit() { + _impl_.limit_ = int64_t{0}; +} +inline int64_t HloInstructionProto_SliceDimensions::_internal_limit() const { + return _impl_.limit_; +} +inline int64_t HloInstructionProto_SliceDimensions::limit() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.SliceDimensions.limit) + return _internal_limit(); +} +inline void HloInstructionProto_SliceDimensions::_internal_set_limit(int64_t value) { + + _impl_.limit_ = value; +} +inline void HloInstructionProto_SliceDimensions::set_limit(int64_t value) { + _internal_set_limit(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.SliceDimensions.limit) +} + +// int64 stride = 3; +inline void HloInstructionProto_SliceDimensions::clear_stride() { + _impl_.stride_ = int64_t{0}; +} +inline int64_t HloInstructionProto_SliceDimensions::_internal_stride() const { + return _impl_.stride_; +} +inline int64_t HloInstructionProto_SliceDimensions::stride() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.SliceDimensions.stride) + return _internal_stride(); +} +inline void HloInstructionProto_SliceDimensions::_internal_set_stride(int64_t value) { + + _impl_.stride_ = value; +} +inline void HloInstructionProto_SliceDimensions::set_stride(int64_t value) { + _internal_set_stride(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.SliceDimensions.stride) +} + +// ------------------------------------------------------------------- + +// HloInstructionProto + +// string name = 1; +inline void HloInstructionProto::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::name() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.name) +} +inline std::string* HloInstructionProto::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.name) + return _s; +} +inline const std::string& HloInstructionProto::_internal_name() const { + return _impl_.name_.Get(); +} +inline void HloInstructionProto::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_name() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.name) + return _impl_.name_.Release(); +} +inline void HloInstructionProto::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:xla.HloInstructionProto.name) +} + +// string opcode = 2; +inline void HloInstructionProto::clear_opcode() { + _impl_.opcode_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::opcode() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.opcode) + return _internal_opcode(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_opcode(ArgT0&& arg0, ArgT... args) { + + _impl_.opcode_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.opcode) +} +inline std::string* HloInstructionProto::mutable_opcode() { + std::string* _s = _internal_mutable_opcode(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.opcode) + return _s; +} +inline const std::string& HloInstructionProto::_internal_opcode() const { + return _impl_.opcode_.Get(); +} +inline void HloInstructionProto::_internal_set_opcode(const std::string& value) { + + _impl_.opcode_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_opcode() { + + return _impl_.opcode_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_opcode() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.opcode) + return _impl_.opcode_.Release(); +} +inline void HloInstructionProto::set_allocated_opcode(std::string* opcode) { + if (opcode != nullptr) { + + } else { + + } + _impl_.opcode_.SetAllocated(opcode, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.opcode_.IsDefault()) { + _impl_.opcode_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.opcode) +} + +// .xla.ShapeProto shape = 3; +inline bool HloInstructionProto::_internal_has_shape() const { + return this != internal_default_instance() && _impl_.shape_ != nullptr; +} +inline bool HloInstructionProto::has_shape() const { + return _internal_has_shape(); +} +inline const ::xla::ShapeProto& HloInstructionProto::_internal_shape() const { + const ::xla::ShapeProto* p = _impl_.shape_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ShapeProto_default_instance_); +} +inline const ::xla::ShapeProto& HloInstructionProto::shape() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.shape) + return _internal_shape(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_shape( + ::xla::ShapeProto* shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + _impl_.shape_ = shape; + if (shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.shape) +} +inline ::xla::ShapeProto* HloInstructionProto::release_shape() { + + ::xla::ShapeProto* temp = _impl_.shape_; + _impl_.shape_ = 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::ShapeProto* HloInstructionProto::unsafe_arena_release_shape() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.shape) + + ::xla::ShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; + return temp; +} +inline ::xla::ShapeProto* HloInstructionProto::_internal_mutable_shape() { + + if (_impl_.shape_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ShapeProto>(GetArenaForAllocation()); + _impl_.shape_ = p; + } + return _impl_.shape_; +} +inline ::xla::ShapeProto* HloInstructionProto::mutable_shape() { + ::xla::ShapeProto* _msg = _internal_mutable_shape(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.shape) + return _msg; +} +inline void HloInstructionProto::set_allocated_shape(::xla::ShapeProto* shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + if (shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(shape)); + if (message_arena != submessage_arena) { + shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, shape, submessage_arena); + } + + } else { + + } + _impl_.shape_ = shape; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.shape) +} + +// .xla.OpMetadata metadata = 7; +inline bool HloInstructionProto::_internal_has_metadata() const { + return this != internal_default_instance() && _impl_.metadata_ != nullptr; +} +inline bool HloInstructionProto::has_metadata() const { + return _internal_has_metadata(); +} +inline const ::xla::OpMetadata& HloInstructionProto::_internal_metadata() const { + const ::xla::OpMetadata* p = _impl_.metadata_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_OpMetadata_default_instance_); +} +inline const ::xla::OpMetadata& HloInstructionProto::metadata() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.metadata) + return _internal_metadata(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_metadata( + ::xla::OpMetadata* metadata) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.metadata_); + } + _impl_.metadata_ = metadata; + if (metadata) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.metadata) +} +inline ::xla::OpMetadata* HloInstructionProto::release_metadata() { + + ::xla::OpMetadata* temp = _impl_.metadata_; + _impl_.metadata_ = 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::OpMetadata* HloInstructionProto::unsafe_arena_release_metadata() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.metadata) + + ::xla::OpMetadata* temp = _impl_.metadata_; + _impl_.metadata_ = nullptr; + return temp; +} +inline ::xla::OpMetadata* HloInstructionProto::_internal_mutable_metadata() { + + if (_impl_.metadata_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::OpMetadata>(GetArenaForAllocation()); + _impl_.metadata_ = p; + } + return _impl_.metadata_; +} +inline ::xla::OpMetadata* HloInstructionProto::mutable_metadata() { + ::xla::OpMetadata* _msg = _internal_mutable_metadata(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.metadata) + return _msg; +} +inline void HloInstructionProto::set_allocated_metadata(::xla::OpMetadata* metadata) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.metadata_); + } + if (metadata) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(metadata)); + if (message_arena != submessage_arena) { + metadata = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, metadata, submessage_arena); + } + + } else { + + } + _impl_.metadata_ = metadata; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.metadata) +} + +// .xla.LiteralProto literal = 8; +inline bool HloInstructionProto::_internal_has_literal() const { + return this != internal_default_instance() && _impl_.literal_ != nullptr; +} +inline bool HloInstructionProto::has_literal() const { + return _internal_has_literal(); +} +inline const ::xla::LiteralProto& HloInstructionProto::_internal_literal() const { + const ::xla::LiteralProto* p = _impl_.literal_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_LiteralProto_default_instance_); +} +inline const ::xla::LiteralProto& HloInstructionProto::literal() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.literal) + return _internal_literal(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_literal( + ::xla::LiteralProto* literal) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.literal_); + } + _impl_.literal_ = literal; + if (literal) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.literal) +} +inline ::xla::LiteralProto* HloInstructionProto::release_literal() { + + ::xla::LiteralProto* temp = _impl_.literal_; + _impl_.literal_ = 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::LiteralProto* HloInstructionProto::unsafe_arena_release_literal() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.literal) + + ::xla::LiteralProto* temp = _impl_.literal_; + _impl_.literal_ = nullptr; + return temp; +} +inline ::xla::LiteralProto* HloInstructionProto::_internal_mutable_literal() { + + if (_impl_.literal_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::LiteralProto>(GetArenaForAllocation()); + _impl_.literal_ = p; + } + return _impl_.literal_; +} +inline ::xla::LiteralProto* HloInstructionProto::mutable_literal() { + ::xla::LiteralProto* _msg = _internal_mutable_literal(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.literal) + return _msg; +} +inline void HloInstructionProto::set_allocated_literal(::xla::LiteralProto* literal) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.literal_); + } + if (literal) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(literal)); + if (message_arena != submessage_arena) { + literal = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, literal, submessage_arena); + } + + } else { + + } + _impl_.literal_ = literal; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.literal) +} + +// int64 parameter_number = 9; +inline void HloInstructionProto::clear_parameter_number() { + _impl_.parameter_number_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_parameter_number() const { + return _impl_.parameter_number_; +} +inline int64_t HloInstructionProto::parameter_number() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.parameter_number) + return _internal_parameter_number(); +} +inline void HloInstructionProto::_internal_set_parameter_number(int64_t value) { + + _impl_.parameter_number_ = value; +} +inline void HloInstructionProto::set_parameter_number(int64_t value) { + _internal_set_parameter_number(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.parameter_number) +} + +// string fusion_kind = 11; +inline void HloInstructionProto::clear_fusion_kind() { + _impl_.fusion_kind_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::fusion_kind() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.fusion_kind) + return _internal_fusion_kind(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_fusion_kind(ArgT0&& arg0, ArgT... args) { + + _impl_.fusion_kind_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.fusion_kind) +} +inline std::string* HloInstructionProto::mutable_fusion_kind() { + std::string* _s = _internal_mutable_fusion_kind(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.fusion_kind) + return _s; +} +inline const std::string& HloInstructionProto::_internal_fusion_kind() const { + return _impl_.fusion_kind_.Get(); +} +inline void HloInstructionProto::_internal_set_fusion_kind(const std::string& value) { + + _impl_.fusion_kind_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_fusion_kind() { + + return _impl_.fusion_kind_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_fusion_kind() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.fusion_kind) + return _impl_.fusion_kind_.Release(); +} +inline void HloInstructionProto::set_allocated_fusion_kind(std::string* fusion_kind) { + if (fusion_kind != nullptr) { + + } else { + + } + _impl_.fusion_kind_.SetAllocated(fusion_kind, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.fusion_kind_.IsDefault()) { + _impl_.fusion_kind_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.fusion_kind) +} + +// int64 tuple_index = 13; +inline void HloInstructionProto::clear_tuple_index() { + _impl_.tuple_index_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_tuple_index() const { + return _impl_.tuple_index_; +} +inline int64_t HloInstructionProto::tuple_index() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.tuple_index) + return _internal_tuple_index(); +} +inline void HloInstructionProto::_internal_set_tuple_index(int64_t value) { + + _impl_.tuple_index_ = value; +} +inline void HloInstructionProto::set_tuple_index(int64_t value) { + _internal_set_tuple_index(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.tuple_index) +} + +// repeated int64 dimensions = 14; +inline int HloInstructionProto::_internal_dimensions_size() const { + return _impl_.dimensions_.size(); +} +inline int HloInstructionProto::dimensions_size() const { + return _internal_dimensions_size(); +} +inline void HloInstructionProto::clear_dimensions() { + _impl_.dimensions_.Clear(); +} +inline int64_t HloInstructionProto::_internal_dimensions(int index) const { + return _impl_.dimensions_.Get(index); +} +inline int64_t HloInstructionProto::dimensions(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.dimensions) + return _internal_dimensions(index); +} +inline void HloInstructionProto::set_dimensions(int index, int64_t value) { + _impl_.dimensions_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.dimensions) +} +inline void HloInstructionProto::_internal_add_dimensions(int64_t value) { + _impl_.dimensions_.Add(value); +} +inline void HloInstructionProto::add_dimensions(int64_t value) { + _internal_add_dimensions(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.dimensions) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_dimensions() const { + return _impl_.dimensions_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::dimensions() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.dimensions) + return _internal_dimensions(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_dimensions() { + return &_impl_.dimensions_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_dimensions() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.dimensions) + return _internal_mutable_dimensions(); +} + +// .xla.Window window = 15; +inline bool HloInstructionProto::_internal_has_window() const { + return this != internal_default_instance() && _impl_.window_ != nullptr; +} +inline bool HloInstructionProto::has_window() const { + return _internal_has_window(); +} +inline const ::xla::Window& HloInstructionProto::_internal_window() const { + const ::xla::Window* p = _impl_.window_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_Window_default_instance_); +} +inline const ::xla::Window& HloInstructionProto::window() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.window) + return _internal_window(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_window( + ::xla::Window* window) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.window_); + } + _impl_.window_ = window; + if (window) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.window) +} +inline ::xla::Window* HloInstructionProto::release_window() { + + ::xla::Window* temp = _impl_.window_; + _impl_.window_ = 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::Window* HloInstructionProto::unsafe_arena_release_window() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.window) + + ::xla::Window* temp = _impl_.window_; + _impl_.window_ = nullptr; + return temp; +} +inline ::xla::Window* HloInstructionProto::_internal_mutable_window() { + + if (_impl_.window_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::Window>(GetArenaForAllocation()); + _impl_.window_ = p; + } + return _impl_.window_; +} +inline ::xla::Window* HloInstructionProto::mutable_window() { + ::xla::Window* _msg = _internal_mutable_window(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.window) + return _msg; +} +inline void HloInstructionProto::set_allocated_window(::xla::Window* window) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.window_); + } + if (window) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(window)); + if (message_arena != submessage_arena) { + window = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, window, submessage_arena); + } + + } else { + + } + _impl_.window_ = window; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.window) +} + +// .xla.ConvolutionDimensionNumbers convolution_dimension_numbers = 16; +inline bool HloInstructionProto::_internal_has_convolution_dimension_numbers() const { + return this != internal_default_instance() && _impl_.convolution_dimension_numbers_ != nullptr; +} +inline bool HloInstructionProto::has_convolution_dimension_numbers() const { + return _internal_has_convolution_dimension_numbers(); +} +inline const ::xla::ConvolutionDimensionNumbers& HloInstructionProto::_internal_convolution_dimension_numbers() const { + const ::xla::ConvolutionDimensionNumbers* p = _impl_.convolution_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ConvolutionDimensionNumbers_default_instance_); +} +inline const ::xla::ConvolutionDimensionNumbers& HloInstructionProto::convolution_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.convolution_dimension_numbers) + return _internal_convolution_dimension_numbers(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_convolution_dimension_numbers( + ::xla::ConvolutionDimensionNumbers* convolution_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.convolution_dimension_numbers_); + } + _impl_.convolution_dimension_numbers_ = convolution_dimension_numbers; + if (convolution_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.convolution_dimension_numbers) +} +inline ::xla::ConvolutionDimensionNumbers* HloInstructionProto::release_convolution_dimension_numbers() { + + ::xla::ConvolutionDimensionNumbers* temp = _impl_.convolution_dimension_numbers_; + _impl_.convolution_dimension_numbers_ = 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::ConvolutionDimensionNumbers* HloInstructionProto::unsafe_arena_release_convolution_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.convolution_dimension_numbers) + + ::xla::ConvolutionDimensionNumbers* temp = _impl_.convolution_dimension_numbers_; + _impl_.convolution_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::ConvolutionDimensionNumbers* HloInstructionProto::_internal_mutable_convolution_dimension_numbers() { + + if (_impl_.convolution_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ConvolutionDimensionNumbers>(GetArenaForAllocation()); + _impl_.convolution_dimension_numbers_ = p; + } + return _impl_.convolution_dimension_numbers_; +} +inline ::xla::ConvolutionDimensionNumbers* HloInstructionProto::mutable_convolution_dimension_numbers() { + ::xla::ConvolutionDimensionNumbers* _msg = _internal_mutable_convolution_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.convolution_dimension_numbers) + return _msg; +} +inline void HloInstructionProto::set_allocated_convolution_dimension_numbers(::xla::ConvolutionDimensionNumbers* convolution_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.convolution_dimension_numbers_); + } + if (convolution_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(convolution_dimension_numbers)); + if (message_arena != submessage_arena) { + convolution_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, convolution_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.convolution_dimension_numbers_ = convolution_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.convolution_dimension_numbers) +} + +// int64 feature_group_count = 50; +inline void HloInstructionProto::clear_feature_group_count() { + _impl_.feature_group_count_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_feature_group_count() const { + return _impl_.feature_group_count_; +} +inline int64_t HloInstructionProto::feature_group_count() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.feature_group_count) + return _internal_feature_group_count(); +} +inline void HloInstructionProto::_internal_set_feature_group_count(int64_t value) { + + _impl_.feature_group_count_ = value; +} +inline void HloInstructionProto::set_feature_group_count(int64_t value) { + _internal_set_feature_group_count(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.feature_group_count) +} + +// int64 batch_group_count = 58; +inline void HloInstructionProto::clear_batch_group_count() { + _impl_.batch_group_count_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_batch_group_count() const { + return _impl_.batch_group_count_; +} +inline int64_t HloInstructionProto::batch_group_count() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.batch_group_count) + return _internal_batch_group_count(); +} +inline void HloInstructionProto::_internal_set_batch_group_count(int64_t value) { + + _impl_.batch_group_count_ = value; +} +inline void HloInstructionProto::set_batch_group_count(int64_t value) { + _internal_set_batch_group_count(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.batch_group_count) +} + +// repeated .xla.HloInstructionProto.SliceDimensions slice_dimensions = 17; +inline int HloInstructionProto::_internal_slice_dimensions_size() const { + return _impl_.slice_dimensions_.size(); +} +inline int HloInstructionProto::slice_dimensions_size() const { + return _internal_slice_dimensions_size(); +} +inline void HloInstructionProto::clear_slice_dimensions() { + _impl_.slice_dimensions_.Clear(); +} +inline ::xla::HloInstructionProto_SliceDimensions* HloInstructionProto::mutable_slice_dimensions(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.slice_dimensions) + return _impl_.slice_dimensions_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto_SliceDimensions >* +HloInstructionProto::mutable_slice_dimensions() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.slice_dimensions) + return &_impl_.slice_dimensions_; +} +inline const ::xla::HloInstructionProto_SliceDimensions& HloInstructionProto::_internal_slice_dimensions(int index) const { + return _impl_.slice_dimensions_.Get(index); +} +inline const ::xla::HloInstructionProto_SliceDimensions& HloInstructionProto::slice_dimensions(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.slice_dimensions) + return _internal_slice_dimensions(index); +} +inline ::xla::HloInstructionProto_SliceDimensions* HloInstructionProto::_internal_add_slice_dimensions() { + return _impl_.slice_dimensions_.Add(); +} +inline ::xla::HloInstructionProto_SliceDimensions* HloInstructionProto::add_slice_dimensions() { + ::xla::HloInstructionProto_SliceDimensions* _add = _internal_add_slice_dimensions(); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.slice_dimensions) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto_SliceDimensions >& +HloInstructionProto::slice_dimensions() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.slice_dimensions) + return _impl_.slice_dimensions_; +} + +// int32 exponent_bits = 18; +inline void HloInstructionProto::clear_exponent_bits() { + _impl_.exponent_bits_ = 0; +} +inline int32_t HloInstructionProto::_internal_exponent_bits() const { + return _impl_.exponent_bits_; +} +inline int32_t HloInstructionProto::exponent_bits() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.exponent_bits) + return _internal_exponent_bits(); +} +inline void HloInstructionProto::_internal_set_exponent_bits(int32_t value) { + + _impl_.exponent_bits_ = value; +} +inline void HloInstructionProto::set_exponent_bits(int32_t value) { + _internal_set_exponent_bits(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.exponent_bits) +} + +// int32 mantissa_bits = 19; +inline void HloInstructionProto::clear_mantissa_bits() { + _impl_.mantissa_bits_ = 0; +} +inline int32_t HloInstructionProto::_internal_mantissa_bits() const { + return _impl_.mantissa_bits_; +} +inline int32_t HloInstructionProto::mantissa_bits() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.mantissa_bits) + return _internal_mantissa_bits(); +} +inline void HloInstructionProto::_internal_set_mantissa_bits(int32_t value) { + + _impl_.mantissa_bits_ = value; +} +inline void HloInstructionProto::set_mantissa_bits(int32_t value) { + _internal_set_mantissa_bits(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.mantissa_bits) +} + +// repeated int64 dynamic_slice_sizes = 20; +inline int HloInstructionProto::_internal_dynamic_slice_sizes_size() const { + return _impl_.dynamic_slice_sizes_.size(); +} +inline int HloInstructionProto::dynamic_slice_sizes_size() const { + return _internal_dynamic_slice_sizes_size(); +} +inline void HloInstructionProto::clear_dynamic_slice_sizes() { + _impl_.dynamic_slice_sizes_.Clear(); +} +inline int64_t HloInstructionProto::_internal_dynamic_slice_sizes(int index) const { + return _impl_.dynamic_slice_sizes_.Get(index); +} +inline int64_t HloInstructionProto::dynamic_slice_sizes(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.dynamic_slice_sizes) + return _internal_dynamic_slice_sizes(index); +} +inline void HloInstructionProto::set_dynamic_slice_sizes(int index, int64_t value) { + _impl_.dynamic_slice_sizes_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.dynamic_slice_sizes) +} +inline void HloInstructionProto::_internal_add_dynamic_slice_sizes(int64_t value) { + _impl_.dynamic_slice_sizes_.Add(value); +} +inline void HloInstructionProto::add_dynamic_slice_sizes(int64_t value) { + _internal_add_dynamic_slice_sizes(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.dynamic_slice_sizes) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_dynamic_slice_sizes() const { + return _impl_.dynamic_slice_sizes_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::dynamic_slice_sizes() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.dynamic_slice_sizes) + return _internal_dynamic_slice_sizes(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_dynamic_slice_sizes() { + return &_impl_.dynamic_slice_sizes_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_dynamic_slice_sizes() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.dynamic_slice_sizes) + return _internal_mutable_dynamic_slice_sizes(); +} + +// .xla.PaddingConfig padding_config = 21; +inline bool HloInstructionProto::_internal_has_padding_config() const { + return this != internal_default_instance() && _impl_.padding_config_ != nullptr; +} +inline bool HloInstructionProto::has_padding_config() const { + return _internal_has_padding_config(); +} +inline const ::xla::PaddingConfig& HloInstructionProto::_internal_padding_config() const { + const ::xla::PaddingConfig* p = _impl_.padding_config_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_PaddingConfig_default_instance_); +} +inline const ::xla::PaddingConfig& HloInstructionProto::padding_config() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.padding_config) + return _internal_padding_config(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_padding_config( + ::xla::PaddingConfig* padding_config) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.padding_config_); + } + _impl_.padding_config_ = padding_config; + if (padding_config) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.padding_config) +} +inline ::xla::PaddingConfig* HloInstructionProto::release_padding_config() { + + ::xla::PaddingConfig* temp = _impl_.padding_config_; + _impl_.padding_config_ = 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::PaddingConfig* HloInstructionProto::unsafe_arena_release_padding_config() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.padding_config) + + ::xla::PaddingConfig* temp = _impl_.padding_config_; + _impl_.padding_config_ = nullptr; + return temp; +} +inline ::xla::PaddingConfig* HloInstructionProto::_internal_mutable_padding_config() { + + if (_impl_.padding_config_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::PaddingConfig>(GetArenaForAllocation()); + _impl_.padding_config_ = p; + } + return _impl_.padding_config_; +} +inline ::xla::PaddingConfig* HloInstructionProto::mutable_padding_config() { + ::xla::PaddingConfig* _msg = _internal_mutable_padding_config(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.padding_config) + return _msg; +} +inline void HloInstructionProto::set_allocated_padding_config(::xla::PaddingConfig* padding_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.padding_config_); + } + if (padding_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(padding_config)); + if (message_arena != submessage_arena) { + padding_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, padding_config, submessage_arena); + } + + } else { + + } + _impl_.padding_config_ = padding_config; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.padding_config) +} + +// bytes outfeed_config = 22; +inline void HloInstructionProto::clear_outfeed_config() { + _impl_.outfeed_config_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::outfeed_config() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.outfeed_config) + return _internal_outfeed_config(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_outfeed_config(ArgT0&& arg0, ArgT... args) { + + _impl_.outfeed_config_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.outfeed_config) +} +inline std::string* HloInstructionProto::mutable_outfeed_config() { + std::string* _s = _internal_mutable_outfeed_config(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.outfeed_config) + return _s; +} +inline const std::string& HloInstructionProto::_internal_outfeed_config() const { + return _impl_.outfeed_config_.Get(); +} +inline void HloInstructionProto::_internal_set_outfeed_config(const std::string& value) { + + _impl_.outfeed_config_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_outfeed_config() { + + return _impl_.outfeed_config_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_outfeed_config() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.outfeed_config) + return _impl_.outfeed_config_.Release(); +} +inline void HloInstructionProto::set_allocated_outfeed_config(std::string* outfeed_config) { + if (outfeed_config != nullptr) { + + } else { + + } + _impl_.outfeed_config_.SetAllocated(outfeed_config, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.outfeed_config_.IsDefault()) { + _impl_.outfeed_config_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.outfeed_config) +} + +// .xla.RandomDistribution distribution = 23; +inline void HloInstructionProto::clear_distribution() { + _impl_.distribution_ = 0; +} +inline ::xla::RandomDistribution HloInstructionProto::_internal_distribution() const { + return static_cast< ::xla::RandomDistribution >(_impl_.distribution_); +} +inline ::xla::RandomDistribution HloInstructionProto::distribution() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.distribution) + return _internal_distribution(); +} +inline void HloInstructionProto::_internal_set_distribution(::xla::RandomDistribution value) { + + _impl_.distribution_ = value; +} +inline void HloInstructionProto::set_distribution(::xla::RandomDistribution value) { + _internal_set_distribution(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.distribution) +} + +// float epsilon = 24; +inline void HloInstructionProto::clear_epsilon() { + _impl_.epsilon_ = 0; +} +inline float HloInstructionProto::_internal_epsilon() const { + return _impl_.epsilon_; +} +inline float HloInstructionProto::epsilon() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.epsilon) + return _internal_epsilon(); +} +inline void HloInstructionProto::_internal_set_epsilon(float value) { + + _impl_.epsilon_ = value; +} +inline void HloInstructionProto::set_epsilon(float value) { + _internal_set_epsilon(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.epsilon) +} + +// int64 feature_index = 25; +inline void HloInstructionProto::clear_feature_index() { + _impl_.feature_index_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_feature_index() const { + return _impl_.feature_index_; +} +inline int64_t HloInstructionProto::feature_index() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.feature_index) + return _internal_feature_index(); +} +inline void HloInstructionProto::_internal_set_feature_index(int64_t value) { + + _impl_.feature_index_ = value; +} +inline void HloInstructionProto::set_feature_index(int64_t value) { + _internal_set_feature_index(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.feature_index) +} + +// int64 channel_id = 26; +inline void HloInstructionProto::clear_channel_id() { + _impl_.channel_id_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_channel_id() const { + return _impl_.channel_id_; +} +inline int64_t HloInstructionProto::channel_id() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.channel_id) + return _internal_channel_id(); +} +inline void HloInstructionProto::_internal_set_channel_id(int64_t value) { + + _impl_.channel_id_ = value; +} +inline void HloInstructionProto::set_channel_id(int64_t value) { + _internal_set_channel_id(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.channel_id) +} + +// bytes infeed_config = 27; +inline void HloInstructionProto::clear_infeed_config() { + _impl_.infeed_config_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::infeed_config() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.infeed_config) + return _internal_infeed_config(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_infeed_config(ArgT0&& arg0, ArgT... args) { + + _impl_.infeed_config_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.infeed_config) +} +inline std::string* HloInstructionProto::mutable_infeed_config() { + std::string* _s = _internal_mutable_infeed_config(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.infeed_config) + return _s; +} +inline const std::string& HloInstructionProto::_internal_infeed_config() const { + return _impl_.infeed_config_.Get(); +} +inline void HloInstructionProto::_internal_set_infeed_config(const std::string& value) { + + _impl_.infeed_config_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_infeed_config() { + + return _impl_.infeed_config_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_infeed_config() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.infeed_config) + return _impl_.infeed_config_.Release(); +} +inline void HloInstructionProto::set_allocated_infeed_config(std::string* infeed_config) { + if (infeed_config != nullptr) { + + } else { + + } + _impl_.infeed_config_.SetAllocated(infeed_config, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.infeed_config_.IsDefault()) { + _impl_.infeed_config_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.infeed_config) +} + +// string custom_call_target = 28; +inline void HloInstructionProto::clear_custom_call_target() { + _impl_.custom_call_target_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::custom_call_target() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.custom_call_target) + return _internal_custom_call_target(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_custom_call_target(ArgT0&& arg0, ArgT... args) { + + _impl_.custom_call_target_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.custom_call_target) +} +inline std::string* HloInstructionProto::mutable_custom_call_target() { + std::string* _s = _internal_mutable_custom_call_target(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.custom_call_target) + return _s; +} +inline const std::string& HloInstructionProto::_internal_custom_call_target() const { + return _impl_.custom_call_target_.Get(); +} +inline void HloInstructionProto::_internal_set_custom_call_target(const std::string& value) { + + _impl_.custom_call_target_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_custom_call_target() { + + return _impl_.custom_call_target_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_custom_call_target() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.custom_call_target) + return _impl_.custom_call_target_.Release(); +} +inline void HloInstructionProto::set_allocated_custom_call_target(std::string* custom_call_target) { + if (custom_call_target != nullptr) { + + } else { + + } + _impl_.custom_call_target_.SetAllocated(custom_call_target, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.custom_call_target_.IsDefault()) { + _impl_.custom_call_target_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.custom_call_target) +} + +// .xla.ShapeProto outfeed_shape = 29; +inline bool HloInstructionProto::_internal_has_outfeed_shape() const { + return this != internal_default_instance() && _impl_.outfeed_shape_ != nullptr; +} +inline bool HloInstructionProto::has_outfeed_shape() const { + return _internal_has_outfeed_shape(); +} +inline const ::xla::ShapeProto& HloInstructionProto::_internal_outfeed_shape() const { + const ::xla::ShapeProto* p = _impl_.outfeed_shape_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ShapeProto_default_instance_); +} +inline const ::xla::ShapeProto& HloInstructionProto::outfeed_shape() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.outfeed_shape) + return _internal_outfeed_shape(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_outfeed_shape( + ::xla::ShapeProto* outfeed_shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.outfeed_shape_); + } + _impl_.outfeed_shape_ = outfeed_shape; + if (outfeed_shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.outfeed_shape) +} +inline ::xla::ShapeProto* HloInstructionProto::release_outfeed_shape() { + + ::xla::ShapeProto* temp = _impl_.outfeed_shape_; + _impl_.outfeed_shape_ = 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::ShapeProto* HloInstructionProto::unsafe_arena_release_outfeed_shape() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.outfeed_shape) + + ::xla::ShapeProto* temp = _impl_.outfeed_shape_; + _impl_.outfeed_shape_ = nullptr; + return temp; +} +inline ::xla::ShapeProto* HloInstructionProto::_internal_mutable_outfeed_shape() { + + if (_impl_.outfeed_shape_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ShapeProto>(GetArenaForAllocation()); + _impl_.outfeed_shape_ = p; + } + return _impl_.outfeed_shape_; +} +inline ::xla::ShapeProto* HloInstructionProto::mutable_outfeed_shape() { + ::xla::ShapeProto* _msg = _internal_mutable_outfeed_shape(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.outfeed_shape) + return _msg; +} +inline void HloInstructionProto::set_allocated_outfeed_shape(::xla::ShapeProto* outfeed_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.outfeed_shape_); + } + if (outfeed_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(outfeed_shape)); + if (message_arena != submessage_arena) { + outfeed_shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, outfeed_shape, submessage_arena); + } + + } else { + + } + _impl_.outfeed_shape_ = outfeed_shape; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.outfeed_shape) +} + +// .xla.DotDimensionNumbers dot_dimension_numbers = 30; +inline bool HloInstructionProto::_internal_has_dot_dimension_numbers() const { + return this != internal_default_instance() && _impl_.dot_dimension_numbers_ != nullptr; +} +inline bool HloInstructionProto::has_dot_dimension_numbers() const { + return _internal_has_dot_dimension_numbers(); +} +inline const ::xla::DotDimensionNumbers& HloInstructionProto::_internal_dot_dimension_numbers() const { + const ::xla::DotDimensionNumbers* p = _impl_.dot_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DotDimensionNumbers_default_instance_); +} +inline const ::xla::DotDimensionNumbers& HloInstructionProto::dot_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.dot_dimension_numbers) + return _internal_dot_dimension_numbers(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_dot_dimension_numbers( + ::xla::DotDimensionNumbers* dot_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dot_dimension_numbers_); + } + _impl_.dot_dimension_numbers_ = dot_dimension_numbers; + if (dot_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.dot_dimension_numbers) +} +inline ::xla::DotDimensionNumbers* HloInstructionProto::release_dot_dimension_numbers() { + + ::xla::DotDimensionNumbers* temp = _impl_.dot_dimension_numbers_; + _impl_.dot_dimension_numbers_ = 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::DotDimensionNumbers* HloInstructionProto::unsafe_arena_release_dot_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.dot_dimension_numbers) + + ::xla::DotDimensionNumbers* temp = _impl_.dot_dimension_numbers_; + _impl_.dot_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::DotDimensionNumbers* HloInstructionProto::_internal_mutable_dot_dimension_numbers() { + + if (_impl_.dot_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DotDimensionNumbers>(GetArenaForAllocation()); + _impl_.dot_dimension_numbers_ = p; + } + return _impl_.dot_dimension_numbers_; +} +inline ::xla::DotDimensionNumbers* HloInstructionProto::mutable_dot_dimension_numbers() { + ::xla::DotDimensionNumbers* _msg = _internal_mutable_dot_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.dot_dimension_numbers) + return _msg; +} +inline void HloInstructionProto::set_allocated_dot_dimension_numbers(::xla::DotDimensionNumbers* dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dot_dimension_numbers_); + } + if (dot_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(dot_dimension_numbers)); + if (message_arena != submessage_arena) { + dot_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, dot_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.dot_dimension_numbers_ = dot_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.dot_dimension_numbers) +} + +// .xla.FftType fft_type = 31; +inline void HloInstructionProto::clear_fft_type() { + _impl_.fft_type_ = 0; +} +inline ::xla::FftType HloInstructionProto::_internal_fft_type() const { + return static_cast< ::xla::FftType >(_impl_.fft_type_); +} +inline ::xla::FftType HloInstructionProto::fft_type() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.fft_type) + return _internal_fft_type(); +} +inline void HloInstructionProto::_internal_set_fft_type(::xla::FftType value) { + + _impl_.fft_type_ = value; +} +inline void HloInstructionProto::set_fft_type(::xla::FftType value) { + _internal_set_fft_type(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.fft_type) +} + +// repeated int64 fft_length = 32; +inline int HloInstructionProto::_internal_fft_length_size() const { + return _impl_.fft_length_.size(); +} +inline int HloInstructionProto::fft_length_size() const { + return _internal_fft_length_size(); +} +inline void HloInstructionProto::clear_fft_length() { + _impl_.fft_length_.Clear(); +} +inline int64_t HloInstructionProto::_internal_fft_length(int index) const { + return _impl_.fft_length_.Get(index); +} +inline int64_t HloInstructionProto::fft_length(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.fft_length) + return _internal_fft_length(index); +} +inline void HloInstructionProto::set_fft_length(int index, int64_t value) { + _impl_.fft_length_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.fft_length) +} +inline void HloInstructionProto::_internal_add_fft_length(int64_t value) { + _impl_.fft_length_.Add(value); +} +inline void HloInstructionProto::add_fft_length(int64_t value) { + _internal_add_fft_length(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.fft_length) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_fft_length() const { + return _impl_.fft_length_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::fft_length() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.fft_length) + return _internal_fft_length(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_fft_length() { + return &_impl_.fft_length_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_fft_length() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.fft_length) + return _internal_mutable_fft_length(); +} + +// string comparison_direction = 63; +inline void HloInstructionProto::clear_comparison_direction() { + _impl_.comparison_direction_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::comparison_direction() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.comparison_direction) + return _internal_comparison_direction(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_comparison_direction(ArgT0&& arg0, ArgT... args) { + + _impl_.comparison_direction_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.comparison_direction) +} +inline std::string* HloInstructionProto::mutable_comparison_direction() { + std::string* _s = _internal_mutable_comparison_direction(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.comparison_direction) + return _s; +} +inline const std::string& HloInstructionProto::_internal_comparison_direction() const { + return _impl_.comparison_direction_.Get(); +} +inline void HloInstructionProto::_internal_set_comparison_direction(const std::string& value) { + + _impl_.comparison_direction_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_comparison_direction() { + + return _impl_.comparison_direction_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_comparison_direction() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.comparison_direction) + return _impl_.comparison_direction_.Release(); +} +inline void HloInstructionProto::set_allocated_comparison_direction(std::string* comparison_direction) { + if (comparison_direction != nullptr) { + + } else { + + } + _impl_.comparison_direction_.SetAllocated(comparison_direction, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.comparison_direction_.IsDefault()) { + _impl_.comparison_direction_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.comparison_direction) +} + +// .xla.GatherDimensionNumbers gather_dimension_numbers = 33; +inline bool HloInstructionProto::_internal_has_gather_dimension_numbers() const { + return this != internal_default_instance() && _impl_.gather_dimension_numbers_ != nullptr; +} +inline bool HloInstructionProto::has_gather_dimension_numbers() const { + return _internal_has_gather_dimension_numbers(); +} +inline const ::xla::GatherDimensionNumbers& HloInstructionProto::_internal_gather_dimension_numbers() const { + const ::xla::GatherDimensionNumbers* p = _impl_.gather_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_GatherDimensionNumbers_default_instance_); +} +inline const ::xla::GatherDimensionNumbers& HloInstructionProto::gather_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.gather_dimension_numbers) + return _internal_gather_dimension_numbers(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_gather_dimension_numbers( + ::xla::GatherDimensionNumbers* gather_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.gather_dimension_numbers_); + } + _impl_.gather_dimension_numbers_ = gather_dimension_numbers; + if (gather_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.gather_dimension_numbers) +} +inline ::xla::GatherDimensionNumbers* HloInstructionProto::release_gather_dimension_numbers() { + + ::xla::GatherDimensionNumbers* temp = _impl_.gather_dimension_numbers_; + _impl_.gather_dimension_numbers_ = 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::GatherDimensionNumbers* HloInstructionProto::unsafe_arena_release_gather_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.gather_dimension_numbers) + + ::xla::GatherDimensionNumbers* temp = _impl_.gather_dimension_numbers_; + _impl_.gather_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::GatherDimensionNumbers* HloInstructionProto::_internal_mutable_gather_dimension_numbers() { + + if (_impl_.gather_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::GatherDimensionNumbers>(GetArenaForAllocation()); + _impl_.gather_dimension_numbers_ = p; + } + return _impl_.gather_dimension_numbers_; +} +inline ::xla::GatherDimensionNumbers* HloInstructionProto::mutable_gather_dimension_numbers() { + ::xla::GatherDimensionNumbers* _msg = _internal_mutable_gather_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.gather_dimension_numbers) + return _msg; +} +inline void HloInstructionProto::set_allocated_gather_dimension_numbers(::xla::GatherDimensionNumbers* gather_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.gather_dimension_numbers_); + } + if (gather_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(gather_dimension_numbers)); + if (message_arena != submessage_arena) { + gather_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, gather_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.gather_dimension_numbers_ = gather_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.gather_dimension_numbers) +} + +// repeated int64 gather_slice_sizes = 34; +inline int HloInstructionProto::_internal_gather_slice_sizes_size() const { + return _impl_.gather_slice_sizes_.size(); +} +inline int HloInstructionProto::gather_slice_sizes_size() const { + return _internal_gather_slice_sizes_size(); +} +inline void HloInstructionProto::clear_gather_slice_sizes() { + _impl_.gather_slice_sizes_.Clear(); +} +inline int64_t HloInstructionProto::_internal_gather_slice_sizes(int index) const { + return _impl_.gather_slice_sizes_.Get(index); +} +inline int64_t HloInstructionProto::gather_slice_sizes(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.gather_slice_sizes) + return _internal_gather_slice_sizes(index); +} +inline void HloInstructionProto::set_gather_slice_sizes(int index, int64_t value) { + _impl_.gather_slice_sizes_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.gather_slice_sizes) +} +inline void HloInstructionProto::_internal_add_gather_slice_sizes(int64_t value) { + _impl_.gather_slice_sizes_.Add(value); +} +inline void HloInstructionProto::add_gather_slice_sizes(int64_t value) { + _internal_add_gather_slice_sizes(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.gather_slice_sizes) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_gather_slice_sizes() const { + return _impl_.gather_slice_sizes_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::gather_slice_sizes() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.gather_slice_sizes) + return _internal_gather_slice_sizes(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_gather_slice_sizes() { + return &_impl_.gather_slice_sizes_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_gather_slice_sizes() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.gather_slice_sizes) + return _internal_mutable_gather_slice_sizes(); +} + +// int64 id = 35; +inline void HloInstructionProto::clear_id() { + _impl_.id_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_id() const { + return _impl_.id_; +} +inline int64_t HloInstructionProto::id() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.id) + return _internal_id(); +} +inline void HloInstructionProto::_internal_set_id(int64_t value) { + + _impl_.id_ = value; +} +inline void HloInstructionProto::set_id(int64_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.id) +} + +// repeated int64 operand_ids = 36; +inline int HloInstructionProto::_internal_operand_ids_size() const { + return _impl_.operand_ids_.size(); +} +inline int HloInstructionProto::operand_ids_size() const { + return _internal_operand_ids_size(); +} +inline void HloInstructionProto::clear_operand_ids() { + _impl_.operand_ids_.Clear(); +} +inline int64_t HloInstructionProto::_internal_operand_ids(int index) const { + return _impl_.operand_ids_.Get(index); +} +inline int64_t HloInstructionProto::operand_ids(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.operand_ids) + return _internal_operand_ids(index); +} +inline void HloInstructionProto::set_operand_ids(int index, int64_t value) { + _impl_.operand_ids_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.operand_ids) +} +inline void HloInstructionProto::_internal_add_operand_ids(int64_t value) { + _impl_.operand_ids_.Add(value); +} +inline void HloInstructionProto::add_operand_ids(int64_t value) { + _internal_add_operand_ids(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.operand_ids) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_operand_ids() const { + return _impl_.operand_ids_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::operand_ids() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.operand_ids) + return _internal_operand_ids(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_operand_ids() { + return &_impl_.operand_ids_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_operand_ids() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.operand_ids) + return _internal_mutable_operand_ids(); +} + +// repeated int64 control_predecessor_ids = 37; +inline int HloInstructionProto::_internal_control_predecessor_ids_size() const { + return _impl_.control_predecessor_ids_.size(); +} +inline int HloInstructionProto::control_predecessor_ids_size() const { + return _internal_control_predecessor_ids_size(); +} +inline void HloInstructionProto::clear_control_predecessor_ids() { + _impl_.control_predecessor_ids_.Clear(); +} +inline int64_t HloInstructionProto::_internal_control_predecessor_ids(int index) const { + return _impl_.control_predecessor_ids_.Get(index); +} +inline int64_t HloInstructionProto::control_predecessor_ids(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.control_predecessor_ids) + return _internal_control_predecessor_ids(index); +} +inline void HloInstructionProto::set_control_predecessor_ids(int index, int64_t value) { + _impl_.control_predecessor_ids_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.control_predecessor_ids) +} +inline void HloInstructionProto::_internal_add_control_predecessor_ids(int64_t value) { + _impl_.control_predecessor_ids_.Add(value); +} +inline void HloInstructionProto::add_control_predecessor_ids(int64_t value) { + _internal_add_control_predecessor_ids(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.control_predecessor_ids) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_control_predecessor_ids() const { + return _impl_.control_predecessor_ids_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::control_predecessor_ids() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.control_predecessor_ids) + return _internal_control_predecessor_ids(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_control_predecessor_ids() { + return &_impl_.control_predecessor_ids_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_control_predecessor_ids() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.control_predecessor_ids) + return _internal_mutable_control_predecessor_ids(); +} + +// repeated int64 called_computation_ids = 38; +inline int HloInstructionProto::_internal_called_computation_ids_size() const { + return _impl_.called_computation_ids_.size(); +} +inline int HloInstructionProto::called_computation_ids_size() const { + return _internal_called_computation_ids_size(); +} +inline void HloInstructionProto::clear_called_computation_ids() { + _impl_.called_computation_ids_.Clear(); +} +inline int64_t HloInstructionProto::_internal_called_computation_ids(int index) const { + return _impl_.called_computation_ids_.Get(index); +} +inline int64_t HloInstructionProto::called_computation_ids(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.called_computation_ids) + return _internal_called_computation_ids(index); +} +inline void HloInstructionProto::set_called_computation_ids(int index, int64_t value) { + _impl_.called_computation_ids_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.called_computation_ids) +} +inline void HloInstructionProto::_internal_add_called_computation_ids(int64_t value) { + _impl_.called_computation_ids_.Add(value); +} +inline void HloInstructionProto::add_called_computation_ids(int64_t value) { + _internal_add_called_computation_ids(value); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.called_computation_ids) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::_internal_called_computation_ids() const { + return _impl_.called_computation_ids_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInstructionProto::called_computation_ids() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.called_computation_ids) + return _internal_called_computation_ids(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::_internal_mutable_called_computation_ids() { + return &_impl_.called_computation_ids_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInstructionProto::mutable_called_computation_ids() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.called_computation_ids) + return _internal_mutable_called_computation_ids(); +} + +// .xla.OpSharding sharding = 40; +inline bool HloInstructionProto::_internal_has_sharding() const { + return this != internal_default_instance() && _impl_.sharding_ != nullptr; +} +inline bool HloInstructionProto::has_sharding() const { + return _internal_has_sharding(); +} +inline const ::xla::OpSharding& HloInstructionProto::_internal_sharding() const { + const ::xla::OpSharding* p = _impl_.sharding_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_OpSharding_default_instance_); +} +inline const ::xla::OpSharding& HloInstructionProto::sharding() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.sharding) + return _internal_sharding(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_sharding( + ::xla::OpSharding* sharding) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.sharding_); + } + _impl_.sharding_ = sharding; + if (sharding) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.sharding) +} +inline ::xla::OpSharding* HloInstructionProto::release_sharding() { + + ::xla::OpSharding* temp = _impl_.sharding_; + _impl_.sharding_ = 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::OpSharding* HloInstructionProto::unsafe_arena_release_sharding() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.sharding) + + ::xla::OpSharding* temp = _impl_.sharding_; + _impl_.sharding_ = nullptr; + return temp; +} +inline ::xla::OpSharding* HloInstructionProto::_internal_mutable_sharding() { + + if (_impl_.sharding_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::OpSharding>(GetArenaForAllocation()); + _impl_.sharding_ = p; + } + return _impl_.sharding_; +} +inline ::xla::OpSharding* HloInstructionProto::mutable_sharding() { + ::xla::OpSharding* _msg = _internal_mutable_sharding(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.sharding) + return _msg; +} +inline void HloInstructionProto::set_allocated_sharding(::xla::OpSharding* sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.sharding_); + } + if (sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(sharding)); + if (message_arena != submessage_arena) { + sharding = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, sharding, submessage_arena); + } + + } else { + + } + _impl_.sharding_ = sharding; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.sharding) +} + +// bytes backend_config = 43; +inline void HloInstructionProto::clear_backend_config() { + _impl_.backend_config_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::backend_config() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.backend_config) + return _internal_backend_config(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_backend_config(ArgT0&& arg0, ArgT... args) { + + _impl_.backend_config_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.backend_config) +} +inline std::string* HloInstructionProto::mutable_backend_config() { + std::string* _s = _internal_mutable_backend_config(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.backend_config) + return _s; +} +inline const std::string& HloInstructionProto::_internal_backend_config() const { + return _impl_.backend_config_.Get(); +} +inline void HloInstructionProto::_internal_set_backend_config(const std::string& value) { + + _impl_.backend_config_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_backend_config() { + + return _impl_.backend_config_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_backend_config() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.backend_config) + return _impl_.backend_config_.Release(); +} +inline void HloInstructionProto::set_allocated_backend_config(std::string* backend_config) { + if (backend_config != nullptr) { + + } else { + + } + _impl_.backend_config_.SetAllocated(backend_config, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.backend_config_.IsDefault()) { + _impl_.backend_config_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.backend_config) +} + +// repeated .xla.ReplicaGroup replica_groups = 49; +inline int HloInstructionProto::_internal_replica_groups_size() const { + return _impl_.replica_groups_.size(); +} +inline int HloInstructionProto::replica_groups_size() const { + return _internal_replica_groups_size(); +} +inline ::xla::ReplicaGroup* HloInstructionProto::mutable_replica_groups(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.replica_groups) + return _impl_.replica_groups_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ReplicaGroup >* +HloInstructionProto::mutable_replica_groups() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.replica_groups) + return &_impl_.replica_groups_; +} +inline const ::xla::ReplicaGroup& HloInstructionProto::_internal_replica_groups(int index) const { + return _impl_.replica_groups_.Get(index); +} +inline const ::xla::ReplicaGroup& HloInstructionProto::replica_groups(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.replica_groups) + return _internal_replica_groups(index); +} +inline ::xla::ReplicaGroup* HloInstructionProto::_internal_add_replica_groups() { + return _impl_.replica_groups_.Add(); +} +inline ::xla::ReplicaGroup* HloInstructionProto::add_replica_groups() { + ::xla::ReplicaGroup* _add = _internal_add_replica_groups(); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.replica_groups) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ReplicaGroup >& +HloInstructionProto::replica_groups() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.replica_groups) + return _impl_.replica_groups_; +} + +// int64 all_reduce_id = 45 [deprecated = true]; +inline void HloInstructionProto::clear_all_reduce_id() { + _impl_.all_reduce_id_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_all_reduce_id() const { + return _impl_.all_reduce_id_; +} +inline int64_t HloInstructionProto::all_reduce_id() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.all_reduce_id) + return _internal_all_reduce_id(); +} +inline void HloInstructionProto::_internal_set_all_reduce_id(int64_t value) { + + _impl_.all_reduce_id_ = value; +} +inline void HloInstructionProto::set_all_reduce_id(int64_t value) { + _internal_set_all_reduce_id(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.all_reduce_id) +} + +// bool use_global_device_ids = 71; +inline void HloInstructionProto::clear_use_global_device_ids() { + _impl_.use_global_device_ids_ = false; +} +inline bool HloInstructionProto::_internal_use_global_device_ids() const { + return _impl_.use_global_device_ids_; +} +inline bool HloInstructionProto::use_global_device_ids() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.use_global_device_ids) + return _internal_use_global_device_ids(); +} +inline void HloInstructionProto::_internal_set_use_global_device_ids(bool value) { + + _impl_.use_global_device_ids_ = value; +} +inline void HloInstructionProto::set_use_global_device_ids(bool value) { + _internal_set_use_global_device_ids(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.use_global_device_ids) +} + +// bool is_host_transfer = 47; +inline void HloInstructionProto::clear_is_host_transfer() { + _impl_.is_host_transfer_ = false; +} +inline bool HloInstructionProto::_internal_is_host_transfer() const { + return _impl_.is_host_transfer_; +} +inline bool HloInstructionProto::is_host_transfer() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.is_host_transfer) + return _internal_is_host_transfer(); +} +inline void HloInstructionProto::_internal_set_is_host_transfer(bool value) { + + _impl_.is_host_transfer_ = value; +} +inline void HloInstructionProto::set_is_host_transfer(bool value) { + _internal_set_is_host_transfer(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.is_host_transfer) +} + +// bool is_stable = 60; +inline void HloInstructionProto::clear_is_stable() { + _impl_.is_stable_ = false; +} +inline bool HloInstructionProto::_internal_is_stable() const { + return _impl_.is_stable_; +} +inline bool HloInstructionProto::is_stable() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.is_stable) + return _internal_is_stable(); +} +inline void HloInstructionProto::_internal_set_is_stable(bool value) { + + _impl_.is_stable_ = value; +} +inline void HloInstructionProto::set_is_stable(bool value) { + _internal_set_is_stable(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.is_stable) +} + +// .xla.ScatterDimensionNumbers scatter_dimension_numbers = 48; +inline bool HloInstructionProto::_internal_has_scatter_dimension_numbers() const { + return this != internal_default_instance() && _impl_.scatter_dimension_numbers_ != nullptr; +} +inline bool HloInstructionProto::has_scatter_dimension_numbers() const { + return _internal_has_scatter_dimension_numbers(); +} +inline const ::xla::ScatterDimensionNumbers& HloInstructionProto::_internal_scatter_dimension_numbers() const { + const ::xla::ScatterDimensionNumbers* p = _impl_.scatter_dimension_numbers_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ScatterDimensionNumbers_default_instance_); +} +inline const ::xla::ScatterDimensionNumbers& HloInstructionProto::scatter_dimension_numbers() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.scatter_dimension_numbers) + return _internal_scatter_dimension_numbers(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_scatter_dimension_numbers( + ::xla::ScatterDimensionNumbers* scatter_dimension_numbers) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.scatter_dimension_numbers_); + } + _impl_.scatter_dimension_numbers_ = scatter_dimension_numbers; + if (scatter_dimension_numbers) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.scatter_dimension_numbers) +} +inline ::xla::ScatterDimensionNumbers* HloInstructionProto::release_scatter_dimension_numbers() { + + ::xla::ScatterDimensionNumbers* temp = _impl_.scatter_dimension_numbers_; + _impl_.scatter_dimension_numbers_ = 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::ScatterDimensionNumbers* HloInstructionProto::unsafe_arena_release_scatter_dimension_numbers() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.scatter_dimension_numbers) + + ::xla::ScatterDimensionNumbers* temp = _impl_.scatter_dimension_numbers_; + _impl_.scatter_dimension_numbers_ = nullptr; + return temp; +} +inline ::xla::ScatterDimensionNumbers* HloInstructionProto::_internal_mutable_scatter_dimension_numbers() { + + if (_impl_.scatter_dimension_numbers_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ScatterDimensionNumbers>(GetArenaForAllocation()); + _impl_.scatter_dimension_numbers_ = p; + } + return _impl_.scatter_dimension_numbers_; +} +inline ::xla::ScatterDimensionNumbers* HloInstructionProto::mutable_scatter_dimension_numbers() { + ::xla::ScatterDimensionNumbers* _msg = _internal_mutable_scatter_dimension_numbers(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.scatter_dimension_numbers) + return _msg; +} +inline void HloInstructionProto::set_allocated_scatter_dimension_numbers(::xla::ScatterDimensionNumbers* scatter_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.scatter_dimension_numbers_); + } + if (scatter_dimension_numbers) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(scatter_dimension_numbers)); + if (message_arena != submessage_arena) { + scatter_dimension_numbers = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, scatter_dimension_numbers, submessage_arena); + } + + } else { + + } + _impl_.scatter_dimension_numbers_ = scatter_dimension_numbers; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.scatter_dimension_numbers) +} + +// .xla.PrecisionConfig precision_config = 51; +inline bool HloInstructionProto::_internal_has_precision_config() const { + return this != internal_default_instance() && _impl_.precision_config_ != nullptr; +} +inline bool HloInstructionProto::has_precision_config() const { + return _internal_has_precision_config(); +} +inline const ::xla::PrecisionConfig& HloInstructionProto::_internal_precision_config() const { + const ::xla::PrecisionConfig* p = _impl_.precision_config_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_PrecisionConfig_default_instance_); +} +inline const ::xla::PrecisionConfig& HloInstructionProto::precision_config() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.precision_config) + return _internal_precision_config(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_precision_config( + ::xla::PrecisionConfig* precision_config) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.precision_config_); + } + _impl_.precision_config_ = precision_config; + if (precision_config) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.precision_config) +} +inline ::xla::PrecisionConfig* HloInstructionProto::release_precision_config() { + + ::xla::PrecisionConfig* temp = _impl_.precision_config_; + _impl_.precision_config_ = 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::PrecisionConfig* HloInstructionProto::unsafe_arena_release_precision_config() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.precision_config) + + ::xla::PrecisionConfig* temp = _impl_.precision_config_; + _impl_.precision_config_ = nullptr; + return temp; +} +inline ::xla::PrecisionConfig* HloInstructionProto::_internal_mutable_precision_config() { + + if (_impl_.precision_config_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::PrecisionConfig>(GetArenaForAllocation()); + _impl_.precision_config_ = p; + } + return _impl_.precision_config_; +} +inline ::xla::PrecisionConfig* HloInstructionProto::mutable_precision_config() { + ::xla::PrecisionConfig* _msg = _internal_mutable_precision_config(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.precision_config) + return _msg; +} +inline void HloInstructionProto::set_allocated_precision_config(::xla::PrecisionConfig* precision_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.precision_config_); + } + if (precision_config) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(precision_config)); + if (message_arena != submessage_arena) { + precision_config = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, precision_config, submessage_arena); + } + + } else { + + } + _impl_.precision_config_ = precision_config; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.precision_config) +} + +// repeated .xla.SourceTarget source_target_pairs = 52; +inline int HloInstructionProto::_internal_source_target_pairs_size() const { + return _impl_.source_target_pairs_.size(); +} +inline int HloInstructionProto::source_target_pairs_size() const { + return _internal_source_target_pairs_size(); +} +inline ::xla::SourceTarget* HloInstructionProto::mutable_source_target_pairs(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.source_target_pairs) + return _impl_.source_target_pairs_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::SourceTarget >* +HloInstructionProto::mutable_source_target_pairs() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.source_target_pairs) + return &_impl_.source_target_pairs_; +} +inline const ::xla::SourceTarget& HloInstructionProto::_internal_source_target_pairs(int index) const { + return _impl_.source_target_pairs_.Get(index); +} +inline const ::xla::SourceTarget& HloInstructionProto::source_target_pairs(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.source_target_pairs) + return _internal_source_target_pairs(index); +} +inline ::xla::SourceTarget* HloInstructionProto::_internal_add_source_target_pairs() { + return _impl_.source_target_pairs_.Add(); +} +inline ::xla::SourceTarget* HloInstructionProto::add_source_target_pairs() { + ::xla::SourceTarget* _add = _internal_add_source_target_pairs(); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.source_target_pairs) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::SourceTarget >& +HloInstructionProto::source_target_pairs() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.source_target_pairs) + return _impl_.source_target_pairs_; +} + +// .xla.OpSharding domain_entry_sharding = 54; +inline bool HloInstructionProto::_internal_has_domain_entry_sharding() const { + return this != internal_default_instance() && _impl_.domain_entry_sharding_ != nullptr; +} +inline bool HloInstructionProto::has_domain_entry_sharding() const { + return _internal_has_domain_entry_sharding(); +} +inline const ::xla::OpSharding& HloInstructionProto::_internal_domain_entry_sharding() const { + const ::xla::OpSharding* p = _impl_.domain_entry_sharding_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_OpSharding_default_instance_); +} +inline const ::xla::OpSharding& HloInstructionProto::domain_entry_sharding() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.domain_entry_sharding) + return _internal_domain_entry_sharding(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_domain_entry_sharding( + ::xla::OpSharding* domain_entry_sharding) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.domain_entry_sharding_); + } + _impl_.domain_entry_sharding_ = domain_entry_sharding; + if (domain_entry_sharding) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.domain_entry_sharding) +} +inline ::xla::OpSharding* HloInstructionProto::release_domain_entry_sharding() { + + ::xla::OpSharding* temp = _impl_.domain_entry_sharding_; + _impl_.domain_entry_sharding_ = 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::OpSharding* HloInstructionProto::unsafe_arena_release_domain_entry_sharding() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.domain_entry_sharding) + + ::xla::OpSharding* temp = _impl_.domain_entry_sharding_; + _impl_.domain_entry_sharding_ = nullptr; + return temp; +} +inline ::xla::OpSharding* HloInstructionProto::_internal_mutable_domain_entry_sharding() { + + if (_impl_.domain_entry_sharding_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::OpSharding>(GetArenaForAllocation()); + _impl_.domain_entry_sharding_ = p; + } + return _impl_.domain_entry_sharding_; +} +inline ::xla::OpSharding* HloInstructionProto::mutable_domain_entry_sharding() { + ::xla::OpSharding* _msg = _internal_mutable_domain_entry_sharding(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.domain_entry_sharding) + return _msg; +} +inline void HloInstructionProto::set_allocated_domain_entry_sharding(::xla::OpSharding* domain_entry_sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.domain_entry_sharding_); + } + if (domain_entry_sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(domain_entry_sharding)); + if (message_arena != submessage_arena) { + domain_entry_sharding = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, domain_entry_sharding, submessage_arena); + } + + } else { + + } + _impl_.domain_entry_sharding_ = domain_entry_sharding; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.domain_entry_sharding) +} + +// .xla.OpSharding domain_exit_sharding = 55; +inline bool HloInstructionProto::_internal_has_domain_exit_sharding() const { + return this != internal_default_instance() && _impl_.domain_exit_sharding_ != nullptr; +} +inline bool HloInstructionProto::has_domain_exit_sharding() const { + return _internal_has_domain_exit_sharding(); +} +inline const ::xla::OpSharding& HloInstructionProto::_internal_domain_exit_sharding() const { + const ::xla::OpSharding* p = _impl_.domain_exit_sharding_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_OpSharding_default_instance_); +} +inline const ::xla::OpSharding& HloInstructionProto::domain_exit_sharding() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.domain_exit_sharding) + return _internal_domain_exit_sharding(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_domain_exit_sharding( + ::xla::OpSharding* domain_exit_sharding) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.domain_exit_sharding_); + } + _impl_.domain_exit_sharding_ = domain_exit_sharding; + if (domain_exit_sharding) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.domain_exit_sharding) +} +inline ::xla::OpSharding* HloInstructionProto::release_domain_exit_sharding() { + + ::xla::OpSharding* temp = _impl_.domain_exit_sharding_; + _impl_.domain_exit_sharding_ = 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::OpSharding* HloInstructionProto::unsafe_arena_release_domain_exit_sharding() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.domain_exit_sharding) + + ::xla::OpSharding* temp = _impl_.domain_exit_sharding_; + _impl_.domain_exit_sharding_ = nullptr; + return temp; +} +inline ::xla::OpSharding* HloInstructionProto::_internal_mutable_domain_exit_sharding() { + + if (_impl_.domain_exit_sharding_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::OpSharding>(GetArenaForAllocation()); + _impl_.domain_exit_sharding_ = p; + } + return _impl_.domain_exit_sharding_; +} +inline ::xla::OpSharding* HloInstructionProto::mutable_domain_exit_sharding() { + ::xla::OpSharding* _msg = _internal_mutable_domain_exit_sharding(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.domain_exit_sharding) + return _msg; +} +inline void HloInstructionProto::set_allocated_domain_exit_sharding(::xla::OpSharding* domain_exit_sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.domain_exit_sharding_); + } + if (domain_exit_sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(domain_exit_sharding)); + if (message_arena != submessage_arena) { + domain_exit_sharding = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, domain_exit_sharding, submessage_arena); + } + + } else { + + } + _impl_.domain_exit_sharding_ = domain_exit_sharding; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.domain_exit_sharding) +} + +// bool constrain_layout = 56; +inline void HloInstructionProto::clear_constrain_layout() { + _impl_.constrain_layout_ = false; +} +inline bool HloInstructionProto::_internal_constrain_layout() const { + return _impl_.constrain_layout_; +} +inline bool HloInstructionProto::constrain_layout() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.constrain_layout) + return _internal_constrain_layout(); +} +inline void HloInstructionProto::_internal_set_constrain_layout(bool value) { + + _impl_.constrain_layout_ = value; +} +inline void HloInstructionProto::set_constrain_layout(bool value) { + _internal_set_constrain_layout(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.constrain_layout) +} + +// repeated .xla.ShapeProto operand_shapes_with_layout = 57; +inline int HloInstructionProto::_internal_operand_shapes_with_layout_size() const { + return _impl_.operand_shapes_with_layout_.size(); +} +inline int HloInstructionProto::operand_shapes_with_layout_size() const { + return _internal_operand_shapes_with_layout_size(); +} +inline ::xla::ShapeProto* HloInstructionProto::mutable_operand_shapes_with_layout(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.operand_shapes_with_layout) + return _impl_.operand_shapes_with_layout_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >* +HloInstructionProto::mutable_operand_shapes_with_layout() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.operand_shapes_with_layout) + return &_impl_.operand_shapes_with_layout_; +} +inline const ::xla::ShapeProto& HloInstructionProto::_internal_operand_shapes_with_layout(int index) const { + return _impl_.operand_shapes_with_layout_.Get(index); +} +inline const ::xla::ShapeProto& HloInstructionProto::operand_shapes_with_layout(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.operand_shapes_with_layout) + return _internal_operand_shapes_with_layout(index); +} +inline ::xla::ShapeProto* HloInstructionProto::_internal_add_operand_shapes_with_layout() { + return _impl_.operand_shapes_with_layout_.Add(); +} +inline ::xla::ShapeProto* HloInstructionProto::add_operand_shapes_with_layout() { + ::xla::ShapeProto* _add = _internal_add_operand_shapes_with_layout(); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.operand_shapes_with_layout) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >& +HloInstructionProto::operand_shapes_with_layout() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.operand_shapes_with_layout) + return _impl_.operand_shapes_with_layout_; +} + +// .xla.TriangularSolveOptions triangular_solve_options = 59; +inline bool HloInstructionProto::_internal_has_triangular_solve_options() const { + return this != internal_default_instance() && _impl_.triangular_solve_options_ != nullptr; +} +inline bool HloInstructionProto::has_triangular_solve_options() const { + return _internal_has_triangular_solve_options(); +} +inline const ::xla::TriangularSolveOptions& HloInstructionProto::_internal_triangular_solve_options() const { + const ::xla::TriangularSolveOptions* p = _impl_.triangular_solve_options_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_TriangularSolveOptions_default_instance_); +} +inline const ::xla::TriangularSolveOptions& HloInstructionProto::triangular_solve_options() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.triangular_solve_options) + return _internal_triangular_solve_options(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_triangular_solve_options( + ::xla::TriangularSolveOptions* triangular_solve_options) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.triangular_solve_options_); + } + _impl_.triangular_solve_options_ = triangular_solve_options; + if (triangular_solve_options) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.triangular_solve_options) +} +inline ::xla::TriangularSolveOptions* HloInstructionProto::release_triangular_solve_options() { + + ::xla::TriangularSolveOptions* temp = _impl_.triangular_solve_options_; + _impl_.triangular_solve_options_ = 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::TriangularSolveOptions* HloInstructionProto::unsafe_arena_release_triangular_solve_options() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.triangular_solve_options) + + ::xla::TriangularSolveOptions* temp = _impl_.triangular_solve_options_; + _impl_.triangular_solve_options_ = nullptr; + return temp; +} +inline ::xla::TriangularSolveOptions* HloInstructionProto::_internal_mutable_triangular_solve_options() { + + if (_impl_.triangular_solve_options_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::TriangularSolveOptions>(GetArenaForAllocation()); + _impl_.triangular_solve_options_ = p; + } + return _impl_.triangular_solve_options_; +} +inline ::xla::TriangularSolveOptions* HloInstructionProto::mutable_triangular_solve_options() { + ::xla::TriangularSolveOptions* _msg = _internal_mutable_triangular_solve_options(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.triangular_solve_options) + return _msg; +} +inline void HloInstructionProto::set_allocated_triangular_solve_options(::xla::TriangularSolveOptions* triangular_solve_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.triangular_solve_options_); + } + if (triangular_solve_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(triangular_solve_options)); + if (message_arena != submessage_arena) { + triangular_solve_options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, triangular_solve_options, submessage_arena); + } + + } else { + + } + _impl_.triangular_solve_options_ = triangular_solve_options; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.triangular_solve_options) +} + +// .xla.CholeskyOptions cholesky_options = 62; +inline bool HloInstructionProto::_internal_has_cholesky_options() const { + return this != internal_default_instance() && _impl_.cholesky_options_ != nullptr; +} +inline bool HloInstructionProto::has_cholesky_options() const { + return _internal_has_cholesky_options(); +} +inline const ::xla::CholeskyOptions& HloInstructionProto::_internal_cholesky_options() const { + const ::xla::CholeskyOptions* p = _impl_.cholesky_options_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_CholeskyOptions_default_instance_); +} +inline const ::xla::CholeskyOptions& HloInstructionProto::cholesky_options() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.cholesky_options) + return _internal_cholesky_options(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_cholesky_options( + ::xla::CholeskyOptions* cholesky_options) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cholesky_options_); + } + _impl_.cholesky_options_ = cholesky_options; + if (cholesky_options) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.cholesky_options) +} +inline ::xla::CholeskyOptions* HloInstructionProto::release_cholesky_options() { + + ::xla::CholeskyOptions* temp = _impl_.cholesky_options_; + _impl_.cholesky_options_ = 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::CholeskyOptions* HloInstructionProto::unsafe_arena_release_cholesky_options() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.cholesky_options) + + ::xla::CholeskyOptions* temp = _impl_.cholesky_options_; + _impl_.cholesky_options_ = nullptr; + return temp; +} +inline ::xla::CholeskyOptions* HloInstructionProto::_internal_mutable_cholesky_options() { + + if (_impl_.cholesky_options_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::CholeskyOptions>(GetArenaForAllocation()); + _impl_.cholesky_options_ = p; + } + return _impl_.cholesky_options_; +} +inline ::xla::CholeskyOptions* HloInstructionProto::mutable_cholesky_options() { + ::xla::CholeskyOptions* _msg = _internal_mutable_cholesky_options(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.cholesky_options) + return _msg; +} +inline void HloInstructionProto::set_allocated_cholesky_options(::xla::CholeskyOptions* cholesky_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cholesky_options_); + } + if (cholesky_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(cholesky_options)); + if (message_arena != submessage_arena) { + cholesky_options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, cholesky_options, submessage_arena); + } + + } else { + + } + _impl_.cholesky_options_ = cholesky_options; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.cholesky_options) +} + +// .xla.ParameterReplication parameter_replication = 61; +inline bool HloInstructionProto::_internal_has_parameter_replication() const { + return this != internal_default_instance() && _impl_.parameter_replication_ != nullptr; +} +inline bool HloInstructionProto::has_parameter_replication() const { + return _internal_has_parameter_replication(); +} +inline const ::xla::ParameterReplication& HloInstructionProto::_internal_parameter_replication() const { + const ::xla::ParameterReplication* p = _impl_.parameter_replication_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ParameterReplication_default_instance_); +} +inline const ::xla::ParameterReplication& HloInstructionProto::parameter_replication() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.parameter_replication) + return _internal_parameter_replication(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_parameter_replication( + ::xla::ParameterReplication* parameter_replication) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.parameter_replication_); + } + _impl_.parameter_replication_ = parameter_replication; + if (parameter_replication) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.parameter_replication) +} +inline ::xla::ParameterReplication* HloInstructionProto::release_parameter_replication() { + + ::xla::ParameterReplication* temp = _impl_.parameter_replication_; + _impl_.parameter_replication_ = 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::ParameterReplication* HloInstructionProto::unsafe_arena_release_parameter_replication() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.parameter_replication) + + ::xla::ParameterReplication* temp = _impl_.parameter_replication_; + _impl_.parameter_replication_ = nullptr; + return temp; +} +inline ::xla::ParameterReplication* HloInstructionProto::_internal_mutable_parameter_replication() { + + if (_impl_.parameter_replication_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ParameterReplication>(GetArenaForAllocation()); + _impl_.parameter_replication_ = p; + } + return _impl_.parameter_replication_; +} +inline ::xla::ParameterReplication* HloInstructionProto::mutable_parameter_replication() { + ::xla::ParameterReplication* _msg = _internal_mutable_parameter_replication(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.parameter_replication) + return _msg; +} +inline void HloInstructionProto::set_allocated_parameter_replication(::xla::ParameterReplication* parameter_replication) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.parameter_replication_); + } + if (parameter_replication) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(parameter_replication)); + if (message_arena != submessage_arena) { + parameter_replication = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, parameter_replication, submessage_arena); + } + + } else { + + } + _impl_.parameter_replication_ = parameter_replication; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.parameter_replication) +} + +// bool custom_call_has_side_effect = 65; +inline void HloInstructionProto::clear_custom_call_has_side_effect() { + _impl_.custom_call_has_side_effect_ = false; +} +inline bool HloInstructionProto::_internal_custom_call_has_side_effect() const { + return _impl_.custom_call_has_side_effect_; +} +inline bool HloInstructionProto::custom_call_has_side_effect() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.custom_call_has_side_effect) + return _internal_custom_call_has_side_effect(); +} +inline void HloInstructionProto::_internal_set_custom_call_has_side_effect(bool value) { + + _impl_.custom_call_has_side_effect_ = value; +} +inline void HloInstructionProto::set_custom_call_has_side_effect(bool value) { + _internal_set_custom_call_has_side_effect(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.custom_call_has_side_effect) +} + +// repeated .xla.OutputOperandAliasing output_operand_aliasing = 74; +inline int HloInstructionProto::_internal_output_operand_aliasing_size() const { + return _impl_.output_operand_aliasing_.size(); +} +inline int HloInstructionProto::output_operand_aliasing_size() const { + return _internal_output_operand_aliasing_size(); +} +inline ::xla::OutputOperandAliasing* HloInstructionProto::mutable_output_operand_aliasing(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.output_operand_aliasing) + return _impl_.output_operand_aliasing_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OutputOperandAliasing >* +HloInstructionProto::mutable_output_operand_aliasing() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInstructionProto.output_operand_aliasing) + return &_impl_.output_operand_aliasing_; +} +inline const ::xla::OutputOperandAliasing& HloInstructionProto::_internal_output_operand_aliasing(int index) const { + return _impl_.output_operand_aliasing_.Get(index); +} +inline const ::xla::OutputOperandAliasing& HloInstructionProto::output_operand_aliasing(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.output_operand_aliasing) + return _internal_output_operand_aliasing(index); +} +inline ::xla::OutputOperandAliasing* HloInstructionProto::_internal_add_output_operand_aliasing() { + return _impl_.output_operand_aliasing_.Add(); +} +inline ::xla::OutputOperandAliasing* HloInstructionProto::add_output_operand_aliasing() { + ::xla::OutputOperandAliasing* _add = _internal_add_output_operand_aliasing(); + // @@protoc_insertion_point(field_add:xla.HloInstructionProto.output_operand_aliasing) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OutputOperandAliasing >& +HloInstructionProto::output_operand_aliasing() const { + // @@protoc_insertion_point(field_list:xla.HloInstructionProto.output_operand_aliasing) + return _impl_.output_operand_aliasing_; +} + +// .xla.CustomCallSchedule custom_call_schedule = 76; +inline void HloInstructionProto::clear_custom_call_schedule() { + _impl_.custom_call_schedule_ = 0; +} +inline ::xla::CustomCallSchedule HloInstructionProto::_internal_custom_call_schedule() const { + return static_cast< ::xla::CustomCallSchedule >(_impl_.custom_call_schedule_); +} +inline ::xla::CustomCallSchedule HloInstructionProto::custom_call_schedule() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.custom_call_schedule) + return _internal_custom_call_schedule(); +} +inline void HloInstructionProto::_internal_set_custom_call_schedule(::xla::CustomCallSchedule value) { + + _impl_.custom_call_schedule_ = value; +} +inline void HloInstructionProto::set_custom_call_schedule(::xla::CustomCallSchedule value) { + _internal_set_custom_call_schedule(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.custom_call_schedule) +} + +// int64 delta = 66; +inline void HloInstructionProto::clear_delta() { + _impl_.delta_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_delta() const { + return _impl_.delta_; +} +inline int64_t HloInstructionProto::delta() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.delta) + return _internal_delta(); +} +inline void HloInstructionProto::_internal_set_delta(int64_t value) { + + _impl_.delta_ = value; +} +inline void HloInstructionProto::set_delta(int64_t value) { + _internal_set_delta(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.delta) +} + +// bool indices_are_sorted = 67; +inline void HloInstructionProto::clear_indices_are_sorted() { + _impl_.indices_are_sorted_ = false; +} +inline bool HloInstructionProto::_internal_indices_are_sorted() const { + return _impl_.indices_are_sorted_; +} +inline bool HloInstructionProto::indices_are_sorted() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.indices_are_sorted) + return _internal_indices_are_sorted(); +} +inline void HloInstructionProto::_internal_set_indices_are_sorted(bool value) { + + _impl_.indices_are_sorted_ = value; +} +inline void HloInstructionProto::set_indices_are_sorted(bool value) { + _internal_set_indices_are_sorted(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.indices_are_sorted) +} + +// .xla.FrontendAttributes frontend_attributes = 68; +inline bool HloInstructionProto::_internal_has_frontend_attributes() const { + return this != internal_default_instance() && _impl_.frontend_attributes_ != nullptr; +} +inline bool HloInstructionProto::has_frontend_attributes() const { + return _internal_has_frontend_attributes(); +} +inline const ::xla::FrontendAttributes& HloInstructionProto::_internal_frontend_attributes() const { + const ::xla::FrontendAttributes* p = _impl_.frontend_attributes_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_FrontendAttributes_default_instance_); +} +inline const ::xla::FrontendAttributes& HloInstructionProto::frontend_attributes() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.frontend_attributes) + return _internal_frontend_attributes(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_frontend_attributes( + ::xla::FrontendAttributes* frontend_attributes) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.frontend_attributes_); + } + _impl_.frontend_attributes_ = frontend_attributes; + if (frontend_attributes) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.frontend_attributes) +} +inline ::xla::FrontendAttributes* HloInstructionProto::release_frontend_attributes() { + + ::xla::FrontendAttributes* temp = _impl_.frontend_attributes_; + _impl_.frontend_attributes_ = 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::FrontendAttributes* HloInstructionProto::unsafe_arena_release_frontend_attributes() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.frontend_attributes) + + ::xla::FrontendAttributes* temp = _impl_.frontend_attributes_; + _impl_.frontend_attributes_ = nullptr; + return temp; +} +inline ::xla::FrontendAttributes* HloInstructionProto::_internal_mutable_frontend_attributes() { + + if (_impl_.frontend_attributes_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::FrontendAttributes>(GetArenaForAllocation()); + _impl_.frontend_attributes_ = p; + } + return _impl_.frontend_attributes_; +} +inline ::xla::FrontendAttributes* HloInstructionProto::mutable_frontend_attributes() { + ::xla::FrontendAttributes* _msg = _internal_mutable_frontend_attributes(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.frontend_attributes) + return _msg; +} +inline void HloInstructionProto::set_allocated_frontend_attributes(::xla::FrontendAttributes* frontend_attributes) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.frontend_attributes_); + } + if (frontend_attributes) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(frontend_attributes)); + if (message_arena != submessage_arena) { + frontend_attributes = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, frontend_attributes, submessage_arena); + } + + } else { + + } + _impl_.frontend_attributes_ = frontend_attributes; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.frontend_attributes) +} + +// bool unique_indices = 69; +inline void HloInstructionProto::clear_unique_indices() { + _impl_.unique_indices_ = false; +} +inline bool HloInstructionProto::_internal_unique_indices() const { + return _impl_.unique_indices_; +} +inline bool HloInstructionProto::unique_indices() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.unique_indices) + return _internal_unique_indices(); +} +inline void HloInstructionProto::_internal_set_unique_indices(bool value) { + + _impl_.unique_indices_ = value; +} +inline void HloInstructionProto::set_unique_indices(bool value) { + _internal_set_unique_indices(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.unique_indices) +} + +// .xla.RandomAlgorithm rng_algorithm = 70; +inline void HloInstructionProto::clear_rng_algorithm() { + _impl_.rng_algorithm_ = 0; +} +inline ::xla::RandomAlgorithm HloInstructionProto::_internal_rng_algorithm() const { + return static_cast< ::xla::RandomAlgorithm >(_impl_.rng_algorithm_); +} +inline ::xla::RandomAlgorithm HloInstructionProto::rng_algorithm() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.rng_algorithm) + return _internal_rng_algorithm(); +} +inline void HloInstructionProto::_internal_set_rng_algorithm(::xla::RandomAlgorithm value) { + + _impl_.rng_algorithm_ = value; +} +inline void HloInstructionProto::set_rng_algorithm(::xla::RandomAlgorithm value) { + _internal_set_rng_algorithm(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.rng_algorithm) +} + +// string comparison_type = 72; +inline void HloInstructionProto::clear_comparison_type() { + _impl_.comparison_type_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::comparison_type() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.comparison_type) + return _internal_comparison_type(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_comparison_type(ArgT0&& arg0, ArgT... args) { + + _impl_.comparison_type_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.comparison_type) +} +inline std::string* HloInstructionProto::mutable_comparison_type() { + std::string* _s = _internal_mutable_comparison_type(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.comparison_type) + return _s; +} +inline const std::string& HloInstructionProto::_internal_comparison_type() const { + return _impl_.comparison_type_.Get(); +} +inline void HloInstructionProto::_internal_set_comparison_type(const std::string& value) { + + _impl_.comparison_type_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_comparison_type() { + + return _impl_.comparison_type_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_comparison_type() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.comparison_type) + return _impl_.comparison_type_.Release(); +} +inline void HloInstructionProto::set_allocated_comparison_type(std::string* comparison_type) { + if (comparison_type != nullptr) { + + } else { + + } + _impl_.comparison_type_.SetAllocated(comparison_type, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.comparison_type_.IsDefault()) { + _impl_.comparison_type_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.comparison_type) +} + +// bool is_cross_program_prefetch = 73 [deprecated = true]; +inline void HloInstructionProto::clear_is_cross_program_prefetch() { + _impl_.is_cross_program_prefetch_ = false; +} +inline bool HloInstructionProto::_internal_is_cross_program_prefetch() const { + return _impl_.is_cross_program_prefetch_; +} +inline bool HloInstructionProto::is_cross_program_prefetch() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.is_cross_program_prefetch) + return _internal_is_cross_program_prefetch(); +} +inline void HloInstructionProto::_internal_set_is_cross_program_prefetch(bool value) { + + _impl_.is_cross_program_prefetch_ = value; +} +inline void HloInstructionProto::set_is_cross_program_prefetch(bool value) { + _internal_set_is_cross_program_prefetch(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.is_cross_program_prefetch) +} + +// int32 cross_program_prefetch_index = 80; +inline bool HloInstructionProto::_internal_has_cross_program_prefetch_index() const { + return optional_cross_program_prefetch_index_case() == kCrossProgramPrefetchIndex; +} +inline bool HloInstructionProto::has_cross_program_prefetch_index() const { + return _internal_has_cross_program_prefetch_index(); +} +inline void HloInstructionProto::set_has_cross_program_prefetch_index() { + _impl_._oneof_case_[0] = kCrossProgramPrefetchIndex; +} +inline void HloInstructionProto::clear_cross_program_prefetch_index() { + if (_internal_has_cross_program_prefetch_index()) { + _impl_.optional_cross_program_prefetch_index_.cross_program_prefetch_index_ = 0; + clear_has_optional_cross_program_prefetch_index(); + } +} +inline int32_t HloInstructionProto::_internal_cross_program_prefetch_index() const { + if (_internal_has_cross_program_prefetch_index()) { + return _impl_.optional_cross_program_prefetch_index_.cross_program_prefetch_index_; + } + return 0; +} +inline void HloInstructionProto::_internal_set_cross_program_prefetch_index(int32_t value) { + if (!_internal_has_cross_program_prefetch_index()) { + clear_optional_cross_program_prefetch_index(); + set_has_cross_program_prefetch_index(); + } + _impl_.optional_cross_program_prefetch_index_.cross_program_prefetch_index_ = value; +} +inline int32_t HloInstructionProto::cross_program_prefetch_index() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.cross_program_prefetch_index) + return _internal_cross_program_prefetch_index(); +} +inline void HloInstructionProto::set_cross_program_prefetch_index(int32_t value) { + _internal_set_cross_program_prefetch_index(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.cross_program_prefetch_index) +} + +// .xla.PaddingType padding_type = 75; +inline void HloInstructionProto::clear_padding_type() { + _impl_.padding_type_ = 0; +} +inline ::xla::PaddingType HloInstructionProto::_internal_padding_type() const { + return static_cast< ::xla::PaddingType >(_impl_.padding_type_); +} +inline ::xla::PaddingType HloInstructionProto::padding_type() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.padding_type) + return _internal_padding_type(); +} +inline void HloInstructionProto::_internal_set_padding_type(::xla::PaddingType value) { + + _impl_.padding_type_ = value; +} +inline void HloInstructionProto::set_padding_type(::xla::PaddingType value) { + _internal_set_padding_type(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.padding_type) +} + +// .xla.CustomCallApiVersion custom_call_api_version = 77; +inline void HloInstructionProto::clear_custom_call_api_version() { + _impl_.custom_call_api_version_ = 0; +} +inline ::xla::CustomCallApiVersion HloInstructionProto::_internal_custom_call_api_version() const { + return static_cast< ::xla::CustomCallApiVersion >(_impl_.custom_call_api_version_); +} +inline ::xla::CustomCallApiVersion HloInstructionProto::custom_call_api_version() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.custom_call_api_version) + return _internal_custom_call_api_version(); +} +inline void HloInstructionProto::_internal_set_custom_call_api_version(::xla::CustomCallApiVersion value) { + + _impl_.custom_call_api_version_ = value; +} +inline void HloInstructionProto::set_custom_call_api_version(::xla::CustomCallApiVersion value) { + _internal_set_custom_call_api_version(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.custom_call_api_version) +} + +// int64 async_group_id = 78; +inline void HloInstructionProto::clear_async_group_id() { + _impl_.async_group_id_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_async_group_id() const { + return _impl_.async_group_id_; +} +inline int64_t HloInstructionProto::async_group_id() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.async_group_id) + return _internal_async_group_id(); +} +inline void HloInstructionProto::_internal_set_async_group_id(int64_t value) { + + _impl_.async_group_id_ = value; +} +inline void HloInstructionProto::set_async_group_id(int64_t value) { + _internal_set_async_group_id(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.async_group_id) +} + +// string async_execution_thread = 79; +inline void HloInstructionProto::clear_async_execution_thread() { + _impl_.async_execution_thread_.ClearToEmpty(); +} +inline const std::string& HloInstructionProto::async_execution_thread() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.async_execution_thread) + return _internal_async_execution_thread(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloInstructionProto::set_async_execution_thread(ArgT0&& arg0, ArgT... args) { + + _impl_.async_execution_thread_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.async_execution_thread) +} +inline std::string* HloInstructionProto::mutable_async_execution_thread() { + std::string* _s = _internal_mutable_async_execution_thread(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.async_execution_thread) + return _s; +} +inline const std::string& HloInstructionProto::_internal_async_execution_thread() const { + return _impl_.async_execution_thread_.Get(); +} +inline void HloInstructionProto::_internal_set_async_execution_thread(const std::string& value) { + + _impl_.async_execution_thread_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::_internal_mutable_async_execution_thread() { + + return _impl_.async_execution_thread_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloInstructionProto::release_async_execution_thread() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.async_execution_thread) + return _impl_.async_execution_thread_.Release(); +} +inline void HloInstructionProto::set_allocated_async_execution_thread(std::string* async_execution_thread) { + if (async_execution_thread != nullptr) { + + } else { + + } + _impl_.async_execution_thread_.SetAllocated(async_execution_thread, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.async_execution_thread_.IsDefault()) { + _impl_.async_execution_thread_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.async_execution_thread) +} + +// int64 k = 81; +inline void HloInstructionProto::clear_k() { + _impl_.k_ = int64_t{0}; +} +inline int64_t HloInstructionProto::_internal_k() const { + return _impl_.k_; +} +inline int64_t HloInstructionProto::k() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.k) + return _internal_k(); +} +inline void HloInstructionProto::_internal_set_k(int64_t value) { + + _impl_.k_ = value; +} +inline void HloInstructionProto::set_k(int64_t value) { + _internal_set_k(value); + // @@protoc_insertion_point(field_set:xla.HloInstructionProto.k) +} + +// .xla.StatisticsViz statistics_viz = 82; +inline bool HloInstructionProto::_internal_has_statistics_viz() const { + return this != internal_default_instance() && _impl_.statistics_viz_ != nullptr; +} +inline bool HloInstructionProto::has_statistics_viz() const { + return _internal_has_statistics_viz(); +} +inline const ::xla::StatisticsViz& HloInstructionProto::_internal_statistics_viz() const { + const ::xla::StatisticsViz* p = _impl_.statistics_viz_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_StatisticsViz_default_instance_); +} +inline const ::xla::StatisticsViz& HloInstructionProto::statistics_viz() const { + // @@protoc_insertion_point(field_get:xla.HloInstructionProto.statistics_viz) + return _internal_statistics_viz(); +} +inline void HloInstructionProto::unsafe_arena_set_allocated_statistics_viz( + ::xla::StatisticsViz* statistics_viz) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.statistics_viz_); + } + _impl_.statistics_viz_ = statistics_viz; + if (statistics_viz) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloInstructionProto.statistics_viz) +} +inline ::xla::StatisticsViz* HloInstructionProto::release_statistics_viz() { + + ::xla::StatisticsViz* temp = _impl_.statistics_viz_; + _impl_.statistics_viz_ = 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::StatisticsViz* HloInstructionProto::unsafe_arena_release_statistics_viz() { + // @@protoc_insertion_point(field_release:xla.HloInstructionProto.statistics_viz) + + ::xla::StatisticsViz* temp = _impl_.statistics_viz_; + _impl_.statistics_viz_ = nullptr; + return temp; +} +inline ::xla::StatisticsViz* HloInstructionProto::_internal_mutable_statistics_viz() { + + if (_impl_.statistics_viz_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::StatisticsViz>(GetArenaForAllocation()); + _impl_.statistics_viz_ = p; + } + return _impl_.statistics_viz_; +} +inline ::xla::StatisticsViz* HloInstructionProto::mutable_statistics_viz() { + ::xla::StatisticsViz* _msg = _internal_mutable_statistics_viz(); + // @@protoc_insertion_point(field_mutable:xla.HloInstructionProto.statistics_viz) + return _msg; +} +inline void HloInstructionProto::set_allocated_statistics_viz(::xla::StatisticsViz* statistics_viz) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.statistics_viz_); + } + if (statistics_viz) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(statistics_viz)); + if (message_arena != submessage_arena) { + statistics_viz = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, statistics_viz, submessage_arena); + } + + } else { + + } + _impl_.statistics_viz_ = statistics_viz; + // @@protoc_insertion_point(field_set_allocated:xla.HloInstructionProto.statistics_viz) +} + +inline bool HloInstructionProto::has_optional_cross_program_prefetch_index() const { + return optional_cross_program_prefetch_index_case() != OPTIONAL_CROSS_PROGRAM_PREFETCH_INDEX_NOT_SET; +} +inline void HloInstructionProto::clear_has_optional_cross_program_prefetch_index() { + _impl_._oneof_case_[0] = OPTIONAL_CROSS_PROGRAM_PREFETCH_INDEX_NOT_SET; +} +inline HloInstructionProto::OptionalCrossProgramPrefetchIndexCase HloInstructionProto::optional_cross_program_prefetch_index_case() const { + return HloInstructionProto::OptionalCrossProgramPrefetchIndexCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// HloComputationProto + +// string name = 1; +inline void HloComputationProto::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& HloComputationProto::name() const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloComputationProto::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloComputationProto.name) +} +inline std::string* HloComputationProto::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:xla.HloComputationProto.name) + return _s; +} +inline const std::string& HloComputationProto::_internal_name() const { + return _impl_.name_.Get(); +} +inline void HloComputationProto::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloComputationProto::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloComputationProto::release_name() { + // @@protoc_insertion_point(field_release:xla.HloComputationProto.name) + return _impl_.name_.Release(); +} +inline void HloComputationProto::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:xla.HloComputationProto.name) +} + +// repeated .xla.HloInstructionProto instructions = 2; +inline int HloComputationProto::_internal_instructions_size() const { + return _impl_.instructions_.size(); +} +inline int HloComputationProto::instructions_size() const { + return _internal_instructions_size(); +} +inline void HloComputationProto::clear_instructions() { + _impl_.instructions_.Clear(); +} +inline ::xla::HloInstructionProto* HloComputationProto::mutable_instructions(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloComputationProto.instructions) + return _impl_.instructions_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto >* +HloComputationProto::mutable_instructions() { + // @@protoc_insertion_point(field_mutable_list:xla.HloComputationProto.instructions) + return &_impl_.instructions_; +} +inline const ::xla::HloInstructionProto& HloComputationProto::_internal_instructions(int index) const { + return _impl_.instructions_.Get(index); +} +inline const ::xla::HloInstructionProto& HloComputationProto::instructions(int index) const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.instructions) + return _internal_instructions(index); +} +inline ::xla::HloInstructionProto* HloComputationProto::_internal_add_instructions() { + return _impl_.instructions_.Add(); +} +inline ::xla::HloInstructionProto* HloComputationProto::add_instructions() { + ::xla::HloInstructionProto* _add = _internal_add_instructions(); + // @@protoc_insertion_point(field_add:xla.HloComputationProto.instructions) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInstructionProto >& +HloComputationProto::instructions() const { + // @@protoc_insertion_point(field_list:xla.HloComputationProto.instructions) + return _impl_.instructions_; +} + +// .xla.ProgramShapeProto program_shape = 4; +inline bool HloComputationProto::_internal_has_program_shape() const { + return this != internal_default_instance() && _impl_.program_shape_ != nullptr; +} +inline bool HloComputationProto::has_program_shape() const { + return _internal_has_program_shape(); +} +inline const ::xla::ProgramShapeProto& HloComputationProto::_internal_program_shape() const { + const ::xla::ProgramShapeProto* p = _impl_.program_shape_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ProgramShapeProto_default_instance_); +} +inline const ::xla::ProgramShapeProto& HloComputationProto::program_shape() const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.program_shape) + return _internal_program_shape(); +} +inline void HloComputationProto::unsafe_arena_set_allocated_program_shape( + ::xla::ProgramShapeProto* program_shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.program_shape_); + } + _impl_.program_shape_ = program_shape; + if (program_shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloComputationProto.program_shape) +} +inline ::xla::ProgramShapeProto* HloComputationProto::release_program_shape() { + + ::xla::ProgramShapeProto* temp = _impl_.program_shape_; + _impl_.program_shape_ = 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::ProgramShapeProto* HloComputationProto::unsafe_arena_release_program_shape() { + // @@protoc_insertion_point(field_release:xla.HloComputationProto.program_shape) + + ::xla::ProgramShapeProto* temp = _impl_.program_shape_; + _impl_.program_shape_ = nullptr; + return temp; +} +inline ::xla::ProgramShapeProto* HloComputationProto::_internal_mutable_program_shape() { + + if (_impl_.program_shape_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ProgramShapeProto>(GetArenaForAllocation()); + _impl_.program_shape_ = p; + } + return _impl_.program_shape_; +} +inline ::xla::ProgramShapeProto* HloComputationProto::mutable_program_shape() { + ::xla::ProgramShapeProto* _msg = _internal_mutable_program_shape(); + // @@protoc_insertion_point(field_mutable:xla.HloComputationProto.program_shape) + return _msg; +} +inline void HloComputationProto::set_allocated_program_shape(::xla::ProgramShapeProto* program_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.program_shape_); + } + if (program_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(program_shape)); + if (message_arena != submessage_arena) { + program_shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, program_shape, submessage_arena); + } + + } else { + + } + _impl_.program_shape_ = program_shape; + // @@protoc_insertion_point(field_set_allocated:xla.HloComputationProto.program_shape) +} + +// int64 id = 5; +inline void HloComputationProto::clear_id() { + _impl_.id_ = int64_t{0}; +} +inline int64_t HloComputationProto::_internal_id() const { + return _impl_.id_; +} +inline int64_t HloComputationProto::id() const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.id) + return _internal_id(); +} +inline void HloComputationProto::_internal_set_id(int64_t value) { + + _impl_.id_ = value; +} +inline void HloComputationProto::set_id(int64_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:xla.HloComputationProto.id) +} + +// int64 root_id = 6; +inline void HloComputationProto::clear_root_id() { + _impl_.root_id_ = int64_t{0}; +} +inline int64_t HloComputationProto::_internal_root_id() const { + return _impl_.root_id_; +} +inline int64_t HloComputationProto::root_id() const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.root_id) + return _internal_root_id(); +} +inline void HloComputationProto::_internal_set_root_id(int64_t value) { + + _impl_.root_id_ = value; +} +inline void HloComputationProto::set_root_id(int64_t value) { + _internal_set_root_id(value); + // @@protoc_insertion_point(field_set:xla.HloComputationProto.root_id) +} + +// bool is_fusion_computation = 7; +inline void HloComputationProto::clear_is_fusion_computation() { + _impl_.is_fusion_computation_ = false; +} +inline bool HloComputationProto::_internal_is_fusion_computation() const { + return _impl_.is_fusion_computation_; +} +inline bool HloComputationProto::is_fusion_computation() const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.is_fusion_computation) + return _internal_is_fusion_computation(); +} +inline void HloComputationProto::_internal_set_is_fusion_computation(bool value) { + + _impl_.is_fusion_computation_ = value; +} +inline void HloComputationProto::set_is_fusion_computation(bool value) { + _internal_set_is_fusion_computation(value); + // @@protoc_insertion_point(field_set:xla.HloComputationProto.is_fusion_computation) +} + +// string execution_thread = 8; +inline void HloComputationProto::clear_execution_thread() { + _impl_.execution_thread_.ClearToEmpty(); +} +inline const std::string& HloComputationProto::execution_thread() const { + // @@protoc_insertion_point(field_get:xla.HloComputationProto.execution_thread) + return _internal_execution_thread(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloComputationProto::set_execution_thread(ArgT0&& arg0, ArgT... args) { + + _impl_.execution_thread_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloComputationProto.execution_thread) +} +inline std::string* HloComputationProto::mutable_execution_thread() { + std::string* _s = _internal_mutable_execution_thread(); + // @@protoc_insertion_point(field_mutable:xla.HloComputationProto.execution_thread) + return _s; +} +inline const std::string& HloComputationProto::_internal_execution_thread() const { + return _impl_.execution_thread_.Get(); +} +inline void HloComputationProto::_internal_set_execution_thread(const std::string& value) { + + _impl_.execution_thread_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloComputationProto::_internal_mutable_execution_thread() { + + return _impl_.execution_thread_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloComputationProto::release_execution_thread() { + // @@protoc_insertion_point(field_release:xla.HloComputationProto.execution_thread) + return _impl_.execution_thread_.Release(); +} +inline void HloComputationProto::set_allocated_execution_thread(std::string* execution_thread) { + if (execution_thread != nullptr) { + + } else { + + } + _impl_.execution_thread_.SetAllocated(execution_thread, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.execution_thread_.IsDefault()) { + _impl_.execution_thread_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloComputationProto.execution_thread) +} + +// ------------------------------------------------------------------- + +// HloScheduleProto_InstructionSequence + +// repeated int64 instruction_ids = 1; +inline int HloScheduleProto_InstructionSequence::_internal_instruction_ids_size() const { + return _impl_.instruction_ids_.size(); +} +inline int HloScheduleProto_InstructionSequence::instruction_ids_size() const { + return _internal_instruction_ids_size(); +} +inline void HloScheduleProto_InstructionSequence::clear_instruction_ids() { + _impl_.instruction_ids_.Clear(); +} +inline int64_t HloScheduleProto_InstructionSequence::_internal_instruction_ids(int index) const { + return _impl_.instruction_ids_.Get(index); +} +inline int64_t HloScheduleProto_InstructionSequence::instruction_ids(int index) const { + // @@protoc_insertion_point(field_get:xla.HloScheduleProto.InstructionSequence.instruction_ids) + return _internal_instruction_ids(index); +} +inline void HloScheduleProto_InstructionSequence::set_instruction_ids(int index, int64_t value) { + _impl_.instruction_ids_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloScheduleProto.InstructionSequence.instruction_ids) +} +inline void HloScheduleProto_InstructionSequence::_internal_add_instruction_ids(int64_t value) { + _impl_.instruction_ids_.Add(value); +} +inline void HloScheduleProto_InstructionSequence::add_instruction_ids(int64_t value) { + _internal_add_instruction_ids(value); + // @@protoc_insertion_point(field_add:xla.HloScheduleProto.InstructionSequence.instruction_ids) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloScheduleProto_InstructionSequence::_internal_instruction_ids() const { + return _impl_.instruction_ids_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloScheduleProto_InstructionSequence::instruction_ids() const { + // @@protoc_insertion_point(field_list:xla.HloScheduleProto.InstructionSequence.instruction_ids) + return _internal_instruction_ids(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloScheduleProto_InstructionSequence::_internal_mutable_instruction_ids() { + return &_impl_.instruction_ids_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloScheduleProto_InstructionSequence::mutable_instruction_ids() { + // @@protoc_insertion_point(field_mutable_list:xla.HloScheduleProto.InstructionSequence.instruction_ids) + return _internal_mutable_instruction_ids(); +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// HloScheduleProto + +// map sequences = 1; +inline int HloScheduleProto::_internal_sequences_size() const { + return _impl_.sequences_.size(); +} +inline int HloScheduleProto::sequences_size() const { + return _internal_sequences_size(); +} +inline void HloScheduleProto::clear_sequences() { + _impl_.sequences_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >& +HloScheduleProto::_internal_sequences() const { + return _impl_.sequences_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >& +HloScheduleProto::sequences() const { + // @@protoc_insertion_point(field_map:xla.HloScheduleProto.sequences) + return _internal_sequences(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >* +HloScheduleProto::_internal_mutable_sequences() { + return _impl_.sequences_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< int64_t, ::xla::HloScheduleProto_InstructionSequence >* +HloScheduleProto::mutable_sequences() { + // @@protoc_insertion_point(field_mutable_map:xla.HloScheduleProto.sequences) + return _internal_mutable_sequences(); +} + +// ------------------------------------------------------------------- + +// HloInputOutputAliasProto_AliasEntryProto + +// repeated int64 output_shape_index = 1; +inline int HloInputOutputAliasProto_AliasEntryProto::_internal_output_shape_index_size() const { + return _impl_.output_shape_index_.size(); +} +inline int HloInputOutputAliasProto_AliasEntryProto::output_shape_index_size() const { + return _internal_output_shape_index_size(); +} +inline void HloInputOutputAliasProto_AliasEntryProto::clear_output_shape_index() { + _impl_.output_shape_index_.Clear(); +} +inline int64_t HloInputOutputAliasProto_AliasEntryProto::_internal_output_shape_index(int index) const { + return _impl_.output_shape_index_.Get(index); +} +inline int64_t HloInputOutputAliasProto_AliasEntryProto::output_shape_index(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInputOutputAliasProto.AliasEntryProto.output_shape_index) + return _internal_output_shape_index(index); +} +inline void HloInputOutputAliasProto_AliasEntryProto::set_output_shape_index(int index, int64_t value) { + _impl_.output_shape_index_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInputOutputAliasProto.AliasEntryProto.output_shape_index) +} +inline void HloInputOutputAliasProto_AliasEntryProto::_internal_add_output_shape_index(int64_t value) { + _impl_.output_shape_index_.Add(value); +} +inline void HloInputOutputAliasProto_AliasEntryProto::add_output_shape_index(int64_t value) { + _internal_add_output_shape_index(value); + // @@protoc_insertion_point(field_add:xla.HloInputOutputAliasProto.AliasEntryProto.output_shape_index) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInputOutputAliasProto_AliasEntryProto::_internal_output_shape_index() const { + return _impl_.output_shape_index_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInputOutputAliasProto_AliasEntryProto::output_shape_index() const { + // @@protoc_insertion_point(field_list:xla.HloInputOutputAliasProto.AliasEntryProto.output_shape_index) + return _internal_output_shape_index(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInputOutputAliasProto_AliasEntryProto::_internal_mutable_output_shape_index() { + return &_impl_.output_shape_index_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInputOutputAliasProto_AliasEntryProto::mutable_output_shape_index() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInputOutputAliasProto.AliasEntryProto.output_shape_index) + return _internal_mutable_output_shape_index(); +} + +// int64 parameter_number = 2; +inline void HloInputOutputAliasProto_AliasEntryProto::clear_parameter_number() { + _impl_.parameter_number_ = int64_t{0}; +} +inline int64_t HloInputOutputAliasProto_AliasEntryProto::_internal_parameter_number() const { + return _impl_.parameter_number_; +} +inline int64_t HloInputOutputAliasProto_AliasEntryProto::parameter_number() const { + // @@protoc_insertion_point(field_get:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_number) + return _internal_parameter_number(); +} +inline void HloInputOutputAliasProto_AliasEntryProto::_internal_set_parameter_number(int64_t value) { + + _impl_.parameter_number_ = value; +} +inline void HloInputOutputAliasProto_AliasEntryProto::set_parameter_number(int64_t value) { + _internal_set_parameter_number(value); + // @@protoc_insertion_point(field_set:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_number) +} + +// repeated int64 parameter_shape_index = 3; +inline int HloInputOutputAliasProto_AliasEntryProto::_internal_parameter_shape_index_size() const { + return _impl_.parameter_shape_index_.size(); +} +inline int HloInputOutputAliasProto_AliasEntryProto::parameter_shape_index_size() const { + return _internal_parameter_shape_index_size(); +} +inline void HloInputOutputAliasProto_AliasEntryProto::clear_parameter_shape_index() { + _impl_.parameter_shape_index_.Clear(); +} +inline int64_t HloInputOutputAliasProto_AliasEntryProto::_internal_parameter_shape_index(int index) const { + return _impl_.parameter_shape_index_.Get(index); +} +inline int64_t HloInputOutputAliasProto_AliasEntryProto::parameter_shape_index(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_shape_index) + return _internal_parameter_shape_index(index); +} +inline void HloInputOutputAliasProto_AliasEntryProto::set_parameter_shape_index(int index, int64_t value) { + _impl_.parameter_shape_index_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_shape_index) +} +inline void HloInputOutputAliasProto_AliasEntryProto::_internal_add_parameter_shape_index(int64_t value) { + _impl_.parameter_shape_index_.Add(value); +} +inline void HloInputOutputAliasProto_AliasEntryProto::add_parameter_shape_index(int64_t value) { + _internal_add_parameter_shape_index(value); + // @@protoc_insertion_point(field_add:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_shape_index) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInputOutputAliasProto_AliasEntryProto::_internal_parameter_shape_index() const { + return _impl_.parameter_shape_index_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloInputOutputAliasProto_AliasEntryProto::parameter_shape_index() const { + // @@protoc_insertion_point(field_list:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_shape_index) + return _internal_parameter_shape_index(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInputOutputAliasProto_AliasEntryProto::_internal_mutable_parameter_shape_index() { + return &_impl_.parameter_shape_index_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloInputOutputAliasProto_AliasEntryProto::mutable_parameter_shape_index() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInputOutputAliasProto.AliasEntryProto.parameter_shape_index) + return _internal_mutable_parameter_shape_index(); +} + +// .xla.Kind kind = 4; +inline void HloInputOutputAliasProto_AliasEntryProto::clear_kind() { + _impl_.kind_ = 0; +} +inline ::xla::Kind HloInputOutputAliasProto_AliasEntryProto::_internal_kind() const { + return static_cast< ::xla::Kind >(_impl_.kind_); +} +inline ::xla::Kind HloInputOutputAliasProto_AliasEntryProto::kind() const { + // @@protoc_insertion_point(field_get:xla.HloInputOutputAliasProto.AliasEntryProto.kind) + return _internal_kind(); +} +inline void HloInputOutputAliasProto_AliasEntryProto::_internal_set_kind(::xla::Kind value) { + + _impl_.kind_ = value; +} +inline void HloInputOutputAliasProto_AliasEntryProto::set_kind(::xla::Kind value) { + _internal_set_kind(value); + // @@protoc_insertion_point(field_set:xla.HloInputOutputAliasProto.AliasEntryProto.kind) +} + +// ------------------------------------------------------------------- + +// HloInputOutputAliasProto + +// repeated .xla.HloInputOutputAliasProto.AliasEntryProto entries = 1; +inline int HloInputOutputAliasProto::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int HloInputOutputAliasProto::entries_size() const { + return _internal_entries_size(); +} +inline void HloInputOutputAliasProto::clear_entries() { + _impl_.entries_.Clear(); +} +inline ::xla::HloInputOutputAliasProto_AliasEntryProto* HloInputOutputAliasProto::mutable_entries(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloInputOutputAliasProto.entries) + return _impl_.entries_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInputOutputAliasProto_AliasEntryProto >* +HloInputOutputAliasProto::mutable_entries() { + // @@protoc_insertion_point(field_mutable_list:xla.HloInputOutputAliasProto.entries) + return &_impl_.entries_; +} +inline const ::xla::HloInputOutputAliasProto_AliasEntryProto& HloInputOutputAliasProto::_internal_entries(int index) const { + return _impl_.entries_.Get(index); +} +inline const ::xla::HloInputOutputAliasProto_AliasEntryProto& HloInputOutputAliasProto::entries(int index) const { + // @@protoc_insertion_point(field_get:xla.HloInputOutputAliasProto.entries) + return _internal_entries(index); +} +inline ::xla::HloInputOutputAliasProto_AliasEntryProto* HloInputOutputAliasProto::_internal_add_entries() { + return _impl_.entries_.Add(); +} +inline ::xla::HloInputOutputAliasProto_AliasEntryProto* HloInputOutputAliasProto::add_entries() { + ::xla::HloInputOutputAliasProto_AliasEntryProto* _add = _internal_add_entries(); + // @@protoc_insertion_point(field_add:xla.HloInputOutputAliasProto.entries) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloInputOutputAliasProto_AliasEntryProto >& +HloInputOutputAliasProto::entries() const { + // @@protoc_insertion_point(field_list:xla.HloInputOutputAliasProto.entries) + return _impl_.entries_; +} + +// ------------------------------------------------------------------- + +// HloBufferDonorProto_BufferDonorEntryProto + +// int64 parameter_number = 1; +inline void HloBufferDonorProto_BufferDonorEntryProto::clear_parameter_number() { + _impl_.parameter_number_ = int64_t{0}; +} +inline int64_t HloBufferDonorProto_BufferDonorEntryProto::_internal_parameter_number() const { + return _impl_.parameter_number_; +} +inline int64_t HloBufferDonorProto_BufferDonorEntryProto::parameter_number() const { + // @@protoc_insertion_point(field_get:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_number) + return _internal_parameter_number(); +} +inline void HloBufferDonorProto_BufferDonorEntryProto::_internal_set_parameter_number(int64_t value) { + + _impl_.parameter_number_ = value; +} +inline void HloBufferDonorProto_BufferDonorEntryProto::set_parameter_number(int64_t value) { + _internal_set_parameter_number(value); + // @@protoc_insertion_point(field_set:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_number) +} + +// repeated int64 parameter_shape_index = 2; +inline int HloBufferDonorProto_BufferDonorEntryProto::_internal_parameter_shape_index_size() const { + return _impl_.parameter_shape_index_.size(); +} +inline int HloBufferDonorProto_BufferDonorEntryProto::parameter_shape_index_size() const { + return _internal_parameter_shape_index_size(); +} +inline void HloBufferDonorProto_BufferDonorEntryProto::clear_parameter_shape_index() { + _impl_.parameter_shape_index_.Clear(); +} +inline int64_t HloBufferDonorProto_BufferDonorEntryProto::_internal_parameter_shape_index(int index) const { + return _impl_.parameter_shape_index_.Get(index); +} +inline int64_t HloBufferDonorProto_BufferDonorEntryProto::parameter_shape_index(int index) const { + // @@protoc_insertion_point(field_get:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_shape_index) + return _internal_parameter_shape_index(index); +} +inline void HloBufferDonorProto_BufferDonorEntryProto::set_parameter_shape_index(int index, int64_t value) { + _impl_.parameter_shape_index_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_shape_index) +} +inline void HloBufferDonorProto_BufferDonorEntryProto::_internal_add_parameter_shape_index(int64_t value) { + _impl_.parameter_shape_index_.Add(value); +} +inline void HloBufferDonorProto_BufferDonorEntryProto::add_parameter_shape_index(int64_t value) { + _internal_add_parameter_shape_index(value); + // @@protoc_insertion_point(field_add:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_shape_index) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloBufferDonorProto_BufferDonorEntryProto::_internal_parameter_shape_index() const { + return _impl_.parameter_shape_index_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloBufferDonorProto_BufferDonorEntryProto::parameter_shape_index() const { + // @@protoc_insertion_point(field_list:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_shape_index) + return _internal_parameter_shape_index(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloBufferDonorProto_BufferDonorEntryProto::_internal_mutable_parameter_shape_index() { + return &_impl_.parameter_shape_index_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloBufferDonorProto_BufferDonorEntryProto::mutable_parameter_shape_index() { + // @@protoc_insertion_point(field_mutable_list:xla.HloBufferDonorProto.BufferDonorEntryProto.parameter_shape_index) + return _internal_mutable_parameter_shape_index(); +} + +// ------------------------------------------------------------------- + +// HloBufferDonorProto + +// repeated .xla.HloBufferDonorProto.BufferDonorEntryProto entries = 1; +inline int HloBufferDonorProto::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int HloBufferDonorProto::entries_size() const { + return _internal_entries_size(); +} +inline void HloBufferDonorProto::clear_entries() { + _impl_.entries_.Clear(); +} +inline ::xla::HloBufferDonorProto_BufferDonorEntryProto* HloBufferDonorProto::mutable_entries(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloBufferDonorProto.entries) + return _impl_.entries_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloBufferDonorProto_BufferDonorEntryProto >* +HloBufferDonorProto::mutable_entries() { + // @@protoc_insertion_point(field_mutable_list:xla.HloBufferDonorProto.entries) + return &_impl_.entries_; +} +inline const ::xla::HloBufferDonorProto_BufferDonorEntryProto& HloBufferDonorProto::_internal_entries(int index) const { + return _impl_.entries_.Get(index); +} +inline const ::xla::HloBufferDonorProto_BufferDonorEntryProto& HloBufferDonorProto::entries(int index) const { + // @@protoc_insertion_point(field_get:xla.HloBufferDonorProto.entries) + return _internal_entries(index); +} +inline ::xla::HloBufferDonorProto_BufferDonorEntryProto* HloBufferDonorProto::_internal_add_entries() { + return _impl_.entries_.Add(); +} +inline ::xla::HloBufferDonorProto_BufferDonorEntryProto* HloBufferDonorProto::add_entries() { + ::xla::HloBufferDonorProto_BufferDonorEntryProto* _add = _internal_add_entries(); + // @@protoc_insertion_point(field_add:xla.HloBufferDonorProto.entries) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloBufferDonorProto_BufferDonorEntryProto >& +HloBufferDonorProto::entries() const { + // @@protoc_insertion_point(field_list:xla.HloBufferDonorProto.entries) + return _impl_.entries_; +} + +// ------------------------------------------------------------------- + +// CrossProgramPrefetch + +// int64 parameter = 1; +inline void CrossProgramPrefetch::clear_parameter() { + _impl_.parameter_ = int64_t{0}; +} +inline int64_t CrossProgramPrefetch::_internal_parameter() const { + return _impl_.parameter_; +} +inline int64_t CrossProgramPrefetch::parameter() const { + // @@protoc_insertion_point(field_get:xla.CrossProgramPrefetch.parameter) + return _internal_parameter(); +} +inline void CrossProgramPrefetch::_internal_set_parameter(int64_t value) { + + _impl_.parameter_ = value; +} +inline void CrossProgramPrefetch::set_parameter(int64_t value) { + _internal_set_parameter(value); + // @@protoc_insertion_point(field_set:xla.CrossProgramPrefetch.parameter) +} + +// repeated int64 index = 2; +inline int CrossProgramPrefetch::_internal_index_size() const { + return _impl_.index_.size(); +} +inline int CrossProgramPrefetch::index_size() const { + return _internal_index_size(); +} +inline void CrossProgramPrefetch::clear_index() { + _impl_.index_.Clear(); +} +inline int64_t CrossProgramPrefetch::_internal_index(int index) const { + return _impl_.index_.Get(index); +} +inline int64_t CrossProgramPrefetch::index(int index) const { + // @@protoc_insertion_point(field_get:xla.CrossProgramPrefetch.index) + return _internal_index(index); +} +inline void CrossProgramPrefetch::set_index(int index, int64_t value) { + _impl_.index_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.CrossProgramPrefetch.index) +} +inline void CrossProgramPrefetch::_internal_add_index(int64_t value) { + _impl_.index_.Add(value); +} +inline void CrossProgramPrefetch::add_index(int64_t value) { + _internal_add_index(value); + // @@protoc_insertion_point(field_add:xla.CrossProgramPrefetch.index) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +CrossProgramPrefetch::_internal_index() const { + return _impl_.index_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +CrossProgramPrefetch::index() const { + // @@protoc_insertion_point(field_list:xla.CrossProgramPrefetch.index) + return _internal_index(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +CrossProgramPrefetch::_internal_mutable_index() { + return &_impl_.index_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +CrossProgramPrefetch::mutable_index() { + // @@protoc_insertion_point(field_mutable_list:xla.CrossProgramPrefetch.index) + return _internal_mutable_index(); +} + +// int64 offset = 3; +inline void CrossProgramPrefetch::clear_offset() { + _impl_.offset_ = int64_t{0}; +} +inline int64_t CrossProgramPrefetch::_internal_offset() const { + return _impl_.offset_; +} +inline int64_t CrossProgramPrefetch::offset() const { + // @@protoc_insertion_point(field_get:xla.CrossProgramPrefetch.offset) + return _internal_offset(); +} +inline void CrossProgramPrefetch::_internal_set_offset(int64_t value) { + + _impl_.offset_ = value; +} +inline void CrossProgramPrefetch::set_offset(int64_t value) { + _internal_set_offset(value); + // @@protoc_insertion_point(field_set:xla.CrossProgramPrefetch.offset) +} + +// ------------------------------------------------------------------- + +// StackFrameIndexProto_FileLocation + +// int32 file_name_id = 1; +inline void StackFrameIndexProto_FileLocation::clear_file_name_id() { + _impl_.file_name_id_ = 0; +} +inline int32_t StackFrameIndexProto_FileLocation::_internal_file_name_id() const { + return _impl_.file_name_id_; +} +inline int32_t StackFrameIndexProto_FileLocation::file_name_id() const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.FileLocation.file_name_id) + return _internal_file_name_id(); +} +inline void StackFrameIndexProto_FileLocation::_internal_set_file_name_id(int32_t value) { + + _impl_.file_name_id_ = value; +} +inline void StackFrameIndexProto_FileLocation::set_file_name_id(int32_t value) { + _internal_set_file_name_id(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.FileLocation.file_name_id) +} + +// int32 function_name_id = 2; +inline void StackFrameIndexProto_FileLocation::clear_function_name_id() { + _impl_.function_name_id_ = 0; +} +inline int32_t StackFrameIndexProto_FileLocation::_internal_function_name_id() const { + return _impl_.function_name_id_; +} +inline int32_t StackFrameIndexProto_FileLocation::function_name_id() const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.FileLocation.function_name_id) + return _internal_function_name_id(); +} +inline void StackFrameIndexProto_FileLocation::_internal_set_function_name_id(int32_t value) { + + _impl_.function_name_id_ = value; +} +inline void StackFrameIndexProto_FileLocation::set_function_name_id(int32_t value) { + _internal_set_function_name_id(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.FileLocation.function_name_id) +} + +// int32 line = 3; +inline void StackFrameIndexProto_FileLocation::clear_line() { + _impl_.line_ = 0; +} +inline int32_t StackFrameIndexProto_FileLocation::_internal_line() const { + return _impl_.line_; +} +inline int32_t StackFrameIndexProto_FileLocation::line() const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.FileLocation.line) + return _internal_line(); +} +inline void StackFrameIndexProto_FileLocation::_internal_set_line(int32_t value) { + + _impl_.line_ = value; +} +inline void StackFrameIndexProto_FileLocation::set_line(int32_t value) { + _internal_set_line(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.FileLocation.line) +} + +// int32 column = 4; +inline void StackFrameIndexProto_FileLocation::clear_column() { + _impl_.column_ = 0; +} +inline int32_t StackFrameIndexProto_FileLocation::_internal_column() const { + return _impl_.column_; +} +inline int32_t StackFrameIndexProto_FileLocation::column() const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.FileLocation.column) + return _internal_column(); +} +inline void StackFrameIndexProto_FileLocation::_internal_set_column(int32_t value) { + + _impl_.column_ = value; +} +inline void StackFrameIndexProto_FileLocation::set_column(int32_t value) { + _internal_set_column(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.FileLocation.column) +} + +// ------------------------------------------------------------------- + +// StackFrameIndexProto_StackFrame + +// int32 file_location_id = 1; +inline void StackFrameIndexProto_StackFrame::clear_file_location_id() { + _impl_.file_location_id_ = 0; +} +inline int32_t StackFrameIndexProto_StackFrame::_internal_file_location_id() const { + return _impl_.file_location_id_; +} +inline int32_t StackFrameIndexProto_StackFrame::file_location_id() const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.StackFrame.file_location_id) + return _internal_file_location_id(); +} +inline void StackFrameIndexProto_StackFrame::_internal_set_file_location_id(int32_t value) { + + _impl_.file_location_id_ = value; +} +inline void StackFrameIndexProto_StackFrame::set_file_location_id(int32_t value) { + _internal_set_file_location_id(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.StackFrame.file_location_id) +} + +// int32 parent_frame_id = 2; +inline void StackFrameIndexProto_StackFrame::clear_parent_frame_id() { + _impl_.parent_frame_id_ = 0; +} +inline int32_t StackFrameIndexProto_StackFrame::_internal_parent_frame_id() const { + return _impl_.parent_frame_id_; +} +inline int32_t StackFrameIndexProto_StackFrame::parent_frame_id() const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.StackFrame.parent_frame_id) + return _internal_parent_frame_id(); +} +inline void StackFrameIndexProto_StackFrame::_internal_set_parent_frame_id(int32_t value) { + + _impl_.parent_frame_id_ = value; +} +inline void StackFrameIndexProto_StackFrame::set_parent_frame_id(int32_t value) { + _internal_set_parent_frame_id(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.StackFrame.parent_frame_id) +} + +// ------------------------------------------------------------------- + +// StackFrameIndexProto + +// repeated string file_names = 1; +inline int StackFrameIndexProto::_internal_file_names_size() const { + return _impl_.file_names_.size(); +} +inline int StackFrameIndexProto::file_names_size() const { + return _internal_file_names_size(); +} +inline void StackFrameIndexProto::clear_file_names() { + _impl_.file_names_.Clear(); +} +inline std::string* StackFrameIndexProto::add_file_names() { + std::string* _s = _internal_add_file_names(); + // @@protoc_insertion_point(field_add_mutable:xla.StackFrameIndexProto.file_names) + return _s; +} +inline const std::string& StackFrameIndexProto::_internal_file_names(int index) const { + return _impl_.file_names_.Get(index); +} +inline const std::string& StackFrameIndexProto::file_names(int index) const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.file_names) + return _internal_file_names(index); +} +inline std::string* StackFrameIndexProto::mutable_file_names(int index) { + // @@protoc_insertion_point(field_mutable:xla.StackFrameIndexProto.file_names) + return _impl_.file_names_.Mutable(index); +} +inline void StackFrameIndexProto::set_file_names(int index, const std::string& value) { + _impl_.file_names_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.file_names) +} +inline void StackFrameIndexProto::set_file_names(int index, std::string&& value) { + _impl_.file_names_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.file_names) +} +inline void StackFrameIndexProto::set_file_names(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.file_names_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:xla.StackFrameIndexProto.file_names) +} +inline void StackFrameIndexProto::set_file_names(int index, const char* value, size_t size) { + _impl_.file_names_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:xla.StackFrameIndexProto.file_names) +} +inline std::string* StackFrameIndexProto::_internal_add_file_names() { + return _impl_.file_names_.Add(); +} +inline void StackFrameIndexProto::add_file_names(const std::string& value) { + _impl_.file_names_.Add()->assign(value); + // @@protoc_insertion_point(field_add:xla.StackFrameIndexProto.file_names) +} +inline void StackFrameIndexProto::add_file_names(std::string&& value) { + _impl_.file_names_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:xla.StackFrameIndexProto.file_names) +} +inline void StackFrameIndexProto::add_file_names(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.file_names_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:xla.StackFrameIndexProto.file_names) +} +inline void StackFrameIndexProto::add_file_names(const char* value, size_t size) { + _impl_.file_names_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:xla.StackFrameIndexProto.file_names) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +StackFrameIndexProto::file_names() const { + // @@protoc_insertion_point(field_list:xla.StackFrameIndexProto.file_names) + return _impl_.file_names_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +StackFrameIndexProto::mutable_file_names() { + // @@protoc_insertion_point(field_mutable_list:xla.StackFrameIndexProto.file_names) + return &_impl_.file_names_; +} + +// repeated string function_names = 2; +inline int StackFrameIndexProto::_internal_function_names_size() const { + return _impl_.function_names_.size(); +} +inline int StackFrameIndexProto::function_names_size() const { + return _internal_function_names_size(); +} +inline void StackFrameIndexProto::clear_function_names() { + _impl_.function_names_.Clear(); +} +inline std::string* StackFrameIndexProto::add_function_names() { + std::string* _s = _internal_add_function_names(); + // @@protoc_insertion_point(field_add_mutable:xla.StackFrameIndexProto.function_names) + return _s; +} +inline const std::string& StackFrameIndexProto::_internal_function_names(int index) const { + return _impl_.function_names_.Get(index); +} +inline const std::string& StackFrameIndexProto::function_names(int index) const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.function_names) + return _internal_function_names(index); +} +inline std::string* StackFrameIndexProto::mutable_function_names(int index) { + // @@protoc_insertion_point(field_mutable:xla.StackFrameIndexProto.function_names) + return _impl_.function_names_.Mutable(index); +} +inline void StackFrameIndexProto::set_function_names(int index, const std::string& value) { + _impl_.function_names_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.function_names) +} +inline void StackFrameIndexProto::set_function_names(int index, std::string&& value) { + _impl_.function_names_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:xla.StackFrameIndexProto.function_names) +} +inline void StackFrameIndexProto::set_function_names(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.function_names_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:xla.StackFrameIndexProto.function_names) +} +inline void StackFrameIndexProto::set_function_names(int index, const char* value, size_t size) { + _impl_.function_names_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:xla.StackFrameIndexProto.function_names) +} +inline std::string* StackFrameIndexProto::_internal_add_function_names() { + return _impl_.function_names_.Add(); +} +inline void StackFrameIndexProto::add_function_names(const std::string& value) { + _impl_.function_names_.Add()->assign(value); + // @@protoc_insertion_point(field_add:xla.StackFrameIndexProto.function_names) +} +inline void StackFrameIndexProto::add_function_names(std::string&& value) { + _impl_.function_names_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:xla.StackFrameIndexProto.function_names) +} +inline void StackFrameIndexProto::add_function_names(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.function_names_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:xla.StackFrameIndexProto.function_names) +} +inline void StackFrameIndexProto::add_function_names(const char* value, size_t size) { + _impl_.function_names_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:xla.StackFrameIndexProto.function_names) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +StackFrameIndexProto::function_names() const { + // @@protoc_insertion_point(field_list:xla.StackFrameIndexProto.function_names) + return _impl_.function_names_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +StackFrameIndexProto::mutable_function_names() { + // @@protoc_insertion_point(field_mutable_list:xla.StackFrameIndexProto.function_names) + return &_impl_.function_names_; +} + +// repeated .xla.StackFrameIndexProto.FileLocation file_locations = 3; +inline int StackFrameIndexProto::_internal_file_locations_size() const { + return _impl_.file_locations_.size(); +} +inline int StackFrameIndexProto::file_locations_size() const { + return _internal_file_locations_size(); +} +inline void StackFrameIndexProto::clear_file_locations() { + _impl_.file_locations_.Clear(); +} +inline ::xla::StackFrameIndexProto_FileLocation* StackFrameIndexProto::mutable_file_locations(int index) { + // @@protoc_insertion_point(field_mutable:xla.StackFrameIndexProto.file_locations) + return _impl_.file_locations_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_FileLocation >* +StackFrameIndexProto::mutable_file_locations() { + // @@protoc_insertion_point(field_mutable_list:xla.StackFrameIndexProto.file_locations) + return &_impl_.file_locations_; +} +inline const ::xla::StackFrameIndexProto_FileLocation& StackFrameIndexProto::_internal_file_locations(int index) const { + return _impl_.file_locations_.Get(index); +} +inline const ::xla::StackFrameIndexProto_FileLocation& StackFrameIndexProto::file_locations(int index) const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.file_locations) + return _internal_file_locations(index); +} +inline ::xla::StackFrameIndexProto_FileLocation* StackFrameIndexProto::_internal_add_file_locations() { + return _impl_.file_locations_.Add(); +} +inline ::xla::StackFrameIndexProto_FileLocation* StackFrameIndexProto::add_file_locations() { + ::xla::StackFrameIndexProto_FileLocation* _add = _internal_add_file_locations(); + // @@protoc_insertion_point(field_add:xla.StackFrameIndexProto.file_locations) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_FileLocation >& +StackFrameIndexProto::file_locations() const { + // @@protoc_insertion_point(field_list:xla.StackFrameIndexProto.file_locations) + return _impl_.file_locations_; +} + +// repeated .xla.StackFrameIndexProto.StackFrame stack_frames = 4; +inline int StackFrameIndexProto::_internal_stack_frames_size() const { + return _impl_.stack_frames_.size(); +} +inline int StackFrameIndexProto::stack_frames_size() const { + return _internal_stack_frames_size(); +} +inline void StackFrameIndexProto::clear_stack_frames() { + _impl_.stack_frames_.Clear(); +} +inline ::xla::StackFrameIndexProto_StackFrame* StackFrameIndexProto::mutable_stack_frames(int index) { + // @@protoc_insertion_point(field_mutable:xla.StackFrameIndexProto.stack_frames) + return _impl_.stack_frames_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_StackFrame >* +StackFrameIndexProto::mutable_stack_frames() { + // @@protoc_insertion_point(field_mutable_list:xla.StackFrameIndexProto.stack_frames) + return &_impl_.stack_frames_; +} +inline const ::xla::StackFrameIndexProto_StackFrame& StackFrameIndexProto::_internal_stack_frames(int index) const { + return _impl_.stack_frames_.Get(index); +} +inline const ::xla::StackFrameIndexProto_StackFrame& StackFrameIndexProto::stack_frames(int index) const { + // @@protoc_insertion_point(field_get:xla.StackFrameIndexProto.stack_frames) + return _internal_stack_frames(index); +} +inline ::xla::StackFrameIndexProto_StackFrame* StackFrameIndexProto::_internal_add_stack_frames() { + return _impl_.stack_frames_.Add(); +} +inline ::xla::StackFrameIndexProto_StackFrame* StackFrameIndexProto::add_stack_frames() { + ::xla::StackFrameIndexProto_StackFrame* _add = _internal_add_stack_frames(); + // @@protoc_insertion_point(field_add:xla.StackFrameIndexProto.stack_frames) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::StackFrameIndexProto_StackFrame >& +StackFrameIndexProto::stack_frames() const { + // @@protoc_insertion_point(field_list:xla.StackFrameIndexProto.stack_frames) + return _impl_.stack_frames_; +} + +// ------------------------------------------------------------------- + +// HloModuleProto_ProfileInfo + +// .xla.HloModuleProto.ProfileType profile_type = 1; +inline void HloModuleProto_ProfileInfo::clear_profile_type() { + _impl_.profile_type_ = 0; +} +inline ::xla::HloModuleProto_ProfileType HloModuleProto_ProfileInfo::_internal_profile_type() const { + return static_cast< ::xla::HloModuleProto_ProfileType >(_impl_.profile_type_); +} +inline ::xla::HloModuleProto_ProfileType HloModuleProto_ProfileInfo::profile_type() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.ProfileInfo.profile_type) + return _internal_profile_type(); +} +inline void HloModuleProto_ProfileInfo::_internal_set_profile_type(::xla::HloModuleProto_ProfileType value) { + + _impl_.profile_type_ = value; +} +inline void HloModuleProto_ProfileInfo::set_profile_type(::xla::HloModuleProto_ProfileType value) { + _internal_set_profile_type(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.ProfileInfo.profile_type) +} + +// double relative_speedup = 2; +inline void HloModuleProto_ProfileInfo::clear_relative_speedup() { + _impl_.relative_speedup_ = 0; +} +inline double HloModuleProto_ProfileInfo::_internal_relative_speedup() const { + return _impl_.relative_speedup_; +} +inline double HloModuleProto_ProfileInfo::relative_speedup() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.ProfileInfo.relative_speedup) + return _internal_relative_speedup(); +} +inline void HloModuleProto_ProfileInfo::_internal_set_relative_speedup(double value) { + + _impl_.relative_speedup_ = value; +} +inline void HloModuleProto_ProfileInfo::set_relative_speedup(double value) { + _internal_set_relative_speedup(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.ProfileInfo.relative_speedup) +} + +// .xla.ProfileSource profile_source = 3; +inline void HloModuleProto_ProfileInfo::clear_profile_source() { + _impl_.profile_source_ = 0; +} +inline ::xla::ProfileSource HloModuleProto_ProfileInfo::_internal_profile_source() const { + return static_cast< ::xla::ProfileSource >(_impl_.profile_source_); +} +inline ::xla::ProfileSource HloModuleProto_ProfileInfo::profile_source() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.ProfileInfo.profile_source) + return _internal_profile_source(); +} +inline void HloModuleProto_ProfileInfo::_internal_set_profile_source(::xla::ProfileSource value) { + + _impl_.profile_source_ = value; +} +inline void HloModuleProto_ProfileInfo::set_profile_source(::xla::ProfileSource value) { + _internal_set_profile_source(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.ProfileInfo.profile_source) +} + +// .xla.CompilationEvent compilation_event = 4; +inline void HloModuleProto_ProfileInfo::clear_compilation_event() { + _impl_.compilation_event_ = 0; +} +inline ::xla::CompilationEvent HloModuleProto_ProfileInfo::_internal_compilation_event() const { + return static_cast< ::xla::CompilationEvent >(_impl_.compilation_event_); +} +inline ::xla::CompilationEvent HloModuleProto_ProfileInfo::compilation_event() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.ProfileInfo.compilation_event) + return _internal_compilation_event(); +} +inline void HloModuleProto_ProfileInfo::_internal_set_compilation_event(::xla::CompilationEvent value) { + + _impl_.compilation_event_ = value; +} +inline void HloModuleProto_ProfileInfo::set_compilation_event(::xla::CompilationEvent value) { + _internal_set_compilation_event(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.ProfileInfo.compilation_event) +} + +// ------------------------------------------------------------------- + +// HloModuleProto + +// string name = 1; +inline void HloModuleProto::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& HloModuleProto::name() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloModuleProto::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.name) +} +inline std::string* HloModuleProto::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.name) + return _s; +} +inline const std::string& HloModuleProto::_internal_name() const { + return _impl_.name_.Get(); +} +inline void HloModuleProto::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloModuleProto::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloModuleProto::release_name() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.name) + return _impl_.name_.Release(); +} +inline void HloModuleProto::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:xla.HloModuleProto.name) +} + +// string entry_computation_name = 2; +inline void HloModuleProto::clear_entry_computation_name() { + _impl_.entry_computation_name_.ClearToEmpty(); +} +inline const std::string& HloModuleProto::entry_computation_name() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.entry_computation_name) + return _internal_entry_computation_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloModuleProto::set_entry_computation_name(ArgT0&& arg0, ArgT... args) { + + _impl_.entry_computation_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.entry_computation_name) +} +inline std::string* HloModuleProto::mutable_entry_computation_name() { + std::string* _s = _internal_mutable_entry_computation_name(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.entry_computation_name) + return _s; +} +inline const std::string& HloModuleProto::_internal_entry_computation_name() const { + return _impl_.entry_computation_name_.Get(); +} +inline void HloModuleProto::_internal_set_entry_computation_name(const std::string& value) { + + _impl_.entry_computation_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloModuleProto::_internal_mutable_entry_computation_name() { + + return _impl_.entry_computation_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloModuleProto::release_entry_computation_name() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.entry_computation_name) + return _impl_.entry_computation_name_.Release(); +} +inline void HloModuleProto::set_allocated_entry_computation_name(std::string* entry_computation_name) { + if (entry_computation_name != nullptr) { + + } else { + + } + _impl_.entry_computation_name_.SetAllocated(entry_computation_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.entry_computation_name_.IsDefault()) { + _impl_.entry_computation_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.entry_computation_name) +} + +// int64 entry_computation_id = 6; +inline void HloModuleProto::clear_entry_computation_id() { + _impl_.entry_computation_id_ = int64_t{0}; +} +inline int64_t HloModuleProto::_internal_entry_computation_id() const { + return _impl_.entry_computation_id_; +} +inline int64_t HloModuleProto::entry_computation_id() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.entry_computation_id) + return _internal_entry_computation_id(); +} +inline void HloModuleProto::_internal_set_entry_computation_id(int64_t value) { + + _impl_.entry_computation_id_ = value; +} +inline void HloModuleProto::set_entry_computation_id(int64_t value) { + _internal_set_entry_computation_id(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.entry_computation_id) +} + +// repeated .xla.HloComputationProto computations = 3; +inline int HloModuleProto::_internal_computations_size() const { + return _impl_.computations_.size(); +} +inline int HloModuleProto::computations_size() const { + return _internal_computations_size(); +} +inline void HloModuleProto::clear_computations() { + _impl_.computations_.Clear(); +} +inline ::xla::HloComputationProto* HloModuleProto::mutable_computations(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.computations) + return _impl_.computations_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloComputationProto >* +HloModuleProto::mutable_computations() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleProto.computations) + return &_impl_.computations_; +} +inline const ::xla::HloComputationProto& HloModuleProto::_internal_computations(int index) const { + return _impl_.computations_.Get(index); +} +inline const ::xla::HloComputationProto& HloModuleProto::computations(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.computations) + return _internal_computations(index); +} +inline ::xla::HloComputationProto* HloModuleProto::_internal_add_computations() { + return _impl_.computations_.Add(); +} +inline ::xla::HloComputationProto* HloModuleProto::add_computations() { + ::xla::HloComputationProto* _add = _internal_add_computations(); + // @@protoc_insertion_point(field_add:xla.HloModuleProto.computations) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloComputationProto >& +HloModuleProto::computations() const { + // @@protoc_insertion_point(field_list:xla.HloModuleProto.computations) + return _impl_.computations_; +} + +// .xla.ProgramShapeProto host_program_shape = 4; +inline bool HloModuleProto::_internal_has_host_program_shape() const { + return this != internal_default_instance() && _impl_.host_program_shape_ != nullptr; +} +inline bool HloModuleProto::has_host_program_shape() const { + return _internal_has_host_program_shape(); +} +inline const ::xla::ProgramShapeProto& HloModuleProto::_internal_host_program_shape() const { + const ::xla::ProgramShapeProto* p = _impl_.host_program_shape_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ProgramShapeProto_default_instance_); +} +inline const ::xla::ProgramShapeProto& HloModuleProto::host_program_shape() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.host_program_shape) + return _internal_host_program_shape(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_host_program_shape( + ::xla::ProgramShapeProto* host_program_shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.host_program_shape_); + } + _impl_.host_program_shape_ = host_program_shape; + if (host_program_shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.host_program_shape) +} +inline ::xla::ProgramShapeProto* HloModuleProto::release_host_program_shape() { + + ::xla::ProgramShapeProto* temp = _impl_.host_program_shape_; + _impl_.host_program_shape_ = 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::ProgramShapeProto* HloModuleProto::unsafe_arena_release_host_program_shape() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.host_program_shape) + + ::xla::ProgramShapeProto* temp = _impl_.host_program_shape_; + _impl_.host_program_shape_ = nullptr; + return temp; +} +inline ::xla::ProgramShapeProto* HloModuleProto::_internal_mutable_host_program_shape() { + + if (_impl_.host_program_shape_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ProgramShapeProto>(GetArenaForAllocation()); + _impl_.host_program_shape_ = p; + } + return _impl_.host_program_shape_; +} +inline ::xla::ProgramShapeProto* HloModuleProto::mutable_host_program_shape() { + ::xla::ProgramShapeProto* _msg = _internal_mutable_host_program_shape(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.host_program_shape) + return _msg; +} +inline void HloModuleProto::set_allocated_host_program_shape(::xla::ProgramShapeProto* host_program_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.host_program_shape_); + } + if (host_program_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(host_program_shape)); + if (message_arena != submessage_arena) { + host_program_shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, host_program_shape, submessage_arena); + } + + } else { + + } + _impl_.host_program_shape_ = host_program_shape; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.host_program_shape) +} + +// int64 id = 5; +inline void HloModuleProto::clear_id() { + _impl_.id_ = int64_t{0}; +} +inline int64_t HloModuleProto::_internal_id() const { + return _impl_.id_; +} +inline int64_t HloModuleProto::id() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.id) + return _internal_id(); +} +inline void HloModuleProto::_internal_set_id(int64_t value) { + + _impl_.id_ = value; +} +inline void HloModuleProto::set_id(int64_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.id) +} + +// .xla.HloScheduleProto schedule = 7; +inline bool HloModuleProto::_internal_has_schedule() const { + return this != internal_default_instance() && _impl_.schedule_ != nullptr; +} +inline bool HloModuleProto::has_schedule() const { + return _internal_has_schedule(); +} +inline void HloModuleProto::clear_schedule() { + if (GetArenaForAllocation() == nullptr && _impl_.schedule_ != nullptr) { + delete _impl_.schedule_; + } + _impl_.schedule_ = nullptr; +} +inline const ::xla::HloScheduleProto& HloModuleProto::_internal_schedule() const { + const ::xla::HloScheduleProto* p = _impl_.schedule_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloScheduleProto_default_instance_); +} +inline const ::xla::HloScheduleProto& HloModuleProto::schedule() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.schedule) + return _internal_schedule(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_schedule( + ::xla::HloScheduleProto* schedule) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.schedule_); + } + _impl_.schedule_ = schedule; + if (schedule) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.schedule) +} +inline ::xla::HloScheduleProto* HloModuleProto::release_schedule() { + + ::xla::HloScheduleProto* temp = _impl_.schedule_; + _impl_.schedule_ = 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::HloScheduleProto* HloModuleProto::unsafe_arena_release_schedule() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.schedule) + + ::xla::HloScheduleProto* temp = _impl_.schedule_; + _impl_.schedule_ = nullptr; + return temp; +} +inline ::xla::HloScheduleProto* HloModuleProto::_internal_mutable_schedule() { + + if (_impl_.schedule_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloScheduleProto>(GetArenaForAllocation()); + _impl_.schedule_ = p; + } + return _impl_.schedule_; +} +inline ::xla::HloScheduleProto* HloModuleProto::mutable_schedule() { + ::xla::HloScheduleProto* _msg = _internal_mutable_schedule(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.schedule) + return _msg; +} +inline void HloModuleProto::set_allocated_schedule(::xla::HloScheduleProto* schedule) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.schedule_; + } + if (schedule) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(schedule); + if (message_arena != submessage_arena) { + schedule = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, schedule, submessage_arena); + } + + } else { + + } + _impl_.schedule_ = schedule; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.schedule) +} + +// .xla.HloInputOutputAliasProto input_output_alias = 8; +inline bool HloModuleProto::_internal_has_input_output_alias() const { + return this != internal_default_instance() && _impl_.input_output_alias_ != nullptr; +} +inline bool HloModuleProto::has_input_output_alias() const { + return _internal_has_input_output_alias(); +} +inline void HloModuleProto::clear_input_output_alias() { + if (GetArenaForAllocation() == nullptr && _impl_.input_output_alias_ != nullptr) { + delete _impl_.input_output_alias_; + } + _impl_.input_output_alias_ = nullptr; +} +inline const ::xla::HloInputOutputAliasProto& HloModuleProto::_internal_input_output_alias() const { + const ::xla::HloInputOutputAliasProto* p = _impl_.input_output_alias_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloInputOutputAliasProto_default_instance_); +} +inline const ::xla::HloInputOutputAliasProto& HloModuleProto::input_output_alias() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.input_output_alias) + return _internal_input_output_alias(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_input_output_alias( + ::xla::HloInputOutputAliasProto* input_output_alias) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.input_output_alias_); + } + _impl_.input_output_alias_ = input_output_alias; + if (input_output_alias) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.input_output_alias) +} +inline ::xla::HloInputOutputAliasProto* HloModuleProto::release_input_output_alias() { + + ::xla::HloInputOutputAliasProto* temp = _impl_.input_output_alias_; + _impl_.input_output_alias_ = 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::HloInputOutputAliasProto* HloModuleProto::unsafe_arena_release_input_output_alias() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.input_output_alias) + + ::xla::HloInputOutputAliasProto* temp = _impl_.input_output_alias_; + _impl_.input_output_alias_ = nullptr; + return temp; +} +inline ::xla::HloInputOutputAliasProto* HloModuleProto::_internal_mutable_input_output_alias() { + + if (_impl_.input_output_alias_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloInputOutputAliasProto>(GetArenaForAllocation()); + _impl_.input_output_alias_ = p; + } + return _impl_.input_output_alias_; +} +inline ::xla::HloInputOutputAliasProto* HloModuleProto::mutable_input_output_alias() { + ::xla::HloInputOutputAliasProto* _msg = _internal_mutable_input_output_alias(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.input_output_alias) + return _msg; +} +inline void HloModuleProto::set_allocated_input_output_alias(::xla::HloInputOutputAliasProto* input_output_alias) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.input_output_alias_; + } + if (input_output_alias) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(input_output_alias); + if (message_arena != submessage_arena) { + input_output_alias = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, input_output_alias, submessage_arena); + } + + } else { + + } + _impl_.input_output_alias_ = input_output_alias; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.input_output_alias) +} + +// .xla.HloBufferDonorProto buffer_donor = 18; +inline bool HloModuleProto::_internal_has_buffer_donor() const { + return this != internal_default_instance() && _impl_.buffer_donor_ != nullptr; +} +inline bool HloModuleProto::has_buffer_donor() const { + return _internal_has_buffer_donor(); +} +inline void HloModuleProto::clear_buffer_donor() { + if (GetArenaForAllocation() == nullptr && _impl_.buffer_donor_ != nullptr) { + delete _impl_.buffer_donor_; + } + _impl_.buffer_donor_ = nullptr; +} +inline const ::xla::HloBufferDonorProto& HloModuleProto::_internal_buffer_donor() const { + const ::xla::HloBufferDonorProto* p = _impl_.buffer_donor_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloBufferDonorProto_default_instance_); +} +inline const ::xla::HloBufferDonorProto& HloModuleProto::buffer_donor() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.buffer_donor) + return _internal_buffer_donor(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_buffer_donor( + ::xla::HloBufferDonorProto* buffer_donor) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.buffer_donor_); + } + _impl_.buffer_donor_ = buffer_donor; + if (buffer_donor) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.buffer_donor) +} +inline ::xla::HloBufferDonorProto* HloModuleProto::release_buffer_donor() { + + ::xla::HloBufferDonorProto* temp = _impl_.buffer_donor_; + _impl_.buffer_donor_ = 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::HloBufferDonorProto* HloModuleProto::unsafe_arena_release_buffer_donor() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.buffer_donor) + + ::xla::HloBufferDonorProto* temp = _impl_.buffer_donor_; + _impl_.buffer_donor_ = nullptr; + return temp; +} +inline ::xla::HloBufferDonorProto* HloModuleProto::_internal_mutable_buffer_donor() { + + if (_impl_.buffer_donor_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloBufferDonorProto>(GetArenaForAllocation()); + _impl_.buffer_donor_ = p; + } + return _impl_.buffer_donor_; +} +inline ::xla::HloBufferDonorProto* HloModuleProto::mutable_buffer_donor() { + ::xla::HloBufferDonorProto* _msg = _internal_mutable_buffer_donor(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.buffer_donor) + return _msg; +} +inline void HloModuleProto::set_allocated_buffer_donor(::xla::HloBufferDonorProto* buffer_donor) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.buffer_donor_; + } + if (buffer_donor) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(buffer_donor); + if (message_arena != submessage_arena) { + buffer_donor = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, buffer_donor, submessage_arena); + } + + } else { + + } + _impl_.buffer_donor_ = buffer_donor; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.buffer_donor) +} + +// repeated .xla.CrossProgramPrefetch cross_program_prefetches = 10; +inline int HloModuleProto::_internal_cross_program_prefetches_size() const { + return _impl_.cross_program_prefetches_.size(); +} +inline int HloModuleProto::cross_program_prefetches_size() const { + return _internal_cross_program_prefetches_size(); +} +inline void HloModuleProto::clear_cross_program_prefetches() { + _impl_.cross_program_prefetches_.Clear(); +} +inline ::xla::CrossProgramPrefetch* HloModuleProto::mutable_cross_program_prefetches(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.cross_program_prefetches) + return _impl_.cross_program_prefetches_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::CrossProgramPrefetch >* +HloModuleProto::mutable_cross_program_prefetches() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleProto.cross_program_prefetches) + return &_impl_.cross_program_prefetches_; +} +inline const ::xla::CrossProgramPrefetch& HloModuleProto::_internal_cross_program_prefetches(int index) const { + return _impl_.cross_program_prefetches_.Get(index); +} +inline const ::xla::CrossProgramPrefetch& HloModuleProto::cross_program_prefetches(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.cross_program_prefetches) + return _internal_cross_program_prefetches(index); +} +inline ::xla::CrossProgramPrefetch* HloModuleProto::_internal_add_cross_program_prefetches() { + return _impl_.cross_program_prefetches_.Add(); +} +inline ::xla::CrossProgramPrefetch* HloModuleProto::add_cross_program_prefetches() { + ::xla::CrossProgramPrefetch* _add = _internal_add_cross_program_prefetches(); + // @@protoc_insertion_point(field_add:xla.HloModuleProto.cross_program_prefetches) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::CrossProgramPrefetch >& +HloModuleProto::cross_program_prefetches() const { + // @@protoc_insertion_point(field_list:xla.HloModuleProto.cross_program_prefetches) + return _impl_.cross_program_prefetches_; +} + +// bool is_dynamic = 11; +inline void HloModuleProto::clear_is_dynamic() { + _impl_.is_dynamic_ = false; +} +inline bool HloModuleProto::_internal_is_dynamic() const { + return _impl_.is_dynamic_; +} +inline bool HloModuleProto::is_dynamic() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.is_dynamic) + return _internal_is_dynamic(); +} +inline void HloModuleProto::_internal_set_is_dynamic(bool value) { + + _impl_.is_dynamic_ = value; +} +inline void HloModuleProto::set_is_dynamic(bool value) { + _internal_set_is_dynamic(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.is_dynamic) +} + +// .xla.OpSharding spmd_output_sharding = 12; +inline bool HloModuleProto::_internal_has_spmd_output_sharding() const { + return this != internal_default_instance() && _impl_.spmd_output_sharding_ != nullptr; +} +inline bool HloModuleProto::has_spmd_output_sharding() const { + return _internal_has_spmd_output_sharding(); +} +inline const ::xla::OpSharding& HloModuleProto::_internal_spmd_output_sharding() const { + const ::xla::OpSharding* p = _impl_.spmd_output_sharding_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_OpSharding_default_instance_); +} +inline const ::xla::OpSharding& HloModuleProto::spmd_output_sharding() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.spmd_output_sharding) + return _internal_spmd_output_sharding(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_spmd_output_sharding( + ::xla::OpSharding* spmd_output_sharding) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.spmd_output_sharding_); + } + _impl_.spmd_output_sharding_ = spmd_output_sharding; + if (spmd_output_sharding) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.spmd_output_sharding) +} +inline ::xla::OpSharding* HloModuleProto::release_spmd_output_sharding() { + + ::xla::OpSharding* temp = _impl_.spmd_output_sharding_; + _impl_.spmd_output_sharding_ = 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::OpSharding* HloModuleProto::unsafe_arena_release_spmd_output_sharding() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.spmd_output_sharding) + + ::xla::OpSharding* temp = _impl_.spmd_output_sharding_; + _impl_.spmd_output_sharding_ = nullptr; + return temp; +} +inline ::xla::OpSharding* HloModuleProto::_internal_mutable_spmd_output_sharding() { + + if (_impl_.spmd_output_sharding_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::OpSharding>(GetArenaForAllocation()); + _impl_.spmd_output_sharding_ = p; + } + return _impl_.spmd_output_sharding_; +} +inline ::xla::OpSharding* HloModuleProto::mutable_spmd_output_sharding() { + ::xla::OpSharding* _msg = _internal_mutable_spmd_output_sharding(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.spmd_output_sharding) + return _msg; +} +inline void HloModuleProto::set_allocated_spmd_output_sharding(::xla::OpSharding* spmd_output_sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.spmd_output_sharding_); + } + if (spmd_output_sharding) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(spmd_output_sharding)); + if (message_arena != submessage_arena) { + spmd_output_sharding = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, spmd_output_sharding, submessage_arena); + } + + } else { + + } + _impl_.spmd_output_sharding_ = spmd_output_sharding; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.spmd_output_sharding) +} + +// repeated .xla.OpSharding spmd_parameters_shardings = 14; +inline int HloModuleProto::_internal_spmd_parameters_shardings_size() const { + return _impl_.spmd_parameters_shardings_.size(); +} +inline int HloModuleProto::spmd_parameters_shardings_size() const { + return _internal_spmd_parameters_shardings_size(); +} +inline ::xla::OpSharding* HloModuleProto::mutable_spmd_parameters_shardings(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.spmd_parameters_shardings) + return _impl_.spmd_parameters_shardings_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OpSharding >* +HloModuleProto::mutable_spmd_parameters_shardings() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleProto.spmd_parameters_shardings) + return &_impl_.spmd_parameters_shardings_; +} +inline const ::xla::OpSharding& HloModuleProto::_internal_spmd_parameters_shardings(int index) const { + return _impl_.spmd_parameters_shardings_.Get(index); +} +inline const ::xla::OpSharding& HloModuleProto::spmd_parameters_shardings(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.spmd_parameters_shardings) + return _internal_spmd_parameters_shardings(index); +} +inline ::xla::OpSharding* HloModuleProto::_internal_add_spmd_parameters_shardings() { + return _impl_.spmd_parameters_shardings_.Add(); +} +inline ::xla::OpSharding* HloModuleProto::add_spmd_parameters_shardings() { + ::xla::OpSharding* _add = _internal_add_spmd_parameters_shardings(); + // @@protoc_insertion_point(field_add:xla.HloModuleProto.spmd_parameters_shardings) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::OpSharding >& +HloModuleProto::spmd_parameters_shardings() const { + // @@protoc_insertion_point(field_list:xla.HloModuleProto.spmd_parameters_shardings) + return _impl_.spmd_parameters_shardings_; +} + +// bool use_auto_spmd_partitioning = 16; +inline void HloModuleProto::clear_use_auto_spmd_partitioning() { + _impl_.use_auto_spmd_partitioning_ = false; +} +inline bool HloModuleProto::_internal_use_auto_spmd_partitioning() const { + return _impl_.use_auto_spmd_partitioning_; +} +inline bool HloModuleProto::use_auto_spmd_partitioning() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.use_auto_spmd_partitioning) + return _internal_use_auto_spmd_partitioning(); +} +inline void HloModuleProto::_internal_set_use_auto_spmd_partitioning(bool value) { + + _impl_.use_auto_spmd_partitioning_ = value; +} +inline void HloModuleProto::set_use_auto_spmd_partitioning(bool value) { + _internal_set_use_auto_spmd_partitioning(value); + // @@protoc_insertion_point(field_set:xla.HloModuleProto.use_auto_spmd_partitioning) +} + +// repeated .xla.HloModuleProto.ProfileInfo profile_info = 13; +inline int HloModuleProto::_internal_profile_info_size() const { + return _impl_.profile_info_.size(); +} +inline int HloModuleProto::profile_info_size() const { + return _internal_profile_info_size(); +} +inline void HloModuleProto::clear_profile_info() { + _impl_.profile_info_.Clear(); +} +inline ::xla::HloModuleProto_ProfileInfo* HloModuleProto::mutable_profile_info(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.profile_info) + return _impl_.profile_info_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto_ProfileInfo >* +HloModuleProto::mutable_profile_info() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleProto.profile_info) + return &_impl_.profile_info_; +} +inline const ::xla::HloModuleProto_ProfileInfo& HloModuleProto::_internal_profile_info(int index) const { + return _impl_.profile_info_.Get(index); +} +inline const ::xla::HloModuleProto_ProfileInfo& HloModuleProto::profile_info(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.profile_info) + return _internal_profile_info(index); +} +inline ::xla::HloModuleProto_ProfileInfo* HloModuleProto::_internal_add_profile_info() { + return _impl_.profile_info_.Add(); +} +inline ::xla::HloModuleProto_ProfileInfo* HloModuleProto::add_profile_info() { + ::xla::HloModuleProto_ProfileInfo* _add = _internal_add_profile_info(); + // @@protoc_insertion_point(field_add:xla.HloModuleProto.profile_info) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto_ProfileInfo >& +HloModuleProto::profile_info() const { + // @@protoc_insertion_point(field_list:xla.HloModuleProto.profile_info) + return _impl_.profile_info_; +} + +// .xla.DeviceAssignmentProto device_assignment = 15; +inline bool HloModuleProto::_internal_has_device_assignment() const { + return this != internal_default_instance() && _impl_.device_assignment_ != nullptr; +} +inline bool HloModuleProto::has_device_assignment() const { + return _internal_has_device_assignment(); +} +inline const ::xla::DeviceAssignmentProto& HloModuleProto::_internal_device_assignment() const { + const ::xla::DeviceAssignmentProto* p = _impl_.device_assignment_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_DeviceAssignmentProto_default_instance_); +} +inline const ::xla::DeviceAssignmentProto& HloModuleProto::device_assignment() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.device_assignment) + return _internal_device_assignment(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_device_assignment( + ::xla::DeviceAssignmentProto* device_assignment) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.device_assignment_); + } + _impl_.device_assignment_ = device_assignment; + if (device_assignment) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.device_assignment) +} +inline ::xla::DeviceAssignmentProto* HloModuleProto::release_device_assignment() { + + ::xla::DeviceAssignmentProto* temp = _impl_.device_assignment_; + _impl_.device_assignment_ = 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::DeviceAssignmentProto* HloModuleProto::unsafe_arena_release_device_assignment() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.device_assignment) + + ::xla::DeviceAssignmentProto* temp = _impl_.device_assignment_; + _impl_.device_assignment_ = nullptr; + return temp; +} +inline ::xla::DeviceAssignmentProto* HloModuleProto::_internal_mutable_device_assignment() { + + if (_impl_.device_assignment_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::DeviceAssignmentProto>(GetArenaForAllocation()); + _impl_.device_assignment_ = p; + } + return _impl_.device_assignment_; +} +inline ::xla::DeviceAssignmentProto* HloModuleProto::mutable_device_assignment() { + ::xla::DeviceAssignmentProto* _msg = _internal_mutable_device_assignment(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.device_assignment) + return _msg; +} +inline void HloModuleProto::set_allocated_device_assignment(::xla::DeviceAssignmentProto* device_assignment) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.device_assignment_); + } + if (device_assignment) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(device_assignment)); + if (message_arena != submessage_arena) { + device_assignment = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, device_assignment, submessage_arena); + } + + } else { + + } + _impl_.device_assignment_ = device_assignment; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.device_assignment) +} + +// .xla.StackFrameIndexProto stack_frame_index = 17; +inline bool HloModuleProto::_internal_has_stack_frame_index() const { + return this != internal_default_instance() && _impl_.stack_frame_index_ != nullptr; +} +inline bool HloModuleProto::has_stack_frame_index() const { + return _internal_has_stack_frame_index(); +} +inline void HloModuleProto::clear_stack_frame_index() { + if (GetArenaForAllocation() == nullptr && _impl_.stack_frame_index_ != nullptr) { + delete _impl_.stack_frame_index_; + } + _impl_.stack_frame_index_ = nullptr; +} +inline const ::xla::StackFrameIndexProto& HloModuleProto::_internal_stack_frame_index() const { + const ::xla::StackFrameIndexProto* p = _impl_.stack_frame_index_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_StackFrameIndexProto_default_instance_); +} +inline const ::xla::StackFrameIndexProto& HloModuleProto::stack_frame_index() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.stack_frame_index) + return _internal_stack_frame_index(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_stack_frame_index( + ::xla::StackFrameIndexProto* stack_frame_index) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.stack_frame_index_); + } + _impl_.stack_frame_index_ = stack_frame_index; + if (stack_frame_index) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.stack_frame_index) +} +inline ::xla::StackFrameIndexProto* HloModuleProto::release_stack_frame_index() { + + ::xla::StackFrameIndexProto* temp = _impl_.stack_frame_index_; + _impl_.stack_frame_index_ = 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::StackFrameIndexProto* HloModuleProto::unsafe_arena_release_stack_frame_index() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.stack_frame_index) + + ::xla::StackFrameIndexProto* temp = _impl_.stack_frame_index_; + _impl_.stack_frame_index_ = nullptr; + return temp; +} +inline ::xla::StackFrameIndexProto* HloModuleProto::_internal_mutable_stack_frame_index() { + + if (_impl_.stack_frame_index_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::StackFrameIndexProto>(GetArenaForAllocation()); + _impl_.stack_frame_index_ = p; + } + return _impl_.stack_frame_index_; +} +inline ::xla::StackFrameIndexProto* HloModuleProto::mutable_stack_frame_index() { + ::xla::StackFrameIndexProto* _msg = _internal_mutable_stack_frame_index(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.stack_frame_index) + return _msg; +} +inline void HloModuleProto::set_allocated_stack_frame_index(::xla::StackFrameIndexProto* stack_frame_index) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.stack_frame_index_; + } + if (stack_frame_index) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(stack_frame_index); + if (message_arena != submessage_arena) { + stack_frame_index = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, stack_frame_index, submessage_arena); + } + + } else { + + } + _impl_.stack_frame_index_ = stack_frame_index; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.stack_frame_index) +} + +// .xla.FrontendAttributes frontend_attributes = 19; +inline bool HloModuleProto::_internal_has_frontend_attributes() const { + return this != internal_default_instance() && _impl_.frontend_attributes_ != nullptr; +} +inline bool HloModuleProto::has_frontend_attributes() const { + return _internal_has_frontend_attributes(); +} +inline const ::xla::FrontendAttributes& HloModuleProto::_internal_frontend_attributes() const { + const ::xla::FrontendAttributes* p = _impl_.frontend_attributes_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_FrontendAttributes_default_instance_); +} +inline const ::xla::FrontendAttributes& HloModuleProto::frontend_attributes() const { + // @@protoc_insertion_point(field_get:xla.HloModuleProto.frontend_attributes) + return _internal_frontend_attributes(); +} +inline void HloModuleProto::unsafe_arena_set_allocated_frontend_attributes( + ::xla::FrontendAttributes* frontend_attributes) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.frontend_attributes_); + } + _impl_.frontend_attributes_ = frontend_attributes; + if (frontend_attributes) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloModuleProto.frontend_attributes) +} +inline ::xla::FrontendAttributes* HloModuleProto::release_frontend_attributes() { + + ::xla::FrontendAttributes* temp = _impl_.frontend_attributes_; + _impl_.frontend_attributes_ = 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::FrontendAttributes* HloModuleProto::unsafe_arena_release_frontend_attributes() { + // @@protoc_insertion_point(field_release:xla.HloModuleProto.frontend_attributes) + + ::xla::FrontendAttributes* temp = _impl_.frontend_attributes_; + _impl_.frontend_attributes_ = nullptr; + return temp; +} +inline ::xla::FrontendAttributes* HloModuleProto::_internal_mutable_frontend_attributes() { + + if (_impl_.frontend_attributes_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::FrontendAttributes>(GetArenaForAllocation()); + _impl_.frontend_attributes_ = p; + } + return _impl_.frontend_attributes_; +} +inline ::xla::FrontendAttributes* HloModuleProto::mutable_frontend_attributes() { + ::xla::FrontendAttributes* _msg = _internal_mutable_frontend_attributes(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleProto.frontend_attributes) + return _msg; +} +inline void HloModuleProto::set_allocated_frontend_attributes(::xla::FrontendAttributes* frontend_attributes) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.frontend_attributes_); + } + if (frontend_attributes) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(frontend_attributes)); + if (message_arena != submessage_arena) { + frontend_attributes = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, frontend_attributes, submessage_arena); + } + + } else { + + } + _impl_.frontend_attributes_ = frontend_attributes; + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleProto.frontend_attributes) +} + +// ------------------------------------------------------------------- + +// LogicalBufferProto_Location + +// string instruction_name = 2 [deprecated = true]; +inline void LogicalBufferProto_Location::clear_instruction_name() { + _impl_.instruction_name_.ClearToEmpty(); +} +inline const std::string& LogicalBufferProto_Location::instruction_name() const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.Location.instruction_name) + return _internal_instruction_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void LogicalBufferProto_Location::set_instruction_name(ArgT0&& arg0, ArgT... args) { + + _impl_.instruction_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.LogicalBufferProto.Location.instruction_name) +} +inline std::string* LogicalBufferProto_Location::mutable_instruction_name() { + std::string* _s = _internal_mutable_instruction_name(); + // @@protoc_insertion_point(field_mutable:xla.LogicalBufferProto.Location.instruction_name) + return _s; +} +inline const std::string& LogicalBufferProto_Location::_internal_instruction_name() const { + return _impl_.instruction_name_.Get(); +} +inline void LogicalBufferProto_Location::_internal_set_instruction_name(const std::string& value) { + + _impl_.instruction_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* LogicalBufferProto_Location::_internal_mutable_instruction_name() { + + return _impl_.instruction_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* LogicalBufferProto_Location::release_instruction_name() { + // @@protoc_insertion_point(field_release:xla.LogicalBufferProto.Location.instruction_name) + return _impl_.instruction_name_.Release(); +} +inline void LogicalBufferProto_Location::set_allocated_instruction_name(std::string* instruction_name) { + if (instruction_name != nullptr) { + + } else { + + } + _impl_.instruction_name_.SetAllocated(instruction_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.instruction_name_.IsDefault()) { + _impl_.instruction_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.LogicalBufferProto.Location.instruction_name) +} + +// int64 instruction_id = 4; +inline void LogicalBufferProto_Location::clear_instruction_id() { + _impl_.instruction_id_ = int64_t{0}; +} +inline int64_t LogicalBufferProto_Location::_internal_instruction_id() const { + return _impl_.instruction_id_; +} +inline int64_t LogicalBufferProto_Location::instruction_id() const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.Location.instruction_id) + return _internal_instruction_id(); +} +inline void LogicalBufferProto_Location::_internal_set_instruction_id(int64_t value) { + + _impl_.instruction_id_ = value; +} +inline void LogicalBufferProto_Location::set_instruction_id(int64_t value) { + _internal_set_instruction_id(value); + // @@protoc_insertion_point(field_set:xla.LogicalBufferProto.Location.instruction_id) +} + +// repeated int64 shape_index = 3; +inline int LogicalBufferProto_Location::_internal_shape_index_size() const { + return _impl_.shape_index_.size(); +} +inline int LogicalBufferProto_Location::shape_index_size() const { + return _internal_shape_index_size(); +} +inline void LogicalBufferProto_Location::clear_shape_index() { + _impl_.shape_index_.Clear(); +} +inline int64_t LogicalBufferProto_Location::_internal_shape_index(int index) const { + return _impl_.shape_index_.Get(index); +} +inline int64_t LogicalBufferProto_Location::shape_index(int index) const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.Location.shape_index) + return _internal_shape_index(index); +} +inline void LogicalBufferProto_Location::set_shape_index(int index, int64_t value) { + _impl_.shape_index_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.LogicalBufferProto.Location.shape_index) +} +inline void LogicalBufferProto_Location::_internal_add_shape_index(int64_t value) { + _impl_.shape_index_.Add(value); +} +inline void LogicalBufferProto_Location::add_shape_index(int64_t value) { + _internal_add_shape_index(value); + // @@protoc_insertion_point(field_add:xla.LogicalBufferProto.Location.shape_index) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +LogicalBufferProto_Location::_internal_shape_index() const { + return _impl_.shape_index_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +LogicalBufferProto_Location::shape_index() const { + // @@protoc_insertion_point(field_list:xla.LogicalBufferProto.Location.shape_index) + return _internal_shape_index(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +LogicalBufferProto_Location::_internal_mutable_shape_index() { + return &_impl_.shape_index_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +LogicalBufferProto_Location::mutable_shape_index() { + // @@protoc_insertion_point(field_mutable_list:xla.LogicalBufferProto.Location.shape_index) + return _internal_mutable_shape_index(); +} + +// ------------------------------------------------------------------- + +// LogicalBufferProto + +// int64 id = 1; +inline void LogicalBufferProto::clear_id() { + _impl_.id_ = int64_t{0}; +} +inline int64_t LogicalBufferProto::_internal_id() const { + return _impl_.id_; +} +inline int64_t LogicalBufferProto::id() const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.id) + return _internal_id(); +} +inline void LogicalBufferProto::_internal_set_id(int64_t value) { + + _impl_.id_ = value; +} +inline void LogicalBufferProto::set_id(int64_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:xla.LogicalBufferProto.id) +} + +// int64 size = 2; +inline void LogicalBufferProto::clear_size() { + _impl_.size_ = int64_t{0}; +} +inline int64_t LogicalBufferProto::_internal_size() const { + return _impl_.size_; +} +inline int64_t LogicalBufferProto::size() const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.size) + return _internal_size(); +} +inline void LogicalBufferProto::_internal_set_size(int64_t value) { + + _impl_.size_ = value; +} +inline void LogicalBufferProto::set_size(int64_t value) { + _internal_set_size(value); + // @@protoc_insertion_point(field_set:xla.LogicalBufferProto.size) +} + +// .xla.LogicalBufferProto.Location defined_at = 3; +inline bool LogicalBufferProto::_internal_has_defined_at() const { + return this != internal_default_instance() && _impl_.defined_at_ != nullptr; +} +inline bool LogicalBufferProto::has_defined_at() const { + return _internal_has_defined_at(); +} +inline void LogicalBufferProto::clear_defined_at() { + if (GetArenaForAllocation() == nullptr && _impl_.defined_at_ != nullptr) { + delete _impl_.defined_at_; + } + _impl_.defined_at_ = nullptr; +} +inline const ::xla::LogicalBufferProto_Location& LogicalBufferProto::_internal_defined_at() const { + const ::xla::LogicalBufferProto_Location* p = _impl_.defined_at_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_LogicalBufferProto_Location_default_instance_); +} +inline const ::xla::LogicalBufferProto_Location& LogicalBufferProto::defined_at() const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.defined_at) + return _internal_defined_at(); +} +inline void LogicalBufferProto::unsafe_arena_set_allocated_defined_at( + ::xla::LogicalBufferProto_Location* defined_at) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.defined_at_); + } + _impl_.defined_at_ = defined_at; + if (defined_at) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.LogicalBufferProto.defined_at) +} +inline ::xla::LogicalBufferProto_Location* LogicalBufferProto::release_defined_at() { + + ::xla::LogicalBufferProto_Location* temp = _impl_.defined_at_; + _impl_.defined_at_ = 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::LogicalBufferProto_Location* LogicalBufferProto::unsafe_arena_release_defined_at() { + // @@protoc_insertion_point(field_release:xla.LogicalBufferProto.defined_at) + + ::xla::LogicalBufferProto_Location* temp = _impl_.defined_at_; + _impl_.defined_at_ = nullptr; + return temp; +} +inline ::xla::LogicalBufferProto_Location* LogicalBufferProto::_internal_mutable_defined_at() { + + if (_impl_.defined_at_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::LogicalBufferProto_Location>(GetArenaForAllocation()); + _impl_.defined_at_ = p; + } + return _impl_.defined_at_; +} +inline ::xla::LogicalBufferProto_Location* LogicalBufferProto::mutable_defined_at() { + ::xla::LogicalBufferProto_Location* _msg = _internal_mutable_defined_at(); + // @@protoc_insertion_point(field_mutable:xla.LogicalBufferProto.defined_at) + return _msg; +} +inline void LogicalBufferProto::set_allocated_defined_at(::xla::LogicalBufferProto_Location* defined_at) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.defined_at_; + } + if (defined_at) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(defined_at); + if (message_arena != submessage_arena) { + defined_at = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, defined_at, submessage_arena); + } + + } else { + + } + _impl_.defined_at_ = defined_at; + // @@protoc_insertion_point(field_set_allocated:xla.LogicalBufferProto.defined_at) +} + +// int64 color = 4; +inline void LogicalBufferProto::clear_color() { + _impl_.color_ = int64_t{0}; +} +inline int64_t LogicalBufferProto::_internal_color() const { + return _impl_.color_; +} +inline int64_t LogicalBufferProto::color() const { + // @@protoc_insertion_point(field_get:xla.LogicalBufferProto.color) + return _internal_color(); +} +inline void LogicalBufferProto::_internal_set_color(int64_t value) { + + _impl_.color_ = value; +} +inline void LogicalBufferProto::set_color(int64_t value) { + _internal_set_color(value); + // @@protoc_insertion_point(field_set:xla.LogicalBufferProto.color) +} + +// ------------------------------------------------------------------- + +// BufferAllocationProto_Assigned + +// int64 logical_buffer_id = 1; +inline void BufferAllocationProto_Assigned::clear_logical_buffer_id() { + _impl_.logical_buffer_id_ = int64_t{0}; +} +inline int64_t BufferAllocationProto_Assigned::_internal_logical_buffer_id() const { + return _impl_.logical_buffer_id_; +} +inline int64_t BufferAllocationProto_Assigned::logical_buffer_id() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.Assigned.logical_buffer_id) + return _internal_logical_buffer_id(); +} +inline void BufferAllocationProto_Assigned::_internal_set_logical_buffer_id(int64_t value) { + + _impl_.logical_buffer_id_ = value; +} +inline void BufferAllocationProto_Assigned::set_logical_buffer_id(int64_t value) { + _internal_set_logical_buffer_id(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.Assigned.logical_buffer_id) +} + +// int64 offset = 2; +inline void BufferAllocationProto_Assigned::clear_offset() { + _impl_.offset_ = int64_t{0}; +} +inline int64_t BufferAllocationProto_Assigned::_internal_offset() const { + return _impl_.offset_; +} +inline int64_t BufferAllocationProto_Assigned::offset() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.Assigned.offset) + return _internal_offset(); +} +inline void BufferAllocationProto_Assigned::_internal_set_offset(int64_t value) { + + _impl_.offset_ = value; +} +inline void BufferAllocationProto_Assigned::set_offset(int64_t value) { + _internal_set_offset(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.Assigned.offset) +} + +// int64 size = 3; +inline void BufferAllocationProto_Assigned::clear_size() { + _impl_.size_ = int64_t{0}; +} +inline int64_t BufferAllocationProto_Assigned::_internal_size() const { + return _impl_.size_; +} +inline int64_t BufferAllocationProto_Assigned::size() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.Assigned.size) + return _internal_size(); +} +inline void BufferAllocationProto_Assigned::_internal_set_size(int64_t value) { + + _impl_.size_ = value; +} +inline void BufferAllocationProto_Assigned::set_size(int64_t value) { + _internal_set_size(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.Assigned.size) +} + +// ------------------------------------------------------------------- + +// BufferAllocationProto + +// int64 index = 1; +inline void BufferAllocationProto::clear_index() { + _impl_.index_ = int64_t{0}; +} +inline int64_t BufferAllocationProto::_internal_index() const { + return _impl_.index_; +} +inline int64_t BufferAllocationProto::index() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.index) + return _internal_index(); +} +inline void BufferAllocationProto::_internal_set_index(int64_t value) { + + _impl_.index_ = value; +} +inline void BufferAllocationProto::set_index(int64_t value) { + _internal_set_index(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.index) +} + +// int64 size = 2; +inline void BufferAllocationProto::clear_size() { + _impl_.size_ = int64_t{0}; +} +inline int64_t BufferAllocationProto::_internal_size() const { + return _impl_.size_; +} +inline int64_t BufferAllocationProto::size() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.size) + return _internal_size(); +} +inline void BufferAllocationProto::_internal_set_size(int64_t value) { + + _impl_.size_ = value; +} +inline void BufferAllocationProto::set_size(int64_t value) { + _internal_set_size(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.size) +} + +// bool is_thread_local = 3; +inline void BufferAllocationProto::clear_is_thread_local() { + _impl_.is_thread_local_ = false; +} +inline bool BufferAllocationProto::_internal_is_thread_local() const { + return _impl_.is_thread_local_; +} +inline bool BufferAllocationProto::is_thread_local() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.is_thread_local) + return _internal_is_thread_local(); +} +inline void BufferAllocationProto::_internal_set_is_thread_local(bool value) { + + _impl_.is_thread_local_ = value; +} +inline void BufferAllocationProto::set_is_thread_local(bool value) { + _internal_set_is_thread_local(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.is_thread_local) +} + +// bool is_tuple = 11; +inline void BufferAllocationProto::clear_is_tuple() { + _impl_.is_tuple_ = false; +} +inline bool BufferAllocationProto::_internal_is_tuple() const { + return _impl_.is_tuple_; +} +inline bool BufferAllocationProto::is_tuple() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.is_tuple) + return _internal_is_tuple(); +} +inline void BufferAllocationProto::_internal_set_is_tuple(bool value) { + + _impl_.is_tuple_ = value; +} +inline void BufferAllocationProto::set_is_tuple(bool value) { + _internal_set_is_tuple(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.is_tuple) +} + +// bool is_entry_computation_parameter = 5; +inline void BufferAllocationProto::clear_is_entry_computation_parameter() { + _impl_.is_entry_computation_parameter_ = false; +} +inline bool BufferAllocationProto::_internal_is_entry_computation_parameter() const { + return _impl_.is_entry_computation_parameter_; +} +inline bool BufferAllocationProto::is_entry_computation_parameter() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.is_entry_computation_parameter) + return _internal_is_entry_computation_parameter(); +} +inline void BufferAllocationProto::_internal_set_is_entry_computation_parameter(bool value) { + + _impl_.is_entry_computation_parameter_ = value; +} +inline void BufferAllocationProto::set_is_entry_computation_parameter(bool value) { + _internal_set_is_entry_computation_parameter(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.is_entry_computation_parameter) +} + +// bool is_constant = 12; +inline void BufferAllocationProto::clear_is_constant() { + _impl_.is_constant_ = false; +} +inline bool BufferAllocationProto::_internal_is_constant() const { + return _impl_.is_constant_; +} +inline bool BufferAllocationProto::is_constant() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.is_constant) + return _internal_is_constant(); +} +inline void BufferAllocationProto::_internal_set_is_constant(bool value) { + + _impl_.is_constant_ = value; +} +inline void BufferAllocationProto::set_is_constant(bool value) { + _internal_set_is_constant(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.is_constant) +} + +// int64 parameter_number = 6; +inline void BufferAllocationProto::clear_parameter_number() { + _impl_.parameter_number_ = int64_t{0}; +} +inline int64_t BufferAllocationProto::_internal_parameter_number() const { + return _impl_.parameter_number_; +} +inline int64_t BufferAllocationProto::parameter_number() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.parameter_number) + return _internal_parameter_number(); +} +inline void BufferAllocationProto::_internal_set_parameter_number(int64_t value) { + + _impl_.parameter_number_ = value; +} +inline void BufferAllocationProto::set_parameter_number(int64_t value) { + _internal_set_parameter_number(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.parameter_number) +} + +// repeated int64 parameter_shape_index = 10; +inline int BufferAllocationProto::_internal_parameter_shape_index_size() const { + return _impl_.parameter_shape_index_.size(); +} +inline int BufferAllocationProto::parameter_shape_index_size() const { + return _internal_parameter_shape_index_size(); +} +inline void BufferAllocationProto::clear_parameter_shape_index() { + _impl_.parameter_shape_index_.Clear(); +} +inline int64_t BufferAllocationProto::_internal_parameter_shape_index(int index) const { + return _impl_.parameter_shape_index_.Get(index); +} +inline int64_t BufferAllocationProto::parameter_shape_index(int index) const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.parameter_shape_index) + return _internal_parameter_shape_index(index); +} +inline void BufferAllocationProto::set_parameter_shape_index(int index, int64_t value) { + _impl_.parameter_shape_index_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.parameter_shape_index) +} +inline void BufferAllocationProto::_internal_add_parameter_shape_index(int64_t value) { + _impl_.parameter_shape_index_.Add(value); +} +inline void BufferAllocationProto::add_parameter_shape_index(int64_t value) { + _internal_add_parameter_shape_index(value); + // @@protoc_insertion_point(field_add:xla.BufferAllocationProto.parameter_shape_index) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +BufferAllocationProto::_internal_parameter_shape_index() const { + return _impl_.parameter_shape_index_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +BufferAllocationProto::parameter_shape_index() const { + // @@protoc_insertion_point(field_list:xla.BufferAllocationProto.parameter_shape_index) + return _internal_parameter_shape_index(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +BufferAllocationProto::_internal_mutable_parameter_shape_index() { + return &_impl_.parameter_shape_index_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +BufferAllocationProto::mutable_parameter_shape_index() { + // @@protoc_insertion_point(field_mutable_list:xla.BufferAllocationProto.parameter_shape_index) + return _internal_mutable_parameter_shape_index(); +} + +// bool maybe_live_out = 7; +inline void BufferAllocationProto::clear_maybe_live_out() { + _impl_.maybe_live_out_ = false; +} +inline bool BufferAllocationProto::_internal_maybe_live_out() const { + return _impl_.maybe_live_out_; +} +inline bool BufferAllocationProto::maybe_live_out() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.maybe_live_out) + return _internal_maybe_live_out(); +} +inline void BufferAllocationProto::_internal_set_maybe_live_out(bool value) { + + _impl_.maybe_live_out_ = value; +} +inline void BufferAllocationProto::set_maybe_live_out(bool value) { + _internal_set_maybe_live_out(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.maybe_live_out) +} + +// int64 color = 8; +inline void BufferAllocationProto::clear_color() { + _impl_.color_ = int64_t{0}; +} +inline int64_t BufferAllocationProto::_internal_color() const { + return _impl_.color_; +} +inline int64_t BufferAllocationProto::color() const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.color) + return _internal_color(); +} +inline void BufferAllocationProto::_internal_set_color(int64_t value) { + + _impl_.color_ = value; +} +inline void BufferAllocationProto::set_color(int64_t value) { + _internal_set_color(value); + // @@protoc_insertion_point(field_set:xla.BufferAllocationProto.color) +} + +// repeated .xla.BufferAllocationProto.Assigned assigned = 9; +inline int BufferAllocationProto::_internal_assigned_size() const { + return _impl_.assigned_.size(); +} +inline int BufferAllocationProto::assigned_size() const { + return _internal_assigned_size(); +} +inline void BufferAllocationProto::clear_assigned() { + _impl_.assigned_.Clear(); +} +inline ::xla::BufferAllocationProto_Assigned* BufferAllocationProto::mutable_assigned(int index) { + // @@protoc_insertion_point(field_mutable:xla.BufferAllocationProto.assigned) + return _impl_.assigned_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto_Assigned >* +BufferAllocationProto::mutable_assigned() { + // @@protoc_insertion_point(field_mutable_list:xla.BufferAllocationProto.assigned) + return &_impl_.assigned_; +} +inline const ::xla::BufferAllocationProto_Assigned& BufferAllocationProto::_internal_assigned(int index) const { + return _impl_.assigned_.Get(index); +} +inline const ::xla::BufferAllocationProto_Assigned& BufferAllocationProto::assigned(int index) const { + // @@protoc_insertion_point(field_get:xla.BufferAllocationProto.assigned) + return _internal_assigned(index); +} +inline ::xla::BufferAllocationProto_Assigned* BufferAllocationProto::_internal_add_assigned() { + return _impl_.assigned_.Add(); +} +inline ::xla::BufferAllocationProto_Assigned* BufferAllocationProto::add_assigned() { + ::xla::BufferAllocationProto_Assigned* _add = _internal_add_assigned(); + // @@protoc_insertion_point(field_add:xla.BufferAllocationProto.assigned) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto_Assigned >& +BufferAllocationProto::assigned() const { + // @@protoc_insertion_point(field_list:xla.BufferAllocationProto.assigned) + return _impl_.assigned_; +} + +// ------------------------------------------------------------------- + +// HeapSimulatorTrace_Event + +// .xla.HeapSimulatorTrace.Event.Kind kind = 1; +inline void HeapSimulatorTrace_Event::clear_kind() { + _impl_.kind_ = 0; +} +inline ::xla::HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::_internal_kind() const { + return static_cast< ::xla::HeapSimulatorTrace_Event_Kind >(_impl_.kind_); +} +inline ::xla::HeapSimulatorTrace_Event_Kind HeapSimulatorTrace_Event::kind() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.Event.kind) + return _internal_kind(); +} +inline void HeapSimulatorTrace_Event::_internal_set_kind(::xla::HeapSimulatorTrace_Event_Kind value) { + + _impl_.kind_ = value; +} +inline void HeapSimulatorTrace_Event::set_kind(::xla::HeapSimulatorTrace_Event_Kind value) { + _internal_set_kind(value); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.Event.kind) +} + +// int64 buffer_id = 2; +inline void HeapSimulatorTrace_Event::clear_buffer_id() { + _impl_.buffer_id_ = int64_t{0}; +} +inline int64_t HeapSimulatorTrace_Event::_internal_buffer_id() const { + return _impl_.buffer_id_; +} +inline int64_t HeapSimulatorTrace_Event::buffer_id() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.Event.buffer_id) + return _internal_buffer_id(); +} +inline void HeapSimulatorTrace_Event::_internal_set_buffer_id(int64_t value) { + + _impl_.buffer_id_ = value; +} +inline void HeapSimulatorTrace_Event::set_buffer_id(int64_t value) { + _internal_set_buffer_id(value); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.Event.buffer_id) +} + +// string computation_name = 3; +inline void HeapSimulatorTrace_Event::clear_computation_name() { + _impl_.computation_name_.ClearToEmpty(); +} +inline const std::string& HeapSimulatorTrace_Event::computation_name() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.Event.computation_name) + return _internal_computation_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HeapSimulatorTrace_Event::set_computation_name(ArgT0&& arg0, ArgT... args) { + + _impl_.computation_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.Event.computation_name) +} +inline std::string* HeapSimulatorTrace_Event::mutable_computation_name() { + std::string* _s = _internal_mutable_computation_name(); + // @@protoc_insertion_point(field_mutable:xla.HeapSimulatorTrace.Event.computation_name) + return _s; +} +inline const std::string& HeapSimulatorTrace_Event::_internal_computation_name() const { + return _impl_.computation_name_.Get(); +} +inline void HeapSimulatorTrace_Event::_internal_set_computation_name(const std::string& value) { + + _impl_.computation_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HeapSimulatorTrace_Event::_internal_mutable_computation_name() { + + return _impl_.computation_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HeapSimulatorTrace_Event::release_computation_name() { + // @@protoc_insertion_point(field_release:xla.HeapSimulatorTrace.Event.computation_name) + return _impl_.computation_name_.Release(); +} +inline void HeapSimulatorTrace_Event::set_allocated_computation_name(std::string* computation_name) { + if (computation_name != nullptr) { + + } else { + + } + _impl_.computation_name_.SetAllocated(computation_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.computation_name_.IsDefault()) { + _impl_.computation_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HeapSimulatorTrace.Event.computation_name) +} + +// string instruction_name = 4; +inline void HeapSimulatorTrace_Event::clear_instruction_name() { + _impl_.instruction_name_.ClearToEmpty(); +} +inline const std::string& HeapSimulatorTrace_Event::instruction_name() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.Event.instruction_name) + return _internal_instruction_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HeapSimulatorTrace_Event::set_instruction_name(ArgT0&& arg0, ArgT... args) { + + _impl_.instruction_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.Event.instruction_name) +} +inline std::string* HeapSimulatorTrace_Event::mutable_instruction_name() { + std::string* _s = _internal_mutable_instruction_name(); + // @@protoc_insertion_point(field_mutable:xla.HeapSimulatorTrace.Event.instruction_name) + return _s; +} +inline const std::string& HeapSimulatorTrace_Event::_internal_instruction_name() const { + return _impl_.instruction_name_.Get(); +} +inline void HeapSimulatorTrace_Event::_internal_set_instruction_name(const std::string& value) { + + _impl_.instruction_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HeapSimulatorTrace_Event::_internal_mutable_instruction_name() { + + return _impl_.instruction_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HeapSimulatorTrace_Event::release_instruction_name() { + // @@protoc_insertion_point(field_release:xla.HeapSimulatorTrace.Event.instruction_name) + return _impl_.instruction_name_.Release(); +} +inline void HeapSimulatorTrace_Event::set_allocated_instruction_name(std::string* instruction_name) { + if (instruction_name != nullptr) { + + } else { + + } + _impl_.instruction_name_.SetAllocated(instruction_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.instruction_name_.IsDefault()) { + _impl_.instruction_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HeapSimulatorTrace.Event.instruction_name) +} + +// int64 share_with_canonical_id = 5; +inline void HeapSimulatorTrace_Event::clear_share_with_canonical_id() { + _impl_.share_with_canonical_id_ = int64_t{0}; +} +inline int64_t HeapSimulatorTrace_Event::_internal_share_with_canonical_id() const { + return _impl_.share_with_canonical_id_; +} +inline int64_t HeapSimulatorTrace_Event::share_with_canonical_id() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.Event.share_with_canonical_id) + return _internal_share_with_canonical_id(); +} +inline void HeapSimulatorTrace_Event::_internal_set_share_with_canonical_id(int64_t value) { + + _impl_.share_with_canonical_id_ = value; +} +inline void HeapSimulatorTrace_Event::set_share_with_canonical_id(int64_t value) { + _internal_set_share_with_canonical_id(value); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.Event.share_with_canonical_id) +} + +// ------------------------------------------------------------------- + +// HeapSimulatorTrace + +// repeated .xla.HeapSimulatorTrace.Event events = 1; +inline int HeapSimulatorTrace::_internal_events_size() const { + return _impl_.events_.size(); +} +inline int HeapSimulatorTrace::events_size() const { + return _internal_events_size(); +} +inline void HeapSimulatorTrace::clear_events() { + _impl_.events_.Clear(); +} +inline ::xla::HeapSimulatorTrace_Event* HeapSimulatorTrace::mutable_events(int index) { + // @@protoc_insertion_point(field_mutable:xla.HeapSimulatorTrace.events) + return _impl_.events_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace_Event >* +HeapSimulatorTrace::mutable_events() { + // @@protoc_insertion_point(field_mutable_list:xla.HeapSimulatorTrace.events) + return &_impl_.events_; +} +inline const ::xla::HeapSimulatorTrace_Event& HeapSimulatorTrace::_internal_events(int index) const { + return _impl_.events_.Get(index); +} +inline const ::xla::HeapSimulatorTrace_Event& HeapSimulatorTrace::events(int index) const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.events) + return _internal_events(index); +} +inline ::xla::HeapSimulatorTrace_Event* HeapSimulatorTrace::_internal_add_events() { + return _impl_.events_.Add(); +} +inline ::xla::HeapSimulatorTrace_Event* HeapSimulatorTrace::add_events() { + ::xla::HeapSimulatorTrace_Event* _add = _internal_add_events(); + // @@protoc_insertion_point(field_add:xla.HeapSimulatorTrace.events) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace_Event >& +HeapSimulatorTrace::events() const { + // @@protoc_insertion_point(field_list:xla.HeapSimulatorTrace.events) + return _impl_.events_; +} + +// bool whole_module_simulation = 2; +inline void HeapSimulatorTrace::clear_whole_module_simulation() { + _impl_.whole_module_simulation_ = false; +} +inline bool HeapSimulatorTrace::_internal_whole_module_simulation() const { + return _impl_.whole_module_simulation_; +} +inline bool HeapSimulatorTrace::whole_module_simulation() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.whole_module_simulation) + return _internal_whole_module_simulation(); +} +inline void HeapSimulatorTrace::_internal_set_whole_module_simulation(bool value) { + + _impl_.whole_module_simulation_ = value; +} +inline void HeapSimulatorTrace::set_whole_module_simulation(bool value) { + _internal_set_whole_module_simulation(value); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.whole_module_simulation) +} + +// int64 buffer_allocation_index = 3; +inline void HeapSimulatorTrace::clear_buffer_allocation_index() { + _impl_.buffer_allocation_index_ = int64_t{0}; +} +inline int64_t HeapSimulatorTrace::_internal_buffer_allocation_index() const { + return _impl_.buffer_allocation_index_; +} +inline int64_t HeapSimulatorTrace::buffer_allocation_index() const { + // @@protoc_insertion_point(field_get:xla.HeapSimulatorTrace.buffer_allocation_index) + return _internal_buffer_allocation_index(); +} +inline void HeapSimulatorTrace::_internal_set_buffer_allocation_index(int64_t value) { + + _impl_.buffer_allocation_index_ = value; +} +inline void HeapSimulatorTrace::set_buffer_allocation_index(int64_t value) { + _internal_set_buffer_allocation_index(value); + // @@protoc_insertion_point(field_set:xla.HeapSimulatorTrace.buffer_allocation_index) +} + +// ------------------------------------------------------------------- + +// HloModuleGroupProto + +// string name = 1; +inline void HloModuleGroupProto::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& HloModuleGroupProto::name() const { + // @@protoc_insertion_point(field_get:xla.HloModuleGroupProto.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloModuleGroupProto::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloModuleGroupProto.name) +} +inline std::string* HloModuleGroupProto::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleGroupProto.name) + return _s; +} +inline const std::string& HloModuleGroupProto::_internal_name() const { + return _impl_.name_.Get(); +} +inline void HloModuleGroupProto::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloModuleGroupProto::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloModuleGroupProto::release_name() { + // @@protoc_insertion_point(field_release:xla.HloModuleGroupProto.name) + return _impl_.name_.Release(); +} +inline void HloModuleGroupProto::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:xla.HloModuleGroupProto.name) +} + +// repeated .xla.HloModuleProto hlo_modules = 2; +inline int HloModuleGroupProto::_internal_hlo_modules_size() const { + return _impl_.hlo_modules_.size(); +} +inline int HloModuleGroupProto::hlo_modules_size() const { + return _internal_hlo_modules_size(); +} +inline void HloModuleGroupProto::clear_hlo_modules() { + _impl_.hlo_modules_.Clear(); +} +inline ::xla::HloModuleProto* HloModuleGroupProto::mutable_hlo_modules(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloModuleGroupProto.hlo_modules) + return _impl_.hlo_modules_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto >* +HloModuleGroupProto::mutable_hlo_modules() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleGroupProto.hlo_modules) + return &_impl_.hlo_modules_; +} +inline const ::xla::HloModuleProto& HloModuleGroupProto::_internal_hlo_modules(int index) const { + return _impl_.hlo_modules_.Get(index); +} +inline const ::xla::HloModuleProto& HloModuleGroupProto::hlo_modules(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleGroupProto.hlo_modules) + return _internal_hlo_modules(index); +} +inline ::xla::HloModuleProto* HloModuleGroupProto::_internal_add_hlo_modules() { + return _impl_.hlo_modules_.Add(); +} +inline ::xla::HloModuleProto* HloModuleGroupProto::add_hlo_modules() { + ::xla::HloModuleProto* _add = _internal_add_hlo_modules(); + // @@protoc_insertion_point(field_add:xla.HloModuleGroupProto.hlo_modules) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloModuleProto >& +HloModuleGroupProto::hlo_modules() const { + // @@protoc_insertion_point(field_list:xla.HloModuleGroupProto.hlo_modules) + return _impl_.hlo_modules_; +} + +// ------------------------------------------------------------------- + +// BufferAssignmentProto_BufferAlias + +// int64 source_buffer_id = 1; +inline void BufferAssignmentProto_BufferAlias::clear_source_buffer_id() { + _impl_.source_buffer_id_ = int64_t{0}; +} +inline int64_t BufferAssignmentProto_BufferAlias::_internal_source_buffer_id() const { + return _impl_.source_buffer_id_; +} +inline int64_t BufferAssignmentProto_BufferAlias::source_buffer_id() const { + // @@protoc_insertion_point(field_get:xla.BufferAssignmentProto.BufferAlias.source_buffer_id) + return _internal_source_buffer_id(); +} +inline void BufferAssignmentProto_BufferAlias::_internal_set_source_buffer_id(int64_t value) { + + _impl_.source_buffer_id_ = value; +} +inline void BufferAssignmentProto_BufferAlias::set_source_buffer_id(int64_t value) { + _internal_set_source_buffer_id(value); + // @@protoc_insertion_point(field_set:xla.BufferAssignmentProto.BufferAlias.source_buffer_id) +} + +// .xla.LogicalBufferProto.Location location = 2; +inline bool BufferAssignmentProto_BufferAlias::_internal_has_location() const { + return this != internal_default_instance() && _impl_.location_ != nullptr; +} +inline bool BufferAssignmentProto_BufferAlias::has_location() const { + return _internal_has_location(); +} +inline void BufferAssignmentProto_BufferAlias::clear_location() { + if (GetArenaForAllocation() == nullptr && _impl_.location_ != nullptr) { + delete _impl_.location_; + } + _impl_.location_ = nullptr; +} +inline const ::xla::LogicalBufferProto_Location& BufferAssignmentProto_BufferAlias::_internal_location() const { + const ::xla::LogicalBufferProto_Location* p = _impl_.location_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_LogicalBufferProto_Location_default_instance_); +} +inline const ::xla::LogicalBufferProto_Location& BufferAssignmentProto_BufferAlias::location() const { + // @@protoc_insertion_point(field_get:xla.BufferAssignmentProto.BufferAlias.location) + return _internal_location(); +} +inline void BufferAssignmentProto_BufferAlias::unsafe_arena_set_allocated_location( + ::xla::LogicalBufferProto_Location* location) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.location_); + } + _impl_.location_ = location; + if (location) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.BufferAssignmentProto.BufferAlias.location) +} +inline ::xla::LogicalBufferProto_Location* BufferAssignmentProto_BufferAlias::release_location() { + + ::xla::LogicalBufferProto_Location* temp = _impl_.location_; + _impl_.location_ = 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::LogicalBufferProto_Location* BufferAssignmentProto_BufferAlias::unsafe_arena_release_location() { + // @@protoc_insertion_point(field_release:xla.BufferAssignmentProto.BufferAlias.location) + + ::xla::LogicalBufferProto_Location* temp = _impl_.location_; + _impl_.location_ = nullptr; + return temp; +} +inline ::xla::LogicalBufferProto_Location* BufferAssignmentProto_BufferAlias::_internal_mutable_location() { + + if (_impl_.location_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::LogicalBufferProto_Location>(GetArenaForAllocation()); + _impl_.location_ = p; + } + return _impl_.location_; +} +inline ::xla::LogicalBufferProto_Location* BufferAssignmentProto_BufferAlias::mutable_location() { + ::xla::LogicalBufferProto_Location* _msg = _internal_mutable_location(); + // @@protoc_insertion_point(field_mutable:xla.BufferAssignmentProto.BufferAlias.location) + return _msg; +} +inline void BufferAssignmentProto_BufferAlias::set_allocated_location(::xla::LogicalBufferProto_Location* location) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.location_; + } + if (location) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(location); + if (message_arena != submessage_arena) { + location = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, location, submessage_arena); + } + + } else { + + } + _impl_.location_ = location; + // @@protoc_insertion_point(field_set_allocated:xla.BufferAssignmentProto.BufferAlias.location) +} + +// ------------------------------------------------------------------- + +// BufferAssignmentProto + +// repeated .xla.LogicalBufferProto logical_buffers = 1; +inline int BufferAssignmentProto::_internal_logical_buffers_size() const { + return _impl_.logical_buffers_.size(); +} +inline int BufferAssignmentProto::logical_buffers_size() const { + return _internal_logical_buffers_size(); +} +inline void BufferAssignmentProto::clear_logical_buffers() { + _impl_.logical_buffers_.Clear(); +} +inline ::xla::LogicalBufferProto* BufferAssignmentProto::mutable_logical_buffers(int index) { + // @@protoc_insertion_point(field_mutable:xla.BufferAssignmentProto.logical_buffers) + return _impl_.logical_buffers_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LogicalBufferProto >* +BufferAssignmentProto::mutable_logical_buffers() { + // @@protoc_insertion_point(field_mutable_list:xla.BufferAssignmentProto.logical_buffers) + return &_impl_.logical_buffers_; +} +inline const ::xla::LogicalBufferProto& BufferAssignmentProto::_internal_logical_buffers(int index) const { + return _impl_.logical_buffers_.Get(index); +} +inline const ::xla::LogicalBufferProto& BufferAssignmentProto::logical_buffers(int index) const { + // @@protoc_insertion_point(field_get:xla.BufferAssignmentProto.logical_buffers) + return _internal_logical_buffers(index); +} +inline ::xla::LogicalBufferProto* BufferAssignmentProto::_internal_add_logical_buffers() { + return _impl_.logical_buffers_.Add(); +} +inline ::xla::LogicalBufferProto* BufferAssignmentProto::add_logical_buffers() { + ::xla::LogicalBufferProto* _add = _internal_add_logical_buffers(); + // @@protoc_insertion_point(field_add:xla.BufferAssignmentProto.logical_buffers) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LogicalBufferProto >& +BufferAssignmentProto::logical_buffers() const { + // @@protoc_insertion_point(field_list:xla.BufferAssignmentProto.logical_buffers) + return _impl_.logical_buffers_; +} + +// repeated .xla.BufferAssignmentProto.BufferAlias buffer_aliases = 2; +inline int BufferAssignmentProto::_internal_buffer_aliases_size() const { + return _impl_.buffer_aliases_.size(); +} +inline int BufferAssignmentProto::buffer_aliases_size() const { + return _internal_buffer_aliases_size(); +} +inline void BufferAssignmentProto::clear_buffer_aliases() { + _impl_.buffer_aliases_.Clear(); +} +inline ::xla::BufferAssignmentProto_BufferAlias* BufferAssignmentProto::mutable_buffer_aliases(int index) { + // @@protoc_insertion_point(field_mutable:xla.BufferAssignmentProto.buffer_aliases) + return _impl_.buffer_aliases_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAssignmentProto_BufferAlias >* +BufferAssignmentProto::mutable_buffer_aliases() { + // @@protoc_insertion_point(field_mutable_list:xla.BufferAssignmentProto.buffer_aliases) + return &_impl_.buffer_aliases_; +} +inline const ::xla::BufferAssignmentProto_BufferAlias& BufferAssignmentProto::_internal_buffer_aliases(int index) const { + return _impl_.buffer_aliases_.Get(index); +} +inline const ::xla::BufferAssignmentProto_BufferAlias& BufferAssignmentProto::buffer_aliases(int index) const { + // @@protoc_insertion_point(field_get:xla.BufferAssignmentProto.buffer_aliases) + return _internal_buffer_aliases(index); +} +inline ::xla::BufferAssignmentProto_BufferAlias* BufferAssignmentProto::_internal_add_buffer_aliases() { + return _impl_.buffer_aliases_.Add(); +} +inline ::xla::BufferAssignmentProto_BufferAlias* BufferAssignmentProto::add_buffer_aliases() { + ::xla::BufferAssignmentProto_BufferAlias* _add = _internal_add_buffer_aliases(); + // @@protoc_insertion_point(field_add:xla.BufferAssignmentProto.buffer_aliases) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAssignmentProto_BufferAlias >& +BufferAssignmentProto::buffer_aliases() const { + // @@protoc_insertion_point(field_list:xla.BufferAssignmentProto.buffer_aliases) + return _impl_.buffer_aliases_; +} + +// repeated .xla.BufferAllocationProto buffer_allocations = 3; +inline int BufferAssignmentProto::_internal_buffer_allocations_size() const { + return _impl_.buffer_allocations_.size(); +} +inline int BufferAssignmentProto::buffer_allocations_size() const { + return _internal_buffer_allocations_size(); +} +inline void BufferAssignmentProto::clear_buffer_allocations() { + _impl_.buffer_allocations_.Clear(); +} +inline ::xla::BufferAllocationProto* BufferAssignmentProto::mutable_buffer_allocations(int index) { + // @@protoc_insertion_point(field_mutable:xla.BufferAssignmentProto.buffer_allocations) + return _impl_.buffer_allocations_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto >* +BufferAssignmentProto::mutable_buffer_allocations() { + // @@protoc_insertion_point(field_mutable_list:xla.BufferAssignmentProto.buffer_allocations) + return &_impl_.buffer_allocations_; +} +inline const ::xla::BufferAllocationProto& BufferAssignmentProto::_internal_buffer_allocations(int index) const { + return _impl_.buffer_allocations_.Get(index); +} +inline const ::xla::BufferAllocationProto& BufferAssignmentProto::buffer_allocations(int index) const { + // @@protoc_insertion_point(field_get:xla.BufferAssignmentProto.buffer_allocations) + return _internal_buffer_allocations(index); +} +inline ::xla::BufferAllocationProto* BufferAssignmentProto::_internal_add_buffer_allocations() { + return _impl_.buffer_allocations_.Add(); +} +inline ::xla::BufferAllocationProto* BufferAssignmentProto::add_buffer_allocations() { + ::xla::BufferAllocationProto* _add = _internal_add_buffer_allocations(); + // @@protoc_insertion_point(field_add:xla.BufferAssignmentProto.buffer_allocations) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::BufferAllocationProto >& +BufferAssignmentProto::buffer_allocations() const { + // @@protoc_insertion_point(field_list:xla.BufferAssignmentProto.buffer_allocations) + return _impl_.buffer_allocations_; +} + +// repeated .xla.HeapSimulatorTrace heap_simulator_traces = 4; +inline int BufferAssignmentProto::_internal_heap_simulator_traces_size() const { + return _impl_.heap_simulator_traces_.size(); +} +inline int BufferAssignmentProto::heap_simulator_traces_size() const { + return _internal_heap_simulator_traces_size(); +} +inline void BufferAssignmentProto::clear_heap_simulator_traces() { + _impl_.heap_simulator_traces_.Clear(); +} +inline ::xla::HeapSimulatorTrace* BufferAssignmentProto::mutable_heap_simulator_traces(int index) { + // @@protoc_insertion_point(field_mutable:xla.BufferAssignmentProto.heap_simulator_traces) + return _impl_.heap_simulator_traces_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace >* +BufferAssignmentProto::mutable_heap_simulator_traces() { + // @@protoc_insertion_point(field_mutable_list:xla.BufferAssignmentProto.heap_simulator_traces) + return &_impl_.heap_simulator_traces_; +} +inline const ::xla::HeapSimulatorTrace& BufferAssignmentProto::_internal_heap_simulator_traces(int index) const { + return _impl_.heap_simulator_traces_.Get(index); +} +inline const ::xla::HeapSimulatorTrace& BufferAssignmentProto::heap_simulator_traces(int index) const { + // @@protoc_insertion_point(field_get:xla.BufferAssignmentProto.heap_simulator_traces) + return _internal_heap_simulator_traces(index); +} +inline ::xla::HeapSimulatorTrace* BufferAssignmentProto::_internal_add_heap_simulator_traces() { + return _impl_.heap_simulator_traces_.Add(); +} +inline ::xla::HeapSimulatorTrace* BufferAssignmentProto::add_heap_simulator_traces() { + ::xla::HeapSimulatorTrace* _add = _internal_add_heap_simulator_traces(); + // @@protoc_insertion_point(field_add:xla.BufferAssignmentProto.heap_simulator_traces) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HeapSimulatorTrace >& +BufferAssignmentProto::heap_simulator_traces() const { + // @@protoc_insertion_point(field_list:xla.BufferAssignmentProto.heap_simulator_traces) + return _impl_.heap_simulator_traces_; +} + +// ------------------------------------------------------------------- + +// HloProto + +// .xla.HloModuleProto hlo_module = 1; +inline bool HloProto::_internal_has_hlo_module() const { + return this != internal_default_instance() && _impl_.hlo_module_ != nullptr; +} +inline bool HloProto::has_hlo_module() const { + return _internal_has_hlo_module(); +} +inline void HloProto::clear_hlo_module() { + if (GetArenaForAllocation() == nullptr && _impl_.hlo_module_ != nullptr) { + delete _impl_.hlo_module_; + } + _impl_.hlo_module_ = nullptr; +} +inline const ::xla::HloModuleProto& HloProto::_internal_hlo_module() const { + const ::xla::HloModuleProto* p = _impl_.hlo_module_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloModuleProto_default_instance_); +} +inline const ::xla::HloModuleProto& HloProto::hlo_module() const { + // @@protoc_insertion_point(field_get:xla.HloProto.hlo_module) + return _internal_hlo_module(); +} +inline void HloProto::unsafe_arena_set_allocated_hlo_module( + ::xla::HloModuleProto* hlo_module) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.hlo_module_); + } + _impl_.hlo_module_ = hlo_module; + if (hlo_module) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloProto.hlo_module) +} +inline ::xla::HloModuleProto* HloProto::release_hlo_module() { + + ::xla::HloModuleProto* temp = _impl_.hlo_module_; + _impl_.hlo_module_ = 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::HloModuleProto* HloProto::unsafe_arena_release_hlo_module() { + // @@protoc_insertion_point(field_release:xla.HloProto.hlo_module) + + ::xla::HloModuleProto* temp = _impl_.hlo_module_; + _impl_.hlo_module_ = nullptr; + return temp; +} +inline ::xla::HloModuleProto* HloProto::_internal_mutable_hlo_module() { + + if (_impl_.hlo_module_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloModuleProto>(GetArenaForAllocation()); + _impl_.hlo_module_ = p; + } + return _impl_.hlo_module_; +} +inline ::xla::HloModuleProto* HloProto::mutable_hlo_module() { + ::xla::HloModuleProto* _msg = _internal_mutable_hlo_module(); + // @@protoc_insertion_point(field_mutable:xla.HloProto.hlo_module) + return _msg; +} +inline void HloProto::set_allocated_hlo_module(::xla::HloModuleProto* hlo_module) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.hlo_module_; + } + if (hlo_module) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(hlo_module); + if (message_arena != submessage_arena) { + hlo_module = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, hlo_module, submessage_arena); + } + + } else { + + } + _impl_.hlo_module_ = hlo_module; + // @@protoc_insertion_point(field_set_allocated:xla.HloProto.hlo_module) +} + +// .xla.BufferAssignmentProto buffer_assignment = 3; +inline bool HloProto::_internal_has_buffer_assignment() const { + return this != internal_default_instance() && _impl_.buffer_assignment_ != nullptr; +} +inline bool HloProto::has_buffer_assignment() const { + return _internal_has_buffer_assignment(); +} +inline void HloProto::clear_buffer_assignment() { + if (GetArenaForAllocation() == nullptr && _impl_.buffer_assignment_ != nullptr) { + delete _impl_.buffer_assignment_; + } + _impl_.buffer_assignment_ = nullptr; +} +inline const ::xla::BufferAssignmentProto& HloProto::_internal_buffer_assignment() const { + const ::xla::BufferAssignmentProto* p = _impl_.buffer_assignment_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_BufferAssignmentProto_default_instance_); +} +inline const ::xla::BufferAssignmentProto& HloProto::buffer_assignment() const { + // @@protoc_insertion_point(field_get:xla.HloProto.buffer_assignment) + return _internal_buffer_assignment(); +} +inline void HloProto::unsafe_arena_set_allocated_buffer_assignment( + ::xla::BufferAssignmentProto* buffer_assignment) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.buffer_assignment_); + } + _impl_.buffer_assignment_ = buffer_assignment; + if (buffer_assignment) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloProto.buffer_assignment) +} +inline ::xla::BufferAssignmentProto* HloProto::release_buffer_assignment() { + + ::xla::BufferAssignmentProto* temp = _impl_.buffer_assignment_; + _impl_.buffer_assignment_ = 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::BufferAssignmentProto* HloProto::unsafe_arena_release_buffer_assignment() { + // @@protoc_insertion_point(field_release:xla.HloProto.buffer_assignment) + + ::xla::BufferAssignmentProto* temp = _impl_.buffer_assignment_; + _impl_.buffer_assignment_ = nullptr; + return temp; +} +inline ::xla::BufferAssignmentProto* HloProto::_internal_mutable_buffer_assignment() { + + if (_impl_.buffer_assignment_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::BufferAssignmentProto>(GetArenaForAllocation()); + _impl_.buffer_assignment_ = p; + } + return _impl_.buffer_assignment_; +} +inline ::xla::BufferAssignmentProto* HloProto::mutable_buffer_assignment() { + ::xla::BufferAssignmentProto* _msg = _internal_mutable_buffer_assignment(); + // @@protoc_insertion_point(field_mutable:xla.HloProto.buffer_assignment) + return _msg; +} +inline void HloProto::set_allocated_buffer_assignment(::xla::BufferAssignmentProto* buffer_assignment) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.buffer_assignment_; + } + if (buffer_assignment) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(buffer_assignment); + if (message_arena != submessage_arena) { + buffer_assignment = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, buffer_assignment, submessage_arena); + } + + } else { + + } + _impl_.buffer_assignment_ = buffer_assignment; + // @@protoc_insertion_point(field_set_allocated:xla.HloProto.buffer_assignment) +} + +// ------------------------------------------------------------------- + +// HloSnapshot + +// .xla.HloProto hlo = 1; +inline bool HloSnapshot::_internal_has_hlo() const { + return this != internal_default_instance() && _impl_.hlo_ != nullptr; +} +inline bool HloSnapshot::has_hlo() const { + return _internal_has_hlo(); +} +inline void HloSnapshot::clear_hlo() { + if (GetArenaForAllocation() == nullptr && _impl_.hlo_ != nullptr) { + delete _impl_.hlo_; + } + _impl_.hlo_ = nullptr; +} +inline const ::xla::HloProto& HloSnapshot::_internal_hlo() const { + const ::xla::HloProto* p = _impl_.hlo_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloProto_default_instance_); +} +inline const ::xla::HloProto& HloSnapshot::hlo() const { + // @@protoc_insertion_point(field_get:xla.HloSnapshot.hlo) + return _internal_hlo(); +} +inline void HloSnapshot::unsafe_arena_set_allocated_hlo( + ::xla::HloProto* hlo) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.hlo_); + } + _impl_.hlo_ = hlo; + if (hlo) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloSnapshot.hlo) +} +inline ::xla::HloProto* HloSnapshot::release_hlo() { + + ::xla::HloProto* temp = _impl_.hlo_; + _impl_.hlo_ = 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::HloProto* HloSnapshot::unsafe_arena_release_hlo() { + // @@protoc_insertion_point(field_release:xla.HloSnapshot.hlo) + + ::xla::HloProto* temp = _impl_.hlo_; + _impl_.hlo_ = nullptr; + return temp; +} +inline ::xla::HloProto* HloSnapshot::_internal_mutable_hlo() { + + if (_impl_.hlo_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloProto>(GetArenaForAllocation()); + _impl_.hlo_ = p; + } + return _impl_.hlo_; +} +inline ::xla::HloProto* HloSnapshot::mutable_hlo() { + ::xla::HloProto* _msg = _internal_mutable_hlo(); + // @@protoc_insertion_point(field_mutable:xla.HloSnapshot.hlo) + return _msg; +} +inline void HloSnapshot::set_allocated_hlo(::xla::HloProto* hlo) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.hlo_; + } + if (hlo) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(hlo); + if (message_arena != submessage_arena) { + hlo = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, hlo, submessage_arena); + } + + } else { + + } + _impl_.hlo_ = hlo; + // @@protoc_insertion_point(field_set_allocated:xla.HloSnapshot.hlo) +} + +// repeated .xla.LiteralProto arguments = 2; +inline int HloSnapshot::_internal_arguments_size() const { + return _impl_.arguments_.size(); +} +inline int HloSnapshot::arguments_size() const { + return _internal_arguments_size(); +} +inline ::xla::LiteralProto* HloSnapshot::mutable_arguments(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloSnapshot.arguments) + return _impl_.arguments_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LiteralProto >* +HloSnapshot::mutable_arguments() { + // @@protoc_insertion_point(field_mutable_list:xla.HloSnapshot.arguments) + return &_impl_.arguments_; +} +inline const ::xla::LiteralProto& HloSnapshot::_internal_arguments(int index) const { + return _impl_.arguments_.Get(index); +} +inline const ::xla::LiteralProto& HloSnapshot::arguments(int index) const { + // @@protoc_insertion_point(field_get:xla.HloSnapshot.arguments) + return _internal_arguments(index); +} +inline ::xla::LiteralProto* HloSnapshot::_internal_add_arguments() { + return _impl_.arguments_.Add(); +} +inline ::xla::LiteralProto* HloSnapshot::add_arguments() { + ::xla::LiteralProto* _add = _internal_add_arguments(); + // @@protoc_insertion_point(field_add:xla.HloSnapshot.arguments) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::LiteralProto >& +HloSnapshot::arguments() const { + // @@protoc_insertion_point(field_list:xla.HloSnapshot.arguments) + return _impl_.arguments_; +} + +// .xla.LiteralProto result = 3; +inline bool HloSnapshot::_internal_has_result() const { + return this != internal_default_instance() && _impl_.result_ != nullptr; +} +inline bool HloSnapshot::has_result() const { + return _internal_has_result(); +} +inline const ::xla::LiteralProto& HloSnapshot::_internal_result() const { + const ::xla::LiteralProto* p = _impl_.result_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_LiteralProto_default_instance_); +} +inline const ::xla::LiteralProto& HloSnapshot::result() const { + // @@protoc_insertion_point(field_get:xla.HloSnapshot.result) + return _internal_result(); +} +inline void HloSnapshot::unsafe_arena_set_allocated_result( + ::xla::LiteralProto* 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.HloSnapshot.result) +} +inline ::xla::LiteralProto* HloSnapshot::release_result() { + + ::xla::LiteralProto* 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::LiteralProto* HloSnapshot::unsafe_arena_release_result() { + // @@protoc_insertion_point(field_release:xla.HloSnapshot.result) + + ::xla::LiteralProto* temp = _impl_.result_; + _impl_.result_ = nullptr; + return temp; +} +inline ::xla::LiteralProto* HloSnapshot::_internal_mutable_result() { + + if (_impl_.result_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::LiteralProto>(GetArenaForAllocation()); + _impl_.result_ = p; + } + return _impl_.result_; +} +inline ::xla::LiteralProto* HloSnapshot::mutable_result() { + ::xla::LiteralProto* _msg = _internal_mutable_result(); + // @@protoc_insertion_point(field_mutable:xla.HloSnapshot.result) + return _msg; +} +inline void HloSnapshot::set_allocated_result(::xla::LiteralProto* 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.HloSnapshot.result) +} + +// string execution_platform = 4; +inline void HloSnapshot::clear_execution_platform() { + _impl_.execution_platform_.ClearToEmpty(); +} +inline const std::string& HloSnapshot::execution_platform() const { + // @@protoc_insertion_point(field_get:xla.HloSnapshot.execution_platform) + return _internal_execution_platform(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloSnapshot::set_execution_platform(ArgT0&& arg0, ArgT... args) { + + _impl_.execution_platform_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloSnapshot.execution_platform) +} +inline std::string* HloSnapshot::mutable_execution_platform() { + std::string* _s = _internal_mutable_execution_platform(); + // @@protoc_insertion_point(field_mutable:xla.HloSnapshot.execution_platform) + return _s; +} +inline const std::string& HloSnapshot::_internal_execution_platform() const { + return _impl_.execution_platform_.Get(); +} +inline void HloSnapshot::_internal_set_execution_platform(const std::string& value) { + + _impl_.execution_platform_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloSnapshot::_internal_mutable_execution_platform() { + + return _impl_.execution_platform_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloSnapshot::release_execution_platform() { + // @@protoc_insertion_point(field_release:xla.HloSnapshot.execution_platform) + return _impl_.execution_platform_.Release(); +} +inline void HloSnapshot::set_allocated_execution_platform(std::string* execution_platform) { + if (execution_platform != nullptr) { + + } else { + + } + _impl_.execution_platform_.SetAllocated(execution_platform, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.execution_platform_.IsDefault()) { + _impl_.execution_platform_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloSnapshot.execution_platform) +} + +// ------------------------------------------------------------------- + +// HloModuleMetadataProto + +// int64 canonical_module_id = 1; +inline void HloModuleMetadataProto::clear_canonical_module_id() { + _impl_.canonical_module_id_ = int64_t{0}; +} +inline int64_t HloModuleMetadataProto::_internal_canonical_module_id() const { + return _impl_.canonical_module_id_; +} +inline int64_t HloModuleMetadataProto::canonical_module_id() const { + // @@protoc_insertion_point(field_get:xla.HloModuleMetadataProto.canonical_module_id) + return _internal_canonical_module_id(); +} +inline void HloModuleMetadataProto::_internal_set_canonical_module_id(int64_t value) { + + _impl_.canonical_module_id_ = value; +} +inline void HloModuleMetadataProto::set_canonical_module_id(int64_t value) { + _internal_set_canonical_module_id(value); + // @@protoc_insertion_point(field_set:xla.HloModuleMetadataProto.canonical_module_id) +} + +// string module_group_name = 2; +inline void HloModuleMetadataProto::clear_module_group_name() { + _impl_.module_group_name_.ClearToEmpty(); +} +inline const std::string& HloModuleMetadataProto::module_group_name() const { + // @@protoc_insertion_point(field_get:xla.HloModuleMetadataProto.module_group_name) + return _internal_module_group_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloModuleMetadataProto::set_module_group_name(ArgT0&& arg0, ArgT... args) { + + _impl_.module_group_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloModuleMetadataProto.module_group_name) +} +inline std::string* HloModuleMetadataProto::mutable_module_group_name() { + std::string* _s = _internal_mutable_module_group_name(); + // @@protoc_insertion_point(field_mutable:xla.HloModuleMetadataProto.module_group_name) + return _s; +} +inline const std::string& HloModuleMetadataProto::_internal_module_group_name() const { + return _impl_.module_group_name_.Get(); +} +inline void HloModuleMetadataProto::_internal_set_module_group_name(const std::string& value) { + + _impl_.module_group_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloModuleMetadataProto::_internal_mutable_module_group_name() { + + return _impl_.module_group_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloModuleMetadataProto::release_module_group_name() { + // @@protoc_insertion_point(field_release:xla.HloModuleMetadataProto.module_group_name) + return _impl_.module_group_name_.Release(); +} +inline void HloModuleMetadataProto::set_allocated_module_group_name(std::string* module_group_name) { + if (module_group_name != nullptr) { + + } else { + + } + _impl_.module_group_name_.SetAllocated(module_group_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.module_group_name_.IsDefault()) { + _impl_.module_group_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloModuleMetadataProto.module_group_name) +} + +// int64 original_module_id = 3; +inline void HloModuleMetadataProto::clear_original_module_id() { + _impl_.original_module_id_ = int64_t{0}; +} +inline int64_t HloModuleMetadataProto::_internal_original_module_id() const { + return _impl_.original_module_id_; +} +inline int64_t HloModuleMetadataProto::original_module_id() const { + // @@protoc_insertion_point(field_get:xla.HloModuleMetadataProto.original_module_id) + return _internal_original_module_id(); +} +inline void HloModuleMetadataProto::_internal_set_original_module_id(int64_t value) { + + _impl_.original_module_id_ = value; +} +inline void HloModuleMetadataProto::set_original_module_id(int64_t value) { + _internal_set_original_module_id(value); + // @@protoc_insertion_point(field_set:xla.HloModuleMetadataProto.original_module_id) +} + +// repeated int64 partitioned_module_ids = 4; +inline int HloModuleMetadataProto::_internal_partitioned_module_ids_size() const { + return _impl_.partitioned_module_ids_.size(); +} +inline int HloModuleMetadataProto::partitioned_module_ids_size() const { + return _internal_partitioned_module_ids_size(); +} +inline void HloModuleMetadataProto::clear_partitioned_module_ids() { + _impl_.partitioned_module_ids_.Clear(); +} +inline int64_t HloModuleMetadataProto::_internal_partitioned_module_ids(int index) const { + return _impl_.partitioned_module_ids_.Get(index); +} +inline int64_t HloModuleMetadataProto::partitioned_module_ids(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleMetadataProto.partitioned_module_ids) + return _internal_partitioned_module_ids(index); +} +inline void HloModuleMetadataProto::set_partitioned_module_ids(int index, int64_t value) { + _impl_.partitioned_module_ids_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloModuleMetadataProto.partitioned_module_ids) +} +inline void HloModuleMetadataProto::_internal_add_partitioned_module_ids(int64_t value) { + _impl_.partitioned_module_ids_.Add(value); +} +inline void HloModuleMetadataProto::add_partitioned_module_ids(int64_t value) { + _internal_add_partitioned_module_ids(value); + // @@protoc_insertion_point(field_add:xla.HloModuleMetadataProto.partitioned_module_ids) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloModuleMetadataProto::_internal_partitioned_module_ids() const { + return _impl_.partitioned_module_ids_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloModuleMetadataProto::partitioned_module_ids() const { + // @@protoc_insertion_point(field_list:xla.HloModuleMetadataProto.partitioned_module_ids) + return _internal_partitioned_module_ids(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloModuleMetadataProto::_internal_mutable_partitioned_module_ids() { + return &_impl_.partitioned_module_ids_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloModuleMetadataProto::mutable_partitioned_module_ids() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleMetadataProto.partitioned_module_ids) + return _internal_mutable_partitioned_module_ids(); +} + +// repeated .xla.HloPassMetadata pass_metadata = 5; +inline int HloModuleMetadataProto::_internal_pass_metadata_size() const { + return _impl_.pass_metadata_.size(); +} +inline int HloModuleMetadataProto::pass_metadata_size() const { + return _internal_pass_metadata_size(); +} +inline void HloModuleMetadataProto::clear_pass_metadata() { + _impl_.pass_metadata_.Clear(); +} +inline ::xla::HloPassMetadata* HloModuleMetadataProto::mutable_pass_metadata(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloModuleMetadataProto.pass_metadata) + return _impl_.pass_metadata_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloPassMetadata >* +HloModuleMetadataProto::mutable_pass_metadata() { + // @@protoc_insertion_point(field_mutable_list:xla.HloModuleMetadataProto.pass_metadata) + return &_impl_.pass_metadata_; +} +inline const ::xla::HloPassMetadata& HloModuleMetadataProto::_internal_pass_metadata(int index) const { + return _impl_.pass_metadata_.Get(index); +} +inline const ::xla::HloPassMetadata& HloModuleMetadataProto::pass_metadata(int index) const { + // @@protoc_insertion_point(field_get:xla.HloModuleMetadataProto.pass_metadata) + return _internal_pass_metadata(index); +} +inline ::xla::HloPassMetadata* HloModuleMetadataProto::_internal_add_pass_metadata() { + return _impl_.pass_metadata_.Add(); +} +inline ::xla::HloPassMetadata* HloModuleMetadataProto::add_pass_metadata() { + ::xla::HloPassMetadata* _add = _internal_add_pass_metadata(); + // @@protoc_insertion_point(field_add:xla.HloModuleMetadataProto.pass_metadata) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloPassMetadata >& +HloModuleMetadataProto::pass_metadata() const { + // @@protoc_insertion_point(field_list:xla.HloModuleMetadataProto.pass_metadata) + return _impl_.pass_metadata_; +} + +// ------------------------------------------------------------------- + +// HloPassMetadata + +// int64 pass_id = 1; +inline void HloPassMetadata::clear_pass_id() { + _impl_.pass_id_ = int64_t{0}; +} +inline int64_t HloPassMetadata::_internal_pass_id() const { + return _impl_.pass_id_; +} +inline int64_t HloPassMetadata::pass_id() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.pass_id) + return _internal_pass_id(); +} +inline void HloPassMetadata::_internal_set_pass_id(int64_t value) { + + _impl_.pass_id_ = value; +} +inline void HloPassMetadata::set_pass_id(int64_t value) { + _internal_set_pass_id(value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.pass_id) +} + +// string pass_name = 2; +inline void HloPassMetadata::clear_pass_name() { + _impl_.pass_name_.ClearToEmpty(); +} +inline const std::string& HloPassMetadata::pass_name() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.pass_name) + return _internal_pass_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloPassMetadata::set_pass_name(ArgT0&& arg0, ArgT... args) { + + _impl_.pass_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.pass_name) +} +inline std::string* HloPassMetadata::mutable_pass_name() { + std::string* _s = _internal_mutable_pass_name(); + // @@protoc_insertion_point(field_mutable:xla.HloPassMetadata.pass_name) + return _s; +} +inline const std::string& HloPassMetadata::_internal_pass_name() const { + return _impl_.pass_name_.Get(); +} +inline void HloPassMetadata::_internal_set_pass_name(const std::string& value) { + + _impl_.pass_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloPassMetadata::_internal_mutable_pass_name() { + + return _impl_.pass_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloPassMetadata::release_pass_name() { + // @@protoc_insertion_point(field_release:xla.HloPassMetadata.pass_name) + return _impl_.pass_name_.Release(); +} +inline void HloPassMetadata::set_allocated_pass_name(std::string* pass_name) { + if (pass_name != nullptr) { + + } else { + + } + _impl_.pass_name_.SetAllocated(pass_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.pass_name_.IsDefault()) { + _impl_.pass_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloPassMetadata.pass_name) +} + +// string pipeline_name = 3; +inline void HloPassMetadata::clear_pipeline_name() { + _impl_.pipeline_name_.ClearToEmpty(); +} +inline const std::string& HloPassMetadata::pipeline_name() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.pipeline_name) + return _internal_pipeline_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloPassMetadata::set_pipeline_name(ArgT0&& arg0, ArgT... args) { + + _impl_.pipeline_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.pipeline_name) +} +inline std::string* HloPassMetadata::mutable_pipeline_name() { + std::string* _s = _internal_mutable_pipeline_name(); + // @@protoc_insertion_point(field_mutable:xla.HloPassMetadata.pipeline_name) + return _s; +} +inline const std::string& HloPassMetadata::_internal_pipeline_name() const { + return _impl_.pipeline_name_.Get(); +} +inline void HloPassMetadata::_internal_set_pipeline_name(const std::string& value) { + + _impl_.pipeline_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloPassMetadata::_internal_mutable_pipeline_name() { + + return _impl_.pipeline_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloPassMetadata::release_pipeline_name() { + // @@protoc_insertion_point(field_release:xla.HloPassMetadata.pipeline_name) + return _impl_.pipeline_name_.Release(); +} +inline void HloPassMetadata::set_allocated_pipeline_name(std::string* pipeline_name) { + if (pipeline_name != nullptr) { + + } else { + + } + _impl_.pipeline_name_.SetAllocated(pipeline_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.pipeline_name_.IsDefault()) { + _impl_.pipeline_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloPassMetadata.pipeline_name) +} + +// repeated string dump_filenames = 4; +inline int HloPassMetadata::_internal_dump_filenames_size() const { + return _impl_.dump_filenames_.size(); +} +inline int HloPassMetadata::dump_filenames_size() const { + return _internal_dump_filenames_size(); +} +inline void HloPassMetadata::clear_dump_filenames() { + _impl_.dump_filenames_.Clear(); +} +inline std::string* HloPassMetadata::add_dump_filenames() { + std::string* _s = _internal_add_dump_filenames(); + // @@protoc_insertion_point(field_add_mutable:xla.HloPassMetadata.dump_filenames) + return _s; +} +inline const std::string& HloPassMetadata::_internal_dump_filenames(int index) const { + return _impl_.dump_filenames_.Get(index); +} +inline const std::string& HloPassMetadata::dump_filenames(int index) const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.dump_filenames) + return _internal_dump_filenames(index); +} +inline std::string* HloPassMetadata::mutable_dump_filenames(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloPassMetadata.dump_filenames) + return _impl_.dump_filenames_.Mutable(index); +} +inline void HloPassMetadata::set_dump_filenames(int index, const std::string& value) { + _impl_.dump_filenames_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.dump_filenames) +} +inline void HloPassMetadata::set_dump_filenames(int index, std::string&& value) { + _impl_.dump_filenames_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.dump_filenames) +} +inline void HloPassMetadata::set_dump_filenames(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.dump_filenames_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:xla.HloPassMetadata.dump_filenames) +} +inline void HloPassMetadata::set_dump_filenames(int index, const char* value, size_t size) { + _impl_.dump_filenames_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:xla.HloPassMetadata.dump_filenames) +} +inline std::string* HloPassMetadata::_internal_add_dump_filenames() { + return _impl_.dump_filenames_.Add(); +} +inline void HloPassMetadata::add_dump_filenames(const std::string& value) { + _impl_.dump_filenames_.Add()->assign(value); + // @@protoc_insertion_point(field_add:xla.HloPassMetadata.dump_filenames) +} +inline void HloPassMetadata::add_dump_filenames(std::string&& value) { + _impl_.dump_filenames_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:xla.HloPassMetadata.dump_filenames) +} +inline void HloPassMetadata::add_dump_filenames(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.dump_filenames_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:xla.HloPassMetadata.dump_filenames) +} +inline void HloPassMetadata::add_dump_filenames(const char* value, size_t size) { + _impl_.dump_filenames_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:xla.HloPassMetadata.dump_filenames) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +HloPassMetadata::dump_filenames() const { + // @@protoc_insertion_point(field_list:xla.HloPassMetadata.dump_filenames) + return _impl_.dump_filenames_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +HloPassMetadata::mutable_dump_filenames() { + // @@protoc_insertion_point(field_mutable_list:xla.HloPassMetadata.dump_filenames) + return &_impl_.dump_filenames_; +} + +// bool module_changed = 5; +inline void HloPassMetadata::clear_module_changed() { + _impl_.module_changed_ = false; +} +inline bool HloPassMetadata::_internal_module_changed() const { + return _impl_.module_changed_; +} +inline bool HloPassMetadata::module_changed() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.module_changed) + return _internal_module_changed(); +} +inline void HloPassMetadata::_internal_set_module_changed(bool value) { + + _impl_.module_changed_ = value; +} +inline void HloPassMetadata::set_module_changed(bool value) { + _internal_set_module_changed(value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.module_changed) +} + +// int64 module_id = 6; +inline void HloPassMetadata::clear_module_id() { + _impl_.module_id_ = int64_t{0}; +} +inline int64_t HloPassMetadata::_internal_module_id() const { + return _impl_.module_id_; +} +inline int64_t HloPassMetadata::module_id() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.module_id) + return _internal_module_id(); +} +inline void HloPassMetadata::_internal_set_module_id(int64_t value) { + + _impl_.module_id_ = value; +} +inline void HloPassMetadata::set_module_id(int64_t value) { + _internal_set_module_id(value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.module_id) +} + +// repeated int64 module_group_module_ids = 7; +inline int HloPassMetadata::_internal_module_group_module_ids_size() const { + return _impl_.module_group_module_ids_.size(); +} +inline int HloPassMetadata::module_group_module_ids_size() const { + return _internal_module_group_module_ids_size(); +} +inline void HloPassMetadata::clear_module_group_module_ids() { + _impl_.module_group_module_ids_.Clear(); +} +inline int64_t HloPassMetadata::_internal_module_group_module_ids(int index) const { + return _impl_.module_group_module_ids_.Get(index); +} +inline int64_t HloPassMetadata::module_group_module_ids(int index) const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.module_group_module_ids) + return _internal_module_group_module_ids(index); +} +inline void HloPassMetadata::set_module_group_module_ids(int index, int64_t value) { + _impl_.module_group_module_ids_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.module_group_module_ids) +} +inline void HloPassMetadata::_internal_add_module_group_module_ids(int64_t value) { + _impl_.module_group_module_ids_.Add(value); +} +inline void HloPassMetadata::add_module_group_module_ids(int64_t value) { + _internal_add_module_group_module_ids(value); + // @@protoc_insertion_point(field_add:xla.HloPassMetadata.module_group_module_ids) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloPassMetadata::_internal_module_group_module_ids() const { + return _impl_.module_group_module_ids_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloPassMetadata::module_group_module_ids() const { + // @@protoc_insertion_point(field_list:xla.HloPassMetadata.module_group_module_ids) + return _internal_module_group_module_ids(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloPassMetadata::_internal_mutable_module_group_module_ids() { + return &_impl_.module_group_module_ids_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloPassMetadata::mutable_module_group_module_ids() { + // @@protoc_insertion_point(field_mutable_list:xla.HloPassMetadata.module_group_module_ids) + return _internal_mutable_module_group_module_ids(); +} + +// int64 start_timestamp_usec = 8; +inline void HloPassMetadata::clear_start_timestamp_usec() { + _impl_.start_timestamp_usec_ = int64_t{0}; +} +inline int64_t HloPassMetadata::_internal_start_timestamp_usec() const { + return _impl_.start_timestamp_usec_; +} +inline int64_t HloPassMetadata::start_timestamp_usec() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.start_timestamp_usec) + return _internal_start_timestamp_usec(); +} +inline void HloPassMetadata::_internal_set_start_timestamp_usec(int64_t value) { + + _impl_.start_timestamp_usec_ = value; +} +inline void HloPassMetadata::set_start_timestamp_usec(int64_t value) { + _internal_set_start_timestamp_usec(value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.start_timestamp_usec) +} + +// int64 end_timestamp_usec = 9; +inline void HloPassMetadata::clear_end_timestamp_usec() { + _impl_.end_timestamp_usec_ = int64_t{0}; +} +inline int64_t HloPassMetadata::_internal_end_timestamp_usec() const { + return _impl_.end_timestamp_usec_; +} +inline int64_t HloPassMetadata::end_timestamp_usec() const { + // @@protoc_insertion_point(field_get:xla.HloPassMetadata.end_timestamp_usec) + return _internal_end_timestamp_usec(); +} +inline void HloPassMetadata::_internal_set_end_timestamp_usec(int64_t value) { + + _impl_.end_timestamp_usec_ = value; +} +inline void HloPassMetadata::set_end_timestamp_usec(int64_t value) { + _internal_set_end_timestamp_usec(value); + // @@protoc_insertion_point(field_set:xla.HloPassMetadata.end_timestamp_usec) +} + +// ------------------------------------------------------------------- + +// EntryFunctionAttributes_ShapeIndex + +// repeated int64 indices = 1; +inline int EntryFunctionAttributes_ShapeIndex::_internal_indices_size() const { + return _impl_.indices_.size(); +} +inline int EntryFunctionAttributes_ShapeIndex::indices_size() const { + return _internal_indices_size(); +} +inline void EntryFunctionAttributes_ShapeIndex::clear_indices() { + _impl_.indices_.Clear(); +} +inline int64_t EntryFunctionAttributes_ShapeIndex::_internal_indices(int index) const { + return _impl_.indices_.Get(index); +} +inline int64_t EntryFunctionAttributes_ShapeIndex::indices(int index) const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.ShapeIndex.indices) + return _internal_indices(index); +} +inline void EntryFunctionAttributes_ShapeIndex::set_indices(int index, int64_t value) { + _impl_.indices_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.EntryFunctionAttributes.ShapeIndex.indices) +} +inline void EntryFunctionAttributes_ShapeIndex::_internal_add_indices(int64_t value) { + _impl_.indices_.Add(value); +} +inline void EntryFunctionAttributes_ShapeIndex::add_indices(int64_t value) { + _internal_add_indices(value); + // @@protoc_insertion_point(field_add:xla.EntryFunctionAttributes.ShapeIndex.indices) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +EntryFunctionAttributes_ShapeIndex::_internal_indices() const { + return _impl_.indices_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +EntryFunctionAttributes_ShapeIndex::indices() const { + // @@protoc_insertion_point(field_list:xla.EntryFunctionAttributes.ShapeIndex.indices) + return _internal_indices(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +EntryFunctionAttributes_ShapeIndex::_internal_mutable_indices() { + return &_impl_.indices_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +EntryFunctionAttributes_ShapeIndex::mutable_indices() { + // @@protoc_insertion_point(field_mutable_list:xla.EntryFunctionAttributes.ShapeIndex.indices) + return _internal_mutable_indices(); +} + +// ------------------------------------------------------------------- + +// EntryFunctionAttributes_BufferParameterAttributes + +// int64 lmhlo_params = 1; +inline void EntryFunctionAttributes_BufferParameterAttributes::clear_lmhlo_params() { + _impl_.lmhlo_params_ = int64_t{0}; +} +inline int64_t EntryFunctionAttributes_BufferParameterAttributes::_internal_lmhlo_params() const { + return _impl_.lmhlo_params_; +} +inline int64_t EntryFunctionAttributes_BufferParameterAttributes::lmhlo_params() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_params) + return _internal_lmhlo_params(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::_internal_set_lmhlo_params(int64_t value) { + + _impl_.lmhlo_params_ = value; +} +inline void EntryFunctionAttributes_BufferParameterAttributes::set_lmhlo_params(int64_t value) { + _internal_set_lmhlo_params(value); + // @@protoc_insertion_point(field_set:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_params) +} + +// bool lmhlo_params_present = 6; +inline void EntryFunctionAttributes_BufferParameterAttributes::clear_lmhlo_params_present() { + _impl_.lmhlo_params_present_ = false; +} +inline bool EntryFunctionAttributes_BufferParameterAttributes::_internal_lmhlo_params_present() const { + return _impl_.lmhlo_params_present_; +} +inline bool EntryFunctionAttributes_BufferParameterAttributes::lmhlo_params_present() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_params_present) + return _internal_lmhlo_params_present(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::_internal_set_lmhlo_params_present(bool value) { + + _impl_.lmhlo_params_present_ = value; +} +inline void EntryFunctionAttributes_BufferParameterAttributes::set_lmhlo_params_present(bool value) { + _internal_set_lmhlo_params_present(value); + // @@protoc_insertion_point(field_set:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_params_present) +} + +// .xla.EntryFunctionAttributes.ShapeIndex lmhlo_param_shape_index = 2; +inline bool EntryFunctionAttributes_BufferParameterAttributes::_internal_has_lmhlo_param_shape_index() const { + return this != internal_default_instance() && _impl_.lmhlo_param_shape_index_ != nullptr; +} +inline bool EntryFunctionAttributes_BufferParameterAttributes::has_lmhlo_param_shape_index() const { + return _internal_has_lmhlo_param_shape_index(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::clear_lmhlo_param_shape_index() { + if (GetArenaForAllocation() == nullptr && _impl_.lmhlo_param_shape_index_ != nullptr) { + delete _impl_.lmhlo_param_shape_index_; + } + _impl_.lmhlo_param_shape_index_ = nullptr; +} +inline const ::xla::EntryFunctionAttributes_ShapeIndex& EntryFunctionAttributes_BufferParameterAttributes::_internal_lmhlo_param_shape_index() const { + const ::xla::EntryFunctionAttributes_ShapeIndex* p = _impl_.lmhlo_param_shape_index_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_EntryFunctionAttributes_ShapeIndex_default_instance_); +} +inline const ::xla::EntryFunctionAttributes_ShapeIndex& EntryFunctionAttributes_BufferParameterAttributes::lmhlo_param_shape_index() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_param_shape_index) + return _internal_lmhlo_param_shape_index(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::unsafe_arena_set_allocated_lmhlo_param_shape_index( + ::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_param_shape_index) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.lmhlo_param_shape_index_); + } + _impl_.lmhlo_param_shape_index_ = lmhlo_param_shape_index; + if (lmhlo_param_shape_index) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_param_shape_index) +} +inline ::xla::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::release_lmhlo_param_shape_index() { + + ::xla::EntryFunctionAttributes_ShapeIndex* temp = _impl_.lmhlo_param_shape_index_; + _impl_.lmhlo_param_shape_index_ = 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::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::unsafe_arena_release_lmhlo_param_shape_index() { + // @@protoc_insertion_point(field_release:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_param_shape_index) + + ::xla::EntryFunctionAttributes_ShapeIndex* temp = _impl_.lmhlo_param_shape_index_; + _impl_.lmhlo_param_shape_index_ = nullptr; + return temp; +} +inline ::xla::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::_internal_mutable_lmhlo_param_shape_index() { + + if (_impl_.lmhlo_param_shape_index_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::EntryFunctionAttributes_ShapeIndex>(GetArenaForAllocation()); + _impl_.lmhlo_param_shape_index_ = p; + } + return _impl_.lmhlo_param_shape_index_; +} +inline ::xla::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::mutable_lmhlo_param_shape_index() { + ::xla::EntryFunctionAttributes_ShapeIndex* _msg = _internal_mutable_lmhlo_param_shape_index(); + // @@protoc_insertion_point(field_mutable:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_param_shape_index) + return _msg; +} +inline void EntryFunctionAttributes_BufferParameterAttributes::set_allocated_lmhlo_param_shape_index(::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_param_shape_index) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.lmhlo_param_shape_index_; + } + if (lmhlo_param_shape_index) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(lmhlo_param_shape_index); + if (message_arena != submessage_arena) { + lmhlo_param_shape_index = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, lmhlo_param_shape_index, submessage_arena); + } + + } else { + + } + _impl_.lmhlo_param_shape_index_ = lmhlo_param_shape_index; + // @@protoc_insertion_point(field_set_allocated:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_param_shape_index) +} + +// string lmhlo_constant_name = 3; +inline void EntryFunctionAttributes_BufferParameterAttributes::clear_lmhlo_constant_name() { + _impl_.lmhlo_constant_name_.ClearToEmpty(); +} +inline const std::string& EntryFunctionAttributes_BufferParameterAttributes::lmhlo_constant_name() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_constant_name) + return _internal_lmhlo_constant_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void EntryFunctionAttributes_BufferParameterAttributes::set_lmhlo_constant_name(ArgT0&& arg0, ArgT... args) { + + _impl_.lmhlo_constant_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_constant_name) +} +inline std::string* EntryFunctionAttributes_BufferParameterAttributes::mutable_lmhlo_constant_name() { + std::string* _s = _internal_mutable_lmhlo_constant_name(); + // @@protoc_insertion_point(field_mutable:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_constant_name) + return _s; +} +inline const std::string& EntryFunctionAttributes_BufferParameterAttributes::_internal_lmhlo_constant_name() const { + return _impl_.lmhlo_constant_name_.Get(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::_internal_set_lmhlo_constant_name(const std::string& value) { + + _impl_.lmhlo_constant_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* EntryFunctionAttributes_BufferParameterAttributes::_internal_mutable_lmhlo_constant_name() { + + return _impl_.lmhlo_constant_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* EntryFunctionAttributes_BufferParameterAttributes::release_lmhlo_constant_name() { + // @@protoc_insertion_point(field_release:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_constant_name) + return _impl_.lmhlo_constant_name_.Release(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::set_allocated_lmhlo_constant_name(std::string* lmhlo_constant_name) { + if (lmhlo_constant_name != nullptr) { + + } else { + + } + _impl_.lmhlo_constant_name_.SetAllocated(lmhlo_constant_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.lmhlo_constant_name_.IsDefault()) { + _impl_.lmhlo_constant_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_constant_name) +} + +// bool lmhlo_must_alias = 4; +inline void EntryFunctionAttributes_BufferParameterAttributes::clear_lmhlo_must_alias() { + _impl_.lmhlo_must_alias_ = false; +} +inline bool EntryFunctionAttributes_BufferParameterAttributes::_internal_lmhlo_must_alias() const { + return _impl_.lmhlo_must_alias_; +} +inline bool EntryFunctionAttributes_BufferParameterAttributes::lmhlo_must_alias() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_must_alias) + return _internal_lmhlo_must_alias(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::_internal_set_lmhlo_must_alias(bool value) { + + _impl_.lmhlo_must_alias_ = value; +} +inline void EntryFunctionAttributes_BufferParameterAttributes::set_lmhlo_must_alias(bool value) { + _internal_set_lmhlo_must_alias(value); + // @@protoc_insertion_point(field_set:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_must_alias) +} + +// .xla.EntryFunctionAttributes.ShapeIndex lmhlo_output_index = 5; +inline bool EntryFunctionAttributes_BufferParameterAttributes::_internal_has_lmhlo_output_index() const { + return this != internal_default_instance() && _impl_.lmhlo_output_index_ != nullptr; +} +inline bool EntryFunctionAttributes_BufferParameterAttributes::has_lmhlo_output_index() const { + return _internal_has_lmhlo_output_index(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::clear_lmhlo_output_index() { + if (GetArenaForAllocation() == nullptr && _impl_.lmhlo_output_index_ != nullptr) { + delete _impl_.lmhlo_output_index_; + } + _impl_.lmhlo_output_index_ = nullptr; +} +inline const ::xla::EntryFunctionAttributes_ShapeIndex& EntryFunctionAttributes_BufferParameterAttributes::_internal_lmhlo_output_index() const { + const ::xla::EntryFunctionAttributes_ShapeIndex* p = _impl_.lmhlo_output_index_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_EntryFunctionAttributes_ShapeIndex_default_instance_); +} +inline const ::xla::EntryFunctionAttributes_ShapeIndex& EntryFunctionAttributes_BufferParameterAttributes::lmhlo_output_index() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_output_index) + return _internal_lmhlo_output_index(); +} +inline void EntryFunctionAttributes_BufferParameterAttributes::unsafe_arena_set_allocated_lmhlo_output_index( + ::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_output_index) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.lmhlo_output_index_); + } + _impl_.lmhlo_output_index_ = lmhlo_output_index; + if (lmhlo_output_index) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_output_index) +} +inline ::xla::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::release_lmhlo_output_index() { + + ::xla::EntryFunctionAttributes_ShapeIndex* temp = _impl_.lmhlo_output_index_; + _impl_.lmhlo_output_index_ = 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::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::unsafe_arena_release_lmhlo_output_index() { + // @@protoc_insertion_point(field_release:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_output_index) + + ::xla::EntryFunctionAttributes_ShapeIndex* temp = _impl_.lmhlo_output_index_; + _impl_.lmhlo_output_index_ = nullptr; + return temp; +} +inline ::xla::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::_internal_mutable_lmhlo_output_index() { + + if (_impl_.lmhlo_output_index_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::EntryFunctionAttributes_ShapeIndex>(GetArenaForAllocation()); + _impl_.lmhlo_output_index_ = p; + } + return _impl_.lmhlo_output_index_; +} +inline ::xla::EntryFunctionAttributes_ShapeIndex* EntryFunctionAttributes_BufferParameterAttributes::mutable_lmhlo_output_index() { + ::xla::EntryFunctionAttributes_ShapeIndex* _msg = _internal_mutable_lmhlo_output_index(); + // @@protoc_insertion_point(field_mutable:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_output_index) + return _msg; +} +inline void EntryFunctionAttributes_BufferParameterAttributes::set_allocated_lmhlo_output_index(::xla::EntryFunctionAttributes_ShapeIndex* lmhlo_output_index) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.lmhlo_output_index_; + } + if (lmhlo_output_index) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(lmhlo_output_index); + if (message_arena != submessage_arena) { + lmhlo_output_index = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, lmhlo_output_index, submessage_arena); + } + + } else { + + } + _impl_.lmhlo_output_index_ = lmhlo_output_index; + // @@protoc_insertion_point(field_set_allocated:xla.EntryFunctionAttributes.BufferParameterAttributes.lmhlo_output_index) +} + +// ------------------------------------------------------------------- + +// EntryFunctionAttributes + +// repeated .xla.EntryFunctionAttributes.BufferParameterAttributes buffers = 1; +inline int EntryFunctionAttributes::_internal_buffers_size() const { + return _impl_.buffers_.size(); +} +inline int EntryFunctionAttributes::buffers_size() const { + return _internal_buffers_size(); +} +inline void EntryFunctionAttributes::clear_buffers() { + _impl_.buffers_.Clear(); +} +inline ::xla::EntryFunctionAttributes_BufferParameterAttributes* EntryFunctionAttributes::mutable_buffers(int index) { + // @@protoc_insertion_point(field_mutable:xla.EntryFunctionAttributes.buffers) + return _impl_.buffers_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::EntryFunctionAttributes_BufferParameterAttributes >* +EntryFunctionAttributes::mutable_buffers() { + // @@protoc_insertion_point(field_mutable_list:xla.EntryFunctionAttributes.buffers) + return &_impl_.buffers_; +} +inline const ::xla::EntryFunctionAttributes_BufferParameterAttributes& EntryFunctionAttributes::_internal_buffers(int index) const { + return _impl_.buffers_.Get(index); +} +inline const ::xla::EntryFunctionAttributes_BufferParameterAttributes& EntryFunctionAttributes::buffers(int index) const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.buffers) + return _internal_buffers(index); +} +inline ::xla::EntryFunctionAttributes_BufferParameterAttributes* EntryFunctionAttributes::_internal_add_buffers() { + return _impl_.buffers_.Add(); +} +inline ::xla::EntryFunctionAttributes_BufferParameterAttributes* EntryFunctionAttributes::add_buffers() { + ::xla::EntryFunctionAttributes_BufferParameterAttributes* _add = _internal_add_buffers(); + // @@protoc_insertion_point(field_add:xla.EntryFunctionAttributes.buffers) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::EntryFunctionAttributes_BufferParameterAttributes >& +EntryFunctionAttributes::buffers() const { + // @@protoc_insertion_point(field_list:xla.EntryFunctionAttributes.buffers) + return _impl_.buffers_; +} + +// string result_xla_shape = 2; +inline void EntryFunctionAttributes::clear_result_xla_shape() { + _impl_.result_xla_shape_.ClearToEmpty(); +} +inline const std::string& EntryFunctionAttributes::result_xla_shape() const { + // @@protoc_insertion_point(field_get:xla.EntryFunctionAttributes.result_xla_shape) + return _internal_result_xla_shape(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void EntryFunctionAttributes::set_result_xla_shape(ArgT0&& arg0, ArgT... args) { + + _impl_.result_xla_shape_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.EntryFunctionAttributes.result_xla_shape) +} +inline std::string* EntryFunctionAttributes::mutable_result_xla_shape() { + std::string* _s = _internal_mutable_result_xla_shape(); + // @@protoc_insertion_point(field_mutable:xla.EntryFunctionAttributes.result_xla_shape) + return _s; +} +inline const std::string& EntryFunctionAttributes::_internal_result_xla_shape() const { + return _impl_.result_xla_shape_.Get(); +} +inline void EntryFunctionAttributes::_internal_set_result_xla_shape(const std::string& value) { + + _impl_.result_xla_shape_.Set(value, GetArenaForAllocation()); +} +inline std::string* EntryFunctionAttributes::_internal_mutable_result_xla_shape() { + + return _impl_.result_xla_shape_.Mutable(GetArenaForAllocation()); +} +inline std::string* EntryFunctionAttributes::release_result_xla_shape() { + // @@protoc_insertion_point(field_release:xla.EntryFunctionAttributes.result_xla_shape) + return _impl_.result_xla_shape_.Release(); +} +inline void EntryFunctionAttributes::set_allocated_result_xla_shape(std::string* result_xla_shape) { + if (result_xla_shape != nullptr) { + + } else { + + } + _impl_.result_xla_shape_.SetAllocated(result_xla_shape, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.result_xla_shape_.IsDefault()) { + _impl_.result_xla_shape_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.EntryFunctionAttributes.result_xla_shape) +} + +// ------------------------------------------------------------------- + +// XlaRuntimeExecutableProto + +// .xla.HloModuleProto hlo_module_proto = 1; +inline bool XlaRuntimeExecutableProto::_internal_has_hlo_module_proto() const { + return this != internal_default_instance() && _impl_.hlo_module_proto_ != nullptr; +} +inline bool XlaRuntimeExecutableProto::has_hlo_module_proto() const { + return _internal_has_hlo_module_proto(); +} +inline void XlaRuntimeExecutableProto::clear_hlo_module_proto() { + if (GetArenaForAllocation() == nullptr && _impl_.hlo_module_proto_ != nullptr) { + delete _impl_.hlo_module_proto_; + } + _impl_.hlo_module_proto_ = nullptr; +} +inline const ::xla::HloModuleProto& XlaRuntimeExecutableProto::_internal_hlo_module_proto() const { + const ::xla::HloModuleProto* p = _impl_.hlo_module_proto_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloModuleProto_default_instance_); +} +inline const ::xla::HloModuleProto& XlaRuntimeExecutableProto::hlo_module_proto() const { + // @@protoc_insertion_point(field_get:xla.XlaRuntimeExecutableProto.hlo_module_proto) + return _internal_hlo_module_proto(); +} +inline void XlaRuntimeExecutableProto::unsafe_arena_set_allocated_hlo_module_proto( + ::xla::HloModuleProto* hlo_module_proto) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.hlo_module_proto_); + } + _impl_.hlo_module_proto_ = hlo_module_proto; + if (hlo_module_proto) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.XlaRuntimeExecutableProto.hlo_module_proto) +} +inline ::xla::HloModuleProto* XlaRuntimeExecutableProto::release_hlo_module_proto() { + + ::xla::HloModuleProto* temp = _impl_.hlo_module_proto_; + _impl_.hlo_module_proto_ = 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::HloModuleProto* XlaRuntimeExecutableProto::unsafe_arena_release_hlo_module_proto() { + // @@protoc_insertion_point(field_release:xla.XlaRuntimeExecutableProto.hlo_module_proto) + + ::xla::HloModuleProto* temp = _impl_.hlo_module_proto_; + _impl_.hlo_module_proto_ = nullptr; + return temp; +} +inline ::xla::HloModuleProto* XlaRuntimeExecutableProto::_internal_mutable_hlo_module_proto() { + + if (_impl_.hlo_module_proto_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloModuleProto>(GetArenaForAllocation()); + _impl_.hlo_module_proto_ = p; + } + return _impl_.hlo_module_proto_; +} +inline ::xla::HloModuleProto* XlaRuntimeExecutableProto::mutable_hlo_module_proto() { + ::xla::HloModuleProto* _msg = _internal_mutable_hlo_module_proto(); + // @@protoc_insertion_point(field_mutable:xla.XlaRuntimeExecutableProto.hlo_module_proto) + return _msg; +} +inline void XlaRuntimeExecutableProto::set_allocated_hlo_module_proto(::xla::HloModuleProto* hlo_module_proto) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.hlo_module_proto_; + } + if (hlo_module_proto) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(hlo_module_proto); + if (message_arena != submessage_arena) { + hlo_module_proto = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, hlo_module_proto, submessage_arena); + } + + } else { + + } + _impl_.hlo_module_proto_ = hlo_module_proto; + // @@protoc_insertion_point(field_set_allocated:xla.XlaRuntimeExecutableProto.hlo_module_proto) +} + +// bytes obj_file = 3; +inline void XlaRuntimeExecutableProto::clear_obj_file() { + _impl_.obj_file_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeExecutableProto::obj_file() const { + // @@protoc_insertion_point(field_get:xla.XlaRuntimeExecutableProto.obj_file) + return _internal_obj_file(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeExecutableProto::set_obj_file(ArgT0&& arg0, ArgT... args) { + + _impl_.obj_file_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.XlaRuntimeExecutableProto.obj_file) +} +inline std::string* XlaRuntimeExecutableProto::mutable_obj_file() { + std::string* _s = _internal_mutable_obj_file(); + // @@protoc_insertion_point(field_mutable:xla.XlaRuntimeExecutableProto.obj_file) + return _s; +} +inline const std::string& XlaRuntimeExecutableProto::_internal_obj_file() const { + return _impl_.obj_file_.Get(); +} +inline void XlaRuntimeExecutableProto::_internal_set_obj_file(const std::string& value) { + + _impl_.obj_file_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeExecutableProto::_internal_mutable_obj_file() { + + return _impl_.obj_file_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeExecutableProto::release_obj_file() { + // @@protoc_insertion_point(field_release:xla.XlaRuntimeExecutableProto.obj_file) + return _impl_.obj_file_.Release(); +} +inline void XlaRuntimeExecutableProto::set_allocated_obj_file(std::string* obj_file) { + if (obj_file != nullptr) { + + } else { + + } + _impl_.obj_file_.SetAllocated(obj_file, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.obj_file_.IsDefault()) { + _impl_.obj_file_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.XlaRuntimeExecutableProto.obj_file) +} + +// string mlir_module = 4; +inline void XlaRuntimeExecutableProto::clear_mlir_module() { + _impl_.mlir_module_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeExecutableProto::mlir_module() const { + // @@protoc_insertion_point(field_get:xla.XlaRuntimeExecutableProto.mlir_module) + return _internal_mlir_module(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeExecutableProto::set_mlir_module(ArgT0&& arg0, ArgT... args) { + + _impl_.mlir_module_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.XlaRuntimeExecutableProto.mlir_module) +} +inline std::string* XlaRuntimeExecutableProto::mutable_mlir_module() { + std::string* _s = _internal_mutable_mlir_module(); + // @@protoc_insertion_point(field_mutable:xla.XlaRuntimeExecutableProto.mlir_module) + return _s; +} +inline const std::string& XlaRuntimeExecutableProto::_internal_mlir_module() const { + return _impl_.mlir_module_.Get(); +} +inline void XlaRuntimeExecutableProto::_internal_set_mlir_module(const std::string& value) { + + _impl_.mlir_module_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeExecutableProto::_internal_mutable_mlir_module() { + + return _impl_.mlir_module_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeExecutableProto::release_mlir_module() { + // @@protoc_insertion_point(field_release:xla.XlaRuntimeExecutableProto.mlir_module) + return _impl_.mlir_module_.Release(); +} +inline void XlaRuntimeExecutableProto::set_allocated_mlir_module(std::string* mlir_module) { + if (mlir_module != nullptr) { + + } else { + + } + _impl_.mlir_module_.SetAllocated(mlir_module, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.mlir_module_.IsDefault()) { + _impl_.mlir_module_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.XlaRuntimeExecutableProto.mlir_module) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace xla + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::xla::HloModuleProto_ProfileType> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::HloModuleProto_ProfileType>() { + return ::xla::HloModuleProto_ProfileType_descriptor(); +} +template <> struct is_proto_enum< ::xla::HeapSimulatorTrace_Event_Kind> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::HeapSimulatorTrace_Event_Kind>() { + return ::xla::HeapSimulatorTrace_Event_Kind_descriptor(); +} +template <> struct is_proto_enum< ::xla::CustomCallSchedule> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::CustomCallSchedule>() { + return ::xla::CustomCallSchedule_descriptor(); +} +template <> struct is_proto_enum< ::xla::CustomCallApiVersion> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::CustomCallApiVersion>() { + return ::xla::CustomCallApiVersion_descriptor(); +} +template <> struct is_proto_enum< ::xla::Kind> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::Kind>() { + return ::xla::Kind_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_alias_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_alias_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..e3ff80c4f81999fff61bf3ed8b4897dbcb67fd6c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_alias_analysis.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_SERVICE_HLO_ALIAS_ANALYSIS_H_ +#define XLA_SERVICE_HLO_ALIAS_ANALYSIS_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_buffer.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_ordering.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Analysis which allocates HloBuffers to HloValues. +class HloAliasAnalysis { + public: + // The callgraph of the given HloModule must be flattened + // (xla::FlattenCallGraph) prior to running the analysis. + static StatusOr> Run( + const HloModule* module, + const HloDataflowAnalysis::CanShareBuffer& can_share_buffer = nullptr); + + std::string ToString() const; + + // Return the buffer containing the given value. + const HloBuffer& GetBufferContainingValue(const HloValue& value) const { + return *value_to_buffer_.at(&value); + } + HloBuffer& GetBufferContainingValue(const HloValue& value) { + return *value_to_buffer_.at(&value); + } + + // Return the HloBuffer with the given ID. + const HloBuffer& GetBuffer(HloBuffer::Id buffer_id) const { + return buffers_.at(buffer_id); + } + HloBuffer& GetBuffer(HloBuffer::Id buffer_id) { + return buffers_.at(buffer_id); + } + + // Returns the unique buffer at the given position. CHECK fails if the buffer + // set at that position does not contain exactly one buffer. + const HloBuffer& GetUniqueBufferAt(const HloInstruction* instruction, + const ShapeIndex& index = {}) const; + HloBuffer& GetUniqueBufferAt(const HloInstruction* instruction, + const ShapeIndex& index = {}); + + // Compute the set of buffers at the given instruction and index and return as + // a vector. This set is exactly the union of the buffers containing the + // HloValues at this position. + std::vector ComputeBuffersAt( + const HloInstruction* instruction, const ShapeIndex& index = {}) const; + + // Return a vector of all HloBuffers stabily sorted by HloBuffer::Id. This + // vector is lazily computed. Mutating operations on HloAliasAnalysis may + // invalidate the underlying vector requiring recomputation. + const std::vector& buffers() const { return buffers_; } + + // Returns the underlying dataflow analysis used by this alias analysis. + HloDataflowAnalysis& dataflow_analysis() const { return *dataflow_analysis_; } + + // Returns true if a buffer lives out of the module. + bool BufferLivesOut(const HloBuffer& buffer) const { + return live_out_buffers_.contains(&buffer); + } + + // Returns true if a hlo value lives out of the module. + bool ValueLivesOut(const HloValue& value) const { + return live_out_buffers_.contains(&GetBufferContainingValue(value)); + } + + std::vector LiveOutBuffers() const { + std::vector results(live_out_buffers_.begin(), + live_out_buffers_.end()); + absl::c_sort(results, HloBuffer::IdLessThan); + return results; + } + + protected: + explicit HloAliasAnalysis(const HloModule* module); + + // Verify various invariants of the alias analysis. + Status Verify() const; + + const HloModule* module_; + + // A set of buffers that live out the module. + absl::flat_hash_set live_out_buffers_; + + // The underlying dataflow analysis used by this alias analysis. + std::unique_ptr dataflow_analysis_; + + // A map indicating which buffer a value is contained in. + absl::flat_hash_map value_to_buffer_; + + // A lazily constructed vector containing all HloBuffers sorted by + // HloBuffer::Id. + std::vector buffers_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_ALIAS_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..90d064d9b7cc4c891c0bdede9b00f17a06e98266 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_buffer.h @@ -0,0 +1,134 @@ +/* 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_SERVICE_HLO_BUFFER_H_ +#define XLA_SERVICE_HLO_BUFFER_H_ + +#include +#include +#include +#include + +#include "xla/service/hlo_value.h" +#include "xla/shape_tree.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// A container which can hold one or more HloValues. An HLO buffer abstractly +// represents the allocation which HLO instructions write into and read +// from. Generally there is a one-to-one correspondence between HloBuffers and +// HloValue where each HloValue in the module is held in a unique HloBuffer. An +// exception is the while instruction which updates the loop state in-place. In +// this case, we have a single HloBuffer for each HloPosition in the loop state, +// but multiple HloValues. For example: +// +// %init = ... +// %while = While(%init, body, condition) +// +// body: +// %body_param = Param(0) +// ... +// %body_root = ... +// +// condition: +// %cond_param = Param(0) +// ... +// +// For simplicity, assume that %while is array-shaped. In this case, we have a +// single HloBuffer which holds the following HloValues: HloValue{%init}, +// HloValue{%while}, HloValue{%body_param}, HloValue{%body_root}, and +// HloValue{%cond_param}. +// +// HloBuffers may appear at different HloPositions in the module mirroring the +// same property of HloValues. For example: +// +// %sub = Sub(...) +// %add = Add(...) +// %tuple = Tuple(%add, %sub) +// %gte = GetTupleElement(%tuple, 0) +// +// In this case, the HloBuffer containing %add appears at the following +// positions: HloPosition{%add, {}}, HloPosition{%tuple, {0}}, and +// HloPosition{%gte, {}}. +// +// Different HloPositions which share the same HloBuffer indicate mandatory +// aliasing in the HLO module. These positions must share the same memory +// allocation for correctness (the backends rely on this property). This differs +// from incidental aliasing introduced by memory reuse in BufferAssignment where +// different instructions may happen to get the same allocation. +class HloBuffer { + public: + using Id = int64_t; + + // Predicate comparing HloBuffers by increasing id, useful for std::sort. + static bool IdLessThan(const HloBuffer* a, const HloBuffer* b) { + return a->id() < b->id(); + } + + // Predicate comparing HloBuffers by equal id, useful for std::unique. + static bool IdEqual(const HloBuffer* a, const HloBuffer* b) { + return a->id() == b->id(); + } + + HloBuffer(Id id, std::vector values) + : id_(id), values_(std::move(values)) {} + + // Return the unique identifier for this HloBuffer. + Id id() const { return id_; } + + // Return all values contained in this buffer. + const std::vector& values() const { return values_; } + + // Memory space color. Used to indicate the memory space that the hlo buffer + // needs to live in. + BufferValue::Color color() const { + // Invariant: All values in the buffer should have the same color. + BufferValue::Color result = values()[0]->color(); + for (const HloValue* value : values()) { + DCHECK_EQ(result, value->color()); + } + return result; + } + + // Return the unique HLO value in the buffer. CHECK fails if the buffer does + // not contain exactly one value. + const HloValue& GetUniqueValue() const { + CHECK_EQ(values_.size(), 1); + return *values_[0]; + } + + std::vector ComputePositions() const; + + std::string ToString() const; + + bool operator==(const HloBuffer& other) const; + bool operator!=(const HloBuffer& other) const { return !(*this == other); } + + private: + // Unique identifier for this HloBuffer. + Id id_; + + // The set of values contained in this buffer. Vector contains no duplicates + // and is sorted stably by HloValue::Id. + std::vector values_; +}; + +std::ostream& operator<<(std::ostream& out, const HloBuffer& buffer); + +} // namespace xla + +#endif // XLA_SERVICE_HLO_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_computation_deduplicator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_computation_deduplicator.h new file mode 100644 index 0000000000000000000000000000000000000000..42fcb191ce9433b53fbebfdf5aa2531137e0a049 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_computation_deduplicator.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 XLA_SERVICE_HLO_COMPUTATION_DEDUPLICATOR_H_ +#define XLA_SERVICE_HLO_COMPUTATION_DEDUPLICATOR_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Deduplicate computations inside a `HloModule`: If two computations are +// identical then keep the first one (in postorder terms) and remove the rest. +class HloComputationDeduplicator : public HloModulePass { + private: + bool ContainsLargeConstants(HloComputation* comp); + bool mark_fusion_duplications_; + + public: + // Setting mark_fusion_duplications to true will only process fusions in the + // HLO. The comparator in this pass will mark duplicate fusions which is + // needed for groupings in analysis (e.g. Xprof). Currently, the pass + // doesn't change the HLO if the flag is set to true. + explicit HloComputationDeduplicator(bool mark_fusion_duplications = false) + : mark_fusion_duplications_(mark_fusion_duplications) {} + absl::string_view name() const override { return "computation-deduplicator"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_COMPUTATION_DEDUPLICATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_constant_folding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_constant_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..217333f23ed981553c933233870c47ebb7f3586e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_constant_folding.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_HLO_CONSTANT_FOLDING_H_ +#define XLA_SERVICE_HLO_CONSTANT_FOLDING_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which performs constant folding in order to avoid unnecessary +// computation on constants. +class HloConstantFolding : public HloModulePass { + public: + absl::string_view name() const override { return "constant_folding"; } + + // Run constant folding operations on the given module. Returns whether the + // module was changed (constant expressions folded). + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Number of slow constant-folds we've encountered. Used for firing + // SlowOperationAlarms. + static std::atomic slow_op_counter_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_CONSTANT_FOLDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_cost_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_cost_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..8305b0fadd215c7a262deec2d817fe2e83e7ae88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_cost_analysis.h @@ -0,0 +1,638 @@ +/* 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_SERVICE_HLO_COST_ANALYSIS_H_ +#define XLA_SERVICE_HLO_COST_ANALYSIS_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.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/shape_util.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// HloCostAnalysis traverses an HLO graph and calculates the amount of +// computations required for the graph. Each HLO instruction handler provides +// the computation cost of the instruction, and the values are accumulated +// during the traversal for the entire graph. We treat normal floating point +// operations separately from transcendental operations. +class HloCostAnalysis : public ConstDfsHloVisitor { + public: + static inline constexpr absl::string_view kFlopsKey = "flops"; + static inline constexpr absl::string_view kTranscendentalsKey = + "transcendentals"; + static inline constexpr absl::string_view kBytesAccessedKey = + "bytes accessed"; + static inline constexpr absl::string_view kOptimalSecondsKey = + "optimal_seconds"; + static inline constexpr absl::string_view kUtilizationKey = "utilization"; + + // Keys reserved for use by subclasses. These get the same special "fast + // path" treatment in Properties as the other keys above. + static inline constexpr absl::string_view kReserved0Key = "reserved0"; + static inline constexpr absl::string_view kReserved1Key = "reserved1"; + + // A data structure like hash_map for storing info about an HLO + // instruction or computation. + // + // Note that unlike a regular hashtable, there's no notion of an "unset" key. + // All keys are logically present, with value 0. + // + // This data structure *could* be simply map, and indeed it + // was, once. The problem is, XLA:GPU uses HloCostAnalysis during + // compilation. This class is used *everywhere* within cost analysis, and the + // hashtable lookups added up to the majority (!) of its runtime. + // + // This is a bit silly, because the vast majority of the time, we're looking + // up a small, fixed set of keys. So you might be tempted to convert + // Properties into a simple struct of floats. + // + // The problem with *that* is threefold. (1) subclasses expect to be able to + // store arbitrary keys inside Properties. This doesn't work if it's a + // struct. (2) We expect to be able to store *and retrieve* values + // representing e.g. "the utilization of operand n at shape index i", and (3) + // the hashtable-ness of this class is part of XLA's public API and so is hard + // to change. + // + // So instead we end up with this Frankenstein's monster of a class. It + // *acts* like a hashtable, but before falling back to the hashtable, it + // checks whether the string matches one of a list of "known keys". If so, it + // returns that special value from the struct. + // + // Normally this would be much worse than just using a plain hashtable. But + // we happen to know that you're almost always doing prop[kKnownKey], in which + // case operator[] can be inlined and the string comparison optimized away. + // + // Sorry for all this complexity, but this is the most impactful single + // optimization we were able make to GPU compilation time. + // + class Properties { + public: + Properties() + : flops_(0), + transcendentals_(0), + bytes_accessed_(0), + optimal_seconds_(0), + utilization_(0), + operand0_utilization_(0), + operand1_utilization_(0), + operand0_bytes_accessed_(0), + operand1_bytes_accessed_(0), + output_root_bytes_accessed_(0), + reserved0_(0), + reserved1_(0) { + DCHECK_EQ(kOperand0UtilizationKey, GetOperandUtilizationKey(0, {})); + DCHECK_EQ(kOperand1UtilizationKey, GetOperandUtilizationKey(1, {})); + DCHECK_EQ(kOperand0BytesAccessedKey, GetOperandBytesAccessedKey(0, {})); + DCHECK_EQ(kOperand1BytesAccessedKey, GetOperandBytesAccessedKey(1, {})); + DCHECK_EQ(kOutputRootBytesAccessedKey, GetOutputBytesAccessedKey({})); + } + + float& operator[](absl::string_view property) { + if (property == kFlopsKey) { + return flops_; + } + if (property == kTranscendentalsKey) { + return transcendentals_; + } + if (property == kBytesAccessedKey) { + return bytes_accessed_; + } + if (property == kOptimalSecondsKey) { + return optimal_seconds_; + } + if (property == kUtilizationKey) { + return utilization_; + } + if (property == kOperand0UtilizationKey) { + return operand0_utilization_; + } + if (property == kOperand1UtilizationKey) { + return operand1_utilization_; + } + if (property == kOperand0BytesAccessedKey) { + return operand0_bytes_accessed_; + } + if (property == kOperand1BytesAccessedKey) { + return operand1_bytes_accessed_; + } + if (property == kOutputRootBytesAccessedKey) { + return output_root_bytes_accessed_; + } + if (property == kReserved0Key) { + return reserved0_; + } + if (property == kReserved1Key) { + return reserved1_; + } + + auto it = named_props_.lazy_emplace(property, [&](const auto& ctor) { + ctor(std::string(property), 0.f); + }); + return it->second; + } + + float operator[](absl::string_view property) const { + if (property == kFlopsKey) { + return flops_; + } + if (property == kTranscendentalsKey) { + return transcendentals_; + } + if (property == kBytesAccessedKey) { + return bytes_accessed_; + } + if (property == kOptimalSecondsKey) { + return optimal_seconds_; + } + if (property == kUtilizationKey) { + return utilization_; + } + if (property == kOperand0UtilizationKey) { + return operand0_utilization_; + } + if (property == kOperand1UtilizationKey) { + return operand1_utilization_; + } + if (property == kOperand0BytesAccessedKey) { + return operand0_bytes_accessed_; + } + if (property == kOperand1BytesAccessedKey) { + return operand1_bytes_accessed_; + } + if (property == kOutputRootBytesAccessedKey) { + return output_root_bytes_accessed_; + } + if (property == kReserved0Key) { + return reserved0_; + } + if (property == kReserved1Key) { + return reserved1_; + } + + auto it = named_props_.find(property); + if (it != named_props_.end()) { + return it->second; + } + return 0; + } + + template + void ForEach(Fn&& fn) const { + if (flops_ != 0) { + fn(kFlopsKey, flops_); + } + if (transcendentals_ != 0) { + fn(kTranscendentalsKey, transcendentals_); + } + if (bytes_accessed_ != 0) { + fn(kBytesAccessedKey, bytes_accessed_); + } + if (optimal_seconds_ != 0) { + fn(kOptimalSecondsKey, optimal_seconds_); + } + if (utilization_ != 0) { + fn(kUtilizationKey, utilization_); + } + if (operand0_utilization_ != 0) { + fn(kOperand0UtilizationKey, operand0_utilization_); + } + if (operand1_utilization_ != 0) { + fn(kOperand1UtilizationKey, operand1_utilization_); + } + if (operand0_bytes_accessed_ != 0) { + fn(kOperand0BytesAccessedKey, operand0_bytes_accessed_); + } + if (operand1_bytes_accessed_ != 0) { + fn(kOperand1BytesAccessedKey, operand1_bytes_accessed_); + } + if (output_root_bytes_accessed_ != 0) { + fn(kOutputRootBytesAccessedKey, output_root_bytes_accessed_); + } + if (reserved0_ != 0) { + fn(kReserved0Key, reserved0_); + } + if (reserved1_ != 0) { + fn(kReserved1Key, reserved1_); + } + + for (const auto& [k, v] : named_props_) { + if (v != 0) { + fn(k, v); + } + } + } + + // No getters/setters for simple properties like flops(). For these, + // props[kFlopsKey] gets optimized to `return flops_` just fine. + + // Getters/setters for more complex properties like operand utilization, + // where we have a fastpath for e.g. operand 0/1 + shape_index {}. + float operand_utilization(int64_t operand, + const ShapeIndex& shape_index = {}) { + if (operand == 0 && shape_index.empty()) { + return operand0_utilization_; + } + if (operand == 1 && shape_index.empty()) { + return operand1_utilization_; + } + + auto it = + named_props_.find(GetOperandUtilizationKey(operand, shape_index)); + if (it != named_props_.end()) { + return it->second; + } + return 0; + } + void set_operand_utilization(int64_t operand, float value) { + set_operand_utilization(operand, /*shape_index=*/{}, value); + } + void set_operand_utilization(int64_t operand, const ShapeIndex& shape_index, + float value) { + if (operand == 0 && shape_index.empty()) { + operand0_utilization_ = value; + } else if (operand == 1 && shape_index.empty()) { + operand1_utilization_ = value; + } else { + named_props_[GetOperandUtilizationKey(operand, shape_index)] = value; + } + } + + float operand_bytes_accessed(int64_t operand, + const ShapeIndex& shape_index = {}) { + if (operand == 0 && shape_index.empty()) { + return operand0_bytes_accessed_; + } + if (operand == 1 && shape_index.empty()) { + return operand1_bytes_accessed_; + } + + auto it = + named_props_.find(GetOperandBytesAccessedKey(operand, shape_index)); + if (it != named_props_.end()) { + return it->second; + } + return 0; + } + void set_operand_bytes_accessed(int64_t operand, float value) { + set_operand_bytes_accessed(operand, /*shape_index=*/{}, value); + } + void set_operand_bytes_accessed(int64_t operand, + const ShapeIndex& shape_index, + float value) { + if (operand == 0 && shape_index.empty()) { + operand0_bytes_accessed_ = value; + } else if (operand == 1 && shape_index.empty()) { + operand1_bytes_accessed_ = value; + } else { + named_props_[GetOperandBytesAccessedKey(operand, shape_index)] = value; + } + } + + float output_bytes_accessed(const ShapeIndex& shape_index = {}) { + if (shape_index.empty()) { + return output_root_bytes_accessed_; + } + auto it = named_props_.find(GetOutputBytesAccessedKey(shape_index)); + if (it != named_props_.end()) { + return it->second; + } + return 0; + } + void set_output_bytes_accessed(float value) { + set_output_bytes_accessed({}, value); + } + void set_output_bytes_accessed(const ShapeIndex& shape_index, float value) { + if (shape_index.empty()) { + output_root_bytes_accessed_ = value; + } else { + named_props_[GetOutputBytesAccessedKey(shape_index)] = value; + } + } + + private: + // These must match GetOperandUtilizationKey(0, {}) etc. + static inline constexpr absl::string_view kOperand0UtilizationKey = + "utilization operand 0 {}"; + static inline constexpr absl::string_view kOperand1UtilizationKey = + "utilization operand 1 {}"; + static inline constexpr absl::string_view kOperand0BytesAccessedKey = + "bytes accessed operand 0 {}"; + static inline constexpr absl::string_view kOperand1BytesAccessedKey = + "bytes accessed operand 1 {}"; + static inline constexpr absl::string_view kOutputRootBytesAccessedKey = + "bytes accessed output {}"; + + float flops_; + float transcendentals_; + float bytes_accessed_; + float optimal_seconds_; + float utilization_; + + float operand0_utilization_; + float operand1_utilization_; + + float operand0_bytes_accessed_; + float operand1_bytes_accessed_; + + float output_root_bytes_accessed_; + + // Fields reserved for use by subclasses. + float reserved0_; + float reserved1_; + + absl::flat_hash_map named_props_; + }; + + // shape_size is a function which returns the size in bytes of the top-level + // buffer of a shape. + using ShapeSizeFunction = std::function; + + // A struct to encapsulate hardware-related options. This includes the shape + // size function, which is used to encode hardware-specific padding and per + // second rates of FLOPs, bytes per second (available bandwidth), and + // transcendentals per second. + struct Options { + // Function which computes the size of the top-level of a given shape (not + // including nested elements, if any). If null then bytes_accessed methods + // return an error. + ShapeSizeFunction shape_size; + // How much of each property can be processed per second. E.g. if the + // property is bytes accessed, this is the number of bytes that can be + // processed per second. Is empty if no rates have been set. + Properties per_second_rates = {}; + // Operations like broadcast with reused inputs are not handled + // efficiently on some platforms. Depending on the goal of the analysis + // we may need to count or ignore them. + bool count_multiple_input_accesses = false; + + // Set the rates used to calculate the time taken by the computation. + void set_flops_per_second(float value) { + per_second_rates[kFlopsKey] = value; + } + void set_transcendentals_per_second(float value) { + per_second_rates[kTranscendentalsKey] = value; + } + void set_bytes_per_second(float value) { + per_second_rates[kBytesAccessedKey] = value; + } + + // Returns the specified per-second rate used by cost analysis. + float per_second_rate(const std::string& key) const { + return per_second_rates[key]; + } + }; + + explicit HloCostAnalysis(const Options& options); + explicit HloCostAnalysis(ShapeSizeFunction shape_size, + const Properties& per_second_rates = {}); + + Status HandleElementwiseUnary(const HloInstruction* hlo) override; + Status HandleElementwiseBinary(const HloInstruction* hlo) override; + Status HandleConstant(const HloInstruction* constant) override; + Status HandleIota(const HloInstruction* iota) override; + Status HandleGetTupleElement( + const HloInstruction* get_tuple_element) override; + Status HandleSelect(const HloInstruction* hlo) override; + Status HandleCompare(const HloInstruction* compare) override; + Status HandleClamp(const HloInstruction* clamp) override; + Status HandleReducePrecision(const HloInstruction* hlo) override; + Status HandleConcatenate(const HloInstruction* concatenate) override; + Status HandleAsyncStart(const HloInstruction* async_start) override; + Status HandleAsyncUpdate(const HloInstruction* async_update) override; + Status HandleAsyncDone(const HloInstruction* async_done) override; + Status HandleCopyStart(const HloInstruction* send) override; + Status HandleCopyDone(const HloInstruction* send_done) override; + Status HandleSend(const HloInstruction* send) override; + Status HandleSendDone(const HloInstruction* send_done) override; + Status HandleRecv(const HloInstruction* recv) override; + Status HandleRecvDone(const HloInstruction* recv_done) override; + Status HandleConvert(const HloInstruction* convert) override; + Status HandleCopy(const HloInstruction* copy) override; + Status HandleDomain(const HloInstruction* domain) override; + Status HandleDot(const HloInstruction* dot) override; + Status HandleConvolution(const HloInstruction* convolution) override; + Status HandleFft(const HloInstruction* fft) override; + Status HandleTriangularSolve(const HloInstruction* hlo) override; + Status HandleCholesky(const HloInstruction* hlo) override; + Status HandleOptimizationBarrier(const HloInstruction* hlo) override; + Status HandleAllGather(const HloInstruction* hlo) override; + Status HandleAllGatherStart(const HloInstruction* hlo) override; + Status HandleAllGatherDone(const HloInstruction* hlo) override; + Status HandleAllReduce(const HloInstruction* crs) override; + Status HandleReduceScatter(const HloInstruction* hlo) override; + Status HandleAllReduceStart(const HloInstruction* hlo) override; + Status HandleAllReduceDone(const HloInstruction* hlo) override; + Status HandleAllToAll(const HloInstruction* hlo) override; + Status HandleCollectivePermute(const HloInstruction* hlo) override; + Status HandleCollectivePermuteStart(const HloInstruction* hlo) override; + Status HandleCollectivePermuteDone(const HloInstruction* hlo) override; + Status HandleReplicaId(const HloInstruction* hlo) override; + Status HandlePartitionId(const HloInstruction* hlo) override; + Status HandleInfeed(const HloInstruction* infeed) override; + Status HandleOutfeed(const HloInstruction* outfeed) override; + Status HandleRng(const HloInstruction* random) override; + Status HandleRngBitGenerator(const HloInstruction* random) override; + Status HandleRngGetAndUpdateState(const HloInstruction* random) override; + Status HandleReverse(const HloInstruction* reverse) override; + Status HandleSort(const HloInstruction* sort) override; + Status HandleParameter(const HloInstruction* parameter) override; + Status HandleReduce(const HloInstruction* reduce) override; + Status HandleBatchNormTraining( + const HloInstruction* batch_norm_training) override; + Status HandleBatchNormInference( + const HloInstruction* batch_norm_inference) override; + Status HandleBatchNormGrad(const HloInstruction* batch_norm_grad) override; + Status HandleFusion(const HloInstruction* fusion) override; + Status HandleCall(const HloInstruction* call) override; + Status HandleCustomCall(const HloInstruction* custom_call) override; + Status HandleSlice(const HloInstruction* slice) override; + Status HandleDynamicSlice(const HloInstruction* dynamic_slice) override; + Status HandleDynamicUpdateSlice( + const HloInstruction* dynamic_update_slice) override; + Status HandleTuple(const HloInstruction* tuple) override; + Status HandleMap(const HloInstruction* map) override; + Status HandleReduceWindow(const HloInstruction* reduce_window) override; + Status HandleSelectAndScatter(const HloInstruction* instruction) override; + Status HandleBitcast(const HloInstruction* bitcast) override; + Status HandleBroadcast(const HloInstruction* broadcast) override; + Status HandlePad(const HloInstruction* pad) override; + Status HandleReshape(const HloInstruction* reshape) override; + Status HandleDynamicReshape(const HloInstruction* reshape) override; + Status HandleAddDependency(const HloInstruction* add_dependency) override; + Status HandleAfterAll(const HloInstruction* token) override; + Status HandleTranspose(const HloInstruction* transpose) override; + Status HandleWhile(const HloInstruction* xla_while) override; + Status HandleConditional(const HloInstruction* conditional) override; + Status HandleGather(const HloInstruction* gather) override; + Status HandleScatter(const HloInstruction* hlo) override; + Status HandleGetDimensionSize(const HloInstruction* get_size) override; + Status HandleSetDimensionSize(const HloInstruction* set_size) override; + Status HandleTopK(const HloInstruction* topk) override; + Status FinishVisit(const HloInstruction* root) override; + + Status Preprocess(const HloInstruction* hlo) override; + Status Postprocess(const HloInstruction* hlo) override; + + // Enable efficient updates if a known small set of instructions within an + // HLO graph was modified. + // Updates the cost analysis by removing one instruction. + Status RemoveInstruction(HloInstruction* instruction); + // Updates the cost analysis by re-doing the analysis of one instruction. + Status RevisitInstruction(HloInstruction* instruction); + + // Decorates shape_size_ by returning 0 immediately if the shape does not have + // a layout. + int64_t GetShapeSize(const Shape& shape) const; + + // Returns properties for the computation. + float flop_count() const; + float transcendental_count() const; + float bytes_accessed() const; + float optimal_seconds() const; + + // Returns the respective cost computed for a particular HLO instruction, or 0 + // if the HLO was not found to have a cost in the analysis. + // + // Note that the cost for sub HLO instructions are also returned if asked. For + // example, body and condition of a while, fused instructions within a + // fusion, or the add instruction of a reduce. + int64_t flop_count(const HloInstruction& hlo) const; + int64_t transcendental_count(const HloInstruction& hlo) const; + int64_t bytes_accessed(const HloInstruction& hlo) const; + int64_t operand_bytes_accessed(const HloInstruction& hlo, int64_t operand_num, + ShapeIndex index = {}) const; + // Value indicating how much each input of the instruction + // is used assuming its output is fully used. + // This is 1.0 for most cases except operations involving slicing (<1) + // and on some backends in addition reuse of inputs (>1). + float operand_utilization(const HloInstruction& hlo, int64_t operand_num, + ShapeIndex index = {}) const; + int64_t output_bytes_accessed(const HloInstruction& hlo, + ShapeIndex index = {}) const; + float optimal_seconds(const HloInstruction& hlo) const; + + // Get bytes read/written by this HLO. If memory_space is provided, it returns + // the bytes read/written from/to the given memory space only. + int64_t GetBytesRead( + const HloInstruction& hlo, + std::optional memory_space = std::nullopt) const; + int64_t GetBytesWritten( + const HloInstruction& hlo, + std::optional memory_space = std::nullopt) const; + + const Properties& properties() const { return properties_sum_; } + float property(absl::string_view key) { return properties_sum_[key]; } + + // Returns the specified per-second rate used by cost analysis. + float per_second_rate(absl::string_view key) const { + return options_.per_second_rates[key]; + } + + // Return the key that is used to index into Properties for the specified + // input/output at the shape index. + static std::string GetOperandBytesAccessedKey(int64_t operand_num, + const ShapeIndex& index = {}); + static std::string GetOperandUtilizationKey(int64_t operand_num, + const ShapeIndex& index = {}); + static std::string GetOutputBytesAccessedKey(const ShapeIndex& index = {}); + + // Returns the estimated convolution flops. + virtual int64_t GetConvolutionFlops(const HloInstruction* convolution); + // Same as above but with parameters for shapes to allow for backends to + // refine these. + static int64_t GetConvolutionFlops(const HloInstruction* convolutions, + const Shape& lhs_shape, + const Shape& rhs_shape, + const Shape& result_shape); + + // Returns the estimated dot flops. + static int64_t GetDotFlops(const Shape& lhs_shape, const Shape& result_shape, + const DotDimensionNumbers& dnums); + + protected: + typedef absl::flat_hash_map + HloToProperties; + + // An FMA counts as two floating point operations in these analyzes. + static constexpr int64_t kFmaFlops = 2; + + // Small constants can be embedded in the assembly and not require + // memory access. + virtual size_t immediate_constant_max_elements() const { return 1; } + + // Creates a nested instance of HloCostAnalysis using the same Options. + virtual std::unique_ptr CreateNestedCostAnalysis(); + + // Returns the properties computed from visiting the computation rooted at the + // given hlo. The cost of visited sub HLO instructions is saved to + // hlo_properties_, which will be used by functions such as + // flop_count(hlo_instruction) to return cost of a particular HLO instruction. + StatusOr ProcessSubcomputation(HloComputation* computation); + + // Utility function to handle all element-wise operations. + Status HandleElementwiseOp(const HloInstruction* hlo_instruction); + + // Returns 0.0f if the hlo is not present in hlo_to_properties or if the key + // is not present in hlo_to_properties[hlo]. Otherwise, returns the value that + // the key maps to in the properties of the given hlo. + static float GetPropertyForHlo(const HloInstruction& hlo, + absl::string_view key, + const HloToProperties& hlo_to_properties); + + // Traverses a fusion operand to find the actual bytes accessed by the fusion + // node. + virtual int64_t FusionParameterReadBytes(const HloInstruction* hlo) const; + + // Traverses a fusion counting total utilization of every instruction inside. + // Currently implemented non-trivially only in the GPU cost analysis. + virtual Status FusionCalculateUtilizations(const HloInstruction* fusion); + + HloToProperties hlo_properties_; + + // If true, the time taken will be computed from the rates for each property + // and the total time will be the maximum time, which is the time of the + // bottleneck. + bool current_should_compute_bottleneck_time_; + + // The properties of the currently visited instruction. A HandleFoo method can + // modify these to change the default values computed in Preprocess. + Properties current_properties_; + + // The sum of the properties of all HLOs in the computation. + Properties properties_sum_; + + // The hardware-specific options that contains things like the shape size + // function and per-second rates. + Options options_; + + // Determines which properties propagate from subcomputations to parents. + virtual bool KeyToCopyFromSubcomputation(absl::string_view key) const; + + HloCostAnalysis(const HloCostAnalysis&) = delete; + HloCostAnalysis& operator=(const HloCostAnalysis&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_COST_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_creation_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_creation_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..5f5640ad3ec4659ecfb44978c6752d8e3624cc80 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_creation_utils.h @@ -0,0 +1,383 @@ +/* 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_SERVICE_HLO_CREATION_UTILS_H_ +#define XLA_SERVICE_HLO_CREATION_UTILS_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/literal_util.h" +#include "xla/statusor.h" + +namespace xla { + +// Some lightweight utilities intended to make HLO instruction creation more +// ergonomic. We don't have a complete set of helpers yet -- I expect we'll +// expand this interface as needed on an ad-hoc basis. + +// Creates a unary HLO instruction and adds it to the computation containing +// `operand`. +StatusOr MakeUnaryHlo(HloOpcode opcode, + HloInstruction* operand, + const OpMetadata* metadata = nullptr); + +// Creates a binary HLO instruction and adds it to the computation containing +// `lhs` and `rhs` (`lhs` and `rhs` must be in the same computation). +StatusOr MakeBinaryHlo(HloOpcode opcode, HloInstruction* lhs, + HloInstruction* rhs, + const OpMetadata* metadata = nullptr); + +// Creates a kCopy HLO. +HloInstruction* MakeCopyHlo(HloInstruction* from, const Shape& to); + +// Creates a compare HLO instruction and adds it to the computation containing +// `lhs` and `rhs` (`lhs` and `rhs` must be in the same computation). +StatusOr MakeCompareHlo(Comparison::Direction direction, + HloInstruction* lhs, + HloInstruction* rhs, + const OpMetadata* metadata = nullptr); + +// Creates a pad HLO instruction and adds it to the computation containing +// `operand` and `padding_value` (`operand` and `padding_value` must be in the +// same computation). +StatusOr MakePadHlo(HloInstruction* operand, + HloInstruction* padding_value, + const PaddingConfig& padding_config, + const OpMetadata* metadata = nullptr); + +// Creates a slice HLO instruction and adds it to the computation containing +// `operand`. +StatusOr MakeSliceHlo(HloInstruction* operand, + absl::Span start_indices, + absl::Span limit_indices, + absl::Span strides, + const OpMetadata* metadata = nullptr); + +// Creates a convolution HLO instruction and adds it to the computation +// containing `lhs` and `rhs` (`lhs` and `rhs` must be in the same computation). +// If the result shape has integral element type, an optional +// preferred_element_type can be specified to override the element type. +StatusOr MakeConvolveHlo( + 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, + std::optional preferred_element_type, + const OpMetadata* metadata = nullptr); + +// Creates a transpose HLO instruction and adds it to the computation containing +// `operand`. +StatusOr MakeTransposeHlo( + HloInstruction* operand, absl::Span dimensions); + +// Creates a reshape HLO instruction and adds it to the computation containing +// `operand`. +StatusOr MakeReshapeHlo(const Shape& result_shape, + HloInstruction* operand); + +StatusOr MakeReshapeHlo( + absl::Span result_shape_dim_bounds, HloInstruction* operand); + +// Creates a dynamic-slice HLO instruction and adds it to the computation +// containing `operand` and `start_indices` (`operand` and `start_indices` must +// be in the same computation). +StatusOr MakeDynamicSliceHlo( + HloInstruction* operand, absl::Span start_indices, + absl::Span slice_sizes, + const OpMetadata* metadata = nullptr); +StatusOr MakeDynamicSliceHlo( + HloInstruction* operand, HloInstruction* start_indices, + absl::Span slice_sizes, + const OpMetadata* metadata = nullptr); + +// Creates a dynamic-update-slice HLO instruction and adds it to the computation +// containing `operand`, `update` and `start_indices` (`operand`, `update` and +// `start_indices` must be in the same computation). +StatusOr MakeDynamicUpdateSliceHlo( + HloInstruction* operand, HloInstruction* update, + HloInstruction* start_indices, const OpMetadata* metadata = nullptr); + +// a variant of dynamic-update-slice where `start_indices` is a vector of HLO +// instructions +StatusOr MakeDynamicUpdateSliceHlo( + HloInstruction* operand, HloInstruction* update, + absl::Span start_indices, + const OpMetadata* metadata = nullptr); + +// Creates a broadcast HLO instruction and adds it to the computation containing +// `operand`. +HloInstruction* MakeBroadcastHlo(HloInstruction* operand, + absl::Span broadcast_dimensions, + absl::Span result_shape_bounds, + const OpMetadata* metadata = nullptr); +HloInstruction* MakeBroadcastHlo(HloInstruction* operand, + absl::Span broadcast_dimensions, + const Shape& shape, + const OpMetadata* metadata = nullptr); + +// Creates a GetTupleElement HLO instruction and adds it to the computation +// containing `operand`. +StatusOr MakeGetTupleElementHlo( + HloInstruction* operand, int64_t index, + const OpMetadata* metadata = nullptr); + +// Creates a Concatenate HLO instruction and adds it to the computation +// containing `operands` (`operands` must be non-empty and every element must be +// contained in the same computation). +StatusOr MakeConcatHlo( + absl::Span operands, int64_t dimension, + const OpMetadata* metadata = nullptr); + +// Creates a Convert HLO instruction that converts the given instruction to have +// the given primitive type. +HloInstruction* MakeConvertToHlo(HloInstruction* hlo, PrimitiveType type, + const OpMetadata* metadata = nullptr); + +// Creates a Bitcast HLO instruction to the given shape+layout. +HloInstruction* MakeBitcastHlo(HloInstruction* hlo, const Shape& shape, + const OpMetadata* metadata = nullptr); + +// Creates a BitcastConvert HLO instruction. +HloInstruction* MakeBitcastConvertToHlo(HloInstruction* hlo, PrimitiveType type, + const OpMetadata* metadata = nullptr); + +// Creates an Iota HLO instruction. +HloInstruction* MakeIotaHlo(HloComputation* computation, const Shape& shape, + int64_t iota_dimension); + +// Creates a Dot HLO instruction and adds it to the computation containing `lhs` +// and `rhs` (both must be in the same computation). If the result shape has +// integral element type, an optional preferred_element_type can be specified to +// override the element type. +StatusOr MakeDotHlo( + HloInstruction* lhs, HloInstruction* rhs, + const DotDimensionNumbers& dim_numbers, + const PrecisionConfig& precision_config, + std::optional preferred_element_type, + const OpMetadata* metadata = nullptr); + +// Creates a Map HLO instruction and adds it to the computation containing the +// operands. All operands must be in the same computation. +StatusOr MakeMapHlo(absl::Span operands, + HloComputation* map_computation, + const OpMetadata* metadata = nullptr); + +// 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. +HloInstruction* MakeReducePrecisionHlo(HloInstruction* operand, + int exponent_bits, int mantissa_bits, + const OpMetadata* metadata = nullptr); + +StatusOr MakeReduceWindowHlo( + HloInstruction* operand, HloInstruction* init_value, const Window& window, + HloComputation* reduce_computation, const OpMetadata* metadata = nullptr); + +// Creates a Reduce HLO instruction and adds it to the computation containing +// the operand. This will create the sub-computation needed for the reduction in +// the given module. binary_opcode should represent a binary operation. +StatusOr MakeReduceHlo(HloInstruction* operand, + HloInstruction* init_value, + absl::Span dimensions, + HloOpcode binary_opcode, + const OpMetadata* metadata = nullptr); + +StatusOr MakeReduceHlo(HloInstruction* operand, + HloInstruction* init_value, + absl::Span dimensions, + HloComputation* reduce_computation, + const OpMetadata* metadata = nullptr); + +StatusOr MakeReduceHlo(HloInstruction* operand, + HloInstruction* init_value, + HloOpcode binary_opcode, + HloModule* module, + const OpMetadata* metadata = nullptr); + +// Generic helper function to create a reduction. +// +// Precondition: size of operands is equal to the size of init values and equal +// to the size of the computation output shape. +// +// Creates a non-variadic reduction if the size is singular, and a variadic one +// otherwise. +StatusOr MakeReduceHlo( + absl::Span operands, + absl::Span init_values, + absl::Span dimensions, HloComputation* reduce_computation, + const OpMetadata* metadata = nullptr); + +// Creates a Reverse HLO instruction and adds it to the computation containing +// `operand`. +StatusOr MakeReverseHlo(HloInstruction* operand, + absl::Span dimensions, + const OpMetadata* metadata = nullptr); + +// Creates a Select HLO instruction and adds it to the computation containing +// the predicate. The on_true and on_false instructions must also be contained +// in the same computation. If on_true and on_false are tuples, create a tuple +// select instead. `pred` is broadcasted up from a scalar if necessary. +StatusOr MakeSelectHlo(HloInstruction* pred, + HloInstruction* on_true, + HloInstruction* on_false, + HloInstruction* derived_from = nullptr); + +// Forwards the first operand if operands.size() == 1, or creates a tuple +// instruction with all the operands. Crashes if `operands` is empty. +HloInstruction* MaybeMakeTuple(absl::Span operands); + +// Creates a Sort HLO instruction and adds it to the computation containing the +// operands. All operands must be in the same computation. Also creates a +// default compare sub-computation which sorts the first operand into ascending +// order. 'is_stable' specifies whether the sorting should be stable. +StatusOr MakeSortHlo( + const Shape& sort_shape, absl::Span operands, + int64_t dimension_to_sort, bool is_stable, HloComputation::Builder* builder, + HloModule* module, const OpMetadata* metadata = nullptr); + +// Creates an R1 Constant HLO instruction of the given PrimitiveType with the +// given values and adds it to the given computation. +template +StatusOr MakeR1ConstantHlo(HloComputation* computation, + PrimitiveType type, + absl::Span values) { + Literal literal = LiteralUtil::CreateR1(values); + if (literal.shape().element_type() != type) { + TF_ASSIGN_OR_RETURN(literal, literal.Convert(type)); + } + return computation->AddInstruction( + HloInstruction::CreateConstant(std::move(literal))); +} + +// Creates an R0 Constant HLO instruction of the PrimitiveType corresponding to +// `NativeT` with the given value and adds it to the given computation. +template +HloInstruction* MakeR0ConstantHlo(HloComputation* computation, NativeT value) { + return computation->AddInstruction( + HloInstruction::CreateConstant(LiteralUtil::CreateR0(value))); +} + +// Makes a scalar that is elementwise compatible with the shape of the base +// instruction. +template +HloInstruction* MakeScalarLike(HloInstruction* base, NativeT value) { + auto scalar = base->AddInstruction( + HloInstruction::CreateConstant(LiteralUtil::CreateR0(value) + .Convert(base->shape().element_type()) + .value())); + if (base->shape().rank() == 0) { + *scalar->mutable_shape() = base->shape(); + return scalar; + } + return base->AddInstruction( + HloInstruction::CreateBroadcast(base->shape(), scalar, {})); +} + +// Creates a fusion instruction and fuses `fused` into the created fusion +// instruction. +StatusOr MakeFusionInstruction( + HloInstruction* fused, HloInstruction::FusionKind kind); + +// ----------------------------------------------------------------------------- +// Some other miscellaneous helpers to generate common HLO patterns. All of +// these add all the instructions they generate into the computation containing +// their operand(s). + +// Collapses (via reshape) the first N (logical) dimensions of `operand` into a +// single leading dimension. `operand` must have rank > `n` and `n` must not be +// 0. +// +// For instance if `operand` has shape f32[7,8,9] and n is 2 then the output is +// the `operand` reshaped to [56,9]. +StatusOr CollapseFirstNDims(HloInstruction* operand, + int64_t n); + +// Prepends `n` degenerate dimensions (dimensions with bound = 1) to `operand` +// using a reshape. +// +// For instance if operand has shape f32[3,4,5] then this returns the operand +// reshaped to f32[1,3,4,5]. If the operand is a f32 scalar (i.e. has shape +// f32[]) then this returns the operand reshaped to f32[1]. +StatusOr PrependDegenerateDims(HloInstruction* operand, + int64_t n); + +// Expands (via reshape) the first (logical) dimension of `operand` into a +// sequence of `expanded_dims` dimensions. `operand` must at least be of rank 1 +// and the number of elements in its first dimension must be equal to the +// product of `expanded_dims`. +// +// For instance if `operand` has shape f32[200,9,7] and expanded_dims is +// {2,5,20} the result is `operand` reshaped to [2,5,20,9,7]. +StatusOr ExpandFirstDimIntoNDims( + HloInstruction* operand, absl::Span expanded_dims); + +// Elides (via reshape) a set of degenerate dimensions (dimensions containing +// exactly one element), `dims_to_elide` from `operand`. Every dimension in +// `dims_to_elide` must be a degenerate dimension. `dims_to_elide` must be +// sorted and not contain duplicates. +// +// For example if `operand` is of shape f32[19,1,20,1,7,1,9] and dims_to_elide +// is {1,5} then the result is `operand` reshaped to [19,20,1,7,9]. +StatusOr ElideDegenerateDims( + HloInstruction* operand, absl::Span dims_to_elide); + +// Inserts (via reshape) a set of degenerate dimensions (dimensions containing +// exactly one element), `dims_to_insert` into `operand`. The dimensions in +// `dims_to_insert` refer to the dimensions in the result, and hence should be +// less than the rank of the result. Also, `dims_to_insert` must be sorted. +// +// For example, if `operand` is of shape f32[12,21,8,34] and dims_to_insert is +// {0, 2}, then the result is `operand` reshaped to [1,12,1,21,8,34]. +StatusOr InsertDegenerateDims( + HloInstruction* operand, absl::Span dims_to_insert); + +// Pads `operand` (which must have rank 1) with `zeros_to_prepend` zeros in the +// front and `zeros_to_append` zeros in the back. +StatusOr PadVectorWithZeros(HloInstruction* operand, + int64_t zeros_to_prepend, + int64_t zeros_to_append); + +// Broadcasts a zero value of type `element_type` into a tensor with element +// type `element_type` and dimension bounds `broadcast_dimensions`. The +// broadcast instruction is emitted into `computation`. +HloInstruction* BroadcastZeros(HloComputation* computation, + PrimitiveType element_type, + absl::Span broadcast_dimensions); + +// Same as above, but allows to specify the broadcast shape. +HloInstruction* BroadcastZeros(HloComputation* computation, + const Shape& broadcast_shape); + +// Same as above, but fill the tensor with ones. +HloInstruction* BroadcastOnes(HloComputation* computation, + PrimitiveType element_type, + absl::Span broadcast_dimensions); + +// Creates a HLO computation that takes arguments of type `domain` and produces +// a value of type `range`. +StatusOr> CreateComputationWithSignature( + absl::Span domain, const Shape& range, + absl::string_view name); + +// Expands a general degenerate reshape operation to a sequence of degenerate +// adding and removing reshapes that changes only a single dimension. +HloInstruction* ExpandDegenerateReshape(HloInstruction* inst); + +} // namespace xla + +#endif // XLA_SERVICE_HLO_CREATION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_cse.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_cse.h new file mode 100644 index 0000000000000000000000000000000000000000..a7f703d08f3d2404d291dfabbf5b7a1cd2216100 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_cse.h @@ -0,0 +1,58 @@ +/* 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_SERVICE_HLO_CSE_H_ +#define XLA_SERVICE_HLO_CSE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which performs common-subexpression elimination. Identical constants +// and identical instructions with the same operands are commoned. The pass +// iterates over the instructions in topological order which enables the pass to +// find arbitrarily large common expressions. +class HloCSE : public HloModulePass { + public: + // If is_layout_sensitive is true, then the simplifier preserves layout during + // transformation. Otherwise, layout is ignored. + // If ignore_control_dependencies is true, the pass will ignore control deps + // when replacing instructions with their equivalents. + explicit HloCSE(bool is_layout_sensitive, + bool only_fusion_computations = false, + bool ignore_control_dependencies = false) + : is_layout_sensitive_(is_layout_sensitive), + only_fusion_computations_(only_fusion_computations), + ignore_control_dependencies_(ignore_control_dependencies) {} + ~HloCSE() override = default; + absl::string_view name() const override { return "cse"; } + + // Run CSE on the given module. Returns whether the module was changed (common + // subexpressions were found and eliminated). + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const bool is_layout_sensitive_; + const bool only_fusion_computations_; + const bool ignore_control_dependencies_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_CSE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_dataflow_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_dataflow_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..d0cbb63c7d2d82c79c57f1e05bec2a50aae5b088 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_dataflow_analysis.h @@ -0,0 +1,368 @@ +/* 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. +==============================================================================*/ + +// Analysis for determining the possible set of values for all positions +// (instructions and ShapeIndexes) in the HLO module. Analysis is module-scoped +// tracking values across computation boundaries. + +#ifndef XLA_SERVICE_HLO_DATAFLOW_ANALYSIS_H_ +#define XLA_SERVICE_HLO_DATAFLOW_ANALYSIS_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/call_graph.h" +#include "xla/service/hlo_phi_graph.h" +#include "xla/shape_util.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Identifies one array input of an HloInstruction. +struct HloOperandIndex { + // The operand number in which the array value appears. + int64_t operand_number; + + // The shape index within the operand in which the array value appears. + ShapeIndex operand_index; + + bool operator==(const HloOperandIndex& other) const { + return operand_number == other.operand_number && + operand_index == other.operand_index; + } + + bool operator!=(const HloOperandIndex& other) const { + return !(*this == other); + } +}; + +// Analysis which identifies all HLO values and their uses in an HLO module. +class HloDataflowAnalysis { + public: + // Infrastructure for passing may-alias hints: HLO passes can populate the + // may-alias table. If an empty optional is returned, default rules are used. + // + // Must-alias rules (as defined by GetInPlaceInputOutputPairs) cannot be + // overriden using backend-specific overrides. + // + // The first parameter of the function should be the instruction, the + // second parameter should be an operand of the instruction. The third + // parameter should be the output index of the instruction. + using CanShareBuffer = std::function( + const HloInstruction* instr, const HloInstruction* operand, + const ShapeIndex& user_index)>; + + // Infrastructure for overriding whether an instruction defines a new value. + // + // The first parameter is the instruction and the second parameter is the + // output index. If an empty optional is used, default rules are used. If a + // ForwardedOperand object is returned, the value at the corresponding + // operand's index is used for the output, overriding all default logic. + struct ForwardedOperand { + int64_t operand_number; + ShapeIndex operand_index; + }; + using ForwardsValue = std::function( + const HloInstruction* instr, const ShapeIndex& index)>; + + // Runs dataflow analysis on the given module. Parameters: + // + // ssa_form : If true then new values are defined at the merge points of + // kWhile instructions. Abusing nomenclature somewhat, we call these "phi + // values". The merge is formed by the init value and loop backedge. The + // SSA form is minimal in that a new phi value is defined only if the + // merge point is reachable by multiple different values. The SSA form is + // also in loop-closed form in that no values defined inside of a loop + // (while body) is used outside of the loop. Example use of this ssa_form + // mode is to reason about live range interference of buffers. + // + // If ssa_form is false, then merge points do not define new + // values. Rather, the HloValueSet for the merge point contains the union + // of the merged HloValues. + // + // bitcast_defines_value : If true then the Bitcast HLO instruction defines + // a new HLO value in the analysis. If false then Bitcast forwards the + // value of its operand. + static StatusOr> Run( + const HloModule& module, bool ssa_form = false, + bool bitcast_defines_value = false, + const CanShareBuffer& can_share_buffer = nullptr, + const ForwardsValue& forwards_value = nullptr); + + // Returns true if 'instruction' defines an HLO value at the given shape index + // of its output. + bool ValueIsDefinedAt(const HloInstruction* instruction, + const ShapeIndex& index = {}) const; + + // Returns the HloValue defined by 'instruction' at the given shape index of + // its output. + // + // Precondition: ValueIsDefinedAt is true for this instruction and index. + const HloValue& GetValueDefinedAt(const HloInstruction* instruction, + const ShapeIndex& index = {}) const; + HloValue& GetValueDefinedAt(const HloInstruction* instruction, + const ShapeIndex& index = {}); + + // Returns the InstructionValueSet for the given instruction. + const InstructionValueSet& GetInstructionValueSet( + const HloInstruction* instruction) const; + InstructionValueSet& GetInstructionValueSet( + const HloInstruction* instruction); + + // Returns all values that are contained in the output of this instruction in + // a flattened set. + HloValueSet GetFlattenedValueSet(const HloInstruction* instruction) const; + + // Returns the HloValueSet for the given instruction at the given index or the + // given position. + const HloValueSet& GetValueSet(const HloInstruction* instruction, + const ShapeIndex& index = {}) const; + const HloValueSet& GetValueSet(const HloPosition& position) const; + HloValueSet& GetValueSet(const HloPosition& position); + HloValueSet& GetValueSet(const HloInstruction* instruction, + const ShapeIndex& index = {}); + + // Returns the unique value in the HloValueSet at the given instruction and + // shape index. CHECKs if the value set does not contain a exactly one value. + const HloValue& GetUniqueValueAt(const HloInstruction* instruction, + const ShapeIndex& index = {}) const { + return GetValueSet(instruction, index).GetUniqueValue(); + } + HloValue& GetUniqueValueAt(const HloInstruction* instruction, + const ShapeIndex& index = {}) { + return GetValue(GetValueSet(instruction, index).GetUniqueValue().id()); + } + + // Returns the HloValue with the given Id. + const HloValue& GetValue(HloValue::Id value_id) const; + HloValue& GetValue(HloValue::Id value_id); + + // Returns the total number of HloValues. + int64_t value_count() const { return values_.size(); } + + // Returns a vector of all HloValues stabily sorted by HloValue::Id. + const std::vector& values() const { return values_vector_; } + + // Returns the call graph used for computing the dataflow. + const CallGraph& call_graph() const { return *call_graph_; } + + std::string ToString() const; + + // Returns true if 'user' cannot possibly use the buffer at 'index' in + // 'operand'. Returns false otherwise. + // + // 'operand' does not have to be an operand of 'user'. This can be the + // case with indirect uses. + bool DoesNotUseOperandBuffer(const HloInstruction* operand, + const ShapeIndex& index, + const HloInstruction* user) const; + + // Returns true if 'user' (at 'user_index') can share a buffer with its + // operand 'operand' (at 'operand_index'). Returns false otherwise. + // + // REQUIRES: 'operand' is an operand of 'user'. + bool CanShareOperandBufferWithUser(HloInstruction* operand, + const ShapeIndex& operand_index, + HloInstruction* user, + const ShapeIndex& user_index) const; + + const HloModule& module() const { return module_; } + + // Returns true if the operation is an in-place operation and its operand 0 + // must alias with the output. + static bool IsInPlaceOperation(HloOpcode opcode); + + // Returns true if the operation is the start/done of an asynchronous + // operation, where the buffer used/produced by the op needs to stay alive + // until the asynchronous operation completes. + static bool IsAsynchronousOperationStart(HloOpcode opcode); + static bool IsAsynchronousOperationDone(HloOpcode opcode); + + // Returns the pairs of inputs and outputs that must share the same buffer, + // according to the aliasing rules for that instruction. + // + // This function only considers array values as inputs and outputs, so + // when tuples are present it "sees through" to the array values inside. The + // HloUse describing the input parameter contains not only the operand number + // but also a shape index describing its position inside a nested tuple shape + // (if any). Similarly, the output parameter is described by a shape index + // into the nested tuple shape (if any) of the output value. + // + // For example, for this hypothetical op: + // %foo = (f32[1], (f32[2], f32[3])) + // op((f32[4], f32[5]) %arg0, f32[6] %arg1) + // + // ... the results can include any of the 3 * 3 = 9 possible pairs of + // input and output arrays. + static std::vector> + GetInPlaceInputOutputPairs(const HloInstruction* instruction); + + // Verifies various invariants of the dataflow analysis. + Status Verify() const; + + private: + static bool AreTransitiveUsesElementwiseOrTuple(const HloInstruction* inst); + + HloDataflowAnalysis(const HloModule& module, bool ssa_form, + bool bitcast_defines_value = false, + const CanShareBuffer& can_share_buffer = nullptr, + const ForwardsValue& forwards_value = nullptr); + + // 1. During value propagation (Propagate function), always create phi + // values once it see multiple inputs merging at the same point. It then + // records those phi values as well as their inputs in a phi graph. + // + // 2. Post value propagation, Dataflow analysis can then do certain + // optimization(OptimizePhiValues) on the phi graph to prune uncessary phi + // nodes. + // + // Note that this applies in SSA form, and Both of the functions are + // guaranteed to exit. + // + void OptimizePhiValues(); + + // Returns a new HloValue defined at the given instruction and shape index. + HloValue* NewHloValue(HloInstruction* instruction, const ShapeIndex& index, + bool is_phi); + + // Marks the HloValue with the given ID for deletion. + void MarkValueForDeletion(HloValue::Id value_id); + + // Deletes all HloValues marked for deletion. Should be called after + // propagation is complete. + void DeleteMarkedValues(); + + // Constructs and initializes the InstructionValueSets of all instructions to + // contain exactly the HloValues defined by each instruction. These values can + // then propagated throughout the HLO graph by calling Propagate. + Status InitializeInstructionValueSets(); + + // Updates the value set of the given instruction based on the values flowing + // into the instruction (operands and cross-computation dataflow). + bool UpdateInstructionValueSet(HloInstruction* instruction); + + // Updates the value set for a particular instruction type. Returns whether + // the instruction value set changed. + bool UpdateBitcastValueSet(HloInstruction* bitcast); + bool UpdateCallValueSet(HloInstruction* call); + bool UpdateConditionalValueSet(HloInstruction* conditional); + bool UpdateCopyValueSet(HloInstruction* copy); + bool UpdateCustomCallValueSet(HloInstruction* custom_call); + bool UpdateDomainValueSet(HloInstruction* domain); + bool UpdateGetTupleElementValueSet(HloInstruction* gte); + bool UpdateParameterValueSet(HloInstruction* parameter); + // Async op propagation rules: + // - Operand of async-start to parameter of async wrapped computation and at + // index {0, operand_number} of async-start and async-update outputs. + // - Root of async wrapped computation to index {1} of async-start and + // async-update and index {} of async-done. + // - The contexts in indices {2+} of async-start to the same indices of + // async-update. + // + // As a result of this, the operands/outputs of async-start and async-done + // instructions share the same values as the parameters/roots of the async + // wrapped computation. + bool UpdateAsyncStartValueSet(HloInstruction* async_start); + bool UpdateAsyncUpdateValueSet(HloInstruction* async_update); + bool UpdateAsyncDoneValueSet(HloInstruction* async_done); + bool UpdateCopyStartValueSet(HloInstruction* copy_start); + bool UpdateCopyDoneValueSet(HloInstruction* copy_done); + bool UpdateOptimizationBarrierValueSet(HloInstruction* barrier); + bool UpdateRecvDoneValueSet(HloInstruction* recv_done); + bool UpdateSendValueSet(HloInstruction* send); + bool UpdateSetDimensionSizeValueSet(HloInstruction* set_dimension_size); + bool UpdateTupleValueSet(HloInstruction* tuple); + bool UpdateWhileValueSet(HloInstruction* xla_while); + bool UpdateAddDependencyValueSet(HloInstruction* add_dependency); + bool UpdateAllGatherStartValueSet(HloInstruction* all_gather_start); + bool UpdateAllGatherDoneValueSet(HloInstruction* all_gather_done); + bool UpdateAllReduceDoneValueSet(HloInstruction* all_reduce_done); + bool UpdateCollectivePermuteStartValueSet( + HloInstruction* collective_permute_start); + bool UpdateCollectivePermuteDoneValueSet( + HloInstruction* collective_permute_done); + + // Propagates the dataflow through the module. In particular, it propagates + // the HloValueSet from its defining instruction to the users of the + // instructions. + void Propagate(); + + // Returns the result of the SSA Phi function applied to the given inputs at + // the given instruction. + bool Phi(HloInstruction* instruction, + absl::Span inputs); + + // Updates the positions of the HloValues in the output of the given + // instruction. This should be called after the instruction value set of + // 'instruction' has been changed. 'prev_value_set' must point to the previous + // state of the value set prior to the change. 'prev_value_set' may be null if + // this is the first time positions are being computed. The previous state is + // necessary to efficiently remove positions which have been eliminated due to + // changes in the instructions' InstructionValueSet. + void UpdatePositionsOfValuesAt( + HloInstruction* instruction, const InstructionValueSet& new_value_set, + const InstructionValueSet* prev_value_set = nullptr); + + const HloModule& module_; + const bool ssa_form_; + const bool bitcast_defines_value_; + + std::unique_ptr call_graph_; + + // The map of all HloValues in the module. We pass around pointers to the + // mapped HloValues, so the underlying container must keep them valid despite + // mutations touching other map entries. + absl::flat_hash_map> values_; + + // A map from instruction to InstructionValueSet. + absl::flat_hash_map> + value_sets_; + + // Values marked for deletion during construction. We don't delete them + // immediately because references to them may remain in ValueSets temporarily + // during propagation. After construction, these values are deleted. + std::vector value_ids_to_delete_; + + // A vector containing all HloValues sorted by HloValue::Id. + std::vector values_vector_; + + // The Id to use for the next HloValue. + HloValue::Id next_value_id_ = 0; + + // An explicit graph holding phi values and edges. + PhiGraph phi_graph_; + + // Backend specific function that decides whether an instruction can share + // a buffer with its operand. + CanShareBuffer can_share_buffer_ = nullptr; + + ForwardsValue forwards_value_ = nullptr; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_DATAFLOW_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_dce.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_dce.h new file mode 100644 index 0000000000000000000000000000000000000000..96253713c3564b77e061151f1b7bfaaaab2bd173 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_dce.h @@ -0,0 +1,77 @@ +/* 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_SERVICE_HLO_DCE_H_ +#define XLA_SERVICE_HLO_DCE_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass which removes dead instructions from each computation in the module +// and removes dead computations from the module. +// +// An instruction is dead if it is not reachable from the root. A computation is +// dead if it is not the entry computation of the module and it is not reachable +// from the entry computation. +// +// This pass does not remove dead parameter instructions, as parameter +// instructions cannot be deleted. +class HloDCE : public HloModulePass { + public: + HloDCE() : remove_cross_partition_collective_ops_(false) {} + explicit HloDCE(bool remove_cross_partition_collective_ops) + : remove_cross_partition_collective_ops_( + remove_cross_partition_collective_ops) {} + ~HloDCE() override {} + absl::string_view name() const override { return "dce"; } + + // Run DCE on a computation. + static StatusOr RunOnComputation( + HloComputation* computation, bool remove_cross_partition_collective_ops); + + // Run the pass on the given module. Returns whether the module was changed + // (instructions were removed). + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Finds all computations that are not called by any instruction and removes + // them from the module. Returns whether any dead code was removed. + StatusOr RecursivelyRemoveDeadComputations( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + // Given a dead computation, decrements the ref count of all its called + // computations and checks if any of the subcomputations become dead after the + // removal. Returns whether all dead computations were successfully removed + // from the module. + Status RecursivelyRemoveDeadComputation( + HloModule* module, HloComputation* computation, + absl::flat_hash_map& live_call_counts); + + bool remove_cross_partition_collective_ops_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_DCE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_isolator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_isolator.h new file mode 100644 index 0000000000000000000000000000000000000000..59c36463427599843884e79ad83151812296ef00 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_isolator.h @@ -0,0 +1,59 @@ +/* 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_SERVICE_HLO_DOMAIN_ISOLATOR_H_ +#define XLA_SERVICE_HLO_DOMAIN_ISOLATOR_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Domain isolation is the task of placing kDomain instructions between HLO +// instructions having different sharding. A kDomain instruction is essentially +// used to break an HLO graph edge connecting two instructions with different +// sharding. If a set of connected instructions have all the same sharding, no +// kDomain instruction will be placed. +class HloDomainIsolator : public HloModulePass { + public: + // Creates a new kDomain instruction for the edge between the use instruction + // (the first HloInstruction argument), and the operand instruction (the + // third HloInstruction argument) if the interesting attribute of the + // instruction differences from the attribute of the root (the second + // HloInstruction argument). + // Returns nullptr in case no domain separation is necessary. + using DomainCreator = std::function; + using DomainCreatorFactory = std::function; + explicit HloDomainIsolator(DomainCreatorFactory creator_factory_); + + absl::string_view name() const override { return "domain_isolator"; } + + // Update domains for an instruction. + StatusOr UpdateDomains(HloInstruction* instruction); + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + DomainCreatorFactory creator_factory_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_DOMAIN_ISOLATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_map.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_map.h new file mode 100644 index 0000000000000000000000000000000000000000..2ab375fd3f260166b83d67209816ee0d478103a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_map.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_SERVICE_HLO_DOMAIN_MAP_H_ +#define XLA_SERVICE_HLO_DOMAIN_MAP_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.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_module.h" +#include "xla/statusor.h" +#include "tsl/platform/status.h" + +namespace xla { + +// The HloDomainMap splits a set of instructions within a module or computation, +// into different domains, separated by kDomain instructions. +// A domain is composed by a set of instructions which can reach each other via +// operand/user edges, without crossing a kDomain insutrction of a given kind. +// A domain never crosses computation boundaries. +class HloDomainMap { + public: + // Creates a new HloDomainMap, creating all the domains within the input + // computation, of the given kind. If domain_kind is not empty, only the + // kDomain instructions of domain_kind will be considered as separators. + // Otherwise every kDomain instruction will be splitting domains. + static StatusOr> Create( + HloComputation* computation, std::string domain_kind); + + // Creates a new HloDomainMap, creating all the domains within the input + // module, of the given kind. If domain_kind is not empty, only the + // kDomain instructions of domain_kind will be considered as separators. + // Otherwise every kDomain instruction will be splitting domains. + static StatusOr> Create( + HloModule* module, std::string domain_kind); + + // Retrieves all the domains the input module or computation are composed by. + const std::vector>& GetDomains() + const { + return instruction_domains_; + } + + // Checks whether two instructions are within the same domain. + bool InSameDomain(const HloInstruction* instruction1, + const HloInstruction* instruction2) const; + + // Checks whether instruction is a kDomain instruction of the kind we are + // currently processing. + bool IsDomainInstruction(const HloInstruction* instruction) const; + + // Retrieves the domain identifier of the instruction, or -1 in case + // instruction is not found within any domain. + int64_t GetDomainId(const HloInstruction* instruction) const; + + // Returns the unique id of the domain metadata for the domain the given + // instruction belongs to. The given instruction must not be a kDomain + // instruction since each domain instruction is associated with 2 domains. + int64_t GetDomainMetadataId(const HloInstruction* instruction) const; + + private: + // Map used for representing instruction ordering, i.e. + // order_map[a] < order_map[b] means a must be ordered before b. + using InstructionOrderMap = + absl::flat_hash_map; + + HloDomainMap(std::string domain_kind) + : domain_kind_(std::move(domain_kind)) {} + + // Check if the kDomain instruction is facing (via its operand link) another + // kDomain instruction of the same kind, hence defining an empty domain. + // If that is the case, create the empty domain and call the proper + // normalizer. + Status TryProcessEmptyDomain(HloInstruction* instruction); + + Status Populate(HloComputation* computation); + + // Inserts the provided domain into the ones tracked by this object, + // creating a new domain ID. + Status InsertDomain(std::unique_ptr domain); + + // From the given instruction, expands operand and user wise, the set of + // instructions which can be reached without crossing a kDomain instruction + // of the kind specified by domain_kind_. + // The domain data structure will be populated with all the reached + // instructions, and the boundaries of the domain, with the kDomain + // instructions encountered while expanding the reach. + Status ExpandDomain(HloInstruction* instruction, + DomainMetadata::Domain* domain) const; + + // Creates a domain data structure using the ExpandDomain() API. + StatusOr> CreateDomain( + HloInstruction* instruction, + const InstructionOrderMap& instructions_order) const; + + // Out of an instruction set, returns a vector of all the ones which are not + // a kDomain kind. + static std::vector MakeNonDomainInstructions( + const absl::flat_hash_set& instruction_set, + const InstructionOrderMap& instructions_order); + + // Populates domain_metadata_id_ that maps each HloInstruction to the unique + // ID of its associated domain metatadata. + Status PopulateDomainMetadataMap(); + + std::string domain_kind_; + std::vector> instruction_domains_; + absl::flat_hash_map instruction_to_domain_; + absl::flat_hash_map domain_metadata_id_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_DOMAIN_MAP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_remover.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_remover.h new file mode 100644 index 0000000000000000000000000000000000000000..25039fa0e666443bdf073e61a0f1536d459e4d74 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_remover.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_HLO_DOMAIN_REMOVER_H_ +#define XLA_SERVICE_HLO_DOMAIN_REMOVER_H_ + +#include "xla/hlo/ir/hlo_domain_metadata.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "tsl/platform/status.h" + +namespace xla { + +// Removes all the kDomain instructions of a given kind from the input module, +// and calls the normalizer to propagate the properties on the possibly new born +// instructions. +class HloDomainRemover : public HloModulePass { + public: + // Creates a new HloDomainRemover object tasked at removing all the kDomain + // instructions of a given kind. + // In case a reachable set (the set of instructions within a computation, + // which are mutually reachable via operand/user pathways) has all the + // instructions in it with the same attributes (ie, sharding), a normalizer + // function is tasked at applying attribute normalization on the instructions + // within such domain. + HloDomainRemover(absl::string_view kind, + std::function + normalizer) + : kind_(kind), normalizer_(std::move(normalizer)) {} + + absl::string_view name() const override { return "domain_remover"; } + + // Remove domains of a given kind which are used as users of a specific + // instruction. + static StatusOr RemoveExitDomains(HloInstruction* instruction, + absl::string_view domain_kind); + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + class RunContext; + + std::string kind_; + std::function + normalizer_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_DOMAIN_REMOVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_verifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_verifier.h new file mode 100644 index 0000000000000000000000000000000000000000..4ceb131f3862681622b2f3319ac83d78b3310e38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_domain_verifier.h @@ -0,0 +1,69 @@ +/* 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_SERVICE_HLO_DOMAIN_VERIFIER_H_ +#define XLA_SERVICE_HLO_DOMAIN_VERIFIER_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_domain_metadata.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_domain_map.h" +#include "xla/service/hlo_pass_interface.h" +#include "tsl/platform/status.h" + +namespace xla { + +// Verifies that the domain instructions are consistent, and the each domain is +// surrounded by the same metadata. +class HloDomainVerifier : public HloModulePass { + public: + HloDomainVerifier(std::vector kinds) + : kinds_(std::move(kinds)) {} + + absl::string_view name() const override { return "domain_verifier"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Verify that the whole kDomain frontier bounding the instruction reach set, + // has matching metadata. + // A kDomain instruction has two sides of metadata, a user facing and an + // operand facing. + // A reachable instruction set can make contact with a kDomain instruction on + // a user facing side (the kDomain is operand of the instruction), or on a + // operand facing side (the kDomain is user of the instruction). + // And depending on the contact side, the proper metadata object + // (user_side_metadata() vs. operand_side_metadata()) needs to be used for + // consistency checks. + // Returns the DomainMetadata pointer which surrounds the domain, and + // represents the common metadata within such domain. If the returned + // DomainMetadata pointer is nullptr, the input domain had no kDomain + // boundary. + static StatusOr VerifyDomain( + const DomainMetadata::Domain& domain); + + private: + class RunContext; + + std::vector kinds_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_DOMAIN_VERIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_execution_profile.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_execution_profile.h new file mode 100644 index 0000000000000000000000000000000000000000..306c81b43e0fa2a3f8c23dd480b0c61abeced85d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_execution_profile.h @@ -0,0 +1,177 @@ +/* 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_SERVICE_HLO_EXECUTION_PROFILE_H_ +#define XLA_SERVICE_HLO_EXECUTION_PROFILE_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/map_util.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_execution_profile_data.pb.h" +#include "xla/service/hlo_profile_printer.h" +#include "xla/types.h" + +namespace xla { + +class HloInstruction; + +// Maps all HloInstructions and HloComputations in an HloModule to integers. +// These integers form the contiguous range [0, total_count()). +class HloProfileIndexMap { + public: + // Scans `module` to populate this instance of HloProfileIndexMap. + explicit HloProfileIndexMap(const HloModule& module) + : HloProfileIndexMap(module, {}) {} + explicit HloProfileIndexMap(const HloModule& module, + absl::Span extra_metrics); + + HloProfileIndexMap(const HloProfileIndexMap&) = default; + HloProfileIndexMap(HloProfileIndexMap&&) = default; + + HloProfileIndexMap& operator=(const HloProfileIndexMap&) = default; + HloProfileIndexMap& operator=(HloProfileIndexMap&&) = default; + + size_t GetProfileIndexFor(const HloInstruction& instruction) const { + return FindOrDie(instruction_to_profile_idx(), &instruction); + } + + size_t GetProfileIndexFor(const HloComputation& computation) const { + return FindOrDie(computation_to_profile_idx(), &computation); + } + + size_t GetProfileIndexFor(const std::string& key) const { + return xla::FindOrDie(extra_metric_to_profile_idx(), key); + } + + size_t instruction_count() const { + return instruction_to_profile_idx().size(); + } + + size_t computation_count() const { + return computation_to_profile_idx().size(); + } + + size_t extra_metrics_count() const { + return extra_metric_to_profile_idx().size(); + } + + size_t total_count() const { + return instruction_count() + computation_count() + extra_metrics_count(); + } + + const absl::flat_hash_map& + instruction_to_profile_idx() const { + return instruction_to_profile_idx_; + } + + const absl::flat_hash_map& + computation_to_profile_idx() const { + return computation_to_profile_idx_; + } + + const absl::flat_hash_map& extra_metric_to_profile_idx() + const { + return extra_metric_to_profile_idx_; + } + + private: + absl::flat_hash_map + instruction_to_profile_idx_; + absl::flat_hash_map + computation_to_profile_idx_; + absl::flat_hash_map extra_metric_to_profile_idx_; +}; + +// Create an instance of `HloProfilePrinterData`. +std::unique_ptr CreateHloProfilePrinterData( + const HloProfileIndexMap& hlo_profile_index_map, + const HloCostAnalysis& cost_analysis, + absl::string_view entry_computation_name); + +// Describes how much time each HLO operation took. +// +// Each HloComputation takes a certain number of cycles. This class helps break +// down how much time each HLO took. +class HloExecutionProfile { + public: + HloExecutionProfile(const HloProfilePrinterData* hlo_profile_printer_data, + const HloProfileIndexMap* hlo_profile_index_map); + + // Record how many cycles this HLO took to execute. + void SetCyclesTakenBy(const HloInstruction* hlo, uint64_t cycles_taken); + + // Record how many cycles this HLO took to execute. + void SetCyclesTakenBy(size_t index, uint64_t cycles_taken); + + // Returns how many cycles this HLO took to execute. Profiling information + // may not be available for some instructions in which case zero is returned. + uint64_t GetCyclesTakenBy(const HloInstruction& hlo) const; + + // Returns how many cycles this HLO took to execute. Profiling information + // may not be available for some instructions in which case zero is returned. + uint64_t GetCyclesTakenBy(size_t index) const; + + // Return the number of cycles this computation took to execute. + uint64_t total_cycles_executed(const HloComputation& computation) const { + return profile_counters_[hlo_profile_index_map_.GetProfileIndexFor( + computation)]; + } + + // Record how many cycles a computation took to execute. + void set_total_cycles_executed(const HloComputation& computation, + uint64_t total_cycles_executed) { + profile_counters_[hlo_profile_index_map_.GetProfileIndexFor(computation)] = + total_cycles_executed; + } + + // Record extra metric. + void set_extra_metrics(const std::string& metric, uint64_t value) { + profile_counters_[hlo_profile_index_map_.GetProfileIndexFor(metric)] = + value; + } + + // Returns a version of the execution profile suitable for performance + // debugging; e.g. emits cycle counts, execution time at the nominal device + // frequency, and the effective throughput given the provided cost_analysis + // for the operations in a given computation. Returns an empty string if it + // wasn't possible to generate a printable version. + std::string ToString(float clock_rate_ghz) const { + return PrintHloProfile(hlo_profile_printer_data_, profile_counters_.data(), + clock_rate_ghz); + } + + std::vector* mutable_profile_counters() { + return &profile_counters_; + } + const std::vector& profile_counters() const { + return profile_counters_; + } + + HloExecutionProfileData ToProto() const; + + private: + const HloProfilePrinterData& hlo_profile_printer_data_; + const HloProfileIndexMap& hlo_profile_index_map_; + + // Stores per-Hlo profile counters. This is the only thing that changes when + // we execute an XLA computation. + std::vector profile_counters_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_EXECUTION_PROFILE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_execution_profile_data.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_execution_profile_data.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..03a5ee8b03c636e3ecb8641dec18914b494c091e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_execution_profile_data.pb.h @@ -0,0 +1,394 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/hlo_execution_profile_data.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_5fexecution_5fprofile_5fdata_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_5fexecution_5fprofile_5fdata_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/service/hlo_profile_printer_data.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fhlo_5fexecution_5fprofile_5fdata_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fhlo_5fexecution_5fprofile_5fdata_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fhlo_5fexecution_5fprofile_5fdata_2eproto; +namespace xla { +class HloExecutionProfileData; +struct HloExecutionProfileDataDefaultTypeInternal; +extern HloExecutionProfileDataDefaultTypeInternal _HloExecutionProfileData_default_instance_; +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::HloExecutionProfileData* Arena::CreateMaybeMessage<::xla::HloExecutionProfileData>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { + +// =================================================================== + +class HloExecutionProfileData final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloExecutionProfileData) */ { + public: + inline HloExecutionProfileData() : HloExecutionProfileData(nullptr) {} + ~HloExecutionProfileData() override; + explicit PROTOBUF_CONSTEXPR HloExecutionProfileData(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloExecutionProfileData(const HloExecutionProfileData& from); + HloExecutionProfileData(HloExecutionProfileData&& from) noexcept + : HloExecutionProfileData() { + *this = ::std::move(from); + } + + inline HloExecutionProfileData& operator=(const HloExecutionProfileData& from) { + CopyFrom(from); + return *this; + } + inline HloExecutionProfileData& operator=(HloExecutionProfileData&& 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 HloExecutionProfileData& default_instance() { + return *internal_default_instance(); + } + static inline const HloExecutionProfileData* internal_default_instance() { + return reinterpret_cast( + &_HloExecutionProfileData_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(HloExecutionProfileData& a, HloExecutionProfileData& b) { + a.Swap(&b); + } + inline void Swap(HloExecutionProfileData* 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(HloExecutionProfileData* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloExecutionProfileData* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloExecutionProfileData& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloExecutionProfileData& from) { + HloExecutionProfileData::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(HloExecutionProfileData* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloExecutionProfileData"; + } + protected: + explicit HloExecutionProfileData(::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 { + kProfileCountersFieldNumber = 2, + kPrinterDataFieldNumber = 1, + }; + // repeated int64 profile_counters = 2; + int profile_counters_size() const; + private: + int _internal_profile_counters_size() const; + public: + void clear_profile_counters(); + private: + int64_t _internal_profile_counters(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_profile_counters() const; + void _internal_add_profile_counters(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_profile_counters(); + public: + int64_t profile_counters(int index) const; + void set_profile_counters(int index, int64_t value); + void add_profile_counters(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + profile_counters() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_profile_counters(); + + // .xla.HloProfilePrinterData printer_data = 1; + bool has_printer_data() const; + private: + bool _internal_has_printer_data() const; + public: + void clear_printer_data(); + const ::xla::HloProfilePrinterData& printer_data() const; + PROTOBUF_NODISCARD ::xla::HloProfilePrinterData* release_printer_data(); + ::xla::HloProfilePrinterData* mutable_printer_data(); + void set_allocated_printer_data(::xla::HloProfilePrinterData* printer_data); + private: + const ::xla::HloProfilePrinterData& _internal_printer_data() const; + ::xla::HloProfilePrinterData* _internal_mutable_printer_data(); + public: + void unsafe_arena_set_allocated_printer_data( + ::xla::HloProfilePrinterData* printer_data); + ::xla::HloProfilePrinterData* unsafe_arena_release_printer_data(); + + // @@protoc_insertion_point(class_scope:xla.HloExecutionProfileData) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > profile_counters_; + mutable std::atomic _profile_counters_cached_byte_size_; + ::xla::HloProfilePrinterData* printer_data_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_5fexecution_5fprofile_5fdata_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// HloExecutionProfileData + +// .xla.HloProfilePrinterData printer_data = 1; +inline bool HloExecutionProfileData::_internal_has_printer_data() const { + return this != internal_default_instance() && _impl_.printer_data_ != nullptr; +} +inline bool HloExecutionProfileData::has_printer_data() const { + return _internal_has_printer_data(); +} +inline const ::xla::HloProfilePrinterData& HloExecutionProfileData::_internal_printer_data() const { + const ::xla::HloProfilePrinterData* p = _impl_.printer_data_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloProfilePrinterData_default_instance_); +} +inline const ::xla::HloProfilePrinterData& HloExecutionProfileData::printer_data() const { + // @@protoc_insertion_point(field_get:xla.HloExecutionProfileData.printer_data) + return _internal_printer_data(); +} +inline void HloExecutionProfileData::unsafe_arena_set_allocated_printer_data( + ::xla::HloProfilePrinterData* printer_data) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.printer_data_); + } + _impl_.printer_data_ = printer_data; + if (printer_data) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.HloExecutionProfileData.printer_data) +} +inline ::xla::HloProfilePrinterData* HloExecutionProfileData::release_printer_data() { + + ::xla::HloProfilePrinterData* temp = _impl_.printer_data_; + _impl_.printer_data_ = 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::HloProfilePrinterData* HloExecutionProfileData::unsafe_arena_release_printer_data() { + // @@protoc_insertion_point(field_release:xla.HloExecutionProfileData.printer_data) + + ::xla::HloProfilePrinterData* temp = _impl_.printer_data_; + _impl_.printer_data_ = nullptr; + return temp; +} +inline ::xla::HloProfilePrinterData* HloExecutionProfileData::_internal_mutable_printer_data() { + + if (_impl_.printer_data_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloProfilePrinterData>(GetArenaForAllocation()); + _impl_.printer_data_ = p; + } + return _impl_.printer_data_; +} +inline ::xla::HloProfilePrinterData* HloExecutionProfileData::mutable_printer_data() { + ::xla::HloProfilePrinterData* _msg = _internal_mutable_printer_data(); + // @@protoc_insertion_point(field_mutable:xla.HloExecutionProfileData.printer_data) + return _msg; +} +inline void HloExecutionProfileData::set_allocated_printer_data(::xla::HloProfilePrinterData* printer_data) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.printer_data_); + } + if (printer_data) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(printer_data)); + if (message_arena != submessage_arena) { + printer_data = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, printer_data, submessage_arena); + } + + } else { + + } + _impl_.printer_data_ = printer_data; + // @@protoc_insertion_point(field_set_allocated:xla.HloExecutionProfileData.printer_data) +} + +// repeated int64 profile_counters = 2; +inline int HloExecutionProfileData::_internal_profile_counters_size() const { + return _impl_.profile_counters_.size(); +} +inline int HloExecutionProfileData::profile_counters_size() const { + return _internal_profile_counters_size(); +} +inline void HloExecutionProfileData::clear_profile_counters() { + _impl_.profile_counters_.Clear(); +} +inline int64_t HloExecutionProfileData::_internal_profile_counters(int index) const { + return _impl_.profile_counters_.Get(index); +} +inline int64_t HloExecutionProfileData::profile_counters(int index) const { + // @@protoc_insertion_point(field_get:xla.HloExecutionProfileData.profile_counters) + return _internal_profile_counters(index); +} +inline void HloExecutionProfileData::set_profile_counters(int index, int64_t value) { + _impl_.profile_counters_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.HloExecutionProfileData.profile_counters) +} +inline void HloExecutionProfileData::_internal_add_profile_counters(int64_t value) { + _impl_.profile_counters_.Add(value); +} +inline void HloExecutionProfileData::add_profile_counters(int64_t value) { + _internal_add_profile_counters(value); + // @@protoc_insertion_point(field_add:xla.HloExecutionProfileData.profile_counters) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloExecutionProfileData::_internal_profile_counters() const { + return _impl_.profile_counters_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +HloExecutionProfileData::profile_counters() const { + // @@protoc_insertion_point(field_list:xla.HloExecutionProfileData.profile_counters) + return _internal_profile_counters(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloExecutionProfileData::_internal_mutable_profile_counters() { + return &_impl_.profile_counters_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +HloExecutionProfileData::mutable_profile_counters() { + // @@protoc_insertion_point(field_mutable_list:xla.HloExecutionProfileData.profile_counters) + return _internal_mutable_profile_counters(); +} + +#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_2fservice_2fhlo_5fexecution_5fprofile_5fdata_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_graph_dumper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_graph_dumper.h new file mode 100644 index 0000000000000000000000000000000000000000..0017e1f0347dd5cdaa9f17b827168bf65250bc17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_graph_dumper.h @@ -0,0 +1,138 @@ +/* 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_SERVICE_HLO_GRAPH_DUMPER_H_ +#define XLA_SERVICE_HLO_GRAPH_DUMPER_H_ + +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/types.h" +#include "xla/xla.pb.h" + +// This file contains routines for rendering HLO computations into a +// human-readable graphical format. +// +// Fundamentally all graphs are rendered using the DOT language, but they can be +// packaged four different ways: +// +// - as a raw DOT file, which can be rendered using `graphviz`. +// +// - as an HTML file with an embedded DOT file, which can be viewed in a +// browser using a version of graphviz compiled to JavaScript +// +// - as a URL hosted somewhere which somehow embeds the DOT file. +// +// - as an HTML page showing the fusion progress. +// +// Two last options are not implemented by default, but you can add a plugin to +// implement it via RegisterGraphToURLRenderer. +// +// TODO(jlebar): Rename this file to hlo_graph_renderer. + +namespace xla { + +inline constexpr char kRenderDotJS[] = R"( + + + + + +)"; + +// Different formats that a graph can be packaged as. +enum class RenderedGraphFormat { + kDot, + kHtml, + kUrl, +}; + +struct HloRenderOptions { + // Include the backend config string in the rendered graph. + bool show_backend_config = false; + + // Include the fusion subcomputations in the rendered graph. + bool show_fusion_subcomputations = true; +}; + +// Renders an HLO module as a human-readable visual graph. +// +// Note that this only works well for relatively small graphs (no more than a +// few hundred nodes). Beyond that, the dot is usually unrenderable, +// unreadable, or both. To view such graphs, use a tool such as +// interactive_graphviz, which calls RenderNeighborhoodAround to render subsets +// of a graph. +StatusOr RenderGraph( + const HloComputation& computation, absl::string_view label, + const DebugOptions& debug_options, RenderedGraphFormat format, + HloRenderOptions hlo_render_options = {}); + +// Like RenderGraph, but renders only nodes "near" the given node in the graph. +// +// The number of nodes dumped is controlled by the radius parameter, which +// (roughly) corresponds to the max distance a node may be from the primary node +// before it's omitted from the graph. +// +// The optional boundary specifies a set of boundary nodes, beyond which nodes +// will be omitted even if they are within the radius. +StatusOr RenderNeighborhoodAround( + const HloInstruction& node, int radius, RenderedGraphFormat format, + HloRenderOptions hlo_render_options = {}, + const absl::flat_hash_set& boundary = {}); + +// Renders nodes on any of the paths from `from` to `to`. If there are more +// than max_nodes on all paths, restricts to the max_nodes nodes on the shortest +// paths. +StatusOr RenderAllPathsFromTo( + const HloInstruction& from, const HloInstruction& to, int64_t max_nodes, + RenderedGraphFormat format, HloRenderOptions hlo_render_options = {}); + +// Registers the fusion state of the graph for future visualization using +// the kFusionVisulization render format. +// +// The `consumer` node defines the area which should be rendered: if left null, +// computation root is used by default. +// +// The `producer` remains `nullptr` if it's fused, or is set if the desire is to +// highlight it. +void RegisterFusionState(const HloComputation& computation, + absl::string_view label, + const HloInstruction& consumer, + const HloInstruction* producer = nullptr); + +// Registers a function which implements RenderedGraphFormat::kUrl. +// +// The input to the function is dot, and the output should be a URL or an error. +// +// There can only be one active renderer, and the last call to this function +// wins. +void RegisterGraphToURLRenderer( + std::function(absl::string_view dot)> renderer); + +// Generates a fusion explorer for the given computation using the data in +// fusion_visualizer_state. +StatusOr WrapFusionExplorer(const HloComputation& computation); + +} // namespace xla + +#endif // XLA_SERVICE_HLO_GRAPH_DUMPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_lexer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_lexer.h new file mode 100644 index 0000000000000000000000000000000000000000..031ec1ae295330c7c6f25c6348e7a68ac31885d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_lexer.h @@ -0,0 +1,216 @@ +/* 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_SERVICE_HLO_LEXER_H_ +#define XLA_SERVICE_HLO_LEXER_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/shape.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" +#include "tsl/platform/regexp.h" + +namespace xla { + +// Defines different kinds of tokens used by the HLO lexer. +// +// You shouldn't need to use this directly unless you're using HloLexer +// directly, and you probably don't need to do that. Use hlo_parser instead. +enum class TokKind { + // Markers + kEof, + kError, + + // Tokens with no info. + kEqual, // = + kComma, // , + kColon, // : + kAsterisk, // * + kOctothorp, // # + kPlus, // + + kTilde, // ~ + kLsquare, + kRsquare, // [ ] + kLbrace, + kRbrace, // { } + kLparen, + kRparen, // ( ) + kDots, // ... + + kArrow, // -> + kLeq, // <= + + // Keywords + kw_HloModule, + kw_ENTRY, + kw_ROOT, + kw_true, + kw_false, + kw_maximal, + kw_replicated, + kw_manual, + kw_last_tile_dim_replicate, + kw_shard_as, + kw_shard_like, + kw_unknown, + kw_inf, + + kNegInf, // -inf + + // Typed tokens. + kPrimitiveType, // F32, PRED, etc. + kName, // %foo + kAttributeName, // dimensions= + kDimLabels, // [0-9bf?]{2,}_[0-9io?]{2,}->[0-9bf?]{2,} + kDxD, // [0-9]+(x[0-9]+)+ + kPad, // [0-9]+_[0-9]+(_[0-9]+)?(x[0-9]+_[0-9]+(_[0-9]+)?)* + kIdent, // other identifiers + kString, // "abcd\"\n" + kInt, // 42 + kDecimal, // 4.2 +}; + +std::string TokKindToString(TokKind kind); + +// Lexer for the HloModule::ToString() format text. +// +// This class is meant to be used by hlo_parser.cc. You shouldn't need to use +// it directly. +class HloLexer { + public: + explicit HloLexer(absl::string_view buf) : buf_(buf) { + current_ptr_ = buf_.data(); + } + + TokKind Lex() { return token_state_.current_kind = LexToken(); } + + TokKind GetKind() const { return token_state_.current_kind; } + std::string GetStrVal() const { + switch (GetKind()) { + case TokKind::kName: + case TokKind::kAttributeName: + case TokKind::kDimLabels: + case TokKind::kDxD: + case TokKind::kPad: + case TokKind::kString: + case TokKind::kIdent: + return token_state_.str_val; + default: + LOG(FATAL) << "This token does not have string value"; + } + } + int64_t GetInt64Val() const { + CHECK(GetKind() == TokKind::kInt) << TokKindToString(GetKind()); + return token_state_.int64_val; + } + double GetDecimalVal() const { + CHECK(GetKind() == TokKind::kDecimal); + return token_state_.decimal_val; + } + PrimitiveType GetPrimitiveTypeVal() const { + CHECK(GetKind() == TokKind::kPrimitiveType); + return token_state_.primitive_type_val; + } + + typedef const char* LocTy; + + // Returns the location of the current token. + LocTy GetLoc() const { return token_state_.token_start; } + + // Returns the line and column of a location in the buffer. + std::pair GetLineAndColumn(LocTy location) const; + + // Returns the whole line given the location. + absl::string_view GetLine(LocTy loc) const; + + // Looks ahead one token and returns it. Lexer state is unchanged. + TokKind LookAhead(); + + // Lexes a string delimited by matching curly braces. Curlies contained + // inside double quotes don't count. + // + // Requires that you've already lexed the open curly brace. + // + // The returned string value includes the outer curlies. + // + // Returns TokKind::kString on success. + TokKind LexJsonDict(); + + private: + // Returns the current character. If it's neither the end of input buffer nor + // an invalid character, moves the pointer forward. + int GetNextChar(); + + // Returns the current character. + int PeekCurrentChar() const; + + // Creates string_view with the given begin and end. Exits if the begin > end, + // or it's out of the range of the current buffer. + absl::string_view StringViewFromPointers(const char* begin, + const char* end) const; + + // Returns true if the given ptr is dereferenceable within the range of the + // current buffer. + bool CanDereference(const char* ptr) const; + + TokKind LexToken(); + + TokKind LexIdentifier(); + TokKind LexPercent(); + TokKind LexShape(); + TokKind LexConstant(); + TokKind LexNumberOrPattern(); + TokKind LexString(); + + std::optional LexNanPayload(absl::string_view& consumable); + + absl::string_view buf_; + const char* current_ptr_; + + // Information about the current token. + struct TokenState { + const char* token_start = nullptr; + TokKind current_kind; + std::string str_val; + int64_t int64_val; + double decimal_val; + PrimitiveType primitive_type_val; + }; + TokenState token_state_; + + struct LineNoCacheTy { + const char* last_query; + unsigned line_no_of_query; + }; + // This caches the line number of the previous query. + mutable LineNoCacheTy line_no_cache_{nullptr, 0}; +}; + +// Does this string start with "{", end with "}", and contain valid-ish JSON +// in-between? If so, hlo_parser can parse e.g. backend_config={blah: "blah"} +// instead of the much uglier backend_config="{blah: \"blah\"}". +// +// (Technically we're not checking for fully-valid JSON, just something we can +// find the end of reasonably.) +bool LexesAsJsonDict(absl::string_view str); + +} // namespace xla + +#endif // XLA_SERVICE_HLO_LEXER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_memory_scheduler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_memory_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..2d61c077a50558e7a1ac83f13773a0a888cb3d1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_memory_scheduler.h @@ -0,0 +1,187 @@ +/* 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_SERVICE_HLO_MEMORY_SCHEDULER_H_ +#define XLA_SERVICE_HLO_MEMORY_SCHEDULER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_schedule.h" +#include "xla/service/hlo_alias_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/logical_buffer.h" +#include "xla/service/tuple_points_to_analysis.h" +#include "xla/statusor.h" + +namespace xla { + +// Postprocessor of the HloInstructionSequence. This is an opt-in postprocessing +// function to MemorySchedulerAlgorithm to enforce certain hlo schedule +// constraints desired for custom-calls. +using MemorySchedulerPostprocessor = + std::function; + +// A memory scheduler computes an execution sequence for the HLO instructions in +// 'computation' that minimizes peak memory, given a points-to analysis result +// that describes buffer aliasing, together with a target-specific size function +// that maps a tensor's logical size to its padded size. peak_memory (may be +// nullptr) is set to the peak memory of the resulting schedule according to the +// HeapSimulator. +// +// TODO(yunxing): Cleanup usage of TuplePointsToAnalysis. +typedef std::function( + HloComputation*, const TuplePointsToAnalysis&, const HloAliasAnalysis&, + const LogicalBuffer::SizeFunction&, + const absl::flat_hash_map&, + const MemorySchedulerPostprocessor&, + /*peak_memory*/ int64_t*)> + MemorySchedulerAlgorithm; + +// Scheduler for the entire module. +typedef std::function( + const HloModule*, const TuplePointsToAnalysis&, const HloAliasAnalysis&, + const LogicalBuffer::SizeFunction&, + const absl::flat_hash_set& execution_threads, + /*peak_memory*/ int64_t*)> + ModuleSchedulerAlgorithm; + +// Lift a computation scheduler into a module scheduler by calling the +// computation scheduler on all computations in a module. +ModuleSchedulerAlgorithm ComputationSchedulerToModuleScheduler( + const MemorySchedulerAlgorithm&, const MemorySchedulerPostprocessor& = {}); + +// List scheduler +StatusOr ListMemoryScheduler( + HloComputation* computation, + const TuplePointsToAnalysis& points_to_analysis, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const absl::flat_hash_map& + memory_by_computation, + const MemorySchedulerPostprocessor& postprocessor, int64_t* peak_memory); + +// DFS-order scheduler +StatusOr DFSMemoryScheduler( + HloComputation* computation, + const TuplePointsToAnalysis& points_to_analysis, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const absl::flat_hash_map& + memory_by_computation, + const MemorySchedulerPostprocessor& postprocessor, int64_t* peak_memory); + +// Naive Post Order scheduler +StatusOr PostOrderMemoryScheduler( + HloComputation* computation, + const TuplePointsToAnalysis& points_to_analysis, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const absl::flat_hash_map& + memory_by_computation, + const MemorySchedulerPostprocessor& postprocessor, int64_t* peak_memory); + +// The default scheduling algorithm. Runs the list scheduler, the DFS scheduler, +// and the post-order scheduler and chooses whichever returns a lower min- +// memory, not accounting for fragmentation. peak_memory (may be nullptr) is set +// to the peak memory of the resulting schedule according to the HeapSimulator. +StatusOr DefaultMemoryScheduler( + HloComputation* computation, + const TuplePointsToAnalysis& points_to_analysis, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const absl::flat_hash_map& + memory_by_computation, + const MemorySchedulerPostprocessor& postprocessor, int64_t* peak_memory); + +StatusOr DefaultModuleScheduler( + const HloModule* module, const TuplePointsToAnalysis& points_to_analysis, + const HloAliasAnalysis& alias_analysis, + const LogicalBuffer::SizeFunction& size_function, + const absl::flat_hash_set& execution_threads, + int64_t* peak_memory); + +// Returns an HloSchedule which seeks to minimize the memory required for the +// module. size_function is the function returning the number of bytes required +// for a LogicalBuffer. peak_memory (if not nullptr) is set to the largest peak +// memory (according to the HeapSimulator) of all computations in the module. +StatusOr ScheduleModule( + const HloModule* module, const LogicalBuffer::SizeFunction& size_function, + const ModuleSchedulerAlgorithm& algorithm = {}, + const absl::flat_hash_set& execution_threads = {}, + int64_t* peak_memory = nullptr); + +// Computes the schedule for a single computation. +// Currently only used by the GPU backend. +StatusOr ScheduleComputation( + HloComputation* computation, + const LogicalBuffer::SizeFunction& size_function, + const MemorySchedulerPostprocessor& postprocessor); + +// A pass which schedules the HLO instructions in a module. The HloModule's +// schedule field is set to the resulting HloSchedule using +// HloModule::set_schedule. +class HloMemoryScheduler : public HloModulePass { + public: + // size_function is the function returning the number of bytes required for a + // LogicalBuffer. algorithm is the memory scheduling algorithm to use. If not + // specified, then DefaultMemoryScheduler is used. + explicit HloMemoryScheduler(const LogicalBuffer::SizeFunction& size_function, + const ModuleSchedulerAlgorithm& algorithm = {}); + + ~HloMemoryScheduler() override = default; + + absl::string_view name() const override { return "hlo-memory-scheduler"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + LogicalBuffer::SizeFunction size_function_; + + ModuleSchedulerAlgorithm algorithm_; +}; + +// A pass which produces a naive, but correct schedule. The schedule is produced +// using a DFS traversal of the graph with no attempt to minimize memory use. +class HloTrivialScheduler : public HloModulePass { + public: + absl::string_view name() const override { return "hlo-trivial-scheduler"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +// A trivial pass which clears the schedule currently set on the +// HloModule. After this pass runs HloModule::has_schedule will return false. +class HloDescheduler : public HloModulePass { + public: + HloDescheduler() = default; + ~HloDescheduler() override = default; + absl::string_view name() const override { return "hlo-descheduler"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_MEMORY_SCHEDULER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_module_config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_module_config.h new file mode 100644 index 0000000000000000000000000000000000000000..bac9a26e28493665f2e3cbb744a20ea97d886932 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_module_config.h @@ -0,0 +1,489 @@ +/* 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_SERVICE_HLO_MODULE_CONFIG_H_ +#define XLA_SERVICE_HLO_MODULE_CONFIG_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/inlined_vector.h" +#include "absl/strings/string_view.h" +#include "xla/debug_options_flags.h" +#include "xla/service/computation_layout.h" +#include "xla/service/computation_placer.h" +#include "xla/service/hlo.pb.h" +#include "xla/xla.pb.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/protobuf.h" + +namespace xla { + +enum class FusionConfigCollection { + kOff, // Do not collect configuration. + kPerEdge, // Collect per-edge configuration. + kPerNode, // Collect per-node configuration. +}; + +// This class gathers all settings and values which affect the compiled +// executable outside of the HLO code itself. This include layouts of inputs and +// outputs to the module and settings such as HLO profiling. Together the +// HloModule and HloModuleConfig unambiguously determine a particular +// executable. +class HloModuleConfig { + public: + // Represents a pair of input and output of the entry computation that can be + // considered as the original and updated values of a variable maintained by + // the caller, and that can be transparently sharded by XLA as an internal + // optimization. If sharded, XLA will create separate sharding/unsharding + // programs, and the caller is responsible to call the XLA-generated + // sharding/unsharding programs before and after the sharded main program. + // + // If the variable is not updated and there is not a corresponding output, use + // {-1} as the output_shape_index. + // + // The sharding/unsharding programs will include all the input/output pairs in + // shardable_value_update_pairs() as a flat tuple in their inputs/outputs, + // sorted by (input_parameter_number, parameter_shape_index). + // + // A typical usage pattern is to shard the variables first, then repeatedly + // invoke the main program, and finally invoke the unsharding program before + // they are used in full-shape. + struct ShardableValueUpdatePair { + int64_t input_parameter_number; + ShapeIndex parameter_shape_index; + ShapeIndex output_shape_index; + }; + + // A configuration can be created either with, or without an entry + // ComputationLayout. The default ctor creates it without -- in this case + // accessing entry_computation_layout will CHECK-fail. The ctor accepting a + // ProgramShape creates a computation layout using this shape. + // The layouts in the ProgramShape will be reset to default unless + // ignore_layouts is set to false. + HloModuleConfig() { debug_options_ = DefaultDebugOptionsIgnoringFlags(); } + + explicit HloModuleConfig(const ProgramShape& program_shape, + bool ignore_layouts = true); + + explicit HloModuleConfig(ComputationLayout entry_computation_layout); + + // Convert an HloModuleConfig to or from a proto. + StatusOr ToProto() const; + static StatusOr> CreateFromProto( + const HloModuleConfigProto& proto); + + // Assigns the repeated ShardableValueUpdatePairProto field to the given + // values in 'update_pairs'. + static void AssignProtoShardableValueUpdatePairs( + tsl::protobuf::RepeatedPtrField* + proto_update_pairs, + const std::vector& + update_pairs); + + // Assigns shardable_value_update_pairs_ field in 'config' to the given values + // in 'pairs'. + static void AssignStructShardableValueUpdatePairs( + HloModuleConfig& config, + const tsl::protobuf::RepeatedPtrField& + pairs); + + // Checks if this config has an entry computation layout already. + bool has_entry_computation_layout() const { + return entry_computation_layout_.has_value(); + } + + // Sets the entry_computation_layout's parameter and result shapes for this + // config, according to the given program shape. The parameters and result + // are set to default layout. + void SetDefaultComputationLayout(const ProgramShape& program_shape); + + // Same as above but if the given program contains layout for parameters or + // result, the entry_computation_layout's layout is updated accordingly. + void SetComputationLayoutIfExists(const ProgramShape& program_shape); + + // Returns a constant reference to the layout of the entry computation. + // Assumes the layout was set. + const ComputationLayout& entry_computation_layout() const { + CHECK(entry_computation_layout_.has_value()); + return *entry_computation_layout_; + } + + // Returns a mutable pointer to the layout of the entry computation. + // Assumes the layout was set. + ComputationLayout* mutable_entry_computation_layout() { + CHECK(entry_computation_layout_.has_value()); + return &(*entry_computation_layout_); + } + + // Clears the entry computation layout. + void clear_entry_computation_layout() { + entry_computation_layout_ = std::nullopt; + } + + // Returns whether to enable HLO-level profiling. + bool hlo_profiling_enabled() const { + return debug_options_.xla_hlo_profile(); + } + + bool cpu_traceme_enabled() const { + return debug_options_.xla_cpu_enable_xprof_traceme(); + } + + // Sets/returns the module seed set during execution. + void set_seed(uint64_t seed) { seed_ = seed; } + uint64_t seed() const { return seed_; } + + // Set the launch id of the program. Launch id identifies a set of programs + // that should be launched together. + void set_launch_id(uint64_t launch_id) { launch_id_ = launch_id; } + int32_t launch_id() const { return launch_id_; } + + void set_replica_count(int64_t replica_count) { + replica_count_ = replica_count; + } + int64_t replica_count() const { return replica_count_; } + + void set_num_partitions(int64_t num_partitions) { + num_partitions_ = num_partitions; + } + int64_t num_partitions() const { return num_partitions_; } + + const std::vector& param_requires_broadcast_via_collectives() const { + return param_requires_broadcast_via_collectives_; + } + void set_param_requires_broadcast_via_collectives( + const std::vector require_broadcast) { + param_requires_broadcast_via_collectives_ = std::move(require_broadcast); + } + + void set_use_spmd_partitioning(bool use_spmd_partitioning) { + use_spmd_partitioning_ = use_spmd_partitioning; + } + bool use_spmd_partitioning() const { return use_spmd_partitioning_; } + + void set_use_auto_spmd_partitioning(bool use_auto_spmd_partitioning) { + use_auto_spmd_partitioning_ = use_auto_spmd_partitioning; + if (use_auto_spmd_partitioning) { + // TODO(yuemmawang) Remove this warning once auto sharding is thoroughly + // tested with fleetwide models. + LOG(WARNING) << "Warning: Using auto_spmd_partitioning. It is " + "experimental and may contain bugs!"; + LOG(INFO) << "Overwriting use_spmd_partitioning to true, because " + "use_auto_spmd_partitioning is true."; + set_use_spmd_partitioning(true); + } + } + bool use_auto_spmd_partitioning() const { + return use_auto_spmd_partitioning_; + } + + void set_auto_spmd_partitioning_mesh_shape(std::vector mesh_shape) { + auto_spmd_partitioning_mesh_shape_ = mesh_shape; + } + std::vector auto_spmd_partitioning_mesh_shape() const { + return auto_spmd_partitioning_mesh_shape_; + } + + void set_auto_spmd_partitioning_mesh_ids(std::vector mesh_ids) { + auto_spmd_partitioning_mesh_ids_ = mesh_ids; + } + std::vector auto_spmd_partitioning_mesh_ids() const { + return auto_spmd_partitioning_mesh_ids_; + } + + // If enabled, deduplicate equivalent hlos into function calls to reduce code + // size. + void set_deduplicate_hlo(bool deduplicate_hlo) { + deduplicate_hlo_ = deduplicate_hlo; + } + bool deduplicate_hlo() const { return deduplicate_hlo_; } + + void set_device_type(const std::string& device_type) { + device_type_ = device_type; + } + absl::string_view device_type() const { return device_type_; } + + // Return a string which unambiguously represents all the fields of this data + // structure. Used for generating a cache key for storing the compiled + // executable. + std::string compilation_cache_key() const; + + const DebugOptions& debug_options() const { return debug_options_; } + void set_debug_options(const DebugOptions& debug_options) { + debug_options_ = debug_options; + } + + // Sets/returns the number of intra op threads for this module. + void set_intra_op_parallelism_threads( + const int intra_op_parallelism_threads) { + intra_op_parallelism_threads_ = intra_op_parallelism_threads; + } + int64_t intra_op_parallelism_threads() const { + return intra_op_parallelism_threads_; + } + + // Checks if this config has a static device assignment. + bool has_static_device_assignment() const { + return static_device_assignment_.has_value(); + } + // Getter and setter of the compile-time known device assignment. + const DeviceAssignment& static_device_assignment() const { + CHECK(static_device_assignment_.has_value()); + return *static_device_assignment_; + } + void set_static_device_assignment(const DeviceAssignment& device_assignment) { + static_device_assignment_ = device_assignment; + } + + bool allow_separate_sharding_programs() const { + return allow_separate_sharding_programs_; + } + void set_allow_separate_sharding_programs( + bool allow_separate_sharding_programs) { + allow_separate_sharding_programs_ = allow_separate_sharding_programs; + } + + const std::vector& shardable_value_update_pairs() + const { + return shardable_value_update_pairs_; + } + void set_shardable_value_update_pairs( + std::vector pairs) { + shardable_value_update_pairs_ = std::move(pairs); + } + + // 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 content_aware_computation_sorting() const { + return content_aware_computation_sorting_; + } + void set_content_aware_computation_sorting( + bool content_aware_computation_sorting) { + content_aware_computation_sorting_ = content_aware_computation_sorting; + } + + FusionConfigCollection fusion_config_collection() const { + return fusion_config_collection_; + } + void set_fusion_config_collection( + FusionConfigCollection fusion_config_collection) { + fusion_config_collection_ = fusion_config_collection; + } + + const std::vector>& fusion_config() const { + return fusion_config_; + } + std::vector>* mutable_fusion_config() { + return &fusion_config_; + } + + const absl::flat_hash_map>& dot_config() + const { + return dot_config_; + } + absl::flat_hash_map>* mutable_dot_config() { + return &dot_config_; + } + + const std::vector>>& layout_config() const { + return layout_config_; + } + std::vector>>* mutable_layout_config() { + return &layout_config_; + } + + const std::vector>& phase_ordering_config() const { + return phase_ordering_config_; + } + std::vector>* mutable_phase_ordering_config() { + return &phase_ordering_config_; + } + + int phase_index() const { return phase_index_; } + void set_phase_index(const int phase_index) { phase_index_ = phase_index; } + + absl::Span allow_spmd_sharding_propagation_to_output() const { + return allow_spmd_sharding_propagation_to_output_; + } + void set_allow_spmd_sharding_propagation_to_output( + absl::Span data) { + return allow_spmd_sharding_propagation_to_output_.assign(data.begin(), + data.end()); + } + + const std::vector& memory_space_assignment_config() const { + return memory_space_assignment_config_; + } + std::vector* mutable_memory_space_assignment_config() { + return &memory_space_assignment_config_; + } + + int64_t GetAnalysisAllowance(absl::string_view pass_name) const { + auto it = analysis_allowance_map_.find(pass_name); + if (it == analysis_allowance_map_.end()) { + return -1; + } + return (*it).second; + } + void SetAnalysisAllowance(absl::string_view pass_name, int64_t allowance) { + analysis_allowance_map_[pass_name] = allowance; + } + + PrecisionConfig::Precision matrix_unit_operand_precision() const { + return matrix_unit_operand_precision_; + } + void set_matrix_unit_operand_precision( + PrecisionConfig::Precision matrix_unit_operand_precision) { + matrix_unit_operand_precision_ = matrix_unit_operand_precision; + } + + absl::string_view fdo_profile() const { return fdo_profile_; } + std::string* mutable_fdo_profile() { return &fdo_profile_; } + + int64_t device_memory_size() const { return device_memory_size_; } + void set_device_memory_size(int64_t device_memory_size) { + device_memory_size_ = device_memory_size; + } + + private: + // If you add new members, be sure to update compilation_cache_key and the + // HloModuleConfigProto. + // LINT.IfChange + std::optional entry_computation_layout_; + + // Module/graph-level seed handle. + uint64_t seed_ = 0; + + // Program id that identifies a set of program to be launched together. + int32_t launch_id_ = 0; + + // The number of replicas (data parallelism) to compile this binary for. + int64_t replica_count_ = 1; + + // The number of partitions (model parallelism) to compile this binary for. + int64_t num_partitions_ = 1; + + // Whether to broadcast args across all replicas. One entry per arg. + std::vector param_requires_broadcast_via_collectives_; + + // Whether to use SPMD (true) or MPMD (false) when num_partitions_ > 0 and XLA + // needs to partition the module. + bool use_spmd_partitioning_ = false; + + // Whether to automatically generate XLA shardings for SPMD partitioner. + bool use_auto_spmd_partitioning_ = false; + + // Mesh shape and mesh ids used by auto spmd partitioning. + std::vector auto_spmd_partitioning_mesh_shape_; + + std::vector auto_spmd_partitioning_mesh_ids_; + + // If enabled, deduplicate equivalent hlos into function calls to reduce code + // size. + bool deduplicate_hlo_ = false; + + // The target maximum parallelism at which to partition HLOs for parallel + // execution on the CPU backend. + int64_t intra_op_parallelism_threads_ = -1; + + std::string device_type_; + + DebugOptions debug_options_; + + // Compile-time known device assignment. + std::optional static_device_assignment_; + + bool allow_separate_sharding_programs_ = false; + + std::vector shardable_value_update_pairs_; + + bool alias_passthrough_params_ = false; + + bool content_aware_computation_sorting_ = false; + + FusionConfigCollection fusion_config_collection_ = + FusionConfigCollection::kOff; + + // Custom fusion configuration, where fusion_config_[c][v] control if node v + // in computation c must be fused to all its consumers (true) or not (false). + std::vector> fusion_config_; + + // Custom dot canonicalization configuration, where dot_config_[v] control + // how to convert dot operation named 'v' to convolution. + absl::flat_hash_map> dot_config_; + + // Layout configuration, where layout_config_[v][i] controls the layout + // decision i of operation v. + std::vector>> layout_config_; + + // Memory Space Assignment configuration, where + // memory_space_assignment_config_ controls the order of buffer intervals + // of this hlo module. + std::vector memory_space_assignment_config_; + + // Phase ordering configuration, where phase_ordering_config[v][i] controls + // whether a specific pass with index i (e.g. 0 = DCE, 1 = CSE, etc.) is + // inserted after pass v in pipeline. See tuning::PhaseOrderingConfig for + // details on what indices (i) correspond to which passes. + std::vector> phase_ordering_config_; + // Index (v) corresponding to current passes being added for phase ordering. + // This is the variable that stores state to allow us to use the same + // config across functions during compilation. + int phase_index_ = 0; + + // 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. + // Each boolean in the vector specifies if the propagation is allowed to + // change the sharding of a specific leaf in tuple output. One single boolean + // in the vector means we are applying this to every value in the tuple + // output. If the output is not a tuple then only a single value is valid + // here. + absl::InlinedVector allow_spmd_sharding_propagation_to_output_ = { + false}; + + // Each Hlo analysis is allowed at least a constant number of + // abstract cost units, before it is considered for early termination. + absl::flat_hash_map analysis_allowance_map_; + + PrecisionConfig::Precision matrix_unit_operand_precision_ = + PrecisionConfig::DEFAULT; + + // Profiling data for feedback directed optimizations. Note that this is not + // the only way to feed FDO data into the compiler and individual backends + // may choose to get FDO data by other means. + std::string fdo_profile_; + + int64_t device_memory_size_ = 0; + // LINT.ThenChange(//tensorflow/compiler/xla/xla.proto) +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_MODULE_CONFIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_module_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_module_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f74faeb287a53318ec51d0053be99de25e2f9ded --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_module_util.h @@ -0,0 +1,53 @@ +/* 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_SERVICE_HLO_MODULE_UTIL_H_ +#define XLA_SERVICE_HLO_MODULE_UTIL_H_ + +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/service/compiler.h" +#include "xla/service/hlo_module_config.h" +#include "xla/shape.h" +#include "xla/status.h" +#include "xla/statusor.h" + +namespace xla { + +// Creates an HloModuleConfig for a given program shape and arguments. +// If execution_options does not set num_replicas, default_num_replicas is used. +// num_threads is optional; if not given, intra_op_parallelism_threads not set. +// aot_options is optional; if not given a default is used. +StatusOr> CreateModuleConfig( + const ProgramShape& program_shape, + absl::Span argument_shapes, + const ExecutionOptions* execution_options, int default_num_replicas, + std::optional num_threads = std::nullopt, + const AotCompilationOptions* aot_options = nullptr); + +typedef std::function DeviceShapeRepresentationFn; + +// Update entry computation's computation layout by translating each shape +// with shape_representation_fn(shape). It can be used for example to add +// tiling info for each shape. +void UpdateEntryComputationLayout( + HloModule* module, DeviceShapeRepresentationFn shape_representation_fn, + bool empty_tiles_only = true); +} // namespace xla + +#endif // XLA_SERVICE_HLO_MODULE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_ordering.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_ordering.h new file mode 100644 index 0000000000000000000000000000000000000000..c1d255bc0f8cd756994497134d56511c7d45b052 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_ordering.h @@ -0,0 +1,243 @@ +/* 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_SERVICE_HLO_ORDERING_H_ +#define XLA_SERVICE_HLO_ORDERING_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_reachability.h" +#include "xla/hlo/ir/hlo_schedule.h" +#include "xla/service/call_graph.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_value.h" +#include "xla/types.h" + +namespace xla { + +// Base class for describing a partial ordering of HLO instructions. Used to +// determine live range overlap of HLO instruction output buffers. +class HloOrdering { + public: + explicit HloOrdering(const HloModule* module) + : module_(module), call_graph_(CallGraph::Build(module)) {} + virtual ~HloOrdering() = default; + + // Specify the ordering constraints between a pair of instructions a and b. + enum class ExecutionConstraint { + // Indicate a and b are the same instruction; + kIsSame, + // Indicate a runs before b starts; + kRunBeforeStart, + // Indicate a runs before b ends but after b starts, e.g., when b is a + // conditional or while loop; + kRunBeforeEnd, + // Only one of a or b runs each time their common ancestor is evaluated, + // and a is in an earlier branch than b. + kRunExclusiveBefore, + // Only one of a or b runs each time, and a is in a later branch than b. + kRunExclusiveAfter, + // Indicate a runs after b ends. + kRunAfter, + // An order cannot be detrermined as a and b do not have a common ancestor. + kUnordered, + }; + // Return the execution constraint between a and b. + HloOrdering::ExecutionConstraint GetExecutionConstraint( + const HloInstruction* a, const HloInstruction* b) const; + + // Returns true if instruction 'a' executes before instruction 'b'. This is + // not reflexive, that is, an instruction does not execute before itself. + bool ExecutesBefore(const HloInstruction* a, const HloInstruction* b) const; + + // Returns whether the value 'a' is defined before the value 'b' under the + // given ordering. + bool IsDefinedBefore(const HloValue& a, const HloValue& b) const; + + // Returns whether the given use is before the given value definition under + // the given ordering. Set use_is_always_before_def_in_same_instr to false if + // you want the analysis to always consider a use at an instruction's operand + // to be strictly before that instructions definition. The configuration needs + // to be false when result will be used to remove unnecessary copy + // instructions, due to additional buffer sharing constraints. + bool UsesBeforeValueDefinition( + absl::Span uses, const HloValue& value, + const HloDataflowAnalysis& dataflow, + bool use_is_always_before_def_in_same_instr = false) const; + // Returns whether the given values interfere. Two values interfere if they + // may both be simultaneously live. + bool MayInterfere(const HloValue& a, const HloValue& b, + const HloDataflowAnalysis& dataflow) const; + + // Returns true if the live range of the given value 'a' is strictly before + // the live range of value 'b' using the given HLO ordering. + bool LiveRangeStrictlyBefore( + const HloValue& a, const HloValue& b, const HloDataflowAnalysis& dataflow, + bool use_is_always_before_def_in_same_instr = false) const; + + // Returns the sequential instruction order for the given computation, or + // nullptr if the computation does not have a sequential ordering. + virtual const HloInstructionSequence* SequentialOrder( + const HloComputation& computation) const = 0; + + // Return the call graph of the module used to compute ordering. + const CallGraph& call_graph() const { return *call_graph_; } + + virtual std::string ToString() const = 0; + + protected: + // Returns true if instruction 'a' executes before instruction 'b'. + // Precondition: 'a' and 'b' are in the same computation. + // + // Derived classes should implement this method for determining order of + // instructions in the same computation. ExecutesBefore() analyzes the + // callgraph and uses this method to determine ordering of instructions in + // different computations. + virtual bool ExecutesBeforeInSameComputation( + const HloInstruction* a, const HloInstruction* b) const = 0; + + const HloModule* module_; + + std::unique_ptr call_graph_; +}; + +// Base class for partial orderings implemented by a map of predecessors for +// each instruction. Subclasses should fill in predecessors_. +class PredecessorHloOrdering : public HloOrdering { + public: + ~PredecessorHloOrdering() override = default; + + // Returns nullptr indicating the computation does not have a sequential + // ordering. + const HloInstructionSequence* SequentialOrder( + const HloComputation& computation) const override { + return nullptr; + } + + HloReachabilityMap& reachability_map(const HloComputation* computation) { + return *predecessors_.at(computation); + } + const HloReachabilityMap& reachability_map( + const HloComputation* computation) const { + return *predecessors_.at(computation); + } + + protected: + explicit PredecessorHloOrdering(const HloModule* module); + std::string ToStringHelper(const std::string& name) const; + + bool ExecutesBeforeInSameComputation(const HloInstruction* a, + const HloInstruction* b) const override; + + // For each computation in the module, this is the set of the instruction's + // predecessors. An instruction is an element of its own predecessor set. + // + // Subclasses should fill this in to define the desired ordering. + absl::flat_hash_map> + predecessors_; +}; + +// An HLO ordering based on data dependencies in the HLO graph. In this partial +// order, instruction A executes before instruction B only if there is a path +// from A to B in the HLO graph. For example, given the following graph: +/* + param + / \ + negate exp + \ / + add +*/ +// DependencyHloOrdering gives the following executes-before relations: +// param executes before negate, exp, and add +// negate executes before add +// exp executes before add +// add executes before nothing +// negate and exp are not ordered because the dependencies allow either to +// execute before the other (or in parallel). DependencyHloOrdering ordering +// allows maximum parallelism and enables any execution order which satisfies +// data dependencies. This requires pessimistic assumptions about buffer live +// ranges and can result in more memory used than more constrained orderings. +class DependencyHloOrdering : public PredecessorHloOrdering { + public: + explicit DependencyHloOrdering(const HloModule* module); + ~DependencyHloOrdering() override = default; + + std::string ToString() const override; +}; + +// An HLO ordering based on a total order of instructions in each computation. +// The computation total order is a sequencing of all of its instructions in +// the computation (eg, {inst0, inst1, inst2,...}) as in single-threaded +// execution. For example, given the following HLO graph: +/* + param + / \ + negate exp + \ / + add +*/ +// and the following sequence: +// +// {param, negate, exp, add} +// +// SequentialHloOrdering gives the following executes-before relations: +// param executes before negate, exp, and add +// negate executes before exp and add +// exp executes before add +// add executes before nothing +// This is more constrained than DependencyHloOrdering in this example because +// negate and exp are ordered (negate before exp). This enables param to share +// the same buffer as exp (param buffer is dead after exp). Generally, this +// ordering enables more buffer sharing (reduced memory usage) because buffer +// interference is reduced relative to DependencyHloOrdering. +class SequentialHloOrdering : public HloOrdering { + public: + explicit SequentialHloOrdering(const HloSchedule& schedule); + explicit SequentialHloOrdering(HloSchedule&& schedule); + ~SequentialHloOrdering() override = default; + + // Returns the sequential instruction order for the given computation. + const HloInstructionSequence* SequentialOrder( + const HloComputation& computation) const override; + + std::string ToString() const override; + + protected: + void Initialize(); + + bool ExecutesBeforeInSameComputation(const HloInstruction* a, + const HloInstruction* b) const override; + + const HloSchedule schedule_; + + // The position of every instruction in the HLO module in its respective + // computation sequence (a value of zero indicates the instruction is first in + // the sequence, etc). Instructions from all computations are contained in + // this map so more than one instruction may have the same position + // value. This is not a problem because ExecutesBefore also verifies + // instructions are in the same computation. + absl::flat_hash_map order_position_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_ORDERING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_parser.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_parser.h new file mode 100644 index 0000000000000000000000000000000000000000..b3a4633f7bfe4cc3f13db46976fcb501bb2edf06 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_parser.h @@ -0,0 +1,105 @@ +/* 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_SERVICE_HLO_PARSER_H_ +#define XLA_SERVICE_HLO_PARSER_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_lexer.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// For details about the syntax accepted by this parser, see +// g3doc/hlo_parser.md. + +// Given a string in the HloModule::ToString() format, parses the string and +// creates a HloModule with the given config. +// Note: Tests derived from HloTestBase should use +// ParseAndReturnVerifiedModule() instead! +StatusOr> ParseAndReturnUnverifiedModule( + absl::string_view str, const HloModuleConfig& config); + +// Given a string in the HloModule::ToString() format, parses the string and +// creates a HloModule with default config. +// Note: Tests derived from HloTestBase should use +// ParseAndReturnVerifiedModule() instead! +StatusOr> ParseAndReturnUnverifiedModule( + absl::string_view str); + +// Parses sharding from str. str is supposed to contain the body of the +// sharding, i.e. just the rhs of the "sharding={...}" attribute string, e.g., +// "{replicated}". +StatusOr ParseSharding(absl::string_view str); + +// Parses frontend attributes from str. str is supposed to contain the body of +// the frontend attributes , i.e. just the rhs of the +// "frontend_attributes={...}" attribute string, e.g., +// "{attr_a=a,attr_b=b}". +StatusOr ParseFrontendAttributes(absl::string_view str); + +// Parses statistics viz from str. str is supposed to contain the body of the +// statistics visualization, i.e. just the rhs of the "statistics={...}" +// attribute string, e.g., "{visualizing_index=1,nan_percent=50}". +StatusOr ParseStatisticsViz(absl::string_view str); + +// Parses parameter replication from str. str is supposed to contain the body of +// the parameter replication, i.e. just the rhs of the +// "parameter_replication={...}" attribute string, e.g., "{true, false}". +StatusOr> ParseParameterReplication(absl::string_view str); + +// Parses the result of window_util::ToString(const Window&). +StatusOr ParseWindow(absl::string_view str); + +// Parses the result of ConvolutionDimensionNumbersToString(), e.g. +// "b0f_0io->b0f". +StatusOr ParseConvolutionDimensionNumbers( + absl::string_view str); + +// Parses the result of PaddingConfigToString(), e.g. "0_0x1_1". +StatusOr ParsePaddingConfig(absl::string_view str); + +// Parses and returns a Shape::ToString-format string. +StatusOr ParseShape(absl::string_view str); + +// Parses and returns a std::vector from str. str is supposed to +// contain a list of the replica groups, i.e. just the rhs of the +// "replica_groups={...}" attribute string, e.g., "{{0,1}, {2,3}}". +StatusOr> ParseReplicaGroupsOnly( + absl::string_view str); + +class HloParser { + public: + // Runs the parser and constructs the resulting HLO in the given (empty) + // HloModule. Returns the error status in case an error occurred. + virtual Status Run(HloModule* module) = 0; + virtual ~HloParser() {} + + private: + static std::unique_ptr CreateHloParserForTests( + absl::string_view str); + friend class VerifiedHloModule; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_PARSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_fix.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_fix.h new file mode 100644 index 0000000000000000000000000000000000000000..2b62053b3b8775c940dfd8db58bae13e0b1df243 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_fix.h @@ -0,0 +1,134 @@ +/* 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_SERVICE_HLO_PASS_FIX_H_ +#define XLA_SERVICE_HLO_PASS_FIX_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_module_group.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/status_macros.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { + +// Do an HLO pass to a fix point. +template +class HloPassFix : public Pass { + public: + static_assert(std::is_base_of::value, + "Pass must be a subclass of HloPassInterface"); + using RunState = HloPassInterface::RunState; + template + explicit HloPassFix(Args&&... args) : Pass(args...) {} + + Status RunOnChangedComputations(HloModule* module, RunState* outer_run_state, + const absl::flat_hash_set& + execution_threads) override { + RunState run_state; + run_state.changed_last_iteration = outer_run_state->changed_last_iteration; + TF_RETURN_IF_ERROR(RunToFixPoint(module, &run_state, execution_threads)); + outer_run_state->changed_this_iteration.insert(run_state.changed.begin(), + run_state.changed.end()); + return OkStatus(); + } + + using HloPassInterface::Run; + StatusOr Run(HloModule* module, + const absl::flat_hash_set& + execution_threads) override { + RunState run_state(module); + TF_RETURN_IF_ERROR(RunToFixPoint(module, &run_state, execution_threads)); + return !run_state.changed.empty(); + } + + using HloPassInterface::RunOnModuleGroup; + StatusOr RunOnModuleGroup(HloModuleGroup* module_group, + const absl::flat_hash_set& + execution_threads) override { + bool changed = false; + bool changed_this_iteration = true; + int64_t iteration_count = 0; + VLOG(3) << "Running HloPassFix."; + while (changed_this_iteration) { + TF_ASSIGN_OR_RETURN( + changed_this_iteration, + Pass::RunOnModuleGroup(module_group, execution_threads)); + changed |= changed_this_iteration; + VLOG(3) << "changed_this_iteration: " << changed_this_iteration; + ++iteration_count; + if (iteration_count == kIterationLimit) { + VLOG(1) << "Unexpectedly high number of iterations in HLO passes, " + "exiting fixed point loop."; + // Return false in case this is fixed point is nested. + return false; + } + } + return changed; + } + + private: + Status RunToFixPoint( + HloModule* module, RunState* run_state, + const absl::flat_hash_set& execution_threads) { + VLOG(3) << "Running HloPassFix on " << Pass::name(); + while (!run_state->changed_last_iteration.empty()) { + TF_RETURN_IF_ERROR( + RunOnChangedComputationsOnce(module, run_state, execution_threads)); + VLOG(3) << Pass::name() << " iteration " << run_state->iteration + << " changed_this_iteration: " + << !run_state->changed_last_iteration.empty(); + run_state->IncrementIteration(); + if (run_state->iteration == kIterationLimit) { + VLOG(1) << "Unexpectedly high number of iterations in HLO passes '" + << Pass::name() << "' for module '" << module->name() + << "'. Exiting fixed point loop."; + // Clear changed and abort in case this is fixed point is nested. + run_state->changed.clear(); + break; + } + } + return OkStatus(); + } + + Status RunOnChangedComputationsOnce( + HloModule* module, RunState* run_state, + const absl::flat_hash_set& execution_threads) { + // If Pass overrides RunOnChangedComputations, just forward to it. + if (!std::is_same::value) { + return Pass::RunOnChangedComputations(module, run_state, + execution_threads); + } + // If Pass does not override the default + // HloPassInterface::RunOnChangedComputations that calls into + // HloPassFix::Run, avoid infinite recursion. + TF_ASSIGN_OR_RETURN(bool changed, Pass::Run(module, execution_threads)); + if (changed) { + auto computations = module->computations(execution_threads); + run_state->changed_this_iteration.insert(computations.begin(), + computations.end()); + } + return OkStatus(); + } +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_PASS_FIX_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..d3b5c34078b6b081501b4f07ecce079d7ce7bc27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_interface.h @@ -0,0 +1,183 @@ +/* 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_SERVICE_HLO_PASS_INTERFACE_H_ +#define XLA_SERVICE_HLO_PASS_INTERFACE_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_module_group.h" +#include "xla/status_macros.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { + +// Base class for HLO passes. These are used with the HloPassPipeline to +// organize a sequence of passes. An HLO pass should not extend this class +// directly; it should extend HloModulePass or HloModuleGroupPass. +class HloPassInterface { + public: + // Struct that holds states of pass runs across multiple iterations. + struct RunState { + // The current iteration number. + int iteration = 0; + // Set of all changed computations from all pass runs using this state. + absl::flat_hash_set changed; + // Set of changed computation from previous iteration. + absl::flat_hash_set changed_last_iteration; + // Set of changed computation from current iteration. + absl::flat_hash_set changed_this_iteration; + + RunState() = default; + explicit RunState(HloModule* module) + : changed_last_iteration(module->computations().begin(), + module->computations().end()) {} + + // Transition to the next iteration. + // + // Depending on the pass implmentation, one iteration includes all the work + // done between two IncrementIteration calls, there can be arbitrary number + // of passes that ran arbitrary times with this state. + void IncrementIteration() { + using std::swap; + changed.insert(changed_this_iteration.begin(), + changed_this_iteration.end()); + swap(changed_last_iteration, changed_this_iteration); + changed_this_iteration.clear(); + ++iteration; + } + }; + virtual ~HloPassInterface() = default; + virtual absl::string_view name() const = 0; + + // Run the pass on the given HLO module with specified execution_threads. + // Empty execution_threads list means all execution_threads are included. + // Returns whether it modified the module. Note that due to C++ inheritance + // hides overloaded function, Run(HloModule* module) is not a member function + // of a subclass unless it's explicitly brought to the subclass besides + // implementing the virtual version, for instance, + // + // class MyNewPass : public HloModulePass { + // public: + // MyNewPass(); + // absl::string_view name() const override { return "my-new-pass"; } + // + // using HloPassInterface::Run; + // StatusOr Run( + // HloModule* module, + // const absl::flat_hash_set& execution_threads) + // override; + // }; + // + StatusOr Run(HloModule* module) { + return Run(module, /*execution_threads=*/{}); + } + virtual StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) = 0; + + // Run the pass on computation on changed computations from last iteration in + // given HLO module for specified execution_threads, with caller provided + // RunState which holds the state information across multiple iterations. + // + // NOTE: This is a temporary default implementation that conservatively treats + // all computations as changed. Eventually all passes should override this + // method instead of Run() and Run() will call into this method instead. + virtual Status RunOnChangedComputations( + HloModule* module, RunState* run_state, + const absl::flat_hash_set& execution_threads) { + TF_ASSIGN_OR_RETURN(bool changed, Run(module, execution_threads)); + if (changed) { + auto computations = module->computations(execution_threads); + run_state->changed_this_iteration.insert(computations.begin(), + computations.end()); + } + return OkStatus(); + } + + // Run the pass on the given HLO module group for specified + // `execution_threads`. Empty `execution_threads` list means all execution + // threads are included. Returns whether it modified the module group. + // Ideally, the module group variant would be named "Run" as well, but C++ + // does not handle overloaded virtual methods well. + // + // Note that due to C++ inheritance hides overloaded function, + // RunOnModuleGroup(HloModuleGroup* module_group) is not a member function of + // a subclass unless it's explicitly brought to the subclass besides + // implementing the virtual version, for instance, + // + // class MyNewPass : public HloModuleGroupPass { + // public: + // MyNewPass(); + // absl::string_view name() const override { return "my-new-pass"; } + // + // using HloPassInterface::RunOnModuleGroup; + // StatusOr RunOnModuleGroup( + // HloModuleGroup* module_group, + // const absl::flat_hash_set& execution_threads) + // override; + // }; + // + StatusOr RunOnModuleGroup(HloModuleGroup* module_group) { + return RunOnModuleGroup(module_group, /*execution_threads=*/{}); + } + virtual StatusOr RunOnModuleGroup( + HloModuleGroup* module_group, + const absl::flat_hash_set& execution_threads) = 0; + + virtual bool IsPassPipeline() { return false; } +}; + +// Base class for passes which are module-scoped. +class HloModulePass : public HloPassInterface { + public: + // Runs the pass on a module group by iterating through each module in the + // group. + StatusOr RunOnModuleGroup(HloModuleGroup* module_group, + const absl::flat_hash_set& + execution_threads) override { + bool changed = false; + for (HloModule* module : module_group->modules()) { + TF_ASSIGN_OR_RETURN(bool module_changed, Run(module, execution_threads)); + changed |= module_changed; + } + return changed; + }; + + // Update the layout of a Shape to one that is supported by a given backend. + // One can call this function after modifying the Shape in case that modifying + // the Shape requires changes to the layout for the given Backend. + // + // TODO(b/129084868): Make this Backend dependent instead of requiring + // deriving from the pass and overriding this function. + virtual void UpdateLayout(Shape* shape) {} +}; + +// Base class for passes which are module-group scoped. These passes cannot run +// on an HLO module. +class HloModuleGroupPass : public HloPassInterface { + public: + StatusOr Run(HloModule* module, + const absl::flat_hash_set& + execution_threads) override { + return InternalError("Module group pass cannot be run on a module"); + } +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_PASS_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_pipeline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..2fc9ded2afc2fdf62daf19d363240353469a9109 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_pass_pipeline.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_SERVICE_HLO_PASS_PIPELINE_H_ +#define XLA_SERVICE_HLO_PASS_PIPELINE_H_ + +#include +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/compilation_stats.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { + +class PhaseOrderPipeline; + +// Pipeline of HLO passes. +class HloPassPipeline : public HloPassInterface { + public: + explicit HloPassPipeline(const std::string& name, + CompilationStats* compilation_stats = nullptr) + : name_(name), compilation_stats_(compilation_stats) { + if (compilation_stats == nullptr) { + empty_compilation_stats_ = CompilationStats::MakeNoopStats(); + compilation_stats_ = empty_compilation_stats_.get(); + } + } + absl::string_view name() const override { return name_; } + + // Add a pass to the pipeline. It should be called with the arguments for the + // pass constructor: + // + // pipeline.AddPass(constructor_arg1, constructor_arg2); + // + // Returns a reference to the added pass. + template + T& AddPass(Args&&... args) { + CHECK(!run_called_) << "AddPass cannot be called after Run"; + auto pass = new T(std::forward(args)...); + passes_.push_back(std::unique_ptr(pass)); + return *pass; + } + + // Add an invariant-checking pass to the pipeline. It will be run before and + // after each HLO pass. The invariant checking pass must not mutate the graph + // (it is required to always return "false" from its Run() method). + template + T& AddInvariantChecker(Args&&... args) { + CHECK(!run_called_) << "AddInvariantChecker cannot be called after Run"; + auto pass = new T(std::forward(args)...); + invariant_checkers_.push_back(std::unique_ptr(pass)); + return *pass; + } + + // Add an invariant-checking pass to the pipeline on debug builds only. + template + void AddInvariantCheckerDebug(Args&&... args) { +#ifndef NDEBUG + AddInvariantChecker(std::forward(args)...); +#endif // NDEBUG + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + using HloPassInterface::RunOnModuleGroup; + StatusOr RunOnModuleGroup( + HloModuleGroup* module_group, + const absl::flat_hash_set& execution_threads) override; + + bool IsPassPipeline() override { return true; } + + // Return size of passes_. + int PassesSize() { return passes_.size(); } + // Return reference to pass specified by index. + HloPassInterface& GetPass(int index) { return *passes_[index]; } + + private: + // Returns the set of passes which are enabled. DebugOptions can selectively + // disable passes via --xla_disable_hlo_passes flag. + std::vector GetEnabledPasses( + const DebugOptions& debug_options); + + // Maybe dumps the given module or module group depending on flag values + // contained in DebugOptions of module config. If it is dumped, saves the + // filenames of the dumps into module metadata. + void MaybeDumpHloAndSaveFilenames(HloModuleGroup& module_group, + absl::string_view after_pass_name, + absl::string_view before_pass_name); + void MaybeDumpHloAndSaveFilenames(HloModule& module, + absl::string_view after_pass_name, + absl::string_view before_pass_name); + + // Runs the invariant checker on the given HLO for specified + // `execution_threads`. Empty `execution_threads` means all execution threads + // are included. HloT can be either HloModule or HloModuleGroup. + template + Status RunInvariantCheckers(HloT* hlo, absl::string_view after_pass_name) { + return RunInvariantCheckers(hlo, after_pass_name, /*execution_threads=*/{}); + } + template + Status RunInvariantCheckers( + HloT* hlo, absl::string_view after_pass_name, + const absl::flat_hash_set& execution_threads); + + // Helper which runs the given pass on the given HLO. HloT can be either + // HloModule or HloModuleGroup. + template + StatusOr RunPassesInternal( + HloT* hlo, const DebugOptions& debug_options, + const absl::flat_hash_set& execution_threads); + + // Helpers which run the given passes on the given HLO construct. Only + // computations with specified `execution_threads` are considered by the pass, + // empty thread list means all `execution_threads` are considered. These + // helpers enable templating of the core of the pipeline logic by providing + // HloModule and HloModuleGroup specific methods with the same name. + static StatusOr RunHelper( + HloPassInterface* pass, HloModule* module, + const absl::flat_hash_set& execution_threads) { + TF_ASSIGN_OR_RETURN(bool changed, pass->Run(module, execution_threads)); + module->Cleanup(); + return changed; + } + static StatusOr RunHelper( + HloPassInterface* pass, HloModuleGroup* module_group, + const absl::flat_hash_set& execution_threads) { + TF_ASSIGN_OR_RETURN( + bool changed, pass->RunOnModuleGroup(module_group, execution_threads)); + module_group->Cleanup(); + return changed; + } + + const std::string name_; + std::vector> passes_; + std::vector> invariant_checkers_; + bool run_called_ = false; + + CompilationStats* compilation_stats_; + // Default stats instance for when one is not passed in the constructor. + // Use via compilation_stats_, not directly. + std::unique_ptr empty_compilation_stats_; + + // Allow PhaseOrderPipeline to modify private passes_ member in order to + // perform PhaseOrdering. + friend class ::xla::PhaseOrderPipeline; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_PASS_PIPELINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_phi_graph.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_phi_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..f4c00a8964e177f5e2f9da2bc2f5e0f4bc291f2a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_phi_graph.h @@ -0,0 +1,100 @@ +/* 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_SERVICE_HLO_PHI_GRAPH_H_ +#define XLA_SERVICE_HLO_PHI_GRAPH_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_value.h" + +namespace xla { +// Phi graph is a graph that contains and connects phi nodes build on top of +// HloValues with explicit edges, as well as non-phi nodes that are direct +// inputs to the phi nodes. The graph can be viewed as an 'overlay' on top of +// HloValues, with some edges that connect them together. After optimization, +// some phis nodes will be simplified away and the user can then ask two useful +// questions: +// +// 1. Which HloValue should a phi node being replaced with? +// 2. TODO(yunxing): What are the set of aliased HloValues that are connecting +// to the same phi (Must-aliasing). +class PhiGraph { + public: + // Register an hlo value into the phi node. + void RegisterPhi(const HloValue& value, + absl::Span inputs); + + HloValue::Id GetOptimizedId(const HloValue& value); + + // Returns true if the input to a hlo value is the same as `inputs`. + bool InputsEqualTo(const HloValue& value, + absl::Span inputs); + + // Given `id`, returns the new id that `id` should be replaced with. If the + // node is not optimized, returns the same value. + HloValue::Id FindOptimizedValue(const HloValue::Id id); + + // Optimize the entire graph. + void Optimize(); + + std::string ToString(); + + private: + struct Node { + bool is_phi; + // Users of this node. Non-phi node has no operands. + std::vector users; + // Operands of this node. + std::vector operands; + + // The value that the node is originally registered with. + HloValue::Id value_id; + + // mark_as_dead is set to true when a phi node is simplified away + // + // Precondition: node is a phi. + bool mark_as_dead = false; + }; + + Node* CreateOrReuseNode(const HloValue& value); + + // Replace `node` with `replace`. Redirect all users to the `replace` and + // all HloValues pointing to the `node` to `replace`. Also mark `node` as + // dead. + // + // Precondition: node is a phi -- It's only possible to simplify away a + // phi node. + void ReplaceNodeWith(Node* node, Node* replace); + + // A reverse mapping of a node in the phi graph and all HloValues pointing + // to that phi. + absl::flat_hash_map> node_to_value_id_; + + // A mapping from a HloValue to node in the phi graph. + absl::flat_hash_map value_id_to_node_; + std::vector> node_storage_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_PHI_GRAPH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_profile_printer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_profile_printer.h new file mode 100644 index 0000000000000000000000000000000000000000..10c2ace2c9b856d205d15700b1e9c3db4c219dd2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_profile_printer.h @@ -0,0 +1,33 @@ +/* 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_SERVICE_HLO_PROFILE_PRINTER_H_ +#define XLA_SERVICE_HLO_PROFILE_PRINTER_H_ + +#include +#include +#include + +#include "xla/service/hlo_profile_printer_data.pb.h" +#include "xla/types.h" + +namespace xla { +// Pretty-print an array of profile counters using hlo_profile_printer_data. +std::string PrintHloProfile( + const HloProfilePrinterData& hlo_profile_printer_data, + const int64_t* counters, double clock_rate_ghz); +} // namespace xla + +#endif // XLA_SERVICE_HLO_PROFILE_PRINTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_profile_printer_data.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_profile_printer_data.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..3e5af41ddfb88757d5a46bdfbb03c6b52f4124ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_profile_printer_data.pb.h @@ -0,0 +1,1271 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/hlo_profile_printer_data.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_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 +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto; +namespace xla { +class HloProfilePrinterData; +struct HloProfilePrinterDataDefaultTypeInternal; +extern HloProfilePrinterDataDefaultTypeInternal _HloProfilePrinterData_default_instance_; +class HloProfilePrinterData_ExtraMetricsEntry_DoNotUse; +struct HloProfilePrinterData_ExtraMetricsEntry_DoNotUseDefaultTypeInternal; +extern HloProfilePrinterData_ExtraMetricsEntry_DoNotUseDefaultTypeInternal _HloProfilePrinterData_ExtraMetricsEntry_DoNotUse_default_instance_; +class HloProfilePrinterData_HloComputationInfo; +struct HloProfilePrinterData_HloComputationInfoDefaultTypeInternal; +extern HloProfilePrinterData_HloComputationInfoDefaultTypeInternal _HloProfilePrinterData_HloComputationInfo_default_instance_; +class HloProfilePrinterData_HloInstructionInfo; +struct HloProfilePrinterData_HloInstructionInfoDefaultTypeInternal; +extern HloProfilePrinterData_HloInstructionInfoDefaultTypeInternal _HloProfilePrinterData_HloInstructionInfo_default_instance_; +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::HloProfilePrinterData* Arena::CreateMaybeMessage<::xla::HloProfilePrinterData>(Arena*); +template<> ::xla::HloProfilePrinterData_ExtraMetricsEntry_DoNotUse* Arena::CreateMaybeMessage<::xla::HloProfilePrinterData_ExtraMetricsEntry_DoNotUse>(Arena*); +template<> ::xla::HloProfilePrinterData_HloComputationInfo* Arena::CreateMaybeMessage<::xla::HloProfilePrinterData_HloComputationInfo>(Arena*); +template<> ::xla::HloProfilePrinterData_HloInstructionInfo* Arena::CreateMaybeMessage<::xla::HloProfilePrinterData_HloInstructionInfo>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { + +// =================================================================== + +class HloProfilePrinterData_HloInstructionInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloProfilePrinterData.HloInstructionInfo) */ { + public: + inline HloProfilePrinterData_HloInstructionInfo() : HloProfilePrinterData_HloInstructionInfo(nullptr) {} + ~HloProfilePrinterData_HloInstructionInfo() override; + explicit PROTOBUF_CONSTEXPR HloProfilePrinterData_HloInstructionInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloProfilePrinterData_HloInstructionInfo(const HloProfilePrinterData_HloInstructionInfo& from); + HloProfilePrinterData_HloInstructionInfo(HloProfilePrinterData_HloInstructionInfo&& from) noexcept + : HloProfilePrinterData_HloInstructionInfo() { + *this = ::std::move(from); + } + + inline HloProfilePrinterData_HloInstructionInfo& operator=(const HloProfilePrinterData_HloInstructionInfo& from) { + CopyFrom(from); + return *this; + } + inline HloProfilePrinterData_HloInstructionInfo& operator=(HloProfilePrinterData_HloInstructionInfo&& 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 HloProfilePrinterData_HloInstructionInfo& default_instance() { + return *internal_default_instance(); + } + static inline const HloProfilePrinterData_HloInstructionInfo* internal_default_instance() { + return reinterpret_cast( + &_HloProfilePrinterData_HloInstructionInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(HloProfilePrinterData_HloInstructionInfo& a, HloProfilePrinterData_HloInstructionInfo& b) { + a.Swap(&b); + } + inline void Swap(HloProfilePrinterData_HloInstructionInfo* 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(HloProfilePrinterData_HloInstructionInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloProfilePrinterData_HloInstructionInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloProfilePrinterData_HloInstructionInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloProfilePrinterData_HloInstructionInfo& from) { + HloProfilePrinterData_HloInstructionInfo::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(HloProfilePrinterData_HloInstructionInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloProfilePrinterData.HloInstructionInfo"; + } + protected: + explicit HloProfilePrinterData_HloInstructionInfo(::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 { + kLongNameFieldNumber = 1, + kShortNameFieldNumber = 2, + kCategoryFieldNumber = 3, + kFlopCountFieldNumber = 4, + kTranscendentalCountFieldNumber = 5, + kProfileIndexFieldNumber = 8, + kBytesAccessedFieldNumber = 9, + kOptimalSecondsFieldNumber = 7, + }; + // string long_name = 1; + void clear_long_name(); + const std::string& long_name() const; + template + void set_long_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_long_name(); + PROTOBUF_NODISCARD std::string* release_long_name(); + void set_allocated_long_name(std::string* long_name); + private: + const std::string& _internal_long_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_long_name(const std::string& value); + std::string* _internal_mutable_long_name(); + public: + + // string short_name = 2; + void clear_short_name(); + const std::string& short_name() const; + template + void set_short_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_short_name(); + PROTOBUF_NODISCARD std::string* release_short_name(); + void set_allocated_short_name(std::string* short_name); + private: + const std::string& _internal_short_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_short_name(const std::string& value); + std::string* _internal_mutable_short_name(); + public: + + // string category = 3; + void clear_category(); + const std::string& category() const; + template + void set_category(ArgT0&& arg0, ArgT... args); + std::string* mutable_category(); + PROTOBUF_NODISCARD std::string* release_category(); + void set_allocated_category(std::string* category); + private: + const std::string& _internal_category() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_category(const std::string& value); + std::string* _internal_mutable_category(); + public: + + // float flop_count = 4; + void clear_flop_count(); + float flop_count() const; + void set_flop_count(float value); + private: + float _internal_flop_count() const; + void _internal_set_flop_count(float value); + public: + + // float transcendental_count = 5; + void clear_transcendental_count(); + float transcendental_count() const; + void set_transcendental_count(float value); + private: + float _internal_transcendental_count() const; + void _internal_set_transcendental_count(float value); + public: + + // int64 profile_index = 8; + void clear_profile_index(); + int64_t profile_index() const; + void set_profile_index(int64_t value); + private: + int64_t _internal_profile_index() const; + void _internal_set_profile_index(int64_t value); + public: + + // int64 bytes_accessed = 9; + void clear_bytes_accessed(); + int64_t bytes_accessed() const; + void set_bytes_accessed(int64_t value); + private: + int64_t _internal_bytes_accessed() const; + void _internal_set_bytes_accessed(int64_t value); + public: + + // float optimal_seconds = 7; + void clear_optimal_seconds(); + float optimal_seconds() const; + void set_optimal_seconds(float value); + private: + float _internal_optimal_seconds() const; + void _internal_set_optimal_seconds(float value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloProfilePrinterData.HloInstructionInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr long_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr short_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr category_; + float flop_count_; + float transcendental_count_; + int64_t profile_index_; + int64_t bytes_accessed_; + float optimal_seconds_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto; +}; +// ------------------------------------------------------------------- + +class HloProfilePrinterData_HloComputationInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloProfilePrinterData.HloComputationInfo) */ { + public: + inline HloProfilePrinterData_HloComputationInfo() : HloProfilePrinterData_HloComputationInfo(nullptr) {} + ~HloProfilePrinterData_HloComputationInfo() override; + explicit PROTOBUF_CONSTEXPR HloProfilePrinterData_HloComputationInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloProfilePrinterData_HloComputationInfo(const HloProfilePrinterData_HloComputationInfo& from); + HloProfilePrinterData_HloComputationInfo(HloProfilePrinterData_HloComputationInfo&& from) noexcept + : HloProfilePrinterData_HloComputationInfo() { + *this = ::std::move(from); + } + + inline HloProfilePrinterData_HloComputationInfo& operator=(const HloProfilePrinterData_HloComputationInfo& from) { + CopyFrom(from); + return *this; + } + inline HloProfilePrinterData_HloComputationInfo& operator=(HloProfilePrinterData_HloComputationInfo&& 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 HloProfilePrinterData_HloComputationInfo& default_instance() { + return *internal_default_instance(); + } + static inline const HloProfilePrinterData_HloComputationInfo* internal_default_instance() { + return reinterpret_cast( + &_HloProfilePrinterData_HloComputationInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(HloProfilePrinterData_HloComputationInfo& a, HloProfilePrinterData_HloComputationInfo& b) { + a.Swap(&b); + } + inline void Swap(HloProfilePrinterData_HloComputationInfo* 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(HloProfilePrinterData_HloComputationInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloProfilePrinterData_HloComputationInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloProfilePrinterData_HloComputationInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloProfilePrinterData_HloComputationInfo& from) { + HloProfilePrinterData_HloComputationInfo::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(HloProfilePrinterData_HloComputationInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloProfilePrinterData.HloComputationInfo"; + } + protected: + explicit HloProfilePrinterData_HloComputationInfo(::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 { + kInstructionInfosFieldNumber = 3, + kNameFieldNumber = 1, + kProfileIndexFieldNumber = 2, + }; + // repeated .xla.HloProfilePrinterData.HloInstructionInfo instruction_infos = 3; + int instruction_infos_size() const; + private: + int _internal_instruction_infos_size() const; + public: + void clear_instruction_infos(); + ::xla::HloProfilePrinterData_HloInstructionInfo* mutable_instruction_infos(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloInstructionInfo >* + mutable_instruction_infos(); + private: + const ::xla::HloProfilePrinterData_HloInstructionInfo& _internal_instruction_infos(int index) const; + ::xla::HloProfilePrinterData_HloInstructionInfo* _internal_add_instruction_infos(); + public: + const ::xla::HloProfilePrinterData_HloInstructionInfo& instruction_infos(int index) const; + ::xla::HloProfilePrinterData_HloInstructionInfo* add_instruction_infos(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloInstructionInfo >& + instruction_infos() 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 profile_index = 2; + void clear_profile_index(); + int64_t profile_index() const; + void set_profile_index(int64_t value); + private: + int64_t _internal_profile_index() const; + void _internal_set_profile_index(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloProfilePrinterData.HloComputationInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloInstructionInfo > instruction_infos_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + int64_t profile_index_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto; +}; +// ------------------------------------------------------------------- + +class HloProfilePrinterData_ExtraMetricsEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + HloProfilePrinterData_ExtraMetricsEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR HloProfilePrinterData_ExtraMetricsEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit HloProfilePrinterData_ExtraMetricsEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const HloProfilePrinterData_ExtraMetricsEntry_DoNotUse& other); + static const HloProfilePrinterData_ExtraMetricsEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_HloProfilePrinterData_ExtraMetricsEntry_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, "xla.HloProfilePrinterData.ExtraMetricsEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto; +}; + +// ------------------------------------------------------------------- + +class HloProfilePrinterData final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.HloProfilePrinterData) */ { + public: + inline HloProfilePrinterData() : HloProfilePrinterData(nullptr) {} + ~HloProfilePrinterData() override; + explicit PROTOBUF_CONSTEXPR HloProfilePrinterData(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloProfilePrinterData(const HloProfilePrinterData& from); + HloProfilePrinterData(HloProfilePrinterData&& from) noexcept + : HloProfilePrinterData() { + *this = ::std::move(from); + } + + inline HloProfilePrinterData& operator=(const HloProfilePrinterData& from) { + CopyFrom(from); + return *this; + } + inline HloProfilePrinterData& operator=(HloProfilePrinterData&& 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 HloProfilePrinterData& default_instance() { + return *internal_default_instance(); + } + static inline const HloProfilePrinterData* internal_default_instance() { + return reinterpret_cast( + &_HloProfilePrinterData_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(HloProfilePrinterData& a, HloProfilePrinterData& b) { + a.Swap(&b); + } + inline void Swap(HloProfilePrinterData* 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(HloProfilePrinterData* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloProfilePrinterData* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloProfilePrinterData& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloProfilePrinterData& from) { + HloProfilePrinterData::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(HloProfilePrinterData* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.HloProfilePrinterData"; + } + protected: + explicit HloProfilePrinterData(::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 ---------------------------------------------------- + + typedef HloProfilePrinterData_HloInstructionInfo HloInstructionInfo; + typedef HloProfilePrinterData_HloComputationInfo HloComputationInfo; + + // accessors ------------------------------------------------------- + + enum : int { + kComputationInfosFieldNumber = 1, + kExtraMetricsFieldNumber = 3, + kEntryComputationFieldNumber = 4, + kProfileCountersSizeFieldNumber = 2, + }; + // repeated .xla.HloProfilePrinterData.HloComputationInfo computation_infos = 1; + int computation_infos_size() const; + private: + int _internal_computation_infos_size() const; + public: + void clear_computation_infos(); + ::xla::HloProfilePrinterData_HloComputationInfo* mutable_computation_infos(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloComputationInfo >* + mutable_computation_infos(); + private: + const ::xla::HloProfilePrinterData_HloComputationInfo& _internal_computation_infos(int index) const; + ::xla::HloProfilePrinterData_HloComputationInfo* _internal_add_computation_infos(); + public: + const ::xla::HloProfilePrinterData_HloComputationInfo& computation_infos(int index) const; + ::xla::HloProfilePrinterData_HloComputationInfo* add_computation_infos(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloComputationInfo >& + computation_infos() const; + + // map extra_metrics = 3; + int extra_metrics_size() const; + private: + int _internal_extra_metrics_size() const; + public: + void clear_extra_metrics(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& + _internal_extra_metrics() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* + _internal_mutable_extra_metrics(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& + extra_metrics() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* + mutable_extra_metrics(); + + // string entry_computation = 4; + void clear_entry_computation(); + const std::string& entry_computation() const; + template + void set_entry_computation(ArgT0&& arg0, ArgT... args); + std::string* mutable_entry_computation(); + PROTOBUF_NODISCARD std::string* release_entry_computation(); + void set_allocated_entry_computation(std::string* entry_computation); + private: + const std::string& _internal_entry_computation() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_entry_computation(const std::string& value); + std::string* _internal_mutable_entry_computation(); + public: + + // int64 profile_counters_size = 2; + void clear_profile_counters_size(); + int64_t profile_counters_size() const; + void set_profile_counters_size(int64_t value); + private: + int64_t _internal_profile_counters_size() const; + void _internal_set_profile_counters_size(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.HloProfilePrinterData) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloComputationInfo > computation_infos_; + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + HloProfilePrinterData_ExtraMetricsEntry_DoNotUse, + std::string, int64_t, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64> extra_metrics_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr entry_computation_; + int64_t profile_counters_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// HloProfilePrinterData_HloInstructionInfo + +// string long_name = 1; +inline void HloProfilePrinterData_HloInstructionInfo::clear_long_name() { + _impl_.long_name_.ClearToEmpty(); +} +inline const std::string& HloProfilePrinterData_HloInstructionInfo::long_name() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.long_name) + return _internal_long_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloProfilePrinterData_HloInstructionInfo::set_long_name(ArgT0&& arg0, ArgT... args) { + + _impl_.long_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.long_name) +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::mutable_long_name() { + std::string* _s = _internal_mutable_long_name(); + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.HloInstructionInfo.long_name) + return _s; +} +inline const std::string& HloProfilePrinterData_HloInstructionInfo::_internal_long_name() const { + return _impl_.long_name_.Get(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_long_name(const std::string& value) { + + _impl_.long_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::_internal_mutable_long_name() { + + return _impl_.long_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::release_long_name() { + // @@protoc_insertion_point(field_release:xla.HloProfilePrinterData.HloInstructionInfo.long_name) + return _impl_.long_name_.Release(); +} +inline void HloProfilePrinterData_HloInstructionInfo::set_allocated_long_name(std::string* long_name) { + if (long_name != nullptr) { + + } else { + + } + _impl_.long_name_.SetAllocated(long_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.long_name_.IsDefault()) { + _impl_.long_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloProfilePrinterData.HloInstructionInfo.long_name) +} + +// string short_name = 2; +inline void HloProfilePrinterData_HloInstructionInfo::clear_short_name() { + _impl_.short_name_.ClearToEmpty(); +} +inline const std::string& HloProfilePrinterData_HloInstructionInfo::short_name() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.short_name) + return _internal_short_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloProfilePrinterData_HloInstructionInfo::set_short_name(ArgT0&& arg0, ArgT... args) { + + _impl_.short_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.short_name) +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::mutable_short_name() { + std::string* _s = _internal_mutable_short_name(); + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.HloInstructionInfo.short_name) + return _s; +} +inline const std::string& HloProfilePrinterData_HloInstructionInfo::_internal_short_name() const { + return _impl_.short_name_.Get(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_short_name(const std::string& value) { + + _impl_.short_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::_internal_mutable_short_name() { + + return _impl_.short_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::release_short_name() { + // @@protoc_insertion_point(field_release:xla.HloProfilePrinterData.HloInstructionInfo.short_name) + return _impl_.short_name_.Release(); +} +inline void HloProfilePrinterData_HloInstructionInfo::set_allocated_short_name(std::string* short_name) { + if (short_name != nullptr) { + + } else { + + } + _impl_.short_name_.SetAllocated(short_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.short_name_.IsDefault()) { + _impl_.short_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloProfilePrinterData.HloInstructionInfo.short_name) +} + +// string category = 3; +inline void HloProfilePrinterData_HloInstructionInfo::clear_category() { + _impl_.category_.ClearToEmpty(); +} +inline const std::string& HloProfilePrinterData_HloInstructionInfo::category() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.category) + return _internal_category(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloProfilePrinterData_HloInstructionInfo::set_category(ArgT0&& arg0, ArgT... args) { + + _impl_.category_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.category) +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::mutable_category() { + std::string* _s = _internal_mutable_category(); + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.HloInstructionInfo.category) + return _s; +} +inline const std::string& HloProfilePrinterData_HloInstructionInfo::_internal_category() const { + return _impl_.category_.Get(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_category(const std::string& value) { + + _impl_.category_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::_internal_mutable_category() { + + return _impl_.category_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloInstructionInfo::release_category() { + // @@protoc_insertion_point(field_release:xla.HloProfilePrinterData.HloInstructionInfo.category) + return _impl_.category_.Release(); +} +inline void HloProfilePrinterData_HloInstructionInfo::set_allocated_category(std::string* category) { + if (category != nullptr) { + + } else { + + } + _impl_.category_.SetAllocated(category, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.category_.IsDefault()) { + _impl_.category_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloProfilePrinterData.HloInstructionInfo.category) +} + +// float flop_count = 4; +inline void HloProfilePrinterData_HloInstructionInfo::clear_flop_count() { + _impl_.flop_count_ = 0; +} +inline float HloProfilePrinterData_HloInstructionInfo::_internal_flop_count() const { + return _impl_.flop_count_; +} +inline float HloProfilePrinterData_HloInstructionInfo::flop_count() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.flop_count) + return _internal_flop_count(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_flop_count(float value) { + + _impl_.flop_count_ = value; +} +inline void HloProfilePrinterData_HloInstructionInfo::set_flop_count(float value) { + _internal_set_flop_count(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.flop_count) +} + +// float transcendental_count = 5; +inline void HloProfilePrinterData_HloInstructionInfo::clear_transcendental_count() { + _impl_.transcendental_count_ = 0; +} +inline float HloProfilePrinterData_HloInstructionInfo::_internal_transcendental_count() const { + return _impl_.transcendental_count_; +} +inline float HloProfilePrinterData_HloInstructionInfo::transcendental_count() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.transcendental_count) + return _internal_transcendental_count(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_transcendental_count(float value) { + + _impl_.transcendental_count_ = value; +} +inline void HloProfilePrinterData_HloInstructionInfo::set_transcendental_count(float value) { + _internal_set_transcendental_count(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.transcendental_count) +} + +// int64 bytes_accessed = 9; +inline void HloProfilePrinterData_HloInstructionInfo::clear_bytes_accessed() { + _impl_.bytes_accessed_ = int64_t{0}; +} +inline int64_t HloProfilePrinterData_HloInstructionInfo::_internal_bytes_accessed() const { + return _impl_.bytes_accessed_; +} +inline int64_t HloProfilePrinterData_HloInstructionInfo::bytes_accessed() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.bytes_accessed) + return _internal_bytes_accessed(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_bytes_accessed(int64_t value) { + + _impl_.bytes_accessed_ = value; +} +inline void HloProfilePrinterData_HloInstructionInfo::set_bytes_accessed(int64_t value) { + _internal_set_bytes_accessed(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.bytes_accessed) +} + +// float optimal_seconds = 7; +inline void HloProfilePrinterData_HloInstructionInfo::clear_optimal_seconds() { + _impl_.optimal_seconds_ = 0; +} +inline float HloProfilePrinterData_HloInstructionInfo::_internal_optimal_seconds() const { + return _impl_.optimal_seconds_; +} +inline float HloProfilePrinterData_HloInstructionInfo::optimal_seconds() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.optimal_seconds) + return _internal_optimal_seconds(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_optimal_seconds(float value) { + + _impl_.optimal_seconds_ = value; +} +inline void HloProfilePrinterData_HloInstructionInfo::set_optimal_seconds(float value) { + _internal_set_optimal_seconds(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.optimal_seconds) +} + +// int64 profile_index = 8; +inline void HloProfilePrinterData_HloInstructionInfo::clear_profile_index() { + _impl_.profile_index_ = int64_t{0}; +} +inline int64_t HloProfilePrinterData_HloInstructionInfo::_internal_profile_index() const { + return _impl_.profile_index_; +} +inline int64_t HloProfilePrinterData_HloInstructionInfo::profile_index() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloInstructionInfo.profile_index) + return _internal_profile_index(); +} +inline void HloProfilePrinterData_HloInstructionInfo::_internal_set_profile_index(int64_t value) { + + _impl_.profile_index_ = value; +} +inline void HloProfilePrinterData_HloInstructionInfo::set_profile_index(int64_t value) { + _internal_set_profile_index(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloInstructionInfo.profile_index) +} + +// ------------------------------------------------------------------- + +// HloProfilePrinterData_HloComputationInfo + +// string name = 1; +inline void HloProfilePrinterData_HloComputationInfo::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& HloProfilePrinterData_HloComputationInfo::name() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloComputationInfo.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloProfilePrinterData_HloComputationInfo::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloComputationInfo.name) +} +inline std::string* HloProfilePrinterData_HloComputationInfo::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.HloComputationInfo.name) + return _s; +} +inline const std::string& HloProfilePrinterData_HloComputationInfo::_internal_name() const { + return _impl_.name_.Get(); +} +inline void HloProfilePrinterData_HloComputationInfo::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloComputationInfo::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData_HloComputationInfo::release_name() { + // @@protoc_insertion_point(field_release:xla.HloProfilePrinterData.HloComputationInfo.name) + return _impl_.name_.Release(); +} +inline void HloProfilePrinterData_HloComputationInfo::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:xla.HloProfilePrinterData.HloComputationInfo.name) +} + +// int64 profile_index = 2; +inline void HloProfilePrinterData_HloComputationInfo::clear_profile_index() { + _impl_.profile_index_ = int64_t{0}; +} +inline int64_t HloProfilePrinterData_HloComputationInfo::_internal_profile_index() const { + return _impl_.profile_index_; +} +inline int64_t HloProfilePrinterData_HloComputationInfo::profile_index() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloComputationInfo.profile_index) + return _internal_profile_index(); +} +inline void HloProfilePrinterData_HloComputationInfo::_internal_set_profile_index(int64_t value) { + + _impl_.profile_index_ = value; +} +inline void HloProfilePrinterData_HloComputationInfo::set_profile_index(int64_t value) { + _internal_set_profile_index(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.HloComputationInfo.profile_index) +} + +// repeated .xla.HloProfilePrinterData.HloInstructionInfo instruction_infos = 3; +inline int HloProfilePrinterData_HloComputationInfo::_internal_instruction_infos_size() const { + return _impl_.instruction_infos_.size(); +} +inline int HloProfilePrinterData_HloComputationInfo::instruction_infos_size() const { + return _internal_instruction_infos_size(); +} +inline void HloProfilePrinterData_HloComputationInfo::clear_instruction_infos() { + _impl_.instruction_infos_.Clear(); +} +inline ::xla::HloProfilePrinterData_HloInstructionInfo* HloProfilePrinterData_HloComputationInfo::mutable_instruction_infos(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.HloComputationInfo.instruction_infos) + return _impl_.instruction_infos_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloInstructionInfo >* +HloProfilePrinterData_HloComputationInfo::mutable_instruction_infos() { + // @@protoc_insertion_point(field_mutable_list:xla.HloProfilePrinterData.HloComputationInfo.instruction_infos) + return &_impl_.instruction_infos_; +} +inline const ::xla::HloProfilePrinterData_HloInstructionInfo& HloProfilePrinterData_HloComputationInfo::_internal_instruction_infos(int index) const { + return _impl_.instruction_infos_.Get(index); +} +inline const ::xla::HloProfilePrinterData_HloInstructionInfo& HloProfilePrinterData_HloComputationInfo::instruction_infos(int index) const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.HloComputationInfo.instruction_infos) + return _internal_instruction_infos(index); +} +inline ::xla::HloProfilePrinterData_HloInstructionInfo* HloProfilePrinterData_HloComputationInfo::_internal_add_instruction_infos() { + return _impl_.instruction_infos_.Add(); +} +inline ::xla::HloProfilePrinterData_HloInstructionInfo* HloProfilePrinterData_HloComputationInfo::add_instruction_infos() { + ::xla::HloProfilePrinterData_HloInstructionInfo* _add = _internal_add_instruction_infos(); + // @@protoc_insertion_point(field_add:xla.HloProfilePrinterData.HloComputationInfo.instruction_infos) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloInstructionInfo >& +HloProfilePrinterData_HloComputationInfo::instruction_infos() const { + // @@protoc_insertion_point(field_list:xla.HloProfilePrinterData.HloComputationInfo.instruction_infos) + return _impl_.instruction_infos_; +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// HloProfilePrinterData + +// repeated .xla.HloProfilePrinterData.HloComputationInfo computation_infos = 1; +inline int HloProfilePrinterData::_internal_computation_infos_size() const { + return _impl_.computation_infos_.size(); +} +inline int HloProfilePrinterData::computation_infos_size() const { + return _internal_computation_infos_size(); +} +inline void HloProfilePrinterData::clear_computation_infos() { + _impl_.computation_infos_.Clear(); +} +inline ::xla::HloProfilePrinterData_HloComputationInfo* HloProfilePrinterData::mutable_computation_infos(int index) { + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.computation_infos) + return _impl_.computation_infos_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloComputationInfo >* +HloProfilePrinterData::mutable_computation_infos() { + // @@protoc_insertion_point(field_mutable_list:xla.HloProfilePrinterData.computation_infos) + return &_impl_.computation_infos_; +} +inline const ::xla::HloProfilePrinterData_HloComputationInfo& HloProfilePrinterData::_internal_computation_infos(int index) const { + return _impl_.computation_infos_.Get(index); +} +inline const ::xla::HloProfilePrinterData_HloComputationInfo& HloProfilePrinterData::computation_infos(int index) const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.computation_infos) + return _internal_computation_infos(index); +} +inline ::xla::HloProfilePrinterData_HloComputationInfo* HloProfilePrinterData::_internal_add_computation_infos() { + return _impl_.computation_infos_.Add(); +} +inline ::xla::HloProfilePrinterData_HloComputationInfo* HloProfilePrinterData::add_computation_infos() { + ::xla::HloProfilePrinterData_HloComputationInfo* _add = _internal_add_computation_infos(); + // @@protoc_insertion_point(field_add:xla.HloProfilePrinterData.computation_infos) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::HloProfilePrinterData_HloComputationInfo >& +HloProfilePrinterData::computation_infos() const { + // @@protoc_insertion_point(field_list:xla.HloProfilePrinterData.computation_infos) + return _impl_.computation_infos_; +} + +// int64 profile_counters_size = 2; +inline void HloProfilePrinterData::clear_profile_counters_size() { + _impl_.profile_counters_size_ = int64_t{0}; +} +inline int64_t HloProfilePrinterData::_internal_profile_counters_size() const { + return _impl_.profile_counters_size_; +} +inline int64_t HloProfilePrinterData::profile_counters_size() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.profile_counters_size) + return _internal_profile_counters_size(); +} +inline void HloProfilePrinterData::_internal_set_profile_counters_size(int64_t value) { + + _impl_.profile_counters_size_ = value; +} +inline void HloProfilePrinterData::set_profile_counters_size(int64_t value) { + _internal_set_profile_counters_size(value); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.profile_counters_size) +} + +// map extra_metrics = 3; +inline int HloProfilePrinterData::_internal_extra_metrics_size() const { + return _impl_.extra_metrics_.size(); +} +inline int HloProfilePrinterData::extra_metrics_size() const { + return _internal_extra_metrics_size(); +} +inline void HloProfilePrinterData::clear_extra_metrics() { + _impl_.extra_metrics_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& +HloProfilePrinterData::_internal_extra_metrics() const { + return _impl_.extra_metrics_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >& +HloProfilePrinterData::extra_metrics() const { + // @@protoc_insertion_point(field_map:xla.HloProfilePrinterData.extra_metrics) + return _internal_extra_metrics(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* +HloProfilePrinterData::_internal_mutable_extra_metrics() { + return _impl_.extra_metrics_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, int64_t >* +HloProfilePrinterData::mutable_extra_metrics() { + // @@protoc_insertion_point(field_mutable_map:xla.HloProfilePrinterData.extra_metrics) + return _internal_mutable_extra_metrics(); +} + +// string entry_computation = 4; +inline void HloProfilePrinterData::clear_entry_computation() { + _impl_.entry_computation_.ClearToEmpty(); +} +inline const std::string& HloProfilePrinterData::entry_computation() const { + // @@protoc_insertion_point(field_get:xla.HloProfilePrinterData.entry_computation) + return _internal_entry_computation(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void HloProfilePrinterData::set_entry_computation(ArgT0&& arg0, ArgT... args) { + + _impl_.entry_computation_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.HloProfilePrinterData.entry_computation) +} +inline std::string* HloProfilePrinterData::mutable_entry_computation() { + std::string* _s = _internal_mutable_entry_computation(); + // @@protoc_insertion_point(field_mutable:xla.HloProfilePrinterData.entry_computation) + return _s; +} +inline const std::string& HloProfilePrinterData::_internal_entry_computation() const { + return _impl_.entry_computation_.Get(); +} +inline void HloProfilePrinterData::_internal_set_entry_computation(const std::string& value) { + + _impl_.entry_computation_.Set(value, GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData::_internal_mutable_entry_computation() { + + return _impl_.entry_computation_.Mutable(GetArenaForAllocation()); +} +inline std::string* HloProfilePrinterData::release_entry_computation() { + // @@protoc_insertion_point(field_release:xla.HloProfilePrinterData.entry_computation) + return _impl_.entry_computation_.Release(); +} +inline void HloProfilePrinterData::set_allocated_entry_computation(std::string* entry_computation) { + if (entry_computation != nullptr) { + + } else { + + } + _impl_.entry_computation_.SetAllocated(entry_computation, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.entry_computation_.IsDefault()) { + _impl_.entry_computation_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.HloProfilePrinterData.entry_computation) +} + +#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_2fservice_2fhlo_5fprofile_5fprinter_5fdata_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_proto_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_proto_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f52fa8d3f0ef5d16d1f7623b6fe1ad77dc26e7c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_proto_util.h @@ -0,0 +1,60 @@ +/* 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 to manipulate data in hlo.proto. + +#ifndef XLA_SERVICE_HLO_PROTO_UTIL_H_ +#define XLA_SERVICE_HLO_PROTO_UTIL_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/hlo.pb.h" +#include "xla/status.h" + +namespace xla { + +// Returns a serialized representation of the HLO state. +HloProto MakeHloProto(const HloModule& module, + const BufferAssignment& assignment); + +// Returns a serialized representation of the HLO state, but buffer assignment +// will not be included in the output. +HloProto MakeHloProto(const HloModule& module); + +// Create an HLO state from serialized representation. In addition to +// creating the proto with HloModule::CreateFromProto(...) it also +// uses HloVerifier to ensure basic invariants are held. +// The HLO module could be a pre-optimizations (default) or post-optimizations +// module, which affects how the HLO module is verified, e.g., mixed-precision +// is allowed in post-optimizations HLOs. +StatusOr> CreateModuleFromProto( + const HloModuleProto& proto, const HloModuleConfig& module_config, + bool is_module_post_optimizations = false); + +// Returns the shapes of the parameters of the entry computation. Shape pointers +// refer to shapes inside of the given HloProto. +StatusOr> EntryComputationParameterShapes( + const HloProto& hlo_proto); + +// Returns the shape of the output of the entry computation. The shape pointer +// refers to the output shape inside of the given HloProto. +StatusOr EntryComputationOutputShape( + const HloProto& hlo_proto); + +} // namespace xla + +#endif // XLA_SERVICE_HLO_PROTO_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_rematerialization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_rematerialization.h new file mode 100644 index 0000000000000000000000000000000000000000..e73de37112aa172be7b32489c655d0ca5ce9a707 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_rematerialization.h @@ -0,0 +1,248 @@ +/* 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_SERVICE_HLO_REMATERIALIZATION_H_ +#define XLA_SERVICE_HLO_REMATERIALIZATION_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.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_schedule.h" +#include "xla/service/call_graph.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/tuple_points_to_analysis.h" +#include "xla/shape.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass which rematerializes instructions to reduce peak memory use, where +// memory use is defined as the total size of all live HLO instruction +// values. Parameters and constants are included in memory use estimates. +// +// CSE will undo the effects of this optimization and should not be run after +// this pass. In general, this pass should be run very late, immediately before +// code generation. +class HloRematerialization : public HloModulePass { + public: + using ShapeSizeFunction = std::function; + + using CompactShapeFunction = std::function(const Shape&)>; + + // Helper struct that communicates the before / after sizes for the + // rematerialization process. + struct RematerializationSizes { + int64_t before_bytes = -1; + int64_t after_bytes = -1; + }; + + // Mode in which the rematerialization algorithm should be run. + struct RematerializationModeConfig { + RematerializationModeConfig(bool recompute, bool compress, + bool host_offload) + : recompute(recompute), + compress(compress), + host_offload(host_offload) {} + bool recompute; // Enables the kCompress RematStrategy. + bool compress; // Enables the kRecompute RematStrategy. + bool host_offload; // Enables the kHostOffload RematStrategy. + }; + + // This is a struct containing configuration options that are specific to the + // Host Memory Offload strategy. + struct HostMemoryOffloadConfig { + explicit HostMemoryOffloadConfig(int64_t host_memory_space, + float bandwidth_to_host_bytes_per_second, + float bandwidth_from_host_bytes_per_second) + : host_memory_space(host_memory_space), + bandwidth_to_host_bytes_per_second( + bandwidth_to_host_bytes_per_second), + bandwidth_from_host_bytes_per_second( + bandwidth_from_host_bytes_per_second) {} + + // The host memory space, which is used during the host offload strategy. + int64_t host_memory_space; + + float bandwidth_to_host_bytes_per_second; + + float bandwidth_from_host_bytes_per_second; + }; + + static Shape DefaultCompactShapeFunction(const Shape& shape) { return shape; } + + struct Options { + explicit Options( + HloCostAnalysis& hlo_cost_analysis, + const RematerializationModeConfig& remat_mode_config, + int64_t memory_limit_bytes, int block_size_limit, + int block_rematerialization_factor, int64_t min_remat_size, + CompactShapeFunction compact_shape_function, + std::optional host_memory_offload_config) + : hlo_cost_analysis(hlo_cost_analysis), + remat_mode_config(remat_mode_config), + memory_limit_bytes(memory_limit_bytes), + block_size_limit(block_size_limit), + block_rematerialization_factor(block_rematerialization_factor), + min_remat_size(min_remat_size), + compact_shape_function(compact_shape_function == nullptr + ? DefaultCompactShapeFunction + : std::move(compact_shape_function)), + host_memory_offload_config(host_memory_offload_config) {} + + // The cost model used for decisions during rematerialization for host + // memory offload. It is also used for getting Shape size. + HloCostAnalysis& hlo_cost_analysis; + + // Holds the rematerialization strategy configuration to be used by the + // pass. + RematerializationModeConfig remat_mode_config; + + // Function which computes the size of the top-level buffer of a shape. + const ShapeSizeFunction size_function; + + // The threshold number of bytes to reduce memory use to via + // rematerialization. Size of aliased outputs should be subtracted + // from this. + int64_t memory_limit_bytes; + + // Maximum number of consecutive instructions to consider for + // rematerialization. + int block_size_limit; + + // Controls the amount of effort spent trying to find large blocks for + // rematerialization. Larger values leads to longer compilation times in + // return for potentially reduced memory consumption. + int block_rematerialization_factor; + + // The minimim size, in bytes, of a tensor to be considered for + // rematerialization. All tensors smaller than this size will be skipped + // over. + int64_t min_remat_size; + + // Converts a shape into compact form, returns the same shape if a shape is + // already considered compact. + CompactShapeFunction compact_shape_function; + + std::optional host_memory_offload_config; + }; + + explicit HloRematerialization(Options options, RematerializationSizes& sizes) + : options_(std::move(options)), sizes_(sizes) {} + + ~HloRematerialization() override = default; + + absl::string_view name() const override { return "rematerialization"; } + + // Get the next available channel id and increment count. + int64_t NextChannelId() { return next_channel_id_++; } + + // Get the peak memory for the computation. + int64_t ComputationPeakMemory(const HloComputation* computation) const { + return computation_peak_memory_.at(computation); + } + + // Runs rematerialization on the given module. Returns whether the module was + // changed. Requires that the module has a schedule set + // (HloModule::has_schedule() is true) before running. Returns whether any + // instructions were rematerialized. If memory use is already below the limit + // specified in the constructor then no instructions are rematerialized and + // false is returned. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + protected: + // Rematerializes instructions within the given computation. 'order' is the + // order in which the computation's instructions will be emitted in the + // backend. Rematerialized instructions will be added to the HLO computation + // and inserted into 'order'. + StatusOr RematerializeComputation(HloComputation* computation, + HloSchedule* schedule, + int64_t memory_limit_bytes, + int64_t min_remat_size) { + return RematerializeComputation(computation, schedule, memory_limit_bytes, + min_remat_size, /*execution_threads=*/{}); + } + + virtual StatusOr RematerializeComputation( + HloComputation* computation, HloSchedule* schedule, + int64_t memory_limit_bytes, int64_t min_remat_size, + const absl::flat_hash_set& execution_threads); + + // Computes and returns the peak memory used by the given computation. The + // peak memory is the maximum total size of all live HLO instruction values at + // any program point. 'order' is the order in which the HLO instructions will + // be emitted which is used to determine lifespans of HLO values. + StatusOr ComputePeakMemory( + const HloComputation* computation, const HloInstructionSequence& order, + const absl::flat_hash_set& execution_threads) const; + + // Returns the peak memory usage of the called computations for the given + // instruction. Zero is returned if the instruction calls no computations. + StatusOr CalledComputationsMemoryUsage( + const HloInstruction* instruction, + const absl::flat_hash_set& execution_threads) const; + + const Options options_; + + // Reference to data structure which records the peak memory usage of the HLO + // module before/after rematerialization. + RematerializationSizes& sizes_; + + // Call graph of the hlo_module. + std::unique_ptr call_graph_; + + // The peak memory usage of each computation. The map contains only those + // computations called from sequential context + // (CallContext::kSequential). These values are updated as rematerialization + // occurs. + absl::flat_hash_map computation_peak_memory_; + + std::unique_ptr points_to_analysis_; + + // Set of computations which have had rematerialization + // applied. Rematerialization is only applied once per computation. + absl::flat_hash_set rematerialized_computations_; + + // Count of the total instructions rematerialized. + int64_t instructions_rematerialized_ = 0; + + // Count of the net instructions added to the HLO module by + // rematerialization. This can be different than instructions_rematerialized_ + // because some rematerializations are effectively moves in the HLO + // schedule. In these cases, the rematerialization instruction replaces all + // uses of the original instruction and the original instruction is + // dead. Hence, no net instructions were added. + int64_t net_instructions_added_ = 0; + + // Size of the largest block that has been rematerialized. This is actually an + // upper bound (within a factor of 2) on the block size. + int max_rematerialized_block_size_ = 0; + + // Tracking available channel id numbers to use to apply to rematerialized + // channel instructions + int64_t next_channel_id_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_REMATERIALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_replication_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_replication_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..2267a80664979e3594794ef1230c16415dea1d52 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_replication_analysis.h @@ -0,0 +1,153 @@ +/* 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_SERVICE_HLO_REPLICATION_ANALYSIS_H_ +#define XLA_SERVICE_HLO_REPLICATION_ANALYSIS_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// An HLO pass that determines whether each instruction in the module outputs +// the same value across replicas or across partitions (depending on the value +// `cross_partition_spmd`). It propagates sources of replicated values to +// the rest of the module, where sources include cross-replica-sum, annotated +// entry parameters, and constants. +class HloReplicationAnalysis { + public: + // Runs the analysis on module and returns the result or an error. + static StatusOr> Run( + const HloModule* module, bool cross_partition_spmd); + + // Same as above, but the caller can provide additional annotations: a set of + // while loops that are known to have the same iteration counts across + // replicas or partitions. + static StatusOr> Run( + const HloModule* module, bool cross_partition_spmd, + const absl::flat_hash_set* + loops_known_with_same_iterations); + + // Same as above but supports finding partially replicated HLOs. + static StatusOr> + RunWithPartialReplication(const HloModule* module, bool cross_partition_spmd); + + // Returns if the HLO instruction outputs the same value (i.e., replicated) at + // the given index across all replicas or partitions. + bool HloInstructionIsReplicatedAt(const HloInstruction* inst, + const ShapeIndex& index) const; + + bool HloInstructionIsReplicatedAt( + const HloInstruction* inst, const ShapeIndex& index, + absl::Span replica_groups) const; + + private: + // A data structure that represents how an HLO is replicated among a set of + // devices. Device ID could be either partition ID or replica ID. + // We represent partial replication by grouping devices that have the same + // value into the same set. + class HloReplication { + public: + static HloReplication ReplicatedOnAllDevices(); + static HloReplication UniqueOnAllDevices(); + static HloReplication PartiallyReplicated( + absl::Span> device_sets); + HloReplication(); + HloReplication(const HloReplication& other) = default; + HloReplication(HloReplication&& other) = default; + HloReplication& operator=(HloReplication&& other) = default; + HloReplication Merge(const HloReplication& other) const; + bool Equal(const HloReplication& other) const; + bool IsReplicatedOnAllDevices() const; + bool IsUniqueOnAllDevices() const; + bool IsReplicatedWithinSubgroup(absl::Span device_ids) const; + std::string ToString() const; + + private: + enum class State { + kReplicatedOnAllDevices = 0, + kUniqueOnAllDevices = 1, + kPartiallyReplicated = 2, + }; + explicit HloReplication(State state, + absl::Span device_set_root); + State state_; + // Empty if state_ is kReplicatedOnAllDevices or kUniqueOnAllDevices. + // Otherwise, its size equals to the number of devices (either partitions + // or replications). Maps each device ID to the smallest device ID in the + // set. + std::vector device_set_root_; + }; + + static HloReplication DetermineHloInstructionIsReplicated( + const HloInstruction* hlo, const ShapeIndex& index, + bool cross_partition_spmd, + const absl::flat_hash_map>& hlo_replication, + bool support_partial_replication); + + HloReplicationAnalysis(const HloModule* module, bool cross_partition_spmd, + const absl::flat_hash_set* + loops_known_with_same_iterations, + bool support_partial_replication) + : module_(module), + cross_partition_spmd_(cross_partition_spmd), + loops_known_with_same_iterations_(*loops_known_with_same_iterations), + support_partial_replication_(support_partial_replication) {} + + // Computes hlo_replication_. + Status ComputeHloReplication(); + + // A helper function to recursively compute hlo_replication on a computation. + // Returns whether hlo_replication_ is changed. + bool ComputeHloReplicationOnComputation(const HloComputation* computation, + bool mark_everything_not_replicated); + + const HloModule* module_; + + // If true, run this replication analysis for replicated values across + // partitions (not across replicas) on an SPMD partitioned module. This means + // that HloInstructionIsReplicatedAt() returns true if the value is identical + // across partitions for each replica. The module-level parameter and root + // instructions may have HloSharding attributes that indicate whether values + // are identical across partitions. + // + // If false, HloReplicationAnalysis runs across replicas. + bool cross_partition_spmd_; + + // A set of while loops that are known to have the same iteration counts + // across replicas or partitions. This is provided by the caller as additional + // annotations. + const absl::flat_hash_set& + loops_known_with_same_iterations_; + + const bool support_partial_replication_; + + // A map from each analyzed HLO instruction to a shape tree that represents + // whether the instruction outputs the same value across replicas or + // partitions at each shape index. + absl::flat_hash_map> + hlo_replication_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_REPLICATION_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_value.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_value.h new file mode 100644 index 0000000000000000000000000000000000000000..a3b0638a3e141fa30c0fa0bc68b33cee635148b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_value.h @@ -0,0 +1,285 @@ +/* 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_SERVICE_HLO_VALUE_H_ +#define XLA_SERVICE_HLO_VALUE_H_ + +#include + +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_set.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/lazy.h" +#include "xla/service/buffer_value.h" +#include "xla/shape_tree.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Abstraction which identifies a specific point in the XLA graph. An +// HloPosition specifies a ShapeIndex within the output of a specific +// instruction. +struct HloPosition { + HloInstruction* instruction; + ShapeIndex index; + + // Returns the shape at this position. + const Shape& shape() const; + + std::string ToString() const; + + bool operator==(const HloPosition& other) const { + return instruction == other.instruction && index == other.index; + } + bool operator!=(const HloPosition& other) const { return !(*this == other); } + + // Sort by instruction ID, then index. + bool operator<(const HloPosition& other) const { + return std::forward_as_tuple(instruction->unique_id(), index) < + std::forward_as_tuple(other.instruction->unique_id(), other.index); + } + + template + friend H AbslHashValue(H h, const HloPosition& pos) { + return H::combine(std::move(h), pos.instruction, pos.index); + } +}; + +std::ostream& operator<<(std::ostream& out, const HloPosition& position); + +// Defines a single use of an HLO value. +struct HloUse { + // Instruction at which the value is used. + HloInstruction* instruction; + + // The operand number in which the value appears. + int64_t operand_number; + + // The shape index within the operand in which the value appears. + ShapeIndex operand_index; + + std::string ToString() const; + + bool operator==(const HloUse& other) const { + return instruction == other.instruction && + operand_number == other.operand_number && + operand_index == other.operand_index; + } + + bool operator!=(const HloUse& other) const { return !(*this == other); } + + template + friend H AbslHashValue(H h, const HloUse& use) { + return H::combine(std::move(h), use.instruction, use.operand_index, + use.operand_number); + } +}; + +std::ostream& operator<<(std::ostream& out, const HloUse& use); + +// HloDataflowAnalysis uses this subclass of BufferValue. +class HloValue : public BufferValue { + public: + // Predicate comparing HloValues by increasing id, useful for std::sort. + static bool IdLessThan(const HloValue* a, const HloValue* b) { + return a->id() < b->id(); + } + + // Construct an HloValue defined by 'instruction' at shape index 'index'. If + // is_phi is true, then this value is a phi value, for example, at the + // parameter of a while body computation. Phi values are only used in the SSA + // dataflow analysis (HloDataflowAnalysis::ssa_form_ is true). + HloValue(Id id, HloInstruction* instruction, const ShapeIndex& index, + bool is_phi = false); + + // Sets the positions in the module at which the HloValue appears. Should be + // called once and only once. The defining position should not be included in + // 'positions' as this is set at construction time. + void SetPositions(absl::Span positions); + + // Returns whether this value is a phi value. + bool is_phi() const { return is_phi_; } + + // Return the position where this value is defined. + const HloPosition& defining_position() const { return positions_[0]; } + + // Return the instruction which defines this HloValue. + HloInstruction* defining_instruction() const { + return defining_position().instruction; + } + + HloInstruction* instruction() const override { + return defining_instruction(); + } + + // Return the shape index at which this HloValue is defined in the output of + // its defining instruction. + const ShapeIndex& defining_index() const { return defining_position().index; } + + const ShapeIndex& index() const override { return defining_index(); } + + // Return the shape of this HloValue. + const Shape& shape() const override { return defining_position().shape(); } + + using Positions = absl::InlinedVector; + // Return all positions of the HloValue in the module. + const Positions& positions() const { return positions_; } + + // Return all uses of the HloValue. This computes the uses lazily, and the + // overhead could be non-trivial for the first invocation. Therefore even + // though it is marked `const`, it actually can mutate its data members. It is + // kept this way to allow passing around const references. + absl::Span GetUses() const { return uses_.get(); } + + // Returns true if this has a position that is the root of the given + // computation. + bool IsRootOf(const HloComputation* computation) const; + + // Get whether this HloValue is live out of the module. + bool live_out_of_module() const { return live_out_of_module_; } + + bool operator==(const HloValue& other) const { return this == &other; } + bool operator!=(const HloValue& other) const { return !(*this == other); } + + // Return a single-line string representation of the value. + std::string ToShortString() const; + std::string ToString(int indent) const; + std::string ToString() const override { return ToString(0); } + + private: + using Uses = absl::InlinedVector; + // Called when lazily computing the uses. + Uses ComputeUses() const; + + // The set of positions of this HloValue. The first element is always the + // position of the definition. + Positions positions_; + + // The set of uses of this HloValue. This is lazily constructed until getting + // accessed. + Lazy uses_; + + // Whether this instruction is a phi value. + const bool is_phi_; + + // Whether this value is live out of the HLO module. + bool live_out_of_module_ = false; +}; + +std::ostream& operator<<(std::ostream& out, const HloValue& hlo_value); + +// A class representing the possible set of HloValues at a particular point +// (shape index in the output of an instruction) in the XLA graph. This set +// contains the set of reaching HloValue definitions. For a simple array-shaped +// instruction like Add, the HloValueSet of the top-level of the instruction's +// output trivially contains only the HloValue defined by the instruction. For +// instructions which have non-trivial dataflow such as Tuple or Select, the +// HloValueSets of the instruction's output contains one or more HloValues +// defined by the instruction's operands or defined further up in the XLA graph. +class HloValueSet { + public: + HloValueSet() = default; + + explicit HloValueSet(absl::Span values); + explicit HloValueSet(const absl::flat_hash_set& values); + + // Sets this value set to the union of the given value sets. Returns whether + // this value set changed. + bool AssignUnionOf(absl::Span inputs); + + // Return the vector of HloValues in the set. Values in the vector are unique + // and stably sorted by value id. + const std::vector& values() const { return values_; } + + // Adds the value to the set. Returns true iff the value was added and didn't + // already exist in the set. + bool AddValue(const HloValue* value); + + // Clear all values from the set. + void Clear() { values_.clear(); } + + std::vector TakeValues() { return std::move(values_); } + + // Return the unique HLO value in the set. CHECKs if the set does not contain + // exactly one value. + const HloValue& GetUniqueValue() const { + CHECK_EQ(values_.size(), 1); + return *values_[0]; + } + + bool operator==(const HloValueSet& other) const { + if (values_.size() != other.values_.size()) return false; + for (size_t i = 0; i < values_.size(); ++i) { + if (values_[i]->id() != other.values_[i]->id()) { + return false; + } + } + return true; + } + bool operator!=(const HloValueSet& other) const { return !(*this == other); } + + std::string ToString() const; + + private: + // Sorts value_ and removes duplicates. This should be called after adding any + // elements to values_. + void SortAndUniquifyValues(); + + // HloValues sorted by HloValue::Id. + std::vector values_; +}; + +std::ostream& operator<<(std::ostream& out, const HloValueSet& hlo_value); + +// A class collecting the HloValues which might be contained in the output of +// an HLO instruction. For array-shaped instructions, an InstructionValueSet +// trivially holds a single HloValueSet. Tuple-shaped InstructionValueSets +// hold multiple HloValueSets. +class InstructionValueSet : public ShapeTree { + public: + explicit InstructionValueSet(const Shape& shape) + : ShapeTree(shape) {} + + // Sets this value set to the union of the given value sets. Returns whether + // this value set changed. + bool AssignUnionOf(absl::Span inputs); + + // Sets this value set to the input value set at the given index. Returns + // whether this value set changed. + bool AssignUnionOf(const InstructionValueSet& input, + ShapeIndexView input_index); + + // Returns true if any value sets for any subshape element is not a + // singleton. + bool IsAmbiguous() const; + + std::string ToString() const; +}; + +std::ostream& operator<<(std::ostream& out, + const InstructionValueSet& instruction_value_set); + +} // namespace xla + +#endif // XLA_SERVICE_HLO_VALUE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_verifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_verifier.h new file mode 100644 index 0000000000000000000000000000000000000000..600d930327580faf43e431173572359b30346b58 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/hlo_verifier.h @@ -0,0 +1,420 @@ +/* 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_SERVICE_HLO_VERIFIER_H_ +#define XLA_SERVICE_HLO_VERIFIER_H_ + +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Callback to return shape size, in bytes. +using ShapeSizeFn = std::function; + +struct HloVerifierOpts { + HloVerifierOpts&& MakeLayoutSensitive() { + layout_sensitive = true; + return std::move(*this); + } + + HloVerifierOpts&& WithLayoutSensitive(bool layout_sensitive_p) { + layout_sensitive = layout_sensitive_p; + return std::move(*this); + } + + HloVerifierOpts&& WithAllowMixedPrecision(bool allow_mixed_precision_p) { + allow_mixed_precision = allow_mixed_precision_p; + return std::move(*this); + } + + HloVerifierOpts&& AllowMixedPrecision() { + allow_mixed_precision = true; + return std::move(*this); + } + + HloVerifierOpts&& VerifyBroadcastDimensionsOrder() { + verify_broadcast_dimensions_order = true; + return std::move(*this); + } + + HloVerifierOpts&& VerifyReshapeIsBitcast() { + verify_reshape_is_bitcast = true; + return std::move(*this); + } + + HloVerifierOpts&& VerifyCustomCallNestedComputationThreadName() { + verify_custom_call_nested_computation_thread_name = true; + return std::move(*this); + } + + HloVerifierOpts&& WithAllowBitcastToHaveDifferentSize(bool allow) { + allow_bitcast_to_have_different_size = allow; + return std::move(*this); + } + + HloVerifierOpts&& WithInstructionCanChangeLayout( + const HloPredicate& instruction_can_change_layout_p) { + instruction_can_change_layout = instruction_can_change_layout_p; + return std::move(*this); + } + + HloVerifierOpts&& WithCustomShapeSize(const ShapeSizeFn& shape_size_p) { + shape_size = shape_size_p; + return std::move(*this); + } + + HloVerifierOpts&& WithVerifyShardingDeviceNumbers(bool verify) { + verify_sharding_device_numbers = verify; + return std::move(*this); + } + + bool IsLayoutSensitive() const { return layout_sensitive; } + + bool AllowMixedPrecision() const { return allow_mixed_precision; } + + const HloPredicate& InstructionCanChangeLayout() const { + return instruction_can_change_layout; + } + + bool InstructionCanChangeLayout(const HloInstruction* instruction) const { + return !instruction_can_change_layout || + instruction_can_change_layout(instruction); + } + + int64_t ShapeSize(const Shape& shape) const { return shape_size(shape); } + + // If the verifier is layout-sensitive, shapes must be equal to what's + // expected. Otherwise, the shapes must simply be compatible. + bool layout_sensitive = false; + + // Whether the inputs and output of an instruction can contain both F32s and + // BF16s. Tuples that include both F32s and BF16s are allowed regardless of + // this flag. + bool allow_mixed_precision = false; + + // Check that `dimensions` attribute of broadcast is sorted. + bool verify_broadcast_dimensions_order = false; + + // Check that reshape is a physical bitcast. + bool verify_reshape_is_bitcast = false; + + // Check that custom call's called computations have same thread name as + // parent computation. + bool verify_custom_call_nested_computation_thread_name = true; + + // Check device numbers in sharding verification. + bool verify_sharding_device_numbers = true; + + // Whether bitcast should have the same size, including all paddings. + bool allow_bitcast_to_have_different_size = false; + + HloPredicate instruction_can_change_layout; + + // Returns a target-specific shape size. + ShapeSizeFn shape_size = [](const Shape& shape) { + return ShapeUtil::ByteSizeOf(shape); + }; +}; + +// Visitor which verifies that the output shape is correctly set. Verifies +// against the inferred shape for the instruction. +class ShapeVerifier : public DfsHloVisitor { + public: + explicit ShapeVerifier(const HloVerifierOpts& opts) : opts_(opts) {} + + // Verifies that entry computation layout matches parameters and root shape of + // the module's entry computation. + virtual Status VerifyEntryComputationLayout(const HloModule& module); + + Status Preprocess(HloInstruction* hlo) override; + + Status HandleElementwiseUnary(HloInstruction* hlo) override; + Status HandleElementwiseBinary(HloInstruction* hlo) override; + Status HandleClamp(HloInstruction* clamp) override; + Status HandleSelect(HloInstruction* select) override; + Status HandleConcatenate(HloInstruction* concatenate) override; + Status HandleIota(HloInstruction* hlo) override; + Status HandleConvert(HloInstruction* convert) override; + Status HandleBitcastConvert(HloInstruction* convert) override; + Status HandleStochasticConvert(HloInstruction* convert) override; + Status HandleCopy(HloInstruction* copy) override; + Status HandleDot(HloInstruction* dot) override; + Status HandleConvolution(HloInstruction* convolution) override; + Status HandleFft(HloInstruction* fft) override; + Status HandleCholesky(HloInstruction* hlo) override; + Status HandleTriangularSolve(HloInstruction* hlo) override; + Status HandleAllGather(HloInstruction* hlo) override; + Status HandleAllGatherStart(HloInstruction* hlo) override; + Status HandleAllGatherDone(HloInstruction* hlo) override; + Status HandleAllReduce(HloInstruction* hlo) override; + Status HandleAllReduceStart(HloInstruction* hlo) override; + Status HandleAllReduceDone(HloInstruction* hlo) override; + Status HandleAllToAll(HloInstruction* hlo) override; + Status HandleCollectivePermute(HloInstruction* hlo) override; + Status HandleCollectivePermuteStart(HloInstruction* hlo) override; + Status HandleCollectivePermuteDone(HloInstruction* hlo) override; + Status HandlePartitionId(HloInstruction* hlo) override; + Status HandleReplicaId(HloInstruction* hlo) override; + Status HandleReducePrecision(HloInstruction* reduce_precision) override; + Status HandleInfeed(HloInstruction*) override; + Status HandleOptimizationBarrier(HloInstruction* hlo) override; + Status HandleOutfeed(HloInstruction*) override; + Status HandleRng(HloInstruction*) override; + Status HandleRngBitGenerator(HloInstruction*) override; + Status HandleRngGetAndUpdateState(HloInstruction*) override; + Status HandleReverse(HloInstruction* reverse) override; + Status HandleSort(HloInstruction* hlo) override; + Status HandleTopK(HloInstruction* hlo) override; + Status HandleConstant(HloInstruction* constant) override; + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + Status HandleReduce(HloInstruction* reduce) override; + Status HandleBitcast(HloInstruction* bitcast) override; + Status HandleBroadcast(HloInstruction* broadcast) override; + Status HandleReshape(HloInstruction* reshape) override; + Status HandleDynamicReshape(HloInstruction* dynamic_reshape) override; + Status HandleTranspose(HloInstruction* transpose) override; + Status HandleParameter(HloInstruction*) override; + Status HandleFusion(HloInstruction*) override; + Status HandleCall(HloInstruction* call) override; + Status HandleCustomCall(HloInstruction*) override; + Status HandleSlice(HloInstruction* slice) override; + Status HandleDynamicSlice(HloInstruction* dynamic_slice) override; + Status HandleDynamicUpdateSlice( + HloInstruction* dynamic_update_slice) override; + Status HandleTuple(HloInstruction* tuple) override; + Status HandleMap(HloInstruction* map) override; + Status HandleReduceScatter(HloInstruction* hlo) override; + Status HandleReduceWindow(HloInstruction* reduce_window) override; + Status HandleSelectAndScatter(HloInstruction* instruction) override; + Status HandleWhile(HloInstruction* xla_while) override; + Status HandleConditional(HloInstruction* conditional) override; + Status HandlePad(HloInstruction* pad) override; + Status HandleAsyncStart(HloInstruction* async_start) override; + Status HandleAsyncUpdate(HloInstruction* async_update) override; + Status HandleAsyncDone(HloInstruction* async_done) override; + Status HandleCopyStart(HloInstruction* copy_start) override; + Status HandleCopyDone(HloInstruction* copy_done) override; + Status HandleSend(HloInstruction* send) override; + Status HandleSendDone(HloInstruction* send_done) override; + Status HandleRecv(HloInstruction* recv) override; + Status HandleRecvDone(HloInstruction* recv_done) override; + Status HandleBatchNormTraining(HloInstruction* batch_norm_training) override; + Status HandleBatchNormInference( + HloInstruction* batch_norm_inference) override; + Status HandleBatchNormGrad(HloInstruction* batch_norm_grad) override; + Status HandleGather(HloInstruction* gather) override; + Status HandleScatter(HloInstruction* scatter) override; + Status HandleAfterAll(HloInstruction* token) override; + Status HandleGetDimensionSize(HloInstruction* get_size) override; + Status HandleSetDimensionSize(HloInstruction* set_size) override; + Status HandleAddDependency(HloInstruction* add_dependency) override; + + Status FinishVisit(HloInstruction*) override { return OkStatus(); } + + protected: + // Helpers that switch on layout_sensitive_. + bool ShapesSame(const Shape& a, const Shape& b, + bool minor_to_major_only = false, + bool ignore_memory_space = false, bool ignore_tiles = false); + + // Check the instruction's shape against the shape given by ShapeInference + // and return an appropriate error if there is a mismatch. + Status CheckShape(const HloInstruction* instruction, + const Shape& inferred_shape, + bool only_compare_minor_to_major_in_layout = false); + + // Overload which takes a StatusOr to reduce boilerplate in the caller. + Status CheckShape(const HloInstruction* instruction, + const StatusOr& inferred_shape_status); + + static Status CheckParameterCount(const HloInstruction* calling_instruction, + const HloComputation* computation, + int expected); + + // Check a unary (binary, etc) instruction's shape against the inferred shape. + Status CheckUnaryShape(const HloInstruction* instruction); + Status CheckBinaryShape(const HloInstruction* instruction); + Status CheckTernaryShape(const HloInstruction* instruction); + Status CheckVariadicShape(const HloInstruction* instruction); + + private: + bool ShapesSameIgnoringFpPrecision(const Shape& a, const Shape& b, + bool minor_to_major_only = false) { + if (!opts_.layout_sensitive) { + return ShapeUtil::CompatibleIgnoringFpPrecision(a, b); + } + Shape::Equal equal; + if (minor_to_major_only) { + equal.MinorToMajorOnlyInLayout(); + } + equal.IgnoreFpPrecision(); + return equal(a, b); + } + + std::string StringifyShape(const Shape& s) { + return opts_.layout_sensitive ? ShapeUtil::HumanStringWithLayout(s) + : ShapeUtil::HumanString(s); + } + + // Helpers that switch on allow_mixed_precision_. + bool SameElementType(const Shape& a, const Shape& b) { + return opts_.allow_mixed_precision + ? ShapeUtil::SameElementTypeIgnoringFpPrecision(a, b) + : ShapeUtil::SameElementType(a, b); + } + + // Checks that the given operand of the given instruction is of type TOKEN. + Status CheckIsTokenOperand(const HloInstruction* instruction, + int64_t operand_no); + + // Checks that the shape of the given operand of the given instruction matches + // the given parameter of the given computation. + Status CheckOperandAndParameter(const HloInstruction* instruction, + int64_t operand_number, + const HloComputation* computation, + int64_t parameter_number); + + // Checks that the shape of async op operands and results match the called + // computation parameters and root. + Status CheckAsyncOpComputationShapes(const HloInstruction* async_op, + const Shape& async_shape); + + // Returns true if the shapes of the two operands have the same element type, + // and the result shape either has the same element type as the operand shapes + // or mixed precision is allowed and the result shape and the operand shapes + // have floating point element types. + bool HasCompatibleElementTypes(const Shape& shape_0, const Shape& shape_1, + const Shape& result_shape); + + const HloVerifierOpts& opts_; +}; + +// An interface used to encapsulate target-specific verification quirks. +class TargetVerifierMetadata { + public: + explicit TargetVerifierMetadata(HloVerifierOpts&& opts) : opts_(opts) { + CHECK(opts.instruction_can_change_layout == nullptr || + opts.layout_sensitive); + } + + virtual std::unique_ptr GetVerifier() const = 0; + + TargetVerifierMetadata() = default; + virtual ~TargetVerifierMetadata() = default; + + TargetVerifierMetadata(const TargetVerifierMetadata&) = delete; + TargetVerifierMetadata& operator=(const TargetVerifierMetadata&) = delete; + + const HloVerifierOpts& GetVerifierOpts() const { return opts_; } + + private: + HloVerifierOpts opts_; +}; + +// The default implementation of TargetVerifierMetadata, used unless the target +// needs to override it. +class DefaultVerifierMetadata : public TargetVerifierMetadata { + public: + explicit DefaultVerifierMetadata(HloVerifierOpts&& opts) + : TargetVerifierMetadata(std::move(opts)) {} + + // Creates a ShapeVerifier that checks that shapes match inferred + // expectations. This creates a new verifier every time because ShapeVerifier, + // being a DfsHloVisitor, is stateful. We want a clean object for each run of + // the verifier. + std::unique_ptr GetVerifier() const override { + return std::make_unique(GetVerifierOpts()); + } +}; + +// HLO pass that verifies invariants of HLO instructions for each computation in +// the module. +class HloVerifier : public HloModulePass { + public: + HloVerifier( + bool layout_sensitive, bool allow_mixed_precision, + HloPredicate instruction_can_change_layout_func = {}, + std::function shape_size_func = + [](const Shape& shape) { return ShapeUtil::ByteSizeOf(shape); }) + : HloVerifier(HloVerifierOpts{} + .WithLayoutSensitive(layout_sensitive) + .WithAllowMixedPrecision(allow_mixed_precision) + .WithInstructionCanChangeLayout( + instruction_can_change_layout_func) + .WithCustomShapeSize(shape_size_func)) {} + + explicit HloVerifier(HloVerifierOpts&& opts) + : target_metadata_( + std::make_unique(std::move(opts))), + context_("Unknown") {} + + // Uses custom target metadata + explicit HloVerifier(std::unique_ptr target_metadata, + absl::string_view context = "Unknown") + : target_metadata_(std::move(target_metadata)), context_(context) {} + + ~HloVerifier() override = default; + absl::string_view name() const override { return "hlo-verifier"; } + + // Never returns true; no instructions are ever modified by this pass. + using HloPassInterface::Run; + using HloPassInterface::RunOnModuleGroup; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Owns verifier config. + std::unique_ptr target_metadata_; + + // The hlo pass when the verifier is invoked. + std::string context_; +}; + +// Tracks debug metadata coverage on HLO Ops and reports the results as an INFO +// log starting with a `prefix` passed to the ctor. +// TODO(b/261216447): Remove once the work on debug metadata is finished. +class MetadataTracker : public DfsHloVisitorWithDefault { + public: + explicit MetadataTracker(absl::string_view prefix); + ~MetadataTracker() override; + Status DefaultAction(HloInstruction* instruction) override; + void HandleMetadata(const OpMetadata& metadata); + + private: + const std::string prefix_; + int64_t instruction_count_ = 0; + int64_t has_op_type_count_ = 0; + int64_t has_op_name_count_ = 0; + int64_t has_source_file_count_ = 0; + int64_t has_dummy_source_file_count_ = 0; + int64_t has_source_line_count_ = 0; + int64_t has_creation_pass_id_count_ = 0; + int64_t has_logical_creation_pass_id_count_ = 0; + int64_t has_size_of_generated_code_in_bytes_count_ = 0; + int64_t has_size_of_memory_working_set_in_bytes_count_ = 0; + int64_t has_profile_info_count_ = 0; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HLO_VERIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/human_readable_profile_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/human_readable_profile_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..cbd7ebdcd0731f1b0e7070d150cdde3e7768eef5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/human_readable_profile_builder.h @@ -0,0 +1,89 @@ +/* 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_SERVICE_HUMAN_READABLE_PROFILE_BUILDER_H_ +#define XLA_SERVICE_HUMAN_READABLE_PROFILE_BUILDER_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/types.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// HumanReadableProfileBuilder helps you create a textual profile of a +// computation, suitable for consumption by humans. +class HumanReadableProfileBuilder { + public: + explicit HumanReadableProfileBuilder(absl::string_view computation_name, + bool is_entry_computation, + int64_t total_cycles, + double clock_rate_ghz) + : computation_name_(computation_name), + is_entry_computation_(is_entry_computation), + total_cycles_(total_cycles), + clock_rate_ghz_(clock_rate_ghz) { + CHECK_GE(clock_rate_ghz, 1e-9); + } + + int64_t total_cycles() const { return total_cycles_; } + + // Adds an operation to the profile. If you don't know the number of + // floating-point ops or bytes touched by the op, or if you don't know how + // fast it would run optimally, pass -1 for that param. + void AddOp(absl::string_view op_name, absl::string_view short_name, + absl::string_view category, int64_t cycles, int64_t flop_count, + int64_t transcendental_count, int64_t bytes_accessed, + float optimal_seconds) { + op_infos_.push_back({std::string(op_name), std::string(short_name), + std::string(category), cycles, flop_count, + transcendental_count, bytes_accessed, + optimal_seconds}); + } + + // Gets the human-readable profile. + std::string ToString() const; + + private: + struct OpInfo { + std::string name; + std::string short_name; + std::string category; + int64_t cycles; + int64_t flop_count; // -1 if unknown + int64_t transcendental_count; + int64_t bytes_accessed; // -1 if unknown + float optimal_seconds; // -1 if unknown + }; + + double CyclesToSeconds(int64_t cycles) const { + return cycles / clock_rate_ghz_ / 1e9; + } + double CyclesToMicroseconds(int64_t cycles) const { + return cycles / clock_rate_ghz_ / 1000.0; + } + + std::string computation_name_; + bool is_entry_computation_; + int64_t total_cycles_; + double clock_rate_ghz_; + std::vector op_infos_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_HUMAN_READABLE_PROFILE_BUILDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/indexed_array_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/indexed_array_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..4ea4d30e87d8d75ce7c17d534c924f6c38afb260 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/indexed_array_analysis.h @@ -0,0 +1,380 @@ +/* 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_SERVICE_INDEXED_ARRAY_ANALYSIS_H_ +#define XLA_SERVICE_INDEXED_ARRAY_ANALYSIS_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// IndexedArrayAnalysis decides if an HLO instruction can be rewritten as a +// gather from another array. It does this by mapping HLO instructions to +// instances of IndexedArrayAnalysis::Array, which can be inspected to discover +// whether said HLO is equivalent to a gather. +class IndexedArrayAnalysis { + public: + // IndexedArrayAnalysis maps each HLO instruction to an instance of a Array. + // Array really just a sum type of the classes that inherit from it. The + // meaning of each of the subtypes is documented on the subtype declaration. + // + // Array instances are immutable once created. + class Array { + public: + enum Kind { + kUnknown, + kConstant, + kReshaped, + kScalarIndexedConstant, + kScalarIndexed + }; + + virtual Kind kind() const = 0; + virtual const Shape& shape() const = 0; + + // Does a checked downcast from `Array` to `T` which must be one of its + // subtypes. + template + T* as() { + static_assert((std::is_base_of::value), + "target type not derived from source type"); + // We skip the CHECK and hence the dynamic_cast if RTTI is disabled. +#if !defined(__GNUC__) || defined(__GXX_RTTI) + CHECK_NE(dynamic_cast(this), nullptr); +#endif // !defined(__GNUC__) || defined(__GXX_RTTI) + + return static_cast(this); + } + + virtual ~Array() = default; + + Array& operator=(const Array& other) = delete; + }; + + // Represents an HLO instruction that was not analyzable by this + // IndexedArrayAnalysis. Instances of UnknownArray just wrap an existing + // HloInstruction. + class UnknownArray : public Array { + public: + Kind kind() const override { return kUnknown; } + const Shape& shape() const override { return instruction().shape(); } + const HloInstruction& instruction() const { return instruction_; } + + private: + explicit UnknownArray(const HloInstruction* instr) : instruction_(*instr) {} + + const HloInstruction& instruction_; + + friend class IndexedArrayAnalysis; + }; + + // Represents a constant value. This constant value may be present in the HLO + // module being analyzed, or it could have been created on the fly by the + // analysis. + class ConstantArray : public Array { + public: + Kind kind() const override { return kConstant; } + const Shape& shape() const override { return literal()->shape(); } + const Literal* literal() const { return literal_; } + + private: + explicit ConstantArray(const Literal* literal) : literal_(literal) {} + const Literal* literal_; + + friend class IndexedArrayAnalysis; + }; + + // Represents an Array that is a reshape of another Array. + class ReshapedArray : public Array { + public: + Kind kind() const override { return kReshaped; } + + // The array to reshape. + Array* operand() const { return operand_; } + + // The output shape. + const Shape& shape() const override { return shape_; } + + private: + explicit ReshapedArray(Array* operand, Shape shape) + : operand_(operand), shape_(shape) {} + + Array* operand_; + const Shape shape_; + + friend class IndexedArrayAnalysis; + }; + + // --------------------------------------------------------------------------- + // Indexed Array Overview + // --------------------------------------------------------------------------- + // + // ScalarIndexedArray and ScalarIndexedConstantArray form the core of this + // analysis. ScalarIndexedConstantArray is just a specialization of + // ScalarIndexedArray so we will only discuss ScalarIndexedArray in this + // overview. + // + // A ScalarIndexedArray represents an array that can be computed by indexing + // into a "source" array using an "indices" tensor. A simple example is a + // gather operation gathering 12 rows out of a [100,100] matrix -- such an + // operation will be represented by an instance of a ScalarIndexedArray with + // the [100,100] matrix as the "source" array and the [12]-shaped indices + // array as the "indices" tensor. The ScalarIndexedArray operation itself + // will be of shape [12,100] (assuming we were gathering with axis=0). + // + // Gather operations are not the only operation that maps to + // ScalarIndexedArray instances (if that were true there would be little point + // in having a separate analysis). We can often infer ScalarIndexedArrays for + // other operations too. For instance, consider: + // + // %source = f32[100,100] constant + // %indices = s32[12] ... + // %gather = f32[12,100] ... gather from %source using %indices at axis 0 + // %dot = dot(%gather, other_constant) [canonical contracting dims] + // + // The dot operation itself is also a ScalarIndexedArray with source = + // dot(constant, other_constant) and indices = %indices. A reshape of %gather + // to [12,5,20] too is a ScalarIndexedArray with source = an appropriately + // reshaped constant and indices = %indices. + + // Represents the result of a gather operation. This gather operation may + // explicitly be present in the HLO module being analyzed, or it could have + // been created on the fly by the analysis. + // + // An instance of ScalarIndexedArray represents a array whose I'th element can + // be mapped to the J'th element of the `source` array (where I and J are + // multidimensional indices) in this way: + // + // I' = remove components at positions `output_dims` from I + // G' = remove components not at positions `output_dims` from I + // T = indices[G'] + // J = I' with T inserted at position `source_dim` + // + // For example, if source is of shape [11,13,17,19], indices is of shape + // [23,29], output_dims is [0,2] and source_dim is 2 then the output is of + // shape [23,11,29,13,19] and the output index [A,B,C,D,E] is mapped to the + // input index [B,D,indices[A,C],E]. + class ScalarIndexedArray : public Array { + public: + Kind kind() const override { return kScalarIndexed; } + const Shape& shape() const override { return shape_; } + + Array* source() const { return source_; } + Array* indices() const { return indices_; } + + // `source_dim` is the dimension in the source array that is being indexed + // over using indices from the `indices` array. See the class documentation + // and the overview for more details. + int64_t source_dim() const { return source_dim_; } + + // `output_dims` are the dimensions in the output array that are being used + // to compute an index into the `indices` array. See the class + // documentation and the overview for more details. + absl::Span output_dims() const { return output_dims_; } + + private: + explicit ScalarIndexedArray(Array* source, Array* indices, + int64_t source_dim, + std::vector output_dims, Shape shape) + : source_(source), + indices_(indices), + source_dim_(source_dim), + output_dims_(std::move(output_dims)), + shape_(std::move(shape)) {} + + Array* source_; + Array* indices_; + int64_t source_dim_; + std::vector output_dims_; + Shape shape_; + + friend class IndexedArrayAnalysis; + }; + + // A ScalarIndexedConstantArray is just a ScalarIndexedArray constrained to + // have a ConstantArray instance as the source. This is an ergonomic + // concession -- in theory it is possible to just keep ScalarIndexedArray and + // check source()->kind(). + class ScalarIndexedConstantArray : public ScalarIndexedArray { + public: + Kind kind() const override { return kScalarIndexedConstant; } + + const Literal& literal() const { + return *source()->as()->literal(); + } + + private: + explicit ScalarIndexedConstantArray(Array* source, Array* indices, + int64_t source_dim, + std::vector output_dims, + Shape shape) + : ScalarIndexedArray(source, indices, source_dim, + std::move(output_dims), std::move(shape)) { + CHECK(dynamic_cast(source)); + } + + friend class IndexedArrayAnalysis; + }; + + // Returns an Array instance for `instr`. The IndexedArrayAnalysis instance + // keeps ownership of the returned Array instance. + // + // Caching Behavior: IndexedArrayAnalysis has a cache mapping HLO + // instructions to IndexedArrayAnalysis::Array instances. This entire cache + // becomes stale and may cause the analysis to return incorrect results if any + // transitive operand (stopping at the containing computation) is modified for + // any HLO instruction on which GetArrayFor has been invoked. + // + // NB! By inspecting the implementation, you may be able to infer a stronger + // caching guarantee than what is mentioned above. Nevertheless, what is + // stated above is the contract. + StatusOr GetArrayFor(const HloInstruction* instr); + + // Pretty-prints the expression rooted at `root`. + std::string ToString(Array* root, bool print_constants = false); + + private: + // Helper function that ensures that every HLO instruction that is + // transitively used by `root` has an entry in `cache_`. + Status TraverseAndPopulateCache(const HloInstruction* root); + + // Creates an Array instance for `instr` under the assumption that all + // operations of `instr` are present in `cache_`. + StatusOr ComputeArrayFor(const HloInstruction* instr); + + StatusOr ComputeArrayForConstant(const Literal& literal); + + StatusOr ComputeArrayForGather( + const Shape& shape, const GatherDimensionNumbers& dim_numbers, + absl::Span slice_sizes, Array* source, Array* indices); + + StatusOr ComputeArrayForDotWithIndexedLhs( + const Shape& shape, const DotDimensionNumbers& dim_numbers, + const PrecisionConfig& precision_config, ScalarIndexedConstantArray* lhs, + ConstantArray* rhs); + + StatusOr ComputeArrayForDotWithIndexedRhs( + const Shape& shape, const DotDimensionNumbers& dim_numbers, + const PrecisionConfig& precision_config, ConstantArray* lhs, + ScalarIndexedConstantArray* rhs); + + StatusOr ComputeArrayForDot(const Shape& shape, + const DotDimensionNumbers& dim_numbers, + const PrecisionConfig& precision_config, + Array* lhs, Array* rhs); + + // This tries to fold a ScalarIndexedArray which has another + // ScalarIndexedArray as a source into a ScalarIndexedArray that instead has a + // ScalarIndexedArray as indices. If `source` happened to be a + // ScalarIndexedConstantArray this can result in an expression that is more + // canonical. + // + // As an example, consider a gather operation, G0, gathering 7 elements from + // an array "Arr" of shape [100] resulting in an array of shape [7], and a + // second gather operation, G1, which gathers 3 elements out of the result of + // G0 resulting in an array of shape [3]. Let the indices uses by G0 be I0 + // (of shape [7]) and the indices used by G1 be I1 (of shape [3]). We can + // instead rewrite G1 to gather directly from "Arr" with the three indices + // from I0 as per I1. In other words, we can rewrite: + // + // G0 = [Arr[i] for i in I0] + // G1 = [G0[i] for i in I1] + // + // into + // + // I2 = [I0[i] for i in I1] + // G1 = [Arr[i] for i in I2] + StatusOr FoldGatherOfGather( + ScalarIndexedArray* source, Array* indices, int64_t source_dim, + absl::Span output_dims, Shape shape); + + // Reshapes a scalar-indexed node to remove the degenerate dimensions in its + // output. The result is always a scalar-indexed node. + StatusOr ReshapeToRemoveDegenerateDims( + ScalarIndexedArray* operand); + + // Reshapes a scalar-indexed node such that the result has the degenerate + // dimensions `degenerate_dims`. The result is always a scalar-indexed node. + StatusOr ReshapeToAddDegenerateDims( + ScalarIndexedArray* operand, absl::Span degenerate_dims); + + StatusOr FoldReshapeOfGather( + const Shape& shape, ScalarIndexedConstantArray* operand); + StatusOr FoldReshapeOfGatherNoDegenerateDims( + const Shape& shape, ScalarIndexedConstantArray* scalar_indexed); + StatusOr ComputeArrayForReshape(const Shape& shape, Array* operand); + + StatusOr ComputeArrayForElementwiseBinaryOp(HloOpcode opcode, + Array* lhs, Array* rhs); + StatusOr ComputeArrayForElementwiseUnaryOp(HloOpcode opcode, + Array* operand); + + template + T* Construct(Args&&... args) { + T* new_tensor = new T(std::forward(args)...); + owned_tensors_.push_back(std::unique_ptr(new_tensor)); + return new_tensor; + } + + ScalarIndexedArray* ConstructScalarIndexedArray( + Array* source, Array* indices, int64_t source_dim, + std::vector output_dims, Shape shape) { + if (source->kind() == Array::kConstant) { + return Construct(source, indices, source_dim, + std::move(output_dims), + std::move(shape)); + } else { + return Construct(source, indices, source_dim, + std::move(output_dims), + std::move(shape)); + } + } + + Literal* TakeOwnership(Literal literal) { + owned_literals_.push_back(std::move(literal)); + return &owned_literals_.back(); + } + + StatusOr TakeOwnership(StatusOr literal_or_error) { + TF_ASSIGN_OR_RETURN(Literal literal, std::move(literal_or_error)); + owned_literals_.push_back(std::move(literal)); + return &owned_literals_.back(); + } + + std::vector> owned_tensors_; + std::vector owned_literals_; + absl::flat_hash_map cache_; +}; + +// A pass that prints all non-trivial results returned by IndexedArrayAnalysis. +// This pass is a no-op if !VLOG_IS_ON(2) so it should be fine to +// unconditionally add to the regular HLO pass pipeline. +class IndexedArrayAnalysisPrinterPass : public HloModulePass { + public: + absl::string_view name() const override; + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_INDEXED_ARRAY_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/instruction_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/instruction_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..81a22adf0747fe70d59637dfa9b36cb37a4736d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/instruction_fusion.h @@ -0,0 +1,349 @@ +/* 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_SERVICE_INSTRUCTION_FUSION_H_ +#define XLA_SERVICE_INSTRUCTION_FUSION_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +// The source_location.h is not available in open source. +#if defined(PLATFORM_GOOGLE) +#include "absl/types/source_location.h" +#endif // PLATFORM_GOOGLE +#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_reachability.h" +#include "xla/service/fusion_queue.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Propagating explanation of fusion decisions: if something could not be fused, +// explain the reason. +class FusionDecision { + public: + // Can not be fused: explain why. Implicit conversion due to optional-like + // semantics: waiver granted in cl/419938611. + FusionDecision(absl::string_view explanation) // NOLINT + : explanation_(explanation) {} + + // Same constructor as string_view, to allow implicit string conversion (can't + // implicitly convert both char* to string_view and string_view to + // FusionDecision). + FusionDecision(const char* explanation) // NOLINT + : explanation_(explanation) {} + + // If condition is `true` means that we CAN fuse. In that case, explanation is + // discarded. + FusionDecision(bool condition, absl::string_view explanation) { + if (!condition) { + explanation_ = std::string(explanation); + } + } + +#if defined(PLATFORM_GOOGLE) + // We can fuse iff. the decision is `true`. The source location indicates + // where an instance was created, making debugging easier without a need to + // provide explicit explanation. + FusionDecision( // NOLINT + bool decision, + absl::SourceLocation source_location = absl::SourceLocation::current()); +#endif // PLATFORM_GOOGLE + + // Can be fused. + FusionDecision() = default; + + // Returns whether it can be fused. + explicit operator bool() const { return CanFuse(); } + + // Whether the fusion decision is positive. + bool CanFuse() const { return !explanation_.has_value(); } + + // Connects two decisions with a disjunction. This is different than just + // picking one, as we also have to propagate both explanations if only one of + // them is false to show why fusion wasn't performed. + FusionDecision Or(const FusionDecision& decision) const { + if (CanFuse() || decision.CanFuse()) { + return {}; + } + return {absl::StrCat(explanation_.value_or(""), " ; ", decision.Explain())}; + } + + // Connects two fusion decision with a conjunction. Unlike disjunction, + // propagates only one explanation (as it is enough to show that fusion could + // not be done). + FusionDecision And(const FusionDecision& decision) const { + if (CanFuse()) { + return decision; + } + if (decision.CanFuse()) { + return *this; + } + // Both conditions were violated: returning either is valid. + return *this; + } + + // Executes the given fusibility checks in order, until one fails. Returns the + // result of the first failure (or a `FusionDecision` with `CanFuse() == true` + // if none did). + // Usage: + // FusionDecision result = FusionDecision::All(std::tuple{FnOne, FnTwo}, + // arg1, arg2) + template + static FusionDecision All(const std::tuple& checks, + const Args&... args) { + FusionDecision result = {}; + std::apply( + [&](auto&&... fns) { + ((result = result ? fns(args...) : result), ...); + }, + checks); + return result; + } + + // Appends to explanation, or turns the decision negative. + FusionDecision operator<<(absl::string_view explanation) const { + return {absl::StrCat(explanation_.value_or(""), explanation)}; + } + + // Appends to explanation, or turns the decision negative. + FusionDecision operator<<(int64_t explanation) const { + return {absl::StrCat(explanation_.value_or(""), explanation)}; + } + + // Explains why the fusion could not be performed. + std::string Explain() const { return *explanation_; } + + private: + // Empty IFF fusion is possible (explanation provided for negative cases). + std::optional explanation_; +}; + +// HLO pass which performs instruction fusion. Instructions are fused +// "vertically", meaning producing instructions are fused into their consumers +// with the intent that the loops which compute their values will be fused in +// code generation. Derived classes define ShouldFuse method to select which +// instructions to fuse. +class InstructionFusion : public HloModulePass { + public: + explicit InstructionFusion( + std::function is_expensive, + bool may_duplicate = true, + FusionConfigCollection config_collection_mode = + FusionConfigCollection::kOff) + : is_expensive_(is_expensive), + may_duplicate_(may_duplicate), + config_collection_mode_(config_collection_mode) {} + ~InstructionFusion() override = default; + absl::string_view name() const override { return "fusion"; } + + // Run instruction fusion on the given computation. Returns whether the + // computation was changed (instructions were fused). + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Returns true if the computation of the given instruction is significantly + // more expensive than just writing all the values of the instructions' result + // array. Expensive operations will not be duplicated. + static bool IsExpensive(const HloInstruction& instruction); + + // Returns true if it's legal to fuse the producer instruction into consumer + // with regard to in-place semantics of the consumer. For example, it is + // illegal to fuse a slice into a dynamic-update-slice if the slice output is + // used as the update and if slice and dynamic-update-slice indices cannot be + // proven to be the same. + static FusionDecision ShouldFuseInPlaceOp(const HloInstruction* producer, + const HloInstruction* consumer); + + protected: + // Returns a list of computations on which Fusion is performed. + virtual std::vector GetFusionComputations( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + // Returns a FusionQueue that implements custom order of instructions being + // fused. The default implementation processes consumers in reverse post + // order. + virtual std::unique_ptr GetFusionQueue( + HloComputation* computation); + + // Returns whether the given producer instruction should be fused into the + // given consumer instruction. producer is necessarily an operand of consumer. + // Derived classes should define this method to specify which instructions + // should be fused. `operand_index` is which operand of the consumer the + // producer is. + // + // Instructions are traversed in reverse post order (computation root to + // leaves). This method is called for each operand of the instruction (where + // the operand is 'producer' and the instruction is 'consumer') + // + // Subtypes can override this with target-specific heuristics. + virtual FusionDecision ShouldFuse(HloInstruction* consumer, + int64_t operand_index); + + // Returns whether multi-output fusion can be applied to fuse `producer` into + // `consumer`. In contrast to "regular" fusion, the `producer` is not + // duplicated by multi-output fusion. + virtual FusionDecision ShouldFuseIntoMultiOutput(HloInstruction* consumer, + int64_t operand_index) { + return "multi-output fusion not supported by this pass"; + } + + // Chooses a fusion kind for `producer` and `consumer`. + // Default method chooses `kLoop`. + virtual HloInstruction::FusionKind ChooseKind(const HloInstruction* producer, + const HloInstruction* consumer); + + // Fuses 'producer' into 'fusion_instruction'. 'fusion_instruction' needs to + // be a fusion instruction. Returns the newly created clone of 'producer' + // which is part of the fusion computation. + virtual HloInstruction* FuseInstruction(HloInstruction* fusion_instruction, + HloInstruction* producer); + + // Fuses producer into consumer. Returns the fusion instruction. + virtual HloInstruction* Fuse(HloInstruction* producer, + HloInstruction* consumer, + HloComputation* computation); + + // Creates a new fusion instruction containing `producer` and `consumer`. A + // tuple is added as the fusion instruction's root, which consumes from both, + // `producer` and `consumer`. This style of fusion is referred to as + // multi-output fusion. + virtual HloInstruction* FuseIntoMultiOutput(HloInstruction* producer, + HloInstruction* consumer, + HloComputation* computation); + + // An "effectively unary" operation is one that has at most one "large" + // input with the others being negligible in terms of memory usage. + // We use "has a smaller true rank than the output" as a heuristic + // for "negligible" memory usage. + bool EffectivelyAtMostUnary(HloInstruction* hlo); + + // Returns true if fusing producer into consumer would cause producer to be + // duplicated. This is the case if producer has uses other than consumer. + bool FusionWouldDuplicate(const HloInstruction& producer, + const HloInstruction& consumer) { + return !(producer.users().size() == 1 && consumer.IsUserOf(&producer)); + } + + bool is_expensive(const HloInstruction& instruction) { + return is_expensive_(instruction); + } + + // Overwrites the originally initialized is_expensive function. + void set_is_expensive( + std::function is_expensive) { + is_expensive_ = is_expensive; + } + + // Whether multi-output fusion would introduce a cycle into the HLO graph. + bool MultiOutputFusionCreatesCycle(HloInstruction* producer, + HloInstruction* consumer, + const HloReachabilityMap& reachability); + + FusionConfigCollection config_collection_mode() { + return config_collection_mode_; + } + + // Returns whether 'consumer' may reuse elements of its `operand_index`th + // operand. + bool ReusesOperandElements(const HloInstruction* consumer, + int64_t operand_index); + + // The set of producers whose consumers we cannot fuse into. + using HloInstructionSet = absl::flat_hash_set; + + // Computes the set of nodes that we do not want to fuse into any of their + // consumers based on a global analysis of the HLO graph. + virtual HloInstructionSet ComputeGloballyUnfusible( + absl::Span post_order, + const HloReachabilityMap& reachability); + + private: + // Returns the reused operands of `instruction` from reused_fusion_operands_, + // computing them if they have not previously been computed for that + // instruction. + // The returned value has pointer stability, assuming entries are not deleted + // from reused_fusion_operands_. + absl::flat_hash_set& ReusedOperandsOf( + const HloInstruction* instruction); + + // Updates reused_fusion_operands_ for a fusion when we are about to fuse + // `producer` into `fusion_instruction`. + void UpdateReusedOperandsForFusion(HloInstruction* producer, + HloInstruction* fusion_instruction); + + HloInstruction* AddFusionInstruction(HloInstruction* producer, + HloInstruction* consumer, + HloComputation* computation); + + // Whether or not we can fuse producer into consumer on all paths + // from the producer to the consumer where nodes are HLOs and edges are uses. + // + // A map from to a bool is required as the result cache + // to store and query the results of calls to this function, in order to avoid + // repeated computations. + bool CanFuseOnAllPaths( + HloInstruction* producer, HloInstruction* consumer, + const HloInstructionSet& do_not_fuse, + const HloReachabilityMap& reachability, + absl::flat_hash_map, bool>* + result_cache); + + // Used to determine if an HLO is expensive. Expensive operations will not be + // duplicated. + std::function is_expensive_; + + // Dumps the state of computation before fusion. + void DumpPreFusionState(HloComputation* computation, HloInstruction* consumer, + HloInstruction* producer, bool is_mof = false); + + // Dumps the state of computation and the reason why the fusion was not + // performed. + void DumpNotFusingState(HloComputation* computation, HloInstruction* consumer, + HloInstruction* producer, FusionDecision decision); + + // Dumps the state of computation after fusion happened. + void DumpStateAfterFusion(HloComputation* computation, + HloInstruction* fusion_instruction, + const std::string& producer_name); + + // Returns whether we may duplicate an instruction if we want to fuse it. + bool may_duplicate_; + + // Configuration mode. + FusionConfigCollection config_collection_mode_; + + // Caches which operands are reused inside fusion computations. + absl::flat_hash_map< + const HloInstruction*, + std::unique_ptr>> + reused_fusion_operands_; + + InstructionFusion(const InstructionFusion&) = delete; + InstructionFusion& operator=(const InstructionFusion&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_INSTRUCTION_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/latency_hiding_scheduler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/latency_hiding_scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..5c9206d56fe339c0a46fc2c2624e8d1e34fab41c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/latency_hiding_scheduler.h @@ -0,0 +1,893 @@ +/* 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_SERVICE_LATENCY_HIDING_SCHEDULER_H_ +#define XLA_SERVICE_LATENCY_HIDING_SCHEDULER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/strings/str_cat.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_alias_analysis.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/xla.pb.h" + +namespace xla { + +struct CanonicalAsyncOp { + HloOpcode outer; // kAsyncStart or kAsyncDone + HloOpcode inner; // kAllReduce, kAllGather, kAllToAll, kCollectivePermute, + // or kReduceScatter +}; + +CanonicalAsyncOp DefaultGetCanonicalAsyncOp(const HloInstruction& hlo); + +using GetCanonicalAsyncOpFunc = + std::function; + +class HloGraphNode; +class ModulePressureState; + +enum class ResourceType { + kNoResource = 0, + kAllToAll = 1, + kAllGather = 2, + kAllReduce = 3, + kCollectivePermute = 4, + kReduceScatter = 5, + kSendRecv = 6, + kSendHost = 7, + kRecvHost = 8, + kNumResources = 9, + kTargetDefinedResourcesBound = 10000, +}; + +enum class ResourceUsageType { + kNoResource, + kResourceOccupy, + kResourceRelease, +}; + +enum class ResourceHazardType { + kShareable = 0, + kSerial = 1, + kUnshareable = 2, +}; + +constexpr int64_t ResourceTypeToIndex(ResourceType resource_type) { + return static_cast(resource_type); +} + +constexpr int64_t ResourceUsageTypeToIndex( + ResourceUsageType resource_usage_type) { + return static_cast(resource_usage_type); +} + +using ResourcePair = std::pair; +using ResourcesVector = absl::InlinedVector; + +class HloGraphNode; +class HloScheduleGraph; + +struct SchedulerConfig { + int64_t collective_permute_overlap_limit = 1; + int64_t all_to_all_overlap_limit = 1; + int64_t all_gather_overlap_limit = 1; + int64_t all_reduce_overlap_limit = 1; + int64_t reduce_scatter_overlap_limit = 1; + int64_t send_recv_overlap_limit = 1; + int64_t send_recv_host_overlap_limit = 1; + uint64_t memory_limit = UINT64_MAX; + bool schedule_send_recvs = false; + // Consider send recv as the same resource. Some platforms do not take well + // overlapping the send/recv ops between themselves. + bool force_send_recv_to_use_same_resource = false; + bool use_real_cost_model = false; + bool aggressive_scheduling_policies = false; + bool enable_release_start_policy = false; + bool resource_sharing = false; + bool depth_based_memory_pressure_reduction = false; +}; + +// Class used estimate latency between instructions and cost of HLOs. +class LatencyEstimator { + public: + using TimeCost = double; + // Uses the approximate or cost model function for GetLatencyBetween based on + // a flag. + virtual TimeCost GetLatencyBetween(const HloGraphNode& from, + const HloGraphNode& target) const = 0; + // Uses the approximate or cost model function for NodeCost based on a flag. + virtual TimeCost NodeCost(const HloInstruction* node) const = 0; + // Returns the core frequency used in latency estimation. + virtual int CyclesPerMicrosecond() const = 0; + virtual ~LatencyEstimator() = default; + + inline CanonicalAsyncOp GetCanonicalAsyncOp(const HloInstruction& hlo) const { + return get_canonical_async_op_(hlo); + } + bool IsAsyncPair(const HloGraphNode& from, const HloGraphNode& target) const; + explicit LatencyEstimator( + GetCanonicalAsyncOpFunc func = DefaultGetCanonicalAsyncOp) + : get_canonical_async_op_(func) {} + + private: + GetCanonicalAsyncOpFunc get_canonical_async_op_; +}; + +// Implementation of LatencyEstimator using an approximate cost model. +class ApproximateLatencyEstimator : public LatencyEstimator { + public: + explicit ApproximateLatencyEstimator( + GetCanonicalAsyncOpFunc func = DefaultGetCanonicalAsyncOp) + : LatencyEstimator(func) {} + + // Returns a latency estimation between two instructions. + // Currently this is in abstract units. When the real/accurate cost model is + // implemented this will be in cycles. + TimeCost GetLatencyBetween(const HloGraphNode& from, + const HloGraphNode& target) const override; + // Uses the approximate or cost model function for NodeCost based on a flag. + TimeCost NodeCost(const HloInstruction* instr) const override; + // ApproximateLatencyEstimator uses abstract units so this returns 1. + int CyclesPerMicrosecond() const override { return 1; } + + public: + static constexpr TimeCost kLowCost = 1.0; + static constexpr TimeCost kMediumCost = 1000.0; + static constexpr TimeCost kHighCost = 5000.0; + + protected: + // These values are empirically derived to obtain an overlap of one output + // fusion/convolution with 1 async op or 5 loop fusions with an async op. + static constexpr TimeCost kLowLatency = 1.0; + static constexpr TimeCost kHighLatency = 5000.0; +}; + +// Helper class to keep track of which instructions are to be supported and +// how many supported instructions per-type are contained in computations +// recursively. +class AsyncTracker { + public: + virtual ~AsyncTracker() = default; + + // Returns if this is an Async op done that the scheduler supports. + virtual bool IsSupportedAsyncDone(const HloInstruction& hlo) const; + + // Returns if this is an Async op start that the scheduler supports. + virtual bool IsSupportedAsyncStart(const HloInstruction& hlo) const; + + // Returns resources used (i.e., occupied or released) by this instruction + virtual ResourcesVector GetResourcesFromInstruction( + const HloInstruction& hlo) const; + + // Modifies the schedule graph passed as input to add dependencies that are + // implicit based on the system we are running on. + virtual void PostProcessScheduleGraph( + HloScheduleGraph* schedule_graph, + const LatencyEstimator* latency_estimator) const {} + + // Returns the number of resources (of type resource_type) that are used by + // this instruction. + virtual int64_t GetNumResourcesPerInstruction( + ResourceType resource_type, const HloInstruction& instr) const; + virtual int64_t GetNumResourcesPerInstruction( + int64_t resource_type, const HloInstruction& instr) const; + + // Sets the maximum allowed number of instances for each resource + virtual void SetConcurrentResourceLimits( + absl::flat_hash_map& max_concurrent_resource) const; + + // Returns the name of the given resource + virtual absl::string_view GetResourceName(int64_t resource_type) const; + + // Returns the name of the given resource usage + absl::string_view GetResourceUsageName(int64_t resource_usage_type) const; + absl::string_view GetResourceUsageName( + ResourceUsageType resource_usage_type) const; + + // Returns the first target defined resource's id, regardless of if it exits + static int64_t GetFirstTargetDefinedResource() { + return static_cast(ResourceType::kTargetDefinedResourcesBound) + 1; + } + + // Returns the number of target defined resources + virtual int64_t GetNumTargetDefinedResources() const; + + // Returns how many instructions using the given resource_type we can overlap + virtual int64_t GetNumAvailableResources(int64_t resource_type) const; + + // Returns the hazard type that describes how to resolve the conflicts when + // multiple instructions attempt to use the given resource type concurrently. + // Default resources have a hazard type of kUnshareable. + virtual ResourceHazardType GetResourceHazardType(int64_t resource_type) const; + + // Returns the list of the released shareable resources filtered from the + // given resources vector. + virtual absl::InlinedVector + GetReleasedShareableResourcesFromVector( + const ResourcesVector& resources) const; + + // Returns the list of the occupied shareable resources filtered from the + // given resources vector. + virtual absl::InlinedVector + GetOccupiedShareableResourcesFromVector( + const ResourcesVector& resources) const; + + inline CanonicalAsyncOp GetCanonicalAsyncOp(const HloInstruction& hlo) const { + return get_canonical_async_op_(hlo); + } + + explicit AsyncTracker( + const SchedulerConfig& config, + GetCanonicalAsyncOpFunc func = DefaultGetCanonicalAsyncOp) + : config_(config), get_canonical_async_op_(func) {} + + private: + const SchedulerConfig config_; + mutable absl::flat_hash_map> + async_in_computation_cache_; + GetCanonicalAsyncOpFunc get_canonical_async_op_; +}; + +// Base class for the core scheduling algorithm. +class SchedulerCore { + public: + virtual Status InitializeScheduler(const HloModule* module) = 0; + virtual StatusOr> ScheduleComputation( + const HloComputation* computation) = 0; + virtual ~SchedulerCore() = default; +}; + +// Represents an edge between two nodes in the schedule graph. +class HloEdge { + public: + // Nullptr is not a valid value for 'target'. + HloEdge(LatencyEstimator::TimeCost latency, HloGraphNode* target) + : latency_(latency), original_latency_(latency), target_(target) {} + LatencyEstimator::TimeCost Latency() const { return latency_; } + LatencyEstimator::TimeCost OriginalLatency() const { + return original_latency_; + } + void SetLatency(LatencyEstimator::TimeCost latency) { latency_ = latency; } + void SetOriginalLatency(LatencyEstimator::TimeCost original_latency) { + original_latency_ = original_latency; + } + const HloGraphNode& Target() const { return *target_; } + HloGraphNode& Target() { return *target_; } + std::string ToString() const; + + private: + // Latency between the two nodes connected by this edge. The other end of the + // edge is the owner of the HloEdge object. This latency can get updated due + // to various scheduling optimizations. + LatencyEstimator::TimeCost latency_; + // Original latency is the initial latency value (typically computed by a + // latency estimator). + LatencyEstimator::TimeCost original_latency_; + // Target node of this edge. + HloGraphNode* target_; +}; + +// Node in the schedule graph, plus information used for scheduling. +class HloGraphNode { + public: + using TimeCost = LatencyEstimator::TimeCost; + + // Nullptr is not a valid value for 'i'. + explicit HloGraphNode(const HloInstruction* i, int64_t original_position) + : instr_(i), original_position_(original_position) {} + const HloInstruction& GetInstr() const { return *instr_; } + bool IsScheduled() const { return scheduled_; } + int32_t GetIndegree() const { return indegree_; } + int32_t GetOutdegree() const { return outdegree_; } + TimeCost GetReadyTime() const { return ready_time_; } + void SetIndegree(int64_t indeg) { indegree_ = indeg; } + void SetOutdegree(int64_t outdeg) { outdegree_ = outdeg; } + void SetScheduled() { scheduled_ = true; } + void SetReadyTime(TimeCost ready_time) { ready_time_ = ready_time; } + TimeCost GetCost() const { return cost_; } + void SetCost(TimeCost cost) { cost_ = cost; } + TimeCost GetAsyncDepth() const { return async_depth_; } + TimeCost GetDepth() const { return depth_; } + TimeCost GetGraphDepth() const { return graph_depth_; } + void SetAsyncDepth(TimeCost async_depth) { async_depth_ = async_depth; } + void SetDepth(TimeCost depth) { depth_ = depth; } + void SetGraphDepth(TimeCost graph_depth) { graph_depth_ = graph_depth; } + bool GetForceDelay() const { return force_delay_; } + void SetForceDelay(bool force_delay) { force_delay_ = force_delay; } + ResourcesVector GetResources() const { return resources_; } + bool DoesOccupyAnyResource() const { + return absl::c_any_of(resources_, [](const ResourcePair& resource) { + return resource.second == ResourceUsageType::kResourceOccupy; + }); + } + bool DoesReleaseAnyResource() const { + return absl::c_any_of(resources_, [](const ResourcePair& resource) { + return resource.second == ResourceUsageType::kResourceRelease; + }); + } + bool DoesOccupyShareableResource(int64_t resource) const { + return absl::c_linear_search(occupied_shareable_resources_, resource); + } + bool DoesReleaseResource(ResourceType res) const { + return absl::c_any_of(resources_, [res](const ResourcePair& resource) { + return resource.second == ResourceUsageType::kResourceRelease && + resource.first == ResourceTypeToIndex(res); + }); + } + std::optional UsesResourceType(ResourceType res) const { + int64_t res_type = ResourceTypeToIndex(res); + for (const auto& [resource_type, usage_type] : resources_) { + if (resource_type == res_type) { + return usage_type; + } + } + return std::nullopt; + } + std::optional UsesResourceType(int64_t res) const { + for (const auto& [resource_type, usage_type] : resources_) { + if (resource_type == res) { + return usage_type; + } + } + return std::nullopt; + } + std::vector GetShareableResourcesOnEdge(const HloEdge& edge) const { + HloGraphNode node = edge.Target(); + std::vector resources; + absl::c_for_each(released_shareable_resources_, + [&node, &resources](const int64_t resource) { + if (node.DoesOccupyShareableResource(resource)) { + resources.push_back(resource); + } + }); + return resources; + } + absl::Span GetPredecessors() { + return absl::MakeSpan(predecessors_); + } + absl::Span GetPredecessors() const { + return absl::MakeConstSpan(predecessors_); + } + void AddPredecessor(const HloEdge& e) { predecessors_.push_back(e); } + absl::Span GetSuccessors() { return absl::MakeSpan(successors_); } + absl::Span GetSuccessors() const { + return absl::MakeConstSpan(successors_); + } + void AddSuccessor(const HloEdge& e) { successors_.push_back(e); } + int64_t GetOriginalPosition() const { return original_position_; } + std::string ToString(const AsyncTracker* async_tracker = nullptr) const { + std::string result; + absl::StrAppend(&result, "Instr: ", instr_->ToShortString(), "\n"); + absl::StrAppend(&result, "ReadyTime: ", ready_time_, "\n"); + absl::StrAppend(&result, "Indegree: ", indegree_, "\n"); + absl::StrAppend(&result, "Outdegree: ", outdegree_, "\n"); + absl::StrAppend(&result, "Cost: ", cost_, "\n"); + absl::StrAppend(&result, "Async Depth: ", async_depth_, "\n"); + absl::StrAppend(&result, "Depth: ", depth_, "\n"); + absl::StrAppend(&result, "Graph Depth: ", graph_depth_, "\n"); + absl::StrAppend(&result, "Force Delay: ", force_delay_, "\n"); + absl::StrAppend(&result, "Predecessors:\n"); + for (const HloEdge& e : predecessors_) { + absl::StrAppend(&result, e.ToString()); + } + absl::StrAppend(&result, "Successors:\n"); + for (const HloEdge& e : successors_) { + absl::StrAppend(&result, e.ToString()); + } + if (async_tracker != nullptr) { + absl::StrAppend(&result, "Resources:\n"); + for (const auto& [resource, usage] : resources_) { + absl::StrAppend( + &result, "\tResource: ", async_tracker->GetResourceName(resource), + " usage: ", async_tracker->GetResourceUsageName(usage), "\n"); + } + } + return result; + } + + private: + friend class HloScheduleGraph; + // List of predecessor edges. + std::vector predecessors_; + // List of successor edges. + std::vector successors_; + // Instruction this Graph node represents + const HloInstruction* instr_; + // The prosition of this node in the original order. + int64_t original_position_; + // Estimated time at which this node is gonna be ready to be scheduled. + // The node should be added to the ready to be scheduled set when ready_time_ + // is less or equal to the current time in the schedule. + TimeCost ready_time_ = std::numeric_limits::max(); + // Number of predecessor nodes this nodes depends on that haven't been + // scheduled yet. + int32_t indegree_ = 0; + // Number of successor nodes this nodes depends on that haven't been + // scheduled yet. + int32_t outdegree_ = 0; + // Time cost of the execution of the operation of this nodes represent. + TimeCost cost_ = 0.0; + // Depth in latency terms of a node based on Async operation cost on the path. + TimeCost async_depth_ = 0.0; + // Depth in latency terms of node based on operation cost on the path to the + // entry node. + TimeCost depth_ = 0.0; + // Depth in latency terms of node based on distance to the entry node. + int64_t graph_depth_ = 0; + // AsyncResources used by the node. + ResourcesVector resources_; + // Force the scheduling of the nodes with attribute set as late as possible. + bool force_delay_ = false; + // Whether this node has been scheduled or not yet. + bool scheduled_ = false; + // Shareable resources released by this node. + absl::InlinedVector released_shareable_resources_; + // Shareable resources occupied by this node. + absl::InlinedVector occupied_shareable_resources_; +}; + +// Schedule graph that can be used to drive scheduling +// of HLO instructions. +class HloScheduleGraph { + public: + // Instructions in the list passed to the constructor shouldn't be + // altered/deleted during the existence of the HloScheduleGraph. + // Nullptr is not a valid value for 'post_order_instructions' and + // 'alias_analysis'. + HloScheduleGraph(const std::vector* post_order_instructions, + HloAliasAnalysis* alias_analysis, + const LatencyEstimator* latency_estimator, + const AsyncTracker* async_tracker); + + std::string ToString(const AsyncTracker* async_tracker = nullptr) const; + + HloGraphNode& GetNode(const HloInstruction* instr) const; + + std::vector FindBottomRoots() const; + + std::vector FindTopRoots() const; + + void InitializeGraphAnalysis(const AsyncTracker* async_tracker); + + // l of instructions in the original scheduled order. (Before scheduling). + absl::Span GetOriginalInstrList() const { + return absl::MakeConstSpan(original_order_); + } + // Returns what was the original instruction position in the original order. + int64_t OriginalInstructionPosition(const HloInstruction* instr) const { + auto it = instr_order_map_.find(instr); + CHECK(it != instr_order_map_.end()); + return it->second; + } + + private: + // Map that allocates the nodes of the graph. + absl::flat_hash_map> + nodes_; + // Map containing the ordinal value for each instruction. + absl::flat_hash_map instr_order_map_; + // List containing the original order (before scheduling) of the + // instructions). + std::vector original_order_; +}; + +// Tracks data about HloBuffers like where the first definition is in the +// original schedule and caches the buffer size (as Target::ShapeSize()) is +// expensive. +class BufferInfoTracker { + public: + struct ValueInfo { + const HloBuffer* value = nullptr; + const HloInstruction* first_definition = nullptr; + int64_t buffer_size = 0; + }; + BufferInfoTracker(const HloModule* module, + const HloAliasAnalysis* alias_analysis, + const HloCostAnalysis::ShapeSizeFunction& shape_size_bytes); + static ValueInfo CreateBufferInfo( + const HloBuffer* value, const HloInstruction* first_definition, + const HloCostAnalysis::ShapeSizeFunction& shape_size_bytes) { + return ValueInfo{ + /*value=*/value, /*first_definition=*/first_definition, + /*buffer_size=*/shape_size_bytes(value->values()[0]->shape())}; + } + const ValueInfo& GetBufferInfo(HloBuffer::Id id) const { + return buffer_infos_[id]; + } + + private: + std::vector buffer_infos_; +}; + +// Used to track and maintain memory pressure during scheduling. +class MemoryPressureTracker { + public: + using LiveBufferSet = absl::flat_hash_set; + struct MemoryPressureState { + int64_t memory_peak = 0; + absl::flat_hash_set live_ids_at_bottom; + }; + MemoryPressureTracker( + const HloAliasAnalysis* hlo_alias_analysis, + const BufferInfoTracker& buffer_tracker, + const absl::flat_hash_map& + pressure_state_cache) + : hlo_alias_analysis_(hlo_alias_analysis), + live_buffers_(hlo_alias_analysis->buffers().back().id() + 1), + buffer_tracker_(buffer_tracker), + pressure_state_cache_(pressure_state_cache), + live_memory_usage_(0), + initial_memory_pressure_(0) {} + // Intiialize object to be ready to start tracking of computation. + void Initialize(const HloComputation* computation, + const LiveBufferSet& initial_live_buffers); + // After an instruction is scheduled, update the memory pressure effect on + // other instructions. + void UpdateBuffers(const HloInstruction* instruction); + // Return the memory pressure difference estimation if this instruction was + // scheduled. + // Returns a pair of (increase, peak) values. + // "increase" determines by how much the memory pressure increases or + // decreases after this instruction is scheduled. "peak" determines what's the + // peak usage of memory of the computation. The peak can be higher than the + // total memory increase of the instruction (imagine a computation called by a + // while loop, the body of the while could use quite some more memory than the + // amount of memory at the interfaces of the while loop instruction). + std::pair MemoryPressureDifference( + const HloInstruction* instruction) const; + absl::flat_hash_set live_buffers() const { + return live_buffers_set_; + } + bool BufferIsLive(const HloValue* buffer) const { + CHECK_LT(buffer->id(), live_buffers_.size()); + return live_buffers_[buffer->id()]; + } + // Returns the actual memory usage at the current state. It is initial memory + // + current memory usage inside of the computation. + int64_t memory_usage() const { + return live_memory_usage_ + initial_memory_pressure_; + } + // Returns the initial memory pressure at the bottom of the computation. + int64_t initial_memory_pressure() const { return initial_memory_pressure_; } + + // Returns pressure state object for this MemoryPressureTracker object. + const MemoryPressureState& pressure_state() const { return pressure_state_; } + + private: + static bool ShouldSkipBufferAllocations(const HloInstruction* instruction, + const ShapeIndex& idx) { + // Make GetTupleElement/kBitcast make alive only the tuple pointer if not + // array shape. + if ((instruction->opcode() == HloOpcode::kGetTupleElement || + instruction->opcode() == HloOpcode::kBitcast) && + !idx.empty()) { + return true; + } + return false; + } + static bool ShouldSkipBufferReleases(const HloInstruction* instruction) { + // Make GetTupleElement/kBitcast make alive only the tuple pointer if not + // array shape. + if (instruction->opcode() == HloOpcode::kParameter) { + return true; + } + return false; + } + const HloAliasAnalysis* hlo_alias_analysis_; + // Live buffer presence set. This is used to determine if a buffer is live or + // not in a fast way. Because this is checked very often in the evaluation + // function of the scheduler quering the live_buffer_set_ object is too slow. + // This is much faster in a tight loop. Also we use int8_t explicitly rather + // than "bool" as "bool" is optimized and bit-packed trading memory for bit + // extract operations. + std::vector live_buffers_; + // Set of live buffer ids. + LiveBufferSet live_buffers_set_; + const BufferInfoTracker& buffer_tracker_; + // Cache of buffer objects defined that are output of instructions. + absl::flat_hash_map< + HloInstruction*, + std::vector>> + output_buffers_; + // Cache of buffer objects defined that are defined by instructions. + absl::flat_hash_map> + defined_buffers_; + // Map with pressure_state object for other computations. It's updated by + // the user of this class. + const absl::flat_hash_map& + pressure_state_cache_; + // Current memory usage delta from the initial memory of the computation. + int64_t live_memory_usage_; + // Initial memory pressure at the bottom of the computation. + int64_t initial_memory_pressure_; + MemoryPressureState pressure_state_; +}; + +// Module memory pressure state object. Handles and holds all the objects used +// to store information about memory pressure for computations. +// Computes initial pressure state. +class ModulePressureState { + public: + using PressureStateMap = + absl::flat_hash_map; + ModulePressureState( + const HloModule* module, const HloAliasAnalysis* hlo_alias_analysis, + const HloCostAnalysis::ShapeSizeFunction& shape_size_bytes) + : module_(module), + hlo_alias_analysis_(hlo_alias_analysis), + buffer_tracker_(module, hlo_alias_analysis, shape_size_bytes) {} + void InitializePressureStates(); + bool ComputationIsMemoryTracked(const HloComputation* computation) const { + return ContainsKey(memory_pressure_states_, computation); + } + // Get memory pressure state for a certain computation stored in this class. + const MemoryPressureTracker::MemoryPressureState& + GetPressureStateForComputation(const HloComputation* comp) const { + auto it = memory_pressure_states_.find(comp); + CHECK(it != memory_pressure_states_.end()) + << "No state for " << comp->name(); + return it->second; + } + // Updates the memory pressure state cache. + void UpdatePressureStateForComputation( + const HloComputation* comp, + MemoryPressureTracker::MemoryPressureState state) { + memory_pressure_states_[comp] = state; + } + // Returns the underlying pressure state cache object + const PressureStateMap& pressure_state_cache() const { + return memory_pressure_states_; + } + // Returns the buffer tracker object. + const BufferInfoTracker& buffer_tracker() const { return buffer_tracker_; } + + private: + const HloModule* module_; + const HloAliasAnalysis* hlo_alias_analysis_; + absl::flat_hash_map + memory_pressure_states_; + BufferInfoTracker buffer_tracker_; +}; + +// Implementation of the default scheduling algorithm. +class DefaultSchedulerCore : public SchedulerCore { + public: + using ReadyQueueSet = std::vector; + using ResourceMap = absl::flat_hash_map; + using ShouldSkipNodeFunction = std::function; + + // Class used to cache expensive information. Currently memory pressure + // changes are cached. The caching is invalidated at the end of the scheduling + // process for this next candidate. The information shouldn't survive across + // scheduling two different instructions. + struct ScheduleCandidate { + HloGraphNode* node = nullptr; + std::optional> pressure_change; + std::optional estimated_connected_send_ready_time; + std::optional resource_constrained; + }; + + struct CandidateResult { + ScheduleCandidate result; + const char* reason; + }; + + using TargetSchedulingRule = std::function( + ScheduleCandidate&, ScheduleCandidate&)>; + + // Returns nullopt if both parameters are equal, otherwise true if the first + // parameter is true and false if the second is true + static std::optional TrueForOneOnly(bool first, bool second) { + if (first == second) { + return std::nullopt; + } + return first; + } + + static std::optional ChooseBestCandidate( + bool first_cond, const ScheduleCandidate& first_candidate, + bool second_cond, const ScheduleCandidate& second_candidate, + const char* reason) { + if (auto cond = TrueForOneOnly(first_cond, second_cond)) { + return CandidateResult{*cond ? first_candidate : second_candidate, + reason}; + } + return std::nullopt; + } + + // The scheduling state contains everything that is required for the + // bookkeeping of the scheduling algorithm. Functions that perform operations + // over the scheduling state can directly operate on the state contained into + // this struct instead of having to pass many individual pointers to elements + // of the state. + struct SchedulingState { + HloScheduleGraph sched_graph; + // Ready set for the nodes. Its ordered by our heuristic defined in + // ReadySetLt. + ReadyQueueSet ready_set; + // Maximum allowed number of overlapping instructions using the key resource + // type. + ResourceMap max_concurrent_resource; + // New scheduling sequence produced by the scheduler. This is in reversed + // order (because we schedule bottom up). This will be required to be + // reversed before assigning to the HloSchedule. + std::vector new_sequence_reversed; + // Units of time passed in the schedule. To keep track of latency hiding. + HloGraphNode::TimeCost current_time = 0; + // Number of resources in flight. + ResourceMap resources_in_flight; + // Number of instructions using the key resource type in the set waiting to + // be scheduled. + ResourceMap resource_users_in_queue; + // Number of nodes scheduled. + int64_t scheduled_count = 0; + // Class returning information about instruction cost and latency between + // instructions. + const LatencyEstimator* latency_estimator; + // Class used to track which instructions are async instructions and which + // async instructions computations contain. + const AsyncTracker* async_tracker; + // Tracker of memory pressure for the computation. + MemoryPressureTracker* memory_pressure_tracker; + // Vector containing a list of nodes that aren't ready to schedule yet in + // order of time when they are going to become ready. + std::vector next_ready_stack; + // List of the graph edges currently occupying the key shareable resource + // with projected finish times. + absl::flat_hash_map< + int64_t, std::vector>> + shareable_resource_occupiers; + // Reference to this scheduler run configuration. + const SchedulerConfig& config; + SchedulingState(const HloInstructionSequence* instr_sequence, + HloAliasAnalysis* alias_analysis, + const LatencyEstimator* latency_estimator, + const AsyncTracker* async_tracker, + MemoryPressureTracker* memory_pressure_tracker, + const SchedulerConfig& config) + : sched_graph(&instr_sequence->instructions(), alias_analysis, + latency_estimator, async_tracker), + latency_estimator(latency_estimator), + async_tracker(async_tracker), + memory_pressure_tracker(memory_pressure_tracker), + config(config) {} + }; + + using PostProcessingFn = std::function; + + DefaultSchedulerCore( + HloCostAnalysis::ShapeSizeFunction shape_size_bytes, + const AsyncTracker* async_tracker, + const LatencyEstimator* latency_estimator, const SchedulerConfig& config, + TargetSchedulingRule target_scheduling_rule = nullptr, + TargetSchedulingRule early_target_scheduling_rule = nullptr, + PostProcessingFn post_processing_fn = nullptr) + : shape_size_bytes_(shape_size_bytes), + async_tracker_(async_tracker), + latency_estimator_(latency_estimator), + config_(config), + target_scheduling_rule_(target_scheduling_rule), + early_target_scheduling_rule_(early_target_scheduling_rule), + post_processing_fn_(post_processing_fn) {} + Status InitializeScheduler(const HloModule* module) override; + StatusOr> ScheduleComputation( + const HloComputation* computation) override; + static bool AddOccupierToResource( + HloGraphNode::TimeCost current_time, HloEdge& new_edge, + std::vector>& occupiers); + static bool DeleteOccupierFromResource( + HloGraphNode::TimeCost current_time, HloEdge& edge, + std::vector>& occupiers); + + protected: + virtual void LogInstruction(const HloInstruction* instr) const; + // Update node that has been scheduled. + virtual StatusOr ScheduleNode( + HloGraphNode* n, SchedulingState* sched_state) const; + // Perform the scheduling of one or more instructions. Called every time the + // ready set is not empty. + virtual Status SchedulingStep(SchedulingState* sched_state); + // Pick a node to schedule according to cost model. + virtual HloGraphNode* FindAndExtractBestNodeAvailable( + SchedulingState& sched_state, + DefaultSchedulerCore::ShouldSkipNodeFunction should_skip_node); + void DumpLatencyHidingSchedule( + const HloComputation* computation, const HloScheduleGraph& schedule_graph, + const std::vector& instructions, + int cycles_per_microsecond, const DebugOptions& debug_options); + + HloCostAnalysis::ShapeSizeFunction shape_size_bytes_; + std::unique_ptr module_pressure_state_; + std::unique_ptr alias_analysis_; + const AsyncTracker* async_tracker_; + const LatencyEstimator* latency_estimator_; + SchedulerConfig config_; + TargetSchedulingRule target_scheduling_rule_ = nullptr; + TargetSchedulingRule early_target_scheduling_rule_ = nullptr; + PostProcessingFn post_processing_fn_ = nullptr; +}; + +// A scheduler oriented to hiding latencies of operations that can run in +// parallel with other operations. +class LatencyHidingScheduler : public HloModulePass { + public: + struct SchedulerStatistics { + const HloComputation* computation = nullptr; + double all_gather_wasted_cycles = 0; + double all_reduce_wasted_cycles = 0; + double collective_permute_wasted_cycles = 0; + double all_to_all_wasted_cycles = 0; + double reduce_scatter_wasted_cycles = 0; + double send_wasted_cycles = 0; + double recv_wasted_cycles = 0; + double total_cycles = 0; + int64_t memory_pressure_peak = 0; + }; + + LatencyHidingScheduler( + std::unique_ptr latency_estimator, + std::unique_ptr async_tracker, + std::unique_ptr scheduler_core, + const HloCostAnalysis::ShapeSizeFunction& shape_size_bytes) + : latency_estimator_(std::move(latency_estimator)), + async_tracker_(std::move(async_tracker)), + scheduler_core_(std::move(scheduler_core)), + shape_size_bytes_(shape_size_bytes) {} + absl::string_view name() const override { return "latency-hiding-scheduler"; } + + // Returns some printable statistics about the latency hiding for + // operations that can run in parallel to help evaluating the performance of + // the scheduler and improve it. + static SchedulerStatistics LatencyHidingStatistics( + const HloComputation* computation, + const LatencyEstimator* latency_estimator, + const AsyncTracker* async_tracker, + const HloCostAnalysis::ShapeSizeFunction& shape_size_bytes); + // Returns a string representation of the scheduler statistics object. + static std::string SchedulerStatisticsString( + const SchedulerStatistics& sched_stats); + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + virtual void LogScheduleStatistics(const HloComputation* computation); + + private: + std::unique_ptr latency_estimator_; + std::unique_ptr async_tracker_; + std::unique_ptr scheduler_core_; + const HloCostAnalysis::ShapeSizeFunction shape_size_bytes_; + absl::flat_hash_set computations_to_schedule_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LATENCY_HIDING_SCHEDULER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/layout_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/layout_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..a901cef0b98295c1e979e851044b818f3394e9ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/layout_assignment.h @@ -0,0 +1,721 @@ +/* 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_SERVICE_LAYOUT_ASSIGNMENT_H_ +#define XLA_SERVICE_LAYOUT_ASSIGNMENT_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/container/inlined_vector.h" +#include "absl/container/node_hash_map.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/layout_util.h" +#include "xla/service/call_graph.h" +#include "xla/service/computation_layout.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/logical_buffer.h" +#include "xla/service/tuple_points_to_analysis.h" +#include "xla/shape_layout.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { + +class LayoutAssignment; +// Abstract base class for layout constraints. These constraint objects are +// gathered together in LayoutConstraints object. +class LayoutConstraint { + public: + LayoutConstraint(bool mandatory, bool dfs, int64_t priority) + : mandatory_(mandatory), dfs_(dfs), priority_(priority) {} + virtual ~LayoutConstraint() = default; + + virtual std::string ToString() const = 0; + + // True if this constraint cannot be overwritten by a different constraint. + bool mandatory() const { return mandatory_; } + + // When true, propagate in DFS. When false, constraint will propagate in BFS. + bool dfs() const { return dfs_; } + + // Return the priority of the current constraint. When conflicting constraints + // are encountered, the higher priority one should win. + int64_t priority() const { return priority_; } + bool IsDefaultLayout() const { return priority_ == kDefaultPriority; } + + // The priority of all default layouts when not set explicitly. + static constexpr int64_t kDefaultPriority = -2; + // The beginning priority of layout assignment. + static constexpr int64_t kBeginningPriority = 0; + // The priority of layout assignment given by the user for entry computation. + static constexpr int64_t kGivenPriority = 3; + + protected: + bool mandatory_; + bool dfs_; + int64_t priority_; +}; + +std::ostream& operator<<(std::ostream& out, const LayoutConstraint& constraint); + +// Layout constraint on a single LogicalBuffer. This constrains the layout of an +// array produced by a particular instruction. +class BufferLayoutConstraint : public LayoutConstraint { + public: + BufferLayoutConstraint(const Layout& layout, const LogicalBuffer& buffer, + bool mandatory, bool dfs, int64_t priority); + + const LogicalBuffer& buffer() const { return *buffer_; } + const Layout& layout() const { return layout_[0]; } + bool UpdateLayout(int64_t priority, const Layout& layout, bool mandatory, + bool dfs, LayoutAssignment* assignment, + const HloInstruction* from_user = nullptr); + + std::string ToString() const override; + + private: + absl::InlinedVector layout_; + const LogicalBuffer* buffer_; + const HloInstruction* from_user_ = nullptr; +}; + +// Constraint on the layout of the operand of an instruction. The constrained +// shape can be arbitrarily shaped (array or tuple). This is a constraint on the +// use of a shaped value and is not a hard constraint on the instruction(s) +// which define the value as copies may be inserted between the definition and +// use. +class OperandLayoutConstraint : public LayoutConstraint { + public: + OperandLayoutConstraint(const ShapeLayout& shape_layout, + const HloInstruction* instruction, int64_t operand_no, + bool mandatory, bool dfs, int64_t priority); + + const ShapeLayout& shape_layout() const { return shape_layout_[0]; } + const HloInstruction* instruction() const { return instruction_; } + const int64_t operand_no() const { return operand_no_; } + const HloInstruction* operand() const { + return instruction_->operand(operand_no_); + } + // Return whether the layout should be allowed to be modified. + bool UpdateLayout(int64_t priority, const Shape& new_shape, bool mandatory, + bool dfs, LayoutAssignment* assignment); + std::string ToString() const override; + + private: + absl::InlinedVector shape_layout_; + const HloInstruction* instruction_; + int64_t operand_no_; +}; + +// Constraint on the layout of a computation interface. +class ComputationLayoutConstraint : public LayoutConstraint { + public: + static constexpr int64_t kDefaultLayoutIsUsed = 0; + static constexpr int64_t kResultLayoutIsSet = 1; + static constexpr int64_t kParameterLayoutIsSet = 2; + static constexpr int64_t kComputationLayoutIsSet = 3; + explicit ComputationLayoutConstraint(const HloComputation* computation, + ComputationLayout* computation_layout, + int64_t priority) + : LayoutConstraint(/*mandatory=*/true, /*dfs=*/true, priority), + layout_state_((computation_layout == nullptr) + ? kDefaultLayoutIsUsed + : kComputationLayoutIsSet), + computation_layout_( + (computation_layout == nullptr) + ? ComputationLayout(computation->ComputeProgramShape(), + /*ignore_layouts=*/false) + : *computation_layout) {} + + const ComputationLayout& computation_layout() const { + return computation_layout_; + } + void ResetComputationLayout(const ComputationLayout& layout, int64_t priority, + bool prop_result_layout, + bool prop_parameter_layout) { + computation_layout_ = layout; + priority_ = priority; + if (prop_result_layout) { + layout_state_ |= kResultLayoutIsSet; + } + if (prop_parameter_layout) { + layout_state_ |= kParameterLayoutIsSet; + } + } + void ResetResultLayout(const ShapeLayout& shape_layout, int64_t priority) { + *computation_layout_.mutable_result_layout() = shape_layout; + layout_state_ |= kResultLayoutIsSet; + priority_ = priority; + } + bool parameter_layout_is_set() const { + return layout_state_ & kParameterLayoutIsSet; + } + bool result_layout_is_set() const { + return layout_state_ & kResultLayoutIsSet; + } + bool default_layout_is_used() const { + return layout_state_ == kDefaultLayoutIsUsed; + } + std::string ToString() const override; + + private: + // The layout_state_ variable is used to remember whether the layout for + // the overall computation is explicitly set, whether its result layout is + // explicitly set, or whether it only stores the default layout of the + // computation. + int64_t layout_state_; + ComputationLayout computation_layout_; +}; + +// Contains constraints on the layout of channels; sends and recvs. +class ChannelLayoutConstraints { + public: + // Construct an empty constraint set. + ChannelLayoutConstraints() {} + + // Returns true if channel_id has a layout constraint. + bool IsChannelConstrained(int64_t channel_id) const { + return constraints_.contains(channel_id); + } + + // Given `shape`, apply the layout for `channel_id`. `channel_id` must already + // be constrained. + Shape LayoutShapeForChannel(Shape shape, int64_t channel_id) const { + auto it = constraints_.find(channel_id); + CHECK(it != constraints_.end()) << "Channel " << channel_id; + *shape.mutable_layout() = it->second; + return shape; + } + + // Returns the layout constraint for `channel_id`, which must already be + // constrained. + const Layout& LayoutForChannel(int64_t channel_id) const { + auto it = constraints_.find(channel_id); + CHECK(it != constraints_.end()) << "Channel " << channel_id; + return it->second; + } + + // Adds a new layout constraint for `channel_id`. If a constraint for + // `channel_id` has been added, this API returns nullptr, otherwise returns + // the layout which has already been set for the channel. + const Layout* ConstrainChannel(int64_t channel_id, const Layout& layout) { + auto it = constraints_.emplace(std::make_pair(channel_id, layout)); + if (it.second) { + return nullptr; + } + return LayoutUtil::Equal(layout, it.first->second) ? nullptr + : &it.first->second; + } + + private: + absl::flat_hash_map constraints_; +}; + +// HLO pass which assigns layouts to all instructions in the HLO module while +// satisfying all necessary invariants and minimizing cost. +class LayoutAssignment : public HloModulePass { + public: + // entry_computation_layout is modified to populate a layout for the result in + // the case that no particular layout is requested. + // + // channel_constraints is both an input and output. Any sends or recvs that + // are present in channel_constraints will be laid out as constrained. Any + // unconstrained sends or recvs will be laid out as locally optimal and their + // layout will be added as a constraint to channel_constraints. + // + // If channel_constraints is nullptr, no kSend or kRecvs must be contained + // within any module passed to `Run`. + explicit LayoutAssignment( + ComputationLayout* entry_computation_layout, + ChannelLayoutConstraints* channel_constraints = nullptr, + bool reverse_computation_order = false); + ~LayoutAssignment() override {} + const TuplePointsToAnalysis& points_to_analysis() const { + return *points_to_analysis_; + } + absl::string_view name() const override { return "layout-assignment"; } + + // Assign layouts to the given module. Returns whether the module was changed + // (any layouts were changed). + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Class encapsulating the layout constraints of the values in a HLO + // computation. + class LayoutConstraints { + public: + explicit LayoutConstraints(HloComputation* computation, + ComputationLayout* computation_layout, + int64_t priority); + ~LayoutConstraints() = default; + + const HloComputation* computation() const { return computation_; } + HloComputation* computation() { return computation_; } + void ResetOperandConstraints() { operand_constraints_.clear(); } + const ShapeLayout* OperandLayout(const HloInstruction* instruction, + int64_t operand_no) const; + const OperandLayoutConstraint* GetOperandLayoutConstraint( + const HloInstruction* instruction, int64_t operand_no) const; + OperandLayoutConstraint* MutableOperandLayoutConstraint( + const HloInstruction* instruction, int64_t operand_no); + const ShapeLayout* ResultLayout() const; + OperandLayoutConstraint* InsertOperandLayoutConstraint( + const HloInstruction* instruction, int64_t operand_no, + const OperandLayoutConstraint& constraint); + Status SetResultLayout(LayoutAssignment* assignment, + const Shape& shape_with_layout, int64_t priority); + + const ComputationLayout& computation_layout() const { + return computation_constraint_.computation_layout(); + } + const ComputationLayoutConstraint& computation_constraint() const { + return computation_constraint_; + } + ComputationLayoutConstraint* mutable_computation_constraint() { + return &computation_constraint_; + } + + private: + // The set of OperandLayoutConstraints applied to the computation. + using OperandConstraintKey = std::pair; + std::map + operand_constraints_; + + HloComputation* computation_; + ComputationLayoutConstraint computation_constraint_; + }; + + // Determines whether an instruction can change layouts. An instruction not + // being able to change layout means that it requires operands with the same + // rank as the output to have the same layout as the output. + static bool InstructionCanChangeLayout(const HloInstruction* instruction); + + const LayoutConstraints& computation_constraints( + const HloComputation* computation) const { + return *FindOrDie(computation_layouts_, computation); + } + + LayoutConstraints& mutable_computation_constraints( + const HloComputation* computation) { + return *FindOrDie(computation_layouts_, computation); + } + LayoutConstraints* mutable_computation_constraints( + HloComputation* computation) { + auto it = computation_layouts_.find(computation); + LayoutConstraints* constraints = nullptr; + if (it == computation_layouts_.end()) { + computation_layouts_.emplace( + computation, + constraints = new LayoutConstraints( + computation, nullptr, LayoutConstraint::kDefaultPriority)); + } else { + constraints = (*it).second.get(); + } + return constraints; + } + void PushAddedConstraints(const LayoutConstraint* constraint); + + // In case of an array shape returns true iff it is at most rank 1. In case of + // a tuple shape returns true iff all leaf shapes are at most rank 1. + static bool IsAtMostRank1(const Shape& shape); + // Convenience wrapper around SetOperandLayout for setting the layout of a + // operand using a Layout object. The operand must be array-shaped. + Status SetArrayOperandLayout(const Layout& layout, + const HloInstruction* instruction, + int64_t operand_no, bool mandatory = true, + bool dfs = true) { + return SetArrayOperandLayout(layout, instruction, operand_no, mandatory, + dfs, current_priority_); + } + Status SetArrayOperandLayout(const Layout& layout, + const HloInstruction* instruction, + int64_t operand_no, bool mandatory, bool dfs, + int64_t priority); + // Convenience wrapper around SetBufferLayout. Sets the layouts of all buffers + // created by the instruction to the layouts in the given shape. The + // instruction must define every logical buffer in its output. + // If `allow_alias` is false, the function will check that all output buffers + // are defined by `instruction`, not aliased to an instruction elsewhere. + Status SetInstructionLayout(const Shape& shape_with_layout, + const HloInstruction* instruction, + bool mandatory = true, bool dfs = true, + bool allow_alias = false) { + return SetInstructionLayout(shape_with_layout, instruction, mandatory, dfs, + allow_alias, current_priority_); + } + Status SetInstructionLayout(const Shape& shape_with_layout, + const HloInstruction* instruction, bool mandatory, + bool dfs, bool allow_alias, int64_t priority); + // Set the same given layout across all components of the instruction output. + // It works the same as the API above if the output is a single array. + Status SetInstructionLayout(const Layout& layout, + const HloInstruction* instruction, + bool mandatory = true, bool dfs = true, + bool allow_alias = false, int64_t priority = -1); + // Add a constraint on the layout of a LogicalBuffer, the layout of the + // operand of the instruction, or the layout of the result of the computation, + // respectively. + Status SetBufferLayout(const Layout& layout, const LogicalBuffer& buffer, + bool mandatory = true, bool dfs = true) { + return SetBufferLayout(layout, buffer, mandatory, dfs, current_priority_); + } + Status SetBufferLayout(const Layout& layout, const LogicalBuffer& buffer, + bool mandatory, bool dfs, int64_t priority, + const HloInstruction* from_user = nullptr); + Status SetOperandLayout(const Shape& shape_with_layout, + const HloInstruction* instruction, int64_t operand_no, + bool mandatory = true, bool dfs = true) { + return SetOperandLayout(shape_with_layout, instruction, operand_no, + mandatory, dfs, current_priority_); + } + Status SetOperandLayout(const Shape& shape_with_layout, + const HloInstruction* instruction, int64_t operand_no, + bool mandatory, bool dfs, int64_t priority); + bool reverse_computation_order() const { return reverse_computation_order_; } + + ComputationLayout& saved_entry_computation_layout() { + return saved_entry_computation_layout_; + } + virtual bool NegotiateLayout(const HloInstruction* instruction, + const Layout& new_layout, + const Layout& existing_layout, + const HloInstruction* from_user, + const HloInstruction* orig_user) { + return false; + } + virtual bool NegotiateOperandLayout(const HloInstruction* instruction, + int64_t operand_no, + const Layout& new_layout, + const Layout& existing_layout) { + return false; + } + // Should be made consistent with the ChooseOperandLayoutFromOutputLayout + // except that a boolean instead of concrete layout is returned. + virtual bool OperandLayoutAlwaysPropagateForward(const HloInstruction* user); + // Controls when all operands of user must have the same layout. + virtual bool OperandLayoutAlwaysPropagateToSiblings( + const HloInstruction* user); + // Controls when all operands of user must have the same layout as the output. + virtual bool OutputLayoutAlwaysPropagateToOperands( + const HloInstruction* user); + // Whether to propagate the reduction layout to the operand by preserving the + // same relative order of the dimensions that are kept, and making the + // reduction dims the most minor dimensions. + virtual bool PropagateReductionLayoutToOperand(const HloInstruction* user) { + return false; + } + + protected: + // These methods, invoked by PropagateConstraints, propagate a layout + // constraint to its neighbors (i.e. operands and users) in order to minimize + // the cost of the instructions being constrainted on. New constraints are + // added to the given constraint set. + // + // Backends can override these methods with backend-specific propagation + // rules. + virtual Status PropagateBufferConstraint( + const BufferLayoutConstraint& buffer_constraint, + LayoutConstraints* constraints); + virtual Status PropagateOperandConstraint( + const OperandLayoutConstraint& operand_constraint, + LayoutConstraints* constraints); + virtual Status PropagateResultConstraint( + const ComputationLayoutConstraint& layout_constraint, + LayoutConstraints* constraints); + + virtual Layout GetUnconstrainedLayout(const LogicalBuffer& buffer) { + return LayoutUtil::GetDefaultLayoutForShape(buffer.shape()); + } + // Called after layouts of an instruction have been finalized to allow + // subclasses to check for platform specific assumptions. + virtual Status Verify(const HloInstruction* instruction) { + return OkStatus(); + } + + Status PropagateUnconstraintedBuffers(LayoutConstraints* constraints); + const BufferLayoutConstraint* GetBufferLayoutConstraint( + const LogicalBuffer& buffer) const; + StatusOr GetInstructionBufferLayoutConstraint( + const HloInstruction* instruction) const; + // Find a bufferset in the bufferset cache. This is useful since we can + // currently create the flattened buffer set for the same instruction many + // times, which is often slow. + PointsToSet::BufferSet* GetBufferSet(const HloInstruction* instruction) const; + // Similar to above, but returns true only if all buffers associated with that + // operand are forwarded. + bool AllOperandBuffersForwarded(const HloInstruction* instruction, + int64_t operand_no) const; + // Returns true if any buffer in the given operand is forwarded to the output + // of the given instruction. For example, the Tuple instruction forwards the + // buffers of its operands and would return true for each of its operands. + bool AnyOperandBufferForwarded(const HloInstruction* instruction, + int64_t operand_no) const; + StatusOr InferArrayLayout(const HloInstruction* instruction, + const ShapeIndex& index); + + // Propagates a buffer layout constraint into the operands that use it. + Status PropagateBufferConstraintToUses( + const BufferLayoutConstraint& buffer_constraint, + LayoutConstraints* constraints); + + // Propagates a layout constraint on the use of the result of the given + // instruction to the definitions of the LogicalBuffers which make up the + // result. + Status PropagateUseConstraintToDefs(const ShapeLayout& shape_layout, + const HloInstruction* instruction, + LayoutConstraints* constraints, + int64_t priority, + const HloInstruction* user = nullptr); + + // Chooses a layout of operand `operand_no` of `instruction` that minimizes + // the cost of `instruction`. `output_layout` is the layout of `instruction`. + // Returns null if it can't decide the best layout. + // Precondition: `instruction` and the operand are array-shaped. + virtual std::unique_ptr ChooseOperandLayoutFromOutputLayout( + const Layout& output_layout, const HloInstruction* instruction, + int64_t operand_no); + // Given the layout of `user`'s `operand_no`-th operand, chooses a layout of + // `user` that minimizes its cost on that operand. Returns null if it can't + // decide the best layout. + // Precondition: `user` and the operand are array-shaped. + virtual std::unique_ptr ChooseOutputLayoutFromOperandLayout( + const Layout& operand_layout, const HloInstruction* user, + int64_t operand_no); + + // Convenient wrapper for InstructionCanChangeLayout which can be overridden + // in subclasses. + virtual bool InstructionCanChangeLayoutInstance( + const HloInstruction* instruction); + + private: + // Initializes the layout assignment object for a new Run() call. + Status Init(HloModule* module); + + // Adds constraints which must be satisfied for correctness on all + // backends. Called once prior to propagating constraints. + Status AddMandatoryConstraints(ChannelLayoutConstraints* channel_constraints, + LayoutConstraints* constraints); + + // Return a vector containing the constraints which have been added to the + // LayoutConstraints object since the construction of the object or since the + // last time ConsumeAddedConstraints() has been called. This is used to + // identify newly added constraints when propagating layouts. + std::vector ConsumeAddedConstraints() { + std::vector ret_vec(std::move(added_constraints_)); + added_constraints_.clear(); + return ret_vec; + } + void ClearAddedConstraints() { added_constraints_.clear(); } + + // This method can be overridden to add backend-specific constraints to the + // layout of the instructions of a computation. This method is called after + // all mandatory constraints have been added via AddMandatoryConstraints + // and before propagating constraints. + virtual Status AddBackendConstraints(LayoutConstraints* constraints) { + return OkStatus(); + } + + // Construct constraints and assign layouts to all instructions in the + // computation satisfying the given ComputationLayout, if not nullptr. + // Otherwise the ComputationLayout will be calculated by propagating the + // computation instruction constraints. + // Layouts constraints are added, then propagated until all LogicalBuffers in + // the computation are constrained. + Status RunOnComputation(LayoutConstraints* constraints, + ChannelLayoutConstraints* channel_constraints); + + // Assign layouts to the instructions of a computation which satisfy the given + // layout constraints. Copies may be added to satisfy the constraints. The + // given LayoutConstraints must have layout constraints every logical buffer + // in the computation. + Status AssignLayouts(LayoutConstraints& constraints); + + // Propagates layout constraints from a set of initial constraints in order to + // minimize the local cost of the computation. This propagation is *not* + // required for correctness. + Status PropagateConstraints(LayoutConstraints* constraints); + + Status PropagateBufferConstraintToOperands( + const BufferLayoutConstraint& buffer_constraint, + LayoutConstraints* constraints); + + // Check that all layouts in the module have been set and satisfy all + // necessary conditions. + Status CheckLayouts( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + // Computes the ComputationLayout of the given constraints based of the + // layouts assigned to parameters and root instruction. Also propagate + // constraints to computation nested inside. + Status CalculateComputationLayout(LayoutConstraints* constraints); + + // Clears all the layouts which can be cleared within a computation. + Status ClearComputationLayouts(HloComputation* computation); + + // Clears the side effects of a previous pass, like added copy instructions. + Status ClearPreviousPassSideEffects( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + // Propagates the layouts computed by the layout assignment pass on the given + // computation, to the computation layout passed in to this API. + // This API propagates missing layout, and also checks that the caller + // specified have been respected, by comparing those with the parameters and + // root computation instruction. + Status PropagateComputationLayouts(HloComputation* computation, + ComputationLayout* computation_layout); + + // The pointer to the ComputationLayout passed as constructor parameter. + ComputationLayout* entry_computation_layout_; + + // A copy of entry_computation_layout_ used to reset it to the initial values + // during the multiple passes done by the layout assignment operation. + ComputationLayout saved_entry_computation_layout_; + // If set true, reverse the computation traversal order when assigning layout. + bool reverse_computation_order_; + + protected: + static constexpr int64_t kNumberOfPropagationRounds = 2; + // Sets up the copy instruction according to the characteristic (sharding, + // metadata, ...) of the reference instruction. The index argument is used + // when the instruction is a tuple, and in such case the index represents + // the location from where the copy instruction was created from. + // If the index is empty, the whole sharding will be propagated, even in case + // the instruction has a tuple sharding. + static void SetupCopiedInstruction(const HloInstruction& instruction, + HloInstruction* copy, + const ShapeIndex& index); + + // Creates and returns a copy of the given instruction with a different + // layout. Tuple-shaped instructions will be deep-copied, and the last Tuple + // instruction producing the copy is returned. + StatusOr CreateCopyWithNewLayout( + const Shape& shape_with_layout, HloInstruction* instruction); + + // Creates a copy of the given operand if the operand's layout does not match + // the given layout. This copy replaces the use in the given instruction. + // Tuple operands will be deep-copied. + virtual Status CopyOperandIfLayoutsDiffer(const ShapeLayout& operand_layout, + HloInstruction* instruction, + int64_t operand_no); + + // Registers a copy instruction added by the layout assignment pass. + void RegisterAddedCopy(HloInstruction* copy) { + CHECK_EQ(copy->opcode(), HloOpcode::kCopy); + added_copies_.insert(copy); + } + + // Adds a copy for the operand of an instruction, unless such operand is + // already a copy, and has a single user (which is forcibly the instruction + // itself). + Status AddCopyForOperand(HloInstruction* instruction, int64_t operand_number); + + // Apply the channel layout constraints by populating the channel_constraints + // data structure passed in at constructor time. Eventually adds copies in + // case two ends of a channel ended up with a different leyout. + Status ConstrainChannelLayouts(HloComputation* computation, + ChannelLayoutConstraints* channel_constraints); + + // Resets the input ChannelLayoutConstraints to the original copy received + // from the constructor input. + void ResetChannelConstraints() { + if (channel_layout_constraints_ != nullptr) { + *channel_layout_constraints_ = channel_constraints_; + } + } + + // Adds constraints related to host Send/Recv instructions. + Status BuildHostChannelConstraints(HloComputation* computation); + + // Module points to analysis that can be updated for cloned computations. + std::unique_ptr points_to_analysis_; + + // The set of HLO instructions which lacked any layout constraint, thus + // receiving propagated default layouts. + absl::flat_hash_set unconstrained_layout_instructions_; + + HloPredicate instruction_can_change_layout_func_; + + // CallGraph of the module, used to track callsites of each computation. + std::unique_ptr call_graph_; + + std::string ToString(const LayoutConstraints& constraints) const; + + int64_t current_priority() const { return current_priority_; } + + private: + // Map containing the layouts of all computations assigned so + // far. Computations are handled in a topological sort where computations are + // handled before their caller instructions so the layouts of caller + // instructions can be set to match the computation. + absl::flat_hash_map> + computation_layouts_; + + // Map from branch computations to the result layout they should apply. + absl::flat_hash_map conditional_mismatch_; + + // Every copy added to the module by the layout assignment pass is registered + // here. + absl::flat_hash_set added_copies_; + + // The pointer to the channel layout constraints passed in with the + // constructor. If not nullptr, this is an input/output argument. + ChannelLayoutConstraints* channel_layout_constraints_ = nullptr; + + // A copy of the input layout constraints used to reset the above pointer in + // case we have to undo operations due to the multiple passes over the + // computations/instructions. + ChannelLayoutConstraints channel_constraints_; + + // Layout constraints for send/recv instructions which communicate with the + // host. + ChannelLayoutConstraints host_channel_constraints_; + + // Array-shaped buffers which have not yet been constrained. + std::set unconstrained_buffer_ids_; + + mutable absl::flat_hash_map> + buffer_sets_cache_; + + // The set of BufferLayoutConstraints applied to the computation. + absl::node_hash_map + buffer_constraints_; + + // A vector which holds constraints as they are added. Can be cleared with + // ClearAddedConstraints. + std::vector added_constraints_; + int64_t current_priority_ = LayoutConstraint::kBeginningPriority; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LAYOUT_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/layout_normalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/layout_normalization.h new file mode 100644 index 0000000000000000000000000000000000000000..ec03f48a0c96241ac7bac97416d439610a84b762 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/layout_normalization.h @@ -0,0 +1,62 @@ +/* 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_SERVICE_LAYOUT_NORMALIZATION_H_ +#define XLA_SERVICE_LAYOUT_NORMALIZATION_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +using CustomCallTransformer = + std::function>( + HloCustomCallInstruction*)>; + +// Normalize shapes for some subsets of HLOs. +// +// A shape is called "normalized" when it's layout is descending, and no +// degenerate dimensions are present. +// +// The normalization pass converts shapes to physically-equivalent but +// normalized ones, e.g. f32[5,1,4]{0,1,2} is converted to f32[4,5]{1,0}. +class LayoutNormalization : public HloModulePass { + public: + // The provided custom_call_transformer allows backend to specify custom-call + // transformation rules. + explicit LayoutNormalization( + const CustomCallTransformer& custom_call_transformer = nullptr) + : custom_call_transformer_(custom_call_transformer) {} + + absl::string_view name() const override { return "layout_normalization"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + CustomCallTransformer custom_call_transformer_; +}; + +} // end namespace xla + +#endif // XLA_SERVICE_LAYOUT_NORMALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..14a44b18eeee7998356ff4afdc758846e53ee982 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_compiler.h @@ -0,0 +1,85 @@ +/* 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_SERVICE_LLVM_COMPILER_H_ +#define XLA_SERVICE_LLVM_COMPILER_H_ + +#include "llvm/IR/Module.h" +#include "xla/service/compiler.h" + +namespace xla { + +// Interface for an LLVM-based compiler. This provides the ability to register +// hooks to inspect the LLVM IR during compilation, both before and after +// optimizations are applied. +// +// Hooks get called once per HLO module being compiled. The following should not +// be relied on: +// * The order in which hooks get called. +// * Whether or not a hook gets called if a compilation exits with a non-OK +// status. +class LLVMCompiler : public Compiler { + public: + ~LLVMCompiler() override {} + + // A callback of this type can be run before and/or after IR-level + // optimization to e.g. dump out the generated IR to disk or gather some + // statistics. + using ModuleHook = std::function; + + void SetPreOptimizationHook(ModuleHook hook) { + CHECK(!user_pre_optimization_hook_) + << "Pre-optimization hook is already set"; + CHECK(hook) << "hook cannot be null"; + user_pre_optimization_hook_ = hook; + } + + void RemovePreOptimizationHook() { user_pre_optimization_hook_ = nullptr; } + + void SetPostOptimizationHook(ModuleHook hook) { + CHECK(!user_post_optimization_hook_) + << "Post-optimization hook is already set"; + CHECK(hook) << "hook cannot be null"; + user_post_optimization_hook_ = hook; + } + + void RemovePostOptimizationHook() { user_post_optimization_hook_ = nullptr; } + + // Bring in + // StatusOr> RunBackend( + // std::unique_ptr module, + // se::StreamExecutor* stream_exec, + // se::DeviceMemoryAllocator* device_allocator) + // StatusOr> RunHloPasses( + // std::unique_ptr module, + // se::StreamExecutor* stream_exec, + // se::DeviceMemoryAllocator* device_allocator) + using Compiler::Compile; + using Compiler::RunBackend; + using Compiler::RunHloPasses; + + StatusOr>> Compile( + std::unique_ptr module_group, + std::vector> stream_execs, + const CompileOptions& options) override; + + protected: + ModuleHook user_pre_optimization_hook_; + ModuleHook user_post_optimization_hook_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LLVM_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/alias_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/alias_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..9b55939679a6243bc31a7550fea11df5068bbeee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/alias_analysis.h @@ -0,0 +1,92 @@ +/* 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_SERVICE_LLVM_IR_ALIAS_ANALYSIS_H_ +#define XLA_SERVICE_LLVM_IR_ALIAS_ANALYSIS_H_ + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/str_cat.h" +#include "llvm/IR/Module.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/types.h" + +namespace xla { +namespace llvm_ir { + +// Helper functionality used to augment the LLVM IR emitted with alias-scope +// metadata. +class AliasAnalysis { + public: + AliasAnalysis(const HloModule& module, const BufferAssignment& assignment, + llvm::LLVMContext* context) + : module_(module), assignment_(assignment), context_(context) {} + + // Augments IrArray with aliasing information. + void AddAliasingInformationToIrArray(const HloInstruction& hlo, + llvm_ir::IrArray* array, + const ShapeIndex& index = {}); + + private: + // Returns a unique alias domain for this emitter. + llvm::MDNode* GetAliasDomain(); + + // Returns an alias.scope metadata node corresponding to a given buffer slice. + llvm::MDNode* GetAliasScopeMetadataForBuffer( + const BufferAllocation::Slice& buffer_slice, llvm::MDNode* domain); + + // Returns a noalias metadata node corresponding to a given buffer slice. + // + // |buffer_slice| is the buffer slice. + // + // |domain| corresponds to the alias scope domain as documented at + // http://llvm.org/docs/LangRef.html#noalias-and-alias-scope-metadata + // + // |hlo| is the instruction we are computing a noalias set for. + llvm::MDNode* GetNoaliasMetadataForBuffer( + const BufferAllocation::Slice& buffer_slice, llvm::MDNode* domain, + const BufferAssignment& assignment, const HloInstruction& hlo); + + // The HLO module we are compiling for. + const HloModule& module_; + + // Assignment of the temporary buffers needed by the computation and their + // shape information. + const BufferAssignment& assignment_; + + // The LLVM context which we are using for IR emission. + llvm::LLVMContext* context_; + + // Holds the alias domain for this computation. + llvm::MDNode* alias_domain_ = nullptr; + + // A map from a buffer slice to metadata corresponding to its alias.scope + // metadata. The index kParameterAliasSet is used to hold aliasing + // information for parameters. + absl::flat_hash_map + alias_scope_metadata_; + + // A map from a buffer slice and producer to metadata corresponding to its + // noalias metadata. + absl::flat_hash_map, + llvm::MDNode*> + noalias_metadata_; +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_ALIAS_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/buffer_assignment_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/buffer_assignment_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d8b80a58d20a91e3540c6f4a21a9fe2fdb3acc6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/buffer_assignment_util.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 XLA_SERVICE_LLVM_IR_BUFFER_ASSIGNMENT_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_BUFFER_ASSIGNMENT_UTIL_H_ + +#include "xla/service/buffer_assignment.h" + +namespace xla { +namespace llvm_ir { +// Sanitizes the HLO constant instruction name so that it can be used for the +// name of the corresponding constant buffer. In particular, it replaces . and +// - with _. +std::string SanitizeConstantName(const HloInstruction& instr); +std::string SanitizeConstantName(absl::string_view name); + +std::string ConstantHloToGlobalName(const HloInstruction& instr); +std::string ConstantNameToGlobalName(absl::string_view name); + +// In XLA:GPU we map constant buffer allocations to globals in the generated +// LLVM IR. This function gives us the name of the global variable a constant +// buffer is mapped to. Not used on XLA:CPU. +std::string ConstantBufferAllocationToGlobalName( + const BufferAllocation& allocation); + +// Returns the Literal corresponding to `allocation`, which must be a constant +// allocation. +const Literal& LiteralForConstantAllocation(const BufferAllocation& allocation); +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_BUFFER_ASSIGNMENT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/dynamic_update_slice_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/dynamic_update_slice_util.h new file mode 100644 index 0000000000000000000000000000000000000000..88c43e55416b5aedb2d85acab3eae2e80d6fb263 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/dynamic_update_slice_util.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_SERVICE_LLVM_IR_DYNAMIC_UPDATE_SLICE_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_DYNAMIC_UPDATE_SLICE_UTIL_H_ +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/llvm_ir/fused_ir_emitter.h" +#include "xla/service/llvm_ir/ir_array.h" + +// Utilities related to emitting LLVM IR for various HLO ops. + +namespace xla { +namespace llvm_ir { + +using GeneratorForOperandIrArrays = + std::function()>; + +// Determines whether the given instruction might be implemented as an +// in-place dynamic-update-slice after we have a buffer assignment. +// +// If this returns false, then CanUpdateDynamicSliceInPlace and +// CanEmitFusedDynamicUpdateSliceInPlace will also return false. +// +// This is useful if you want to check whether an instruction might be an +// in-place DUS during an HLO pass, at which point you don't have a buffer +// assignment. +// +// Note that simplifications to the HLO graph might change this function from +// returning false to returning true. Specifically, simplifying the contents of +// fusion nodes might cause a false->true transition. In general this isn't a +// problem by the time you're calling this function, but beware. +bool MayBeImplementedAsInPlaceDynamicUpdateSlice(const HloInstruction* instr); + +// Checks if we can emit code for the given DynamicUpdateSlice node that updates +// its input in place. Returns true if the dynamic-update-slice's +// array-to-be-updated and output share the same BufferAllocation::Slice. +// +// dynamic_update_slice must be a DynamicUpdateSlice op. +bool CanUpdateDynamicSliceInPlace(HloInstruction* dynamic_update_slice, + const BufferAssignment& assignment); + +// Checks if the given fusion node is amenable to being implemented by +// EmitFusedDynamicUpdateSliceInPlace. +bool CanEmitFusedDynamicUpdateSliceInPlace(HloInstruction* fusion, + const BufferAssignment& assignment); + +// Emits IR for running the given dynamic-update-slice op in-place -- that is, +// where the input and output buffers share the same slice, so we can simply +// modify the input/output buffer without touching any of the other elements. +Status EmitDynamicUpdateSliceInPlace(absl::Span operand_arrays, + const IrArray& output_array, + absl::string_view name, + llvm::IRBuilder<>* b); + +// Given a loop-fusion node whose root is a dynamic-update-slice op whose +// array-to-be-updated and output share the same buffer slice, emits +// (sequential) code for a fusion node that does the dynamic-update-slice in +// place. +Status EmitFusedDynamicUpdateSliceInPlace(HloInstruction* fusion, + const IrArray& fusion_output_array, + FusedIrEmitter* fused_emitter, + llvm::IRBuilder<>* b); + +// Same as EmitFusedDynamicUpdateSliceInPlace, except emits a parallel loop with +// the given launch dimensions for arbitrarily many independent dynamic slice +// updates. +Status EmitParallelFusedDynamicUpdateSliceInPlace( + const HloComputation* fusion, + const std::vector>& + dus_and_output_array, + FusedIrEmitter* fused_emitter, + const gpu::LaunchDimensions& launch_dimensions, llvm::IRBuilder<>* b); + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_DYNAMIC_UPDATE_SLICE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/fused_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/fused_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..ec958615ab67ee00e3cb9461a71568bd1fe370fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/fused_ir_emitter.h @@ -0,0 +1,85 @@ +/* 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_SERVICE_LLVM_IR_FUSED_IR_EMITTER_H_ +#define XLA_SERVICE_LLVM_IR_FUSED_IR_EMITTER_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/statusor.h" + +namespace xla { + +// FusedIrEmitter is used to generate code for fusion nodes. +// +// Unlike IrEmitter and its ilk, which directly create LLVM IR in an LLVM +// Module, FusedIrEmitter is better understood as "IR generator generator". +// FusedIrEmitter recursively creates a generator (a host function) which the +// compiler can invoke at a later time. Invoking the generator emits LLVM IR +// that, when run, produces the value at a particular index of the output. +// +// After building this generator, the compiler creates a loop (or its moral +// equivalent, e.g. a GPU kernel) and calls the generator from within the loop. +// This generates code that produces each element of the output. +// +// This class handles both vanilla fusion and multi-output fusion. In the MOF +// case, the fusion node ends with a kTuple instruction, and the generator +// created produces an LLVM struct with N elements, one for each element of the +// arrays in the tuple. It follows that the arrays in the tuple must have the +// same length. +class FusedIrEmitter { + public: + using IndexedGenerator = llvm_ir::ElementGenerator; + + explicit FusedIrEmitter(ElementalIrEmitter& elemental_emitter) + : elemental_emitter_(elemental_emitter) {} + + void BindGenerator(const HloInstruction& instruction, + llvm_ir::ElementGenerator generator) { + indexed_generators_[&instruction] = std::move(generator); + } + + // Returns the generator function for the given instruction. + StatusOr GetGenerator(const HloInstruction& instruction); + + private: + StatusOr CreateGenerator(const HloInstruction& instruction); + StatusOr DefaultAction(const HloInstruction& instruction); + IndexedGenerator HandleConstant(const HloInstruction& constant); + StatusOr HandleTuple(const HloInstruction& tuple); + + ElementalIrEmitter& elemental_emitter_; + + // Map from instructions to functions that generate code for the output + // elements. If an instruction is a GetTupleElement instruction, the + // instruction produces non-tuple result. + absl::flat_hash_map + indexed_generators_; + + // Cache of generated values, lest we regenerate an element of a node with + // multiple outgoing edges. + // Use instruction and index values as the key. + using ValueCacheKey = + std::pair>; + absl::flat_hash_map value_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_FUSED_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/ir_array.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/ir_array.h new file mode 100644 index 0000000000000000000000000000000000000000..cfd55362215cc9553ff51b2a762205ee9cb0cf50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/ir_array.h @@ -0,0 +1,378 @@ +/* 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_SERVICE_LLVM_IR_IR_ARRAY_H_ +#define XLA_SERVICE_LLVM_IR_IR_ARRAY_H_ + +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/map_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace llvm_ir { + +// IrArray represents an XLA array at the LLVM IR level. This class +// encapsulates a base pointer to the buffer holding the array (as an LLVM +// Value) and the shape of the array. The class includes methods for emitting +// LLVM IR sequences which access elements of the array at a multidimensional +// index (eg, [x, y, z] in a 3-dimensional array). Arbitrary shape and layouts +// are supported. +class IrArray { + public: + // A multidimensional index into an IrArray. The order of the runtime indices + // (multidim) corresponds to the order of dimensions in the Shape passed to + // the constructor. + // + // This may also keep a linear index and the layout and dimensions it was + // emitted for; if the shape where this `Index` is used matches, the linear + // index may be used, potentially sparing the cost of computing the + // multidimensional index, which LLVM DCE can delete. + class Index { + public: + // Constructs an index for a scalar shape. + explicit Index(llvm::Type* index_ty) : index_type_(index_ty) { + CHECK(index_ty->isIntegerTy()); + } + + // Constructs an index from linear index "linear" and computes the + // multi-dimensional index from "linear" and "shape". "b" is the IR + // builder to emit the index of each dimension in the multi-dimensional + // index. + // + // Precondition: "shape" has a layout. + Index(llvm::Value* linear, const Shape& shape, llvm::IRBuilder<>* b); + + // As before, but also take a multidim to reuse. multidim.size() + // == shape.rank() must be true. If some of the multidim element + // are null we will use the value that would be used if + // deliearized from linear. + Index(llvm::Value* linear, absl::Span multidim, + const Shape& shape, llvm::IRBuilder<>* b); + + // Similar to the above constructor except using "dynamic_dims" instead of + // shape's static dimension to constructs the index. + Index(llvm::Value* linear, const Shape& shape, + absl::Span dynamic_dims, llvm::IRBuilder<>* b); + + // Constructs an index from a multi-dimensional index. 'shape' is the shape + // for which the multi-dimensional index is used. 'index_type' is the type + // of the index. + // + // Precondition: "shape" has a layout. + Index(absl::Span multidim, const Shape& shape, + llvm::Type* index_type); + + // Same as above, but only the dimensions of the shape without layout is + // passed. The layout is assumed to be the default (descending + // minor-to-major) layout. + Index(absl::Span multidim, + absl::Span dimensions, llvm::Type* index_type); + + // Returns an index that adds `addend` to the given `dim` of the object. + Index AddOffsetToDim(llvm::Value* addend, int64_t dim, + llvm::IRBuilder<>* b) const { + Index with_offset = *this; + with_offset.linear_ = nullptr; + with_offset.multidim_[dim] = + b->CreateAdd(with_offset.multidim_[dim], addend); + return with_offset; + } + + const std::vector& multidim() const { return multidim_; } + const std::vector& dims() const { return dims_; } + llvm::Value* linear() const { return linear_; } + + size_t size() const { return multidim().size(); } + + llvm::Value* operator[](size_t i) const { return multidim()[i]; } + + using const_iterator = std::vector::const_iterator; + + const_iterator begin() const { return multidim().begin(); } + const_iterator end() const { return multidim().end(); } + + bool LinearValidOnShape(const Shape& a) const; + + static bool ShapeIsCompatible(const Shape& a, const Shape& b); + + bool ShapeIsCompatible(const Shape& a) const { + return ShapeIsCompatible(a, AsShapeWithType(a.element_type())); + } + + Shape AsShapeWithType(PrimitiveType element_type) const { + return ShapeUtil::MakeShapeWithDenseLayout(element_type, dims_, + layout_.minor_to_major()); + } + + // Given that "this" is the target index of a reshape from `input_shape` + // to `output_shape`, returns the source index. + Index SourceIndexOfReshape(const Shape& output_shape, + const Shape& input_shape, + llvm::IRBuilder<>* builder) const; + + // Returns the index into the source operand from which a slice operation + // selects a value to be placed into index "this". The slice is described + // by starting indices `starts` and stride values `strides`. + // + // Precondition: "this" is an index into a slice whose operand shape is + // `operand_shape`. + Index SourceIndexOfSlice(const Shape& operand_shape, + absl::Span starts, + absl::Span strides, + llvm::IRBuilder<>* builder) const; + + // Given that "this" is the target index of a transpose from `operand_shape` + // to `shape` with the given dimension mapping, returns the source index. + Index SourceIndexOfTranspose( + const Shape& shape, const Shape& operand_shape, + absl::Span dimension_mapping) const; + + // Given that "this" is the target index of a bitcast from `operand_shape` + // to `shape`, returns the source index. + Index SourceIndexOfBitcast(const Shape& shape, const Shape& operand_shape, + llvm::IRBuilder<>* builder) const; + + // Given that "this" is the target index of a broadcast from `operand_shape` + // to `shape` with the given dimension mapping, returns the source index. + Index SourceIndexOfBroadcast(const Shape& shape, const Shape& operand_shape, + absl::Span dimension_mapping, + llvm::IRBuilder<>* builder) const; + + // Linearizes the index into the given shape, i.e. reshapes it to rank-1 and + // returns the index into the sole dimension 0 of the new shape. + llvm::Value* Linearize(absl::Span dimensions, + llvm::IRBuilder<>* builder) const; + + // Linearizes the index into the given dynamic dimensions. + llvm::Value* Linearize(const std::vector& dynamic_dims, + llvm::IRBuilder<>* builder) const; + + llvm::Type* GetType() const { return index_type_; } + + llvm::Constant* GetConstantWithIndexType(int64_t c) const { + // The LLVM function makes sure that the value can be represented by the + // specified type, see ConstantInt::ConstantInt(IntegerType *Ty, const + // APInt &V). + return llvm::ConstantInt::get(index_type_, c); + } + + private: + // Constructs an index from both a multi-dimensional index and a linear + // index. 'shape' is the shape on which the index is used. 'index_type' is + // the type of the index. + // + // Precondition: "shape" has a layout. + Index(absl::Span multidim, llvm::Value* linear, + const Shape& shape, llvm::Type* index_type); + + void Delinearize(std::vector* multidim, llvm::Value* linear, + const Shape& shape, llvm::IRBuilder<>* b) const; + + // Delinearize the linear index with the dynamic dimensions. + void Delinearize(std::vector* multidim, llvm::Value* linear, + const Shape& shape, absl::Span dynamic_dims, + llvm::IRBuilder<>* b) const; + + std::vector multidim_; + + // These values are purely for efficiency; `multidim_` is enough to find the + // element at a given `Index`, but if a loop is emitted with a linear index + // space, that linear index can be saved in `linear_`, and the layout and + // dimensions of the shape the loop was emitted for in `layout_` and + // `dims_`, and if the `Index` is used in another array, and its layout and + // dimensions match, the linear index can be used, sparing the cost of + // computing `multidim_`, which LLVM DCE could potentially so delete. + // Modifying `multidim_` after construction nullifies `linear_`, lest it + // be used wrongly, as it would be valid no more. + // If a loop is emitted with a multidimensional index space, `linear_` would + // be null and `layout_` and `dims_` would be ignored. + llvm::Value* linear_ = nullptr; + Layout layout_; + std::vector dims_; + + llvm::Type* index_type_; + }; + + // Default constructor. Constructs an IrArray in a null status. + IrArray() : base_ptr_(nullptr) {} + + // Construct an IrArray with the given base pointer, pointee type, and shape. + // base_ptr is a pointer type pointing to the first element(lowest address) + // of the array. + // + // For int4 arrays, pointee_type should be i8, not i4, as int4 + // IrArrays are represented as i8 arrays where each i8 value stores two 4-bit + // values. Additionally, reads and write return or take in i8 values which + // hold a value representable by i4, instead of directly returning or taking + // in i4 values. Specifically, the i8 values returned or passed in are between + // 0 and 15 for U4 arrays and between -8 and 7 for S4 arrays. + IrArray(llvm::Value* base_ptr, llvm::Type* pointee_type, Shape shape); + + // Default implementations of copying and moving. + IrArray(IrArray&& other) = default; + IrArray(const IrArray& other) = default; + IrArray& operator=(IrArray&& other) = default; + IrArray& operator=(const IrArray& other) = default; + + llvm::Value* GetBasePointer() const { return base_ptr_; } + llvm::Type* GetBasePointeeType() const { return pointee_type_; } + llvm::Type* GetElementLlvmType() const { return element_type_; } + + const Shape& GetShape() const { return shape_; } + + // Emit a sequence of instructions to compute the address of the element in + // the given array at the given index. Returns the address of the element as + // an LLVM Value. + // + // The optional name is useful for debugging when looking at + // the emitted LLVM IR. + // + // For int4 values, 'is_high_order_bits' must be non-null and this function + // sets '*is_high_order_bits' to a boolean value indicating whether the 4-bit + // value resides in the high-order or low- order bits of the byte that the + // address points to. + llvm::Value* EmitArrayElementAddress( + const Index& index, llvm::IRBuilder<>* b, absl::string_view name = "", + bool use_linear_index = true, + llvm::Value** is_high_order_bits = nullptr) const; + + // Attach metadata this IrArray instance knows about to "instruction". + void AnnotateLoadStoreInstructionWithMetadata( + llvm::Instruction* instruction) const; + + // Emit IR to read an array element at the given index. Returns the read + // result (effectively, a Value loaded from memory). This method seamlessly + // handles scalar shapes by broadcasting their value to all indices (index is + // ignored). + // + // The optional name is useful for debugging when looking at + // the emitted LLVM IR. + // 'use_linear_index' can be used to specify whether the linear index (if + // available) or the multi-dimensional index should be used. + // + // For int4 arrays, returns an i8 value that is representable by i4. The + // returned i8 value will be between 0 and 15 for U4 arrays and between -8 and + // 7 for S4 arrays. + llvm::Value* EmitReadArrayElement(const Index& index, llvm::IRBuilder<>* b, + absl::string_view name = "", + bool use_linear_index = true) const; + + // Emit IR to write the given value to the array element at the given index. + // 'use_linear_index' can be used to specify whether the linear index (if + // available) or the multi-dimensional index should be used. + // + // For int4 arrays, the given value must be an i8 value representable by i4. + // Only 4 bits of a byte in the array are written. First the appropriate byte + // is read from the array, then 4 bits are modified and written back. To avoid + // race conditions, the caller must ensure that the two different 4-bit values + // within a byte are not written to in parallel. + void EmitWriteArrayElement(const Index& index, llvm::Value* value, + llvm::IRBuilder<>* b, + bool use_linear_index = true) const; + + // Returns a new IrArray whose shape is "new_shape" and base pointer is a + // bitcast of the base pointer of "this" IrArray. + // 'use_linear_index' can be used to specify whether the linear index (if + // available) or the multi-dimensional index should be used. + IrArray CastToShape(const Shape& new_shape, llvm::IRBuilder<>* b) const; + + void AddAliasScopeMetadata(llvm::MDNode* alias_scope) { + CHECK_NE(alias_scope, nullptr); + AddMetadata(llvm::LLVMContext::MD_alias_scope, alias_scope); + } + + void AddNoaliasMetadata(llvm::MDNode* noalias) { + CHECK_NE(noalias, nullptr); + AddMetadata(llvm::LLVMContext::MD_noalias, noalias); + } + + // Promises LLVM that the data pointed to by this IrArray never changes after + // it's first loaded. + // + // The temporal scope of this promise is the "whole program" from LLVM's point + // of view, but how this translates to HLOs differs between backends. + // + // In the single-threaded CPU backend, we emit one function that + // runs all the HLOs in sequence, so the whole program is the whole HLO + // module. + // + // In the GPU backend, we emit one GPU kernel per top-level HLO (i.e. per HLO + // in the entry computation). From LLVM's perspective, launching a new kernel + // is like launching a new program, and so the whole program is one top-level + // HLO. Since the scope of the promise is smaller than in the CPU backend, we + // can mark more things as invariant in the GPU backend. + // + // Marking loads as invariant is particularly helpful on GPUs because + // invariant loads can be lowered to PTX ld.global.nc (equivalent to CUDA's + // __ldg intrinsic). These loads use a special cache, and can be + // significantly faster than regular loads. + void MarkInvariantOverWholeProgram(llvm::LLVMContext* context) { + if (is_invariant_) { + return; + } + is_invariant_ = true; + AddMetadata(llvm::LLVMContext::MD_invariant_load, + llvm::MDNode::get(*context, {})); + } + + const std::map& metadata() const { return metadata_; } + + private: + // Add the specified LLVM IR metadata to loads/stores associated with this + // IrArray. + void AddMetadata(int kind, llvm::MDNode* md) { + InsertOrDie(&metadata_, kind, md); + } + + // Like EmitArrayElementAddress, but always uses a linear index. + llvm::Value* EmitLinearArrayElementAddress( + const Index& index, llvm::IRBuilder<>* b, absl::string_view name = "", + llvm::Value** is_high_order_bits = nullptr) const; + + // Address of the base of the array as an LLVM Value. + llvm::Value* base_ptr_; + + // The pointee type of base_ptr_; + llvm::Type* pointee_type_; + + // The LLVM type of the elements in the array. + llvm::Type* element_type_; + + // Shape of the XLA array. + Shape shape_; + + // The list of key/value pairs used when attaching metadata to emitted + // loads/stores for this array. They keys are the metadata kinds and the + // values are the metadata nodes. + std::map metadata_; + + bool is_invariant_ = false; +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_IR_ARRAY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/ir_builder_mixin.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/ir_builder_mixin.h new file mode 100644 index 0000000000000000000000000000000000000000..6f5f6a3f615c30596b2f27475b23bff95a1825a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/ir_builder_mixin.h @@ -0,0 +1,446 @@ +/* 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_SERVICE_LLVM_IR_IR_BUILDER_MIXIN_H_ +#define XLA_SERVICE_LLVM_IR_IR_BUILDER_MIXIN_H_ + +#include + +#include "llvm/IR/IRBuilder.h" + +namespace xla { + +// Mixin class that injects more ergonomic versions of llvm::IRBuilder methods +// into a class. Intended to be used as a CRTP base class, like: +// +// class MyIrEmitter : public IrBuilderMixin { +// llvm::IRBuilder<>* builder() { return builder_; } +// +// void EmitFoo(HloInstruction* foo) { +// Add(Mul(...), FPToUI(...)); +// } +// }; + +template +class IrBuilderMixin { + protected: + template + llvm::Value* Add(Args&&... args) { + return mixin_builder()->CreateAdd(std::forward(args)...); + } + + template + llvm::LoadInst* AlignedLoad(Args&&... args) { + return mixin_builder()->CreateAlignedLoad(std::forward(args)...); + } + + template + llvm::StoreInst* AlignedStore(Args&&... args) { + return mixin_builder()->CreateAlignedStore(std::forward(args)...); + } + + template + llvm::AllocaInst* Alloca(Args&&... args) { + return mixin_builder()->CreateAlloca(std::forward(args)...); + } + + template + llvm::Value* And(Args&&... args) { + return mixin_builder()->CreateAnd(std::forward(args)...); + } + + template + llvm::Value* AtomicCmpXchg(Args&&... args) { + return mixin_builder()->CreateAtomicCmpXchg(std::forward(args)...); + } + + template + llvm::Value* AtomicRMW(Args&&... args) { + return mixin_builder()->CreateAtomicRMW(std::forward(args)...); + } + + template + llvm::Value* BitCast(Args&&... args) { + return mixin_builder()->CreateBitCast(std::forward(args)...); + } + + template + llvm::Value* Br(Args&&... args) { + return mixin_builder()->CreateBr(std::forward(args)...); + } + + llvm::CallInst* Call(llvm::FunctionCallee func_callee, + llvm::ArrayRef args = std::nullopt, + const llvm::Twine& name = "", + llvm::MDNode* fp_math_tag = nullptr) { + return mixin_builder()->CreateCall(func_callee, args, name, fp_math_tag); + } + + llvm::CallInst* Call(llvm::FunctionType* func_type, llvm::Value* callee, + llvm::ArrayRef args = std::nullopt, + const llvm::Twine& name = "", + llvm::MDNode* fp_math_tag = nullptr) { + return mixin_builder()->CreateCall(func_type, callee, args, name, + fp_math_tag); + } + + template + llvm::BranchInst* CondBr(Args&&... args) { + return mixin_builder()->CreateCondBr(std::forward(args)...); + } + + template + llvm::Value* ConstInBoundsGEP1_32(Args&&... args) { + return mixin_builder()->CreateConstInBoundsGEP1_32( + std::forward(args)...); + } + + template + llvm::Value* FAdd(Args&&... args) { + return mixin_builder()->CreateFAdd(std::forward(args)...); + } + + template + llvm::Value* FMul(Args&&... args) { + return mixin_builder()->CreateFMul(std::forward(args)...); + } + + llvm::Value* GEP(llvm::Type* type, llvm::Value* ptr, + llvm::ArrayRef idx_list, + const llvm::Twine& name = "") { + return mixin_builder()->CreateGEP(type, ptr, idx_list, name); + } + + template + llvm::Value* ICmpEQ(Args&&... args) { + return mixin_builder()->CreateICmpEQ(std::forward(args)...); + } + + template + llvm::Value* ICmpNE(Args&&... args) { + return mixin_builder()->CreateICmpNE(std::forward(args)...); + } + + template + llvm::Value* ICmpULE(Args&&... args) { + return mixin_builder()->CreateICmpULE(std::forward(args)...); + } + + template + llvm::Value* ICmpULT(Args&&... args) { + return mixin_builder()->CreateICmpULT(std::forward(args)...); + } + + llvm::Value* InBoundsGEP(llvm::Type* type, llvm::Value* ptr, + llvm::ArrayRef idx_list, + const llvm::Twine& name = "") { + return mixin_builder()->CreateInBoundsGEP(type, ptr, idx_list, name); + } + + llvm::Value* ExtractValue(llvm::Value* agg, llvm::ArrayRef idxs, + const llvm::Twine& name = "") { + return mixin_builder()->CreateExtractValue(agg, idxs, name); + } + + llvm::Value* InsertValue(llvm::Value* agg, llvm::Value* val, + llvm::ArrayRef idxs, + const llvm::Twine& name = "") { + return mixin_builder()->CreateInsertValue(agg, val, idxs, name); + } + + template + llvm::Value* IntToPtr(Args&&... args) { + return mixin_builder()->CreateIntToPtr(std::forward(args)...); + } + + template + llvm::LoadInst* Load(Args&&... args) { + return mixin_builder()->CreateLoad(std::forward(args)...); + } + + template + llvm::CallInst* MemCpy(Args&&... args) { + return mixin_builder()->CreateMemCpy(std::forward(args)...); + } + + template + llvm::Value* Mul(Args&&... args) { + return mixin_builder()->CreateMul(std::forward(args)...); + } + + template + llvm::Value* NSWAdd(Args&&... args) { + return mixin_builder()->CreateNSWAdd(std::forward(args)...); + } + + template + llvm::Value* NSWMul(Args&&... args) { + return mixin_builder()->CreateNSWMul(std::forward(args)...); + } + + template + llvm::Value* NSWSub(Args&&... args) { + return mixin_builder()->CreateNSWSub(std::forward(args)...); + } + + template + llvm::Value* Or(Args&&... args) { + return mixin_builder()->CreateOr(std::forward(args)...); + } + + template + llvm::Value* PointerCast(Args&&... args) { + return mixin_builder()->CreatePointerCast(std::forward(args)...); + } + + template + llvm::Value* PtrToInt(Args&&... args) { + return mixin_builder()->CreatePtrToInt(std::forward(args)...); + } + + template + llvm::Value* SDiv(Args&&... args) { + return mixin_builder()->CreateSDiv(std::forward(args)...); + } + + template + llvm::Value* Select(Args&&... args) { + return mixin_builder()->CreateSelect(std::forward(args)...); + } + + template + llvm::Value* SRem(Args&&... args) { + return mixin_builder()->CreateSRem(std::forward(args)...); + } + + template + llvm::StoreInst* Store(Args&&... args) { + return mixin_builder()->CreateStore(std::forward(args)...); + } + + template + llvm::Value* UDiv(Args&&... args) { + return mixin_builder()->CreateUDiv(std::forward(args)...); + } + + template + llvm::Value* URem(Args&&... args) { + return mixin_builder()->CreateURem(std::forward(args)...); + } + + template + llvm::Value* VectorSplat(Args&&... args) { + return mixin_builder()->CreateVectorSplat(std::forward(args)...); + } + + template + llvm::Value* ZExtOrTrunc(Args&&... args) { + return mixin_builder()->CreateZExtOrTrunc(std::forward(args)...); + } + + template + llvm::Value* AShr(Args&&... args) { + return mixin_builder()->CreateAShr(std::forward(args)...); + } + + template + llvm::Value* FCmpOEQ(Args&&... args) { + return mixin_builder()->CreateFCmpOEQ(std::forward(args)...); + } + + template + llvm::Value* FCmpOGT(Args&&... args) { + return mixin_builder()->CreateFCmpOGT(std::forward(args)...); + } + + template + llvm::Value* FCmpOGE(Args&&... args) { + return mixin_builder()->CreateFCmpOGE(std::forward(args)...); + } + + template + llvm::Value* FCmpOLT(Args&&... args) { + return mixin_builder()->CreateFCmpOLT(std::forward(args)...); + } + + template + llvm::Value* FCmpULT(Args&&... args) { + return mixin_builder()->CreateFCmpULT(std::forward(args)...); + } + + template + llvm::Value* FCmpULE(Args&&... args) { + return mixin_builder()->CreateFCmpULE(std::forward(args)...); + } + + template + llvm::Value* FCmpOLE(Args&&... args) { + return mixin_builder()->CreateFCmpOLE(std::forward(args)...); + } + + template + llvm::Value* FCmpONE(Args&&... args) { + return mixin_builder()->CreateFCmpONE(std::forward(args)...); + } + + template + llvm::Value* FCmpUNE(Args&&... args) { + return mixin_builder()->CreateFCmpUNE(std::forward(args)...); + } + + template + llvm::Value* FCmpUNO(Args&&... args) { + return mixin_builder()->CreateFCmpUNO(std::forward(args)...); + } + + template + llvm::Value* FCmpUGE(Args&&... args) { + return mixin_builder()->CreateFCmpUGE(std::forward(args)...); + } + + template + llvm::Value* FDiv(Args&&... args) { + return mixin_builder()->CreateFDiv(std::forward(args)...); + } + + template + llvm::Value* FNeg(Args&&... args) { + return mixin_builder()->CreateFNeg(std::forward(args)...); + } + + template + llvm::Value* FPCast(Args&&... args) { + return mixin_builder()->CreateFPCast(std::forward(args)...); + } + + template + llvm::Value* FPToSI(Args&&... args) { + return mixin_builder()->CreateFPToSI(std::forward(args)...); + } + + template + llvm::Value* FPToUI(Args&&... args) { + return mixin_builder()->CreateFPToUI(std::forward(args)...); + } + + template + llvm::Value* FPTrunc(Args&&... args) { + return mixin_builder()->CreateFPTrunc(std::forward(args)...); + } + + template + llvm::Value* FRem(Args&&... args) { + return mixin_builder()->CreateFRem(std::forward(args)...); + } + + template + llvm::Value* FSub(Args&&... args) { + return mixin_builder()->CreateFSub(std::forward(args)...); + } + + template + llvm::Value* ICmpSGE(Args&&... args) { + return mixin_builder()->CreateICmpSGE(std::forward(args)...); + } + + template + llvm::Value* ICmpSLT(Args&&... args) { + return mixin_builder()->CreateICmpSLT(std::forward(args)...); + } + + template + llvm::Value* IntCast(Args&&... args) { + return mixin_builder()->CreateIntCast(std::forward(args)...); + } + + template + llvm::Value* LShr(Args&&... args) { + return mixin_builder()->CreateLShr(std::forward(args)...); + } + + template + llvm::Value* MemSet(Args&&... args) { + return mixin_builder()->CreateMemSet(std::forward(args)...); + } + + template + llvm::Value* Neg(Args&&... args) { + return mixin_builder()->CreateNeg(std::forward(args)...); + } + + template + llvm::Value* Not(Args&&... args) { + return mixin_builder()->CreateNot(std::forward(args)...); + } + + template + llvm::PHINode* PHI(Args&&... args) { + return mixin_builder()->CreatePHI(std::forward(args)...); + } + + template + llvm::Value* RetVoid(Args&&... args) { + return mixin_builder()->CreateRetVoid(std::forward(args)...); + } + + template + llvm::Value* SExtOrTrunc(Args&&... args) { + return mixin_builder()->CreateSExtOrTrunc(std::forward(args)...); + } + + template + llvm::Value* Shl(Args&&... args) { + return mixin_builder()->CreateShl(std::forward(args)...); + } + + template + llvm::Value* SIToFP(Args&&... args) { + return mixin_builder()->CreateSIToFP(std::forward(args)...); + } + + template + llvm::Value* Sub(Args&&... args) { + return mixin_builder()->CreateSub(std::forward(args)...); + } + + template + llvm::Value* Trunc(Args&&... args) { + return mixin_builder()->CreateTrunc(std::forward(args)...); + } + + template + llvm::Value* UIToFP(Args&&... args) { + return mixin_builder()->CreateUIToFP(std::forward(args)...); + } + + template + llvm::Value* Unreachable(Args&&... args) { + return mixin_builder()->CreateUnreachable(std::forward(args)...); + } + + template + llvm::Value* Xor(Args&&... args) { + return mixin_builder()->CreateXor(std::forward(args)...); + } + + private: + llvm::IRBuilder<>* mixin_builder() { + return static_cast(this)->builder(); + } +}; + +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_IR_BUILDER_MIXIN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/kernel_support_library.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/kernel_support_library.h new file mode 100644 index 0000000000000000000000000000000000000000..6f8600f42b105c86f501c5f42075f6734bf833c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/kernel_support_library.h @@ -0,0 +1,311 @@ +/* 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_SERVICE_LLVM_IR_KERNEL_SUPPORT_LIBRARY_H_ +#define XLA_SERVICE_LLVM_IR_KERNEL_SUPPORT_LIBRARY_H_ + +#include + +#include "absl/strings/string_view.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/llvm_loop.h" +#include "xla/service/llvm_ir/llvm_util.h" + +namespace xla { +// A thin wrapper around llvm_loop.h to make code generating structured control +// flow more readable. +class KernelSupportLibrary { + public: + // `b` is the llvm::IRBuilder instance used to generate LLVM IR. + // `unroll_mode` specifies the desired LLVM unrolling behavior for every loop + // generated by this instance of KernelSupportLibrary. + explicit KernelSupportLibrary( + llvm::IRBuilder<>* b, + llvm_ir::UnrollMode unroll_mode = llvm_ir::UnrollMode::kNoUnroll, + bool prevent_vectorization = true) + : b_(b), + unroll_mode_(unroll_mode), + prevent_vectorization_(prevent_vectorization) {} + + // Generates the following control flow structure: + // + // if (`start` < `end`) { + // `for_body_generator(/*ind_var=*/start, /*is_first_iteration=*/true)`; + // for (i64 i = `start` + `step`; i s< `end`; i += `step`) + // `for_body_generator(/*ind_var=*/,i, /*is_first_iteration=*/false)`; + // } + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& for_body_generator); + + void For( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& + for_body_generator) { + CHECK_EQ(OkStatus(), + ForWithStatus( + name, start, end, step, + [&](llvm::Value* ind_var, bool is_first_iteration) -> Status { + for_body_generator(ind_var, is_first_iteration); + return OkStatus(); + })); + } + + Status ForWithStatus( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& for_body_generator) { + return ForWithStatus(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + void For( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& + for_body_generator) { + For(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + // Generates the following control flow structure if `peel_first_iteration` is + // true: + // + // if (`start` < `end`) { + // `for_body_generator(/*ind_var=*/start, /*is_first_iteration=*/,true)`; + // for (i64 i = `start` + `step`; i s< `end`; i += `step`) + // `for_body_generator(/*ind_var=*/,i, /*is_first_iteration=*/,false)`; + // } + // + // and the following if `peel_first_iteration` is false: + // + // for (i64 i = `start`; i s< `end`; i += `step`) + // `for_body_generator(/*ind_var=*/,i, + // /*is_first_iteration=*/,(i != `start`))`; + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, bool peel_first_iteration, + const std::function& + for_body_generator); + + void For(absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, bool peel_first_iteration, + const std::function& + for_body_generator) { + TF_CHECK_OK(ForWithStatus( + name, start, end, step, peel_first_iteration, + [&](llvm::Value* ind_var, llvm::Value* is_first_iteration) -> Status { + for_body_generator(ind_var, is_first_iteration); + return OkStatus(); + })); + } + + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, bool peel_first_iteration, + const std::function& + for_body_generator) { + return ForWithStatus( + name, /*start=*/start, /*end=*/end, + /*step=*/llvm::ConstantInt::get(start->getType(), step), + peel_first_iteration, for_body_generator); + } + + void For(absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, bool peel_first_iteration, + const std::function& + for_body_generator) { + For(name, /*start=*/start, /*end=*/end, + /*step=*/llvm::ConstantInt::get(start->getType(), step), + peel_first_iteration, for_body_generator); + } + + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& for_body_generator) { + return ForWithStatus(name, start, end, step, + /*peel_first_iteration=*/false, + [&](llvm::Value* indvar, llvm::Value*) -> Status { + return for_body_generator(indvar); + }); + } + + void For( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& for_body_generator) { + For(name, start, end, step, + /*peel_first_iteration=*/false, [&](llvm::Value* indvar, llvm::Value*) { + return for_body_generator(indvar); + }); + } + + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, + const std::function& for_body_generator) { + return ForWithStatus(name, start, end, + llvm::ConstantInt::get(start->getType(), step), + /*peel_first_iteration=*/false, + [&](llvm::Value* indvar, llvm::Value*) -> Status { + return for_body_generator(indvar); + }); + } + + void For( + absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, + const std::function& for_body_generator) { + For(name, start, end, llvm::ConstantInt::get(start->getType(), step), + for_body_generator); + } + + Status ForWithStatus( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& for_body_generator) { + return ForWithStatus(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + void For( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& for_body_generator) { + For(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + // Generates the following control flow structure: + // + // if (`condition`) + // `true_block_generator()`; + // else + // `false_block_generator()`; + // The else is skipped if false_block_generator is null. + Status IfWithStatus( + absl::string_view name, llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = nullptr); + + Status IfWithStatus( + llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = []() -> Status { + return OkStatus(); + }) { + return IfWithStatus("", condition, true_block_generator, + false_block_generator); + } + + void If(llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = nullptr) { + If("", condition, true_block_generator, false_block_generator); + } + + void If(absl::string_view name, llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = nullptr) { + if (false_block_generator != nullptr) { + TF_CHECK_OK(IfWithStatus( + name, condition, + [&]() { + true_block_generator(); + return OkStatus(); + }, + [&]() { + false_block_generator(); + return OkStatus(); + })); + } else { + TF_CHECK_OK(IfWithStatus(name, condition, [&]() { + true_block_generator(); + return OkStatus(); + })); + } + } + + using ArgumentVector = absl::Span; + + // Generates the following control flow structure: + // + // define @`kernel_name`(arg0, arg1, ... arg`arguments.size()`) { + // kernel_body_generator({arg0, arg1, ... arg`arguments.size()`}); + // } + // + // ... + // call @`kernel_name`(arguments[0], arguments[1] ...) + // ... + // + // If a function called `kernel_name` is already present in the module then + // that function is re-used. In that sense we're using the llvm::Module as a + // cache of outlined kernels, keyed by function name. + // + // If any of the values in `arguments` is nullptr (i.e. a nullptr + // llvm::Value*) then we ignore it when generating LLVM IR, and instead pass + // in a nullptr llvm::Value* in its position to `kernel_body_generator`. + // Currently we only support at most one nullptr value in `arguments`. + static void EmitAndCallOutlinedKernel( + const HloModuleConfig& module_config, llvm::IRBuilder<>* b, + absl::string_view kernel_name, ArgumentVector arguments, + const std::function& kernel_body_generator); + + // Thin wrappers around the more general EmitAndCallOutlinedKernel above. + static void EmitAndCallOutlinedKernel( + const HloModuleConfig& module_config, llvm::IRBuilder<>* b, + absl::string_view kernel_name, llvm::Value* arg0, llvm::Value* arg1, + llvm::Value* arg2, + const std::function& + kernel_body_generator) { + EmitAndCallOutlinedKernel(module_config, b, kernel_name, {arg0, arg1, arg2}, + [&](ArgumentVector args) { + kernel_body_generator(args[0], args[1], + args[2]); + }); + } + + static void EmitAndCallOutlinedKernel( + const HloModuleConfig& module_config, llvm::IRBuilder<>* b, + absl::string_view kernel_name, llvm::Value* arg0, llvm::Value* arg1, + llvm::Value* arg2, llvm::Value* arg3, + const std::function& kernel_body_generator) { + EmitAndCallOutlinedKernel( + module_config, b, kernel_name, {arg0, arg1, arg2, arg3}, + [&](ArgumentVector args) { + kernel_body_generator(args[0], args[1], args[2], args[3]); + }); + } + + private: + llvm::IRBuilder<>* b_; + llvm_ir::UnrollMode unroll_mode_; + bool prevent_vectorization_; +}; +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_KERNEL_SUPPORT_LIBRARY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_command_line_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_command_line_options.h new file mode 100644 index 0000000000000000000000000000000000000000..aa55982ff03949e946ec7ae418ae37492a1a52f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_command_line_options.h @@ -0,0 +1,61 @@ +/* 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_SERVICE_LLVM_IR_LLVM_COMMAND_LINE_OPTIONS_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_COMMAND_LINE_OPTIONS_H_ + +#include +#include + +#include "absl/strings/match.h" +#include "llvm/Support/CommandLine.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace llvm_ir { + +// Given a map with options (e.g. originating from xla_backend_extra_options()) +// pass those that don't start with xla_ to LLVM. +template +void InitializeLLVMCommandLineOptions(const T& options) { + if (!options.empty()) { + std::vector fake_argv_storage; + fake_argv_storage.push_back(""); + for (const auto& it : options) { + // Skip options the XLA backend itself consumes. + if (!absl::StartsWith(it.first, "xla_")) { + if (it.second.empty()) { + fake_argv_storage.push_back(it.first); + } else { + fake_argv_storage.push_back(it.first + "=" + it.second); + } + } + } + + VLOG(2) << "Passing argv to LLVM:"; + std::vector fake_argv; + for (const auto& s : fake_argv_storage) { + fake_argv.push_back(s.c_str()); + VLOG(2) << s; + } + llvm::cl::ParseCommandLineOptions(static_cast(fake_argv.size()), + &fake_argv[0]); + } +} + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_COMMAND_LINE_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_loop.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..a30ec8c8bea92a9072e56efa1fcd6ee8834c750b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_loop.h @@ -0,0 +1,293 @@ +/* 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_SERVICE_LLVM_IR_LLVM_LOOP_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_LOOP_H_ + +#include +#include + +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace llvm_ir { + +enum class UnrollMode { + kDefaultUnroll, + kFullyUnroll, + kNoUnroll, +}; + +// A class for constructing a for-loop in LLVM IR. +class ForLoop { + public: + ForLoop(const ForLoop&) = delete; + ForLoop& operator=(const ForLoop&) = delete; + + // Emit a for-loop at the current insert point of the given IRBuilder. + // + // start_index and end_index are the loop bounds (end_index is not inclusive). + // `step` is the increment of the loop index after each iteration. + // + // The current insert basic block of the builder is the preheader to the loop + // (see below for definition of basic block names). All instructions (if any) + // at or after the insert point in the insert basic block are moved to a newly + // created exit basic block. Instructions before the insert point remain in + // the insert BB: + // + // +--------------+ +----------------+ + // | insert BB | | insert BB | + // | ... | | (preheader BB) | + // | %foo = ... | | ... | + // insert point ->| %bar = ... | ===> | %foo = ... | + // | ... | +----------------+ + // +--------------+ | + // V + // [[ LOOP BBs ]] + // | + // V + // +--------------+ + // | exit BB | + // | %bar = ... | + // | ... | + // +--------------+ + // + // `prefix` is used to disambiguate variable and basic block names emitted in + // LLVM IR. If non-empty, it is prepended to the name of the induction + // variable value and each basic block created for the loop. + // + // `unroll_mode` specifies the desired LLVM unrolling behavior for generated + // loop. + static std::unique_ptr EmitForLoop( + absl::string_view prefix, llvm::Value* start_index, + llvm::Value* end_index, llvm::Value* step, llvm::IRBuilder<>* b, + UnrollMode unroll_mode = llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // The names of the blocks follow LLVM's conventions. Control flow amongst the + // blocks for the example C code looks like: + // + // for (int i = 0; i < n; ++i) { + // do_stuff(i); + // } + // + // +--------------+ + // | preheader BB | + // | i = 0 | + // +--------------+ + // | + // V + // +-------------+ + // | header BB |<-+ + // | if i < n: | | + // | goto body | | + // | else: | | + // | goto exit | | + // +-------------+ | + // | | | + // +--------+ | | + // | V | + // | +-------------+ | + // | | body BB | | + // | | dostuff(i) |--+ + // | | ++i | + // | +-------------+ + // | + // | +-------------+ + // +->| exit BB | + // +-------------+ + // + // Caller-emitted code to execute within the loop should be placed within the + // "body" basic block. + // + // Return pointers to various blocks in the loop. + llvm::BasicBlock* GetPreheaderBasicBlock() const { return preheader_bb_; } + llvm::BasicBlock* GetHeaderBasicBlock() const { return header_bb_; } + llvm::BasicBlock* GetBodyBasicBlock() const { return body_bb_; } + llvm::BasicBlock* GetExitBasicBlock() const { return exit_bb_; } + + // Return the Value representing the induction variable in the body basic + // block of the loop. + llvm::Value* GetIndVarValue() const { return indvar_; } + + private: + // Allow ForLoopNest to call this private constructor. + friend class ForLoopNest; + + ForLoop(absl::string_view prefix, absl::string_view suffix, + llvm::Value* start_index, llvm::Value* end_index, llvm::Value* step, + UnrollMode unroll_mode, bool prevent_vectorization); + + // Emit the loop at the insert point of the builder. + void Emit(llvm::IRBuilder<>* b); + + llvm::BasicBlock* CreateLoopBB(absl::string_view name, llvm::IRBuilder<>* b); + + // Creates a name for an LLVM construct, appending prefix_ and suffix_, if + // they are set. + std::string GetQualifiedName(absl::string_view name); + + // Return a list of metadata nodes that should be associated with the + // llvm::Loop for this `ForLoop`. + std::vector GetLoopMetadata(llvm::IRBuilder<>* b); + + std::string prefix_; + std::string suffix_; + llvm::Value* start_index_; + llvm::Value* end_index_; + llvm::Value* step_; + + // To improve readability of the IR, we want the basic blocks to appear + // consecutively in the following order: preheader, header, body, loop, + // exit. The member insert_before_bb_ points to where the next basic block + // should be created to ensure this ordering. + llvm::BasicBlock* insert_before_bb_; + + llvm::BasicBlock* preheader_bb_; + llvm::BasicBlock* header_bb_; + llvm::BasicBlock* body_bb_; + llvm::BasicBlock* exit_bb_; + llvm::Value* indvar_; + UnrollMode unroll_mode_; + bool prevent_vectorization_; +}; + +// A simple class for constructing nested for-loops. +class ForLoopNest { + public: + ForLoopNest(absl::string_view name, llvm::IRBuilder<>* b, + llvm::Type* index_ty = nullptr) + : name_(name), + outer_loop_preheader_bb_(nullptr), + outer_loop_exit_bb_(nullptr), + inner_loop_body_bb_(nullptr), + b_(b) { + SetIndexType(index_ty); + } + ForLoopNest(const ForLoopNest&) = delete; + ForLoopNest& operator=(const ForLoopNest&) = delete; + + // Adds a loop to the nest. If no loop has been added yet then emit a loop at + // the current insert point of the given builder. If one or more loops have + // been added then emit loop inside the body of the last added loop. + // unroll_mode is used to emit metadata that controls LLVM unrolling. + std::unique_ptr AddLoop( + absl::string_view suffix, llvm::Value* start_index, + llvm::Value* end_index, llvm::Value* stride, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // Like the above, except that it defaults to a stride of one. + std::unique_ptr AddLoop( + absl::string_view suffix, llvm::Value* start_index, + llvm::Value* end_index, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // A convenient wrapper of the other flavor of AddLoop. The given start and + // end index are constant. + std::unique_ptr AddLoop( + int64_t start_index, int64_t end_index, int64_t stride, + absl::string_view suffix, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // Like the above, except that it defaults to a stride of one. + std::unique_ptr AddLoop( + int64_t start_index, int64_t end_index, absl::string_view suffix, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // Add loops to iterate through the indices within the specified + // shape. The returned index collects the induction variables of the + // loops so that it will iterate through all coordinates within the + // specified shape. + // + // E.g. if you pass in a 2x3 shape, you will get back an index with + // two entries that are induction variables of the two loops that + // will be added. That index will iterate through the 6 coordinates + // within the shape. One possible order for that sequence would be: + // + // (0,0), (0,1), (0,2), (1,0), (1,1), (1,2) + IrArray::Index AddLoopsForShape(const Shape& shape, absl::string_view suffix); + + // Add a loop for each dimension in "dimensions". "suffix" is the + // name suffix of the indvar and basic blocks in this new loop nest. + // + // The return value is an index with the induction variables. The + // size equals the rank of shape and there is a null for each + // dimension that is not in "dimensions". + std::vector AddLoopsForShapeOnDimensions( + const Shape& shape, absl::Span dimensions, + absl::string_view suffix); + + // Emits a series of nested loops for iterating over an operand array. Loops + // are constructed in major to minor dimension layout order. No loop is + // emitted for the given 'dimension_to_skip'. The function returns an IrArray + // index for the given operand_array containing the indvars of the loops. All + // dimensions of the index are filled except for 'dimension_to_skip'. + // name_suffix is the string to append to the names of LLVM constructs (eg, + // basic blocks) constructed by this method. + std::vector EmitOperandArrayLoopNest( + const llvm_ir::IrArray& operand_array, int64_t dimension_to_skip, + absl::string_view name_suffix); + + // Convenience methods which return particular basic blocks of the outermost + // or innermost loops. These methods return nullptr if no loops have been + // added yet. + llvm::BasicBlock* GetOuterLoopPreheaderBasicBlock() { + return outer_loop_preheader_bb_; + } + llvm::BasicBlock* GetOuterLoopExitBasicBlock() { return outer_loop_exit_bb_; } + llvm::BasicBlock* GetInnerLoopBodyBasicBlock() { return inner_loop_body_bb_; } + + private: + void SetIndexType(llvm::Type* index_ty) { + index_type_ = index_ty == nullptr ? b_->getInt64Ty() : index_ty; + } + + llvm::Constant* GetConstantWithIndexType(int64_t c) const { + return llvm::ConstantInt::get(index_type_, c); + } + + // Human-friendly name of the loop nest. + std::string name_; + + // The preheader and exit basic block of the outermost loop, or nullptr if no + // loop has been added yet. + llvm::BasicBlock* outer_loop_preheader_bb_; + llvm::BasicBlock* outer_loop_exit_bb_; + + // The body basic block of the most-recently added loop, or nullptr if no loop + // has been added yet. + llvm::BasicBlock* inner_loop_body_bb_; + + llvm::IRBuilder<>* b_; + + llvm::Type* index_type_; +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_LOOP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_type_conversion_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_type_conversion_util.h new file mode 100644 index 0000000000000000000000000000000000000000..033c933deb1577a724518b56be83a132b6a99ce3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_type_conversion_util.h @@ -0,0 +1,55 @@ +/* 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_SERVICE_LLVM_IR_LLVM_TYPE_CONVERSION_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_TYPE_CONVERSION_UTIL_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" + +namespace xla { +namespace llvm_ir { + +// Convert a absl::string_view to a llvm::StringRef. Note: both +// absl::string_view and llvm::StringRef are non-owning pointers into a +// string in memory. This method is used to feed strings to LLVM +// & Clang APIs that expect llvm::StringRef. +inline llvm::StringRef AsStringRef(absl::string_view str) { + return llvm::StringRef(str.data(), str.size()); +} + +inline absl::string_view AsStringView(llvm::StringRef str) { + return absl::string_view(str.data(), str.size()); +} + +template +llvm::ArrayRef AsArrayRef(const std::vector& vec) { + return llvm::ArrayRef(vec.data(), vec.size()); +} + +template +llvm::ArrayRef AsArrayRef(const absl::Span slice) { + return llvm::ArrayRef(slice.data(), slice.size()); +} + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_TYPE_CONVERSION_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_util.h new file mode 100644 index 0000000000000000000000000000000000000000..10f710309781e4f18666a9e7ff05d85d0322db85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/llvm_util.h @@ -0,0 +1,326 @@ +/* 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_SERVICE_LLVM_IR_LLVM_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_UTIL_H_ + +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/FPEnv.h" +#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/literal.h" +#include "xla/service/hlo_module_config.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace llvm { +class FastMathFlags; +class TargetOptions; +}; // namespace llvm + +namespace xla { +namespace llvm_ir { + +// We have different DumpToString functions for each type for findability. We +// use pointers / values based on the usual semantics of the parameter type. + +std::string DumpToString(const llvm::Module* module); +std::string DumpToString(const llvm::Type* type); +std::string DumpToString(const llvm::Value* value); + +// This also works for mlir::Op<...> descendants, such as mlir::ModuleOp and +// mlir::lmhlo::FusionOp. +// +// For findability: +// std::string DumpToString(mlir::Op<...>& op); +// std::string DumpToString(mlir::ModuleOp& module_op); +// std::string DumpToString(mlir::lmhlo::FusionOp& fusion_op); +// +// The `operation` parameter is not const, because the used print() method is +// not const. +std::string DumpToString(mlir::Operation* operation); +std::string DumpToString(mlir::Type type); +std::string DumpToString(mlir::Value value); + +// Constructs a human-friendly name from the given inputs. The result is +// suitable for use as an llvm::Value's name. +// +// This is equivalent to +// +// - changing the HloInstruction* to its name() (if we called that overload), +// - joining all of the nonempty inputs by '.', and then +// - removing all '%'s. +// +std::string IrName(absl::string_view a); +std::string IrName(absl::string_view a, absl::string_view b); +std::string IrName(const HloInstruction* a, absl::string_view b = ""); + +// Construct a module from the given location with an optional name. +// +// The underlying "create" method is unsafe, because it leaks the new module by +// default. This function avoids this by always returning an OwningOpRef. +mlir::OwningOpRef CreateMlirModuleOp( + mlir::Location loc, std::optional name = std::nullopt); + +// Removes special characters from a function name. +// +// Note that this can cause different inputs to map to the same output, so after +// sanitizing a function name, you must run it through a uniquer. +std::string SanitizeFunctionName(std::string function_name); + +// Emits a call to the specified intrinsic with the given operands. Overloaded +// intrinsics (for example, "minnum") must include a type in overloaded_types +// for each overloaded type. Typically, overloaded intrinsics have only a single +// overloaded type. +llvm::CallInst* EmitCallToIntrinsic( + llvm::Intrinsic::ID intrinsic_id, absl::Span operands, + absl::Span overloaded_types, llvm::IRBuilder<>* b, + absl::string_view name = ""); + +// Emit float max. Emit maxnum intrinsic is fast math is disabled, or +// fcmp+select otherwise +llvm::Value* EmitFloatMax(llvm::Value* lhs_value, llvm::Value* rhs_value, + llvm::IRBuilder<>* b, bool enable_fast_min_max, + absl::string_view name = ""); + +// Emit float min. Emit minnum intrinsic is fast math is disabled, or +// fcmp+select otherwise +llvm::Value* EmitFloatMin(llvm::Value* lhs_value, llvm::Value* rhs_value, + llvm::IRBuilder<>* b, bool enable_fast_min_max, + absl::string_view name = ""); + +// Convenience methods for emitting a GEP instruction that indexes into a buffer +// (1-dimensional array), equivalent to array[index]. The element type of the +// array must be explicitly passed in. The int64_t index overload +// wraps the index in a i64 llvm::Value. +llvm::Value* EmitBufferIndexingGEP(llvm::Value* array, llvm::Type* element_type, + llvm::Value* index, llvm::IRBuilder<>* b); +llvm::Value* EmitBufferIndexingGEP(llvm::Value* array, llvm::Type* element_type, + int64_t index, llvm::IRBuilder<>* b); + +// Returns the LLVM type which represents the given XLA primitive type. +llvm::Type* PrimitiveTypeToIrType(PrimitiveType element_type, + llvm::Module* module); + +// Returns the type size in bits. If "type" is a struct, it must be packed. +int GetSizeInBits(llvm::Type* type); + +// Returns the LLVM type which represents the given XLA shape. For example, +// if "shape" is [5 x [10 x f32]], the function returns [5 x [10 x float]]. +llvm::Type* ShapeToIrType(const Shape& shape, llvm::Module* module); + +// Returns a value that represents a pointer to a global string constant that +// encodes the shape as a serialized protobuf. +StatusOr EncodeSelfDescribingShapeConstant(const Shape& shape, + int32_t* shape_size, + llvm::IRBuilder<>* b); + +// Converts a given literal to an IR Constant. Literals have known constant +// values at IR emission time. +llvm::Constant* ConvertLiteralToIrConstant(const Literal& literal, + llvm::Module* module); + +// Allocates a tile of shared memory. +llvm::GlobalVariable* AllocateSharedMemoryTile(llvm::Module* module, + llvm::Type* tile_type, + absl::string_view name); + +// Inserts an allocate of the requested type at the entry point of the +// function that the builder is currently building. The insert point +// of the builder is set to the same place after calling this function +// as before. +// +// This can be useful to avoid e.g. executing an alloca every time +// through a loop. +llvm::AllocaInst* EmitAllocaAtFunctionEntry(llvm::Type* type, + absl::string_view name, + llvm::IRBuilder<>* b, + int alignment = 0); + +// As EmitAllocaAtFunctionEntry, but allocates element_count entries +// instead of a single element. +llvm::AllocaInst* EmitAllocaAtFunctionEntryWithCount(llvm::Type* type, + llvm::Value* element_count, + absl::string_view name, + llvm::IRBuilder<>* b, + int alignment = 0); + +// Creates a basic block with the same context and function as for the +// builder. Inserts at the end of the function if insert_before is +// null. +llvm::BasicBlock* CreateBasicBlock(llvm::BasicBlock* insert_before, + absl::string_view name, + llvm::IRBuilder<>* b); + +// Struct with data on a conditional branch in a diamond shape created +// via EmitIfThenElse. +struct LlvmIfData { + // The block that has the conditional branch. + llvm::BasicBlock* if_block; + + // The block that is executed if the condition is true. + llvm::BasicBlock* true_block; + + // The block that is executed if the condition is false. + llvm::BasicBlock* false_block; + + // The block that follows after both the true_block and the + // false_block. + llvm::BasicBlock* after_block; +}; + +// Inserts a diamond-shaped if-then-else construct at the current +// insertion point of the builder. This involves splitting the current +// block into two blocks, at the insertion point, and introducing a +// true-block and a false-block that connect the two split pieces. The +// true-block is executed if the condition parameter evaluates to true +// and otherwise the false-block is executed. If `emit_else` is false, +// it jumps to the after-block rather than the false-block if the +// condition is false, and the returned `false_block` is null. +// +// Currently the insertion point of the builder must be a well-formed +// block with a terminator. If you need to use this for a +// non-terminated block, just make the function able to do that too. +LlvmIfData EmitIfThenElse(llvm::Value* condition, absl::string_view name, + llvm::IRBuilder<>* b, bool emit_else = true); + +// Emits a compare operation between "lhs" and "rhs" with the given predicate, +// and then converts the result to i8 so that it is addressable. +llvm::Value* EmitComparison(llvm::CmpInst::Predicate predicate, + llvm::Value* lhs, llvm::Value* rhs, + llvm::IRBuilder<>* b, absl::string_view name = ""); + +// Emits a call that logs the given value with the given tag as a prefix. +// The provided tag and value are passed to a runtime logging call that is +// embedded in this translation unit when the emitted code is executed. +// +// This can be very useful for debugging generated programs in short order when +// developing new generated routines. +// +// Precondition: value must be an int64_t. +// Precondition: tag must be a stable pointer for the lifetime of the generated +// program (the constant pointer is burned in to the program). +void EmitLogging(const char* tag, llvm::Value* value, llvm::IRBuilder<>* b); + +// Adds alignment metadata to a load instruction using the given alignment. +// The alignment refers to the result of the load, not the load itself. +void SetAlignmentMetadataForLoad(llvm::LoadInst* load, uint64_t alignment); + +// Adds dereferenceable metadata to a load instruction using the given +// the number of dereferenceable bytes. +// Dereferenceable refers to the result of the load, not the load itself. +void SetDereferenceableMetadataForLoad(llvm::LoadInst* load, + uint64_t dereferenceable_bytes); + +// Tells LLVM `inst >= lower && inst < upper`. Returns `inst` for convenience. +llvm::Instruction* AddRangeMetadata(int32_t lower, int32_t upper, + llvm::Instruction* inst); + +void SetToFirstInsertPoint(llvm::BasicBlock* blk, llvm::IRBuilder<>* builder); + +void SetToLastInsertPoint(llvm::BasicBlock* blk, llvm::IRBuilder<>* builder); + +// Create a bitwise rotation of `rotand` by `rotor`. +llvm::Value* CreateRor(llvm::Value* rotand, llvm::Value* rotor, + llvm::IRBuilder<>* builder); + +// Returns the number of bytes within the shape. +int64_t ByteSizeOf(const Shape& shape, const llvm::DataLayout& data_layout); + +// Gets an llvm::FastMathFlags that reflects the settings in the given +// module config. +llvm::FastMathFlags GetCpuFastMathFlags(const HloModuleConfig& module_config); + +// Computes a conservative union of the metadata in "a" and "b". For +// aliasing-related metadata, this means the result can be applied to +// instructions whose aliasing relationship can be described either by "a" *or* +// by "b". +std::map MergeMetadata( + llvm::LLVMContext* context, const std::map& a, + const std::map& b); + +// Dumps out `llvm_module` to the path specified in DebugOptions, if dumping is +// enabled for the given HLO module. +// +// A sanitized version of `hlo_module_name` is incorporated into the file name. +// If `optimized` is true then a suffix of "-with-opt.ll" is used, else a suffix +// of "-no-opt.ll" is used. +void DumpIrIfEnabled(const HloModule& hlo_module, + const llvm::Module& llvm_module, bool optimized, + absl::string_view filename_suffix = ""); + +llvm::Function* CreateCpuFunction(llvm::FunctionType* function_type, + llvm::GlobalValue::LinkageTypes linkage, + const HloModuleConfig& module_config, + absl::string_view name, llvm::Module* module); + +// Zero-extends two 32-bit values to 64 bits, multiplies them, and returns the +// result as a pair of (low 32 bits, high 32 bits). +std::pair UMulLowHigh32(llvm::IRBuilder<>* b, + llvm::Value* src0, + llvm::Value* src1); +// Splits the 64-bit integer value into its high and low 32 bits. +std::pair SplitInt64ToInt32s( + llvm::IRBuilder<>* b, llvm::Value* value_64bits); + +// Checks whether a global variable is already created to represent the state +// of a random number generator. If not, creates such a variable. Returns the +// global variable. +llvm::GlobalVariable* GetOrCreateVariableRngState(llvm::Module* module, + llvm::IRBuilder<>* b); + +// Adds a delta value to the global state variable and return the old value of +// the variable. +llvm::Value* RngGetAndUpdateState(uint64_t delta, llvm::Module* module, + llvm::IRBuilder<>* b); + +// Gets the LLVM address space that should be used for global variables (e.g. +// XLA's rng state). +unsigned GetGlobalMemoryAddressSpace(); + +// Emits a block which does "return void". Leaves the insert point as is. +llvm::BasicBlock* EmitReturnBlock(llvm::IRBuilder<>* b); + +// Emits `if (condition) return`. Assumes that the current function returns +// void. +// +// Can either use a supplied `return_block`, or generate a new one. +void EmitEarlyReturn(llvm::Value* condition, llvm::IRBuilder<>* b, + llvm::BasicBlock* return_block = nullptr); + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/loop_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/loop_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..c5f3c2322db059e036b8a105eba6e20f57f46ee2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/loop_emitter.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_SERVICE_LLVM_IR_LOOP_EMITTER_H_ +#define XLA_SERVICE_LLVM_IR_LOOP_EMITTER_H_ + +#include + +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/llvm_loop.h" +#include "xla/statusor.h" + +namespace xla { +namespace llvm_ir { + +// A function type for emitting code that generates an element in the target +// array. The function gets a multi-dimensional index as its only input. This +// index specifies the target element for which a value needs to be computed. +// The function has to emit code to compute this value and return the resulting +// llvm::Value*. +using ElementGenerator = + std::function(const IrArray::Index& index)>; +using BodyEmitter = std::function; + +// Creates the body emitter from target arrays. +BodyEmitter MakeBodyEmitter(const ElementGenerator& target_element_generator, + absl::Span target_arrays, + llvm::IRBuilder<>* b, bool is_tuple); + +// Emits a loop for every element in the given shape. +class LoopEmitter { + public: + LoopEmitter(const BodyEmitter& body_emitter, const Shape& shape, + llvm::IRBuilder<>* b); + + // Constructs a LoopEmitter from an body_emitter that generates + // element of the given target array in the dynamic dimension. + LoopEmitter(const BodyEmitter& body_emitter, const Shape& shape, + std::vector dynamic_dims, llvm::IRBuilder<>* b); + + // Constructs a LoopEmitter from an element generator that generates each + // element of the given target array. + LoopEmitter(const ElementGenerator& target_element_generator, + const IrArray& target_array, llvm::IRBuilder<>* b); + + // Constructs a LoopEmitter that emits one element into each of N separate + // arrays on each iteration of the loop. + // + // This is used for multi-output fusion. target_element_generator must + // produce an LLVM struct with N elements. + LoopEmitter(const ElementGenerator& target_element_generator, + absl::Span target_arrays, llvm::IRBuilder<>* b); + + LoopEmitter(const LoopEmitter&) = delete; + LoopEmitter& operator=(const LoopEmitter&) = delete; + virtual ~LoopEmitter() = default; + + // Emits a loop nest (with a yet-to-be-filled loop body) that iterates through + // every element in the given shape. Returns the multi-dimensional index that + // specifies the element, will return multiple indices if the loop is + // unrolled. + virtual std::vector EmitIndexAndSetExitBasicBlock( + absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_index); + + // Emits a complete loop nest for every element in the given shape. + Status EmitLoop(absl::string_view loop_name = "", + llvm::Type* index_type = nullptr); + + protected: + // An IR emitter that generates the loop body. + BodyEmitter body_emitter_; + + // The shape that the emitted loop iterates through. + Shape shape_; + + // Dynamic dimensions that emitted loop iterates through. Generate the + // loop based on the dynamic dimensions if this vector is not empty. + std::vector dynamic_dims_; + + // Points to the exit block of the emitted loop. If the given shape is + // scalar, no loops are emitted and exit_bb_ is nullptr in that case. + llvm::BasicBlock* exit_bb_; + + llvm::IRBuilder<>* b_; + + private: + IrArray::Index EmitStaticIndex(ForLoopNest* loop_nest, + llvm::Type* index_type); + IrArray::Index EmitDynamicIndex(ForLoopNest* loop_nest, + llvm::Type* index_type); +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LOOP_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/math_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/math_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..bc16d4cc593d647847106dd0b134beb9d7e48619 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/math_ops.h @@ -0,0 +1,32 @@ +/* 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_SERVICE_LLVM_IR_MATH_OPS_H_ +#define XLA_SERVICE_LLVM_IR_MATH_OPS_H_ + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" + +namespace xla { +namespace llvm_ir { + +// Emits an approximation of tanh. The implementation uses the same rational +// interpolant as implemented in Eigen3. +llvm::Value* EmitFastTanh(llvm::IRBuilder<>* b, llvm::Value* input); + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_MATH_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/sort_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/sort_util.h new file mode 100644 index 0000000000000000000000000000000000000000..92cfa679ae284700f8c648376338d3615d54cc0b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/sort_util.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_LLVM_IR_SORT_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_SORT_UTIL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/Value.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace llvm_ir { +using EmitCallToNestedComputationCallback = + std::function, llvm::Value*)>; +// Emits llvm IR to do pairwise comparisons/swaps in the 'dimension_to_sort' +// dimension of each array in 'values_arrays'. All other dimensions are kept +// as-is. This implements the inner loop of BitonicSort. It is assumed that +// 'xor_masks' contains only powers of 2, or values 2^k - 1 (k > 0). +Status EmitSortInPlace( + int64_t dimension_to_sort, const std::vector& values_arrays, + absl::string_view name, absl::Span xor_masks, + llvm::IRBuilder<>* b, const gpu::LaunchDimensions& launch_dimensions, + int64_t num_iterations_in_sort_dim, int64_t tile_size, + const EmitCallToNestedComputationCallback& emit_compare_callback); +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_SORT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/tuple_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/tuple_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0ce8249caa9f1e6dc600a63fd82bd6384f5a7304 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/llvm_ir/tuple_ops.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_LLVM_IR_TUPLE_OPS_H_ +#define XLA_SERVICE_LLVM_IR_TUPLE_OPS_H_ + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" + +// Utilities for emitting LLVM IR related to HLO tuples. + +namespace xla { +namespace llvm_ir { + +// A tuple is an array of pointers, one for each operand. Each pointer points to +// the output buffer of its corresponding operand. +void EmitTuple(const IrArray& tuple, absl::Span operands, + llvm::IRBuilder<>* b); + +// Emits one alloca for each element in the tuple of shape tuple_shape, +// returns the emitted allocas. +// Precondition: tuple_shape should be a tuple of scalars. +std::vector EmitTupleAllocasAtFunctionEntry( + const Shape& tuple_shape, llvm::IRBuilder<>* b); + +// Similar to EmitTuple above, except that the output buffers are provided in +// the form of IrArray. +void EmitTuple(const IrArray& tuple, absl::Span buffers, + llvm::IRBuilder<>* b); + +// A tuple is an array of pointers, one for each operand. Each pointer points to +// the output buffer of its corresponding operand. A GetTupleElement instruction +// forwards the pointer to underlying tuple element buffer at the given index. +// Returns an llvm value representing a pointer to the tuple element buffer. +llvm::Value* EmitGetTupleElement(const Shape& target_shape, int64_t index, + int alignment, llvm::Value* operand, + llvm::Type* operand_pointee_type, + llvm::IRBuilder<>* b); +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_TUPLE_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/local_service.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/local_service.h new file mode 100644 index 0000000000000000000000000000000000000000..4bea89ef1f5876727e19ee87faa36076b3663f89 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/local_service.h @@ -0,0 +1,90 @@ +/* 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_SERVICE_LOCAL_SERVICE_H_ +#define XLA_SERVICE_LOCAL_SERVICE_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/client/executable_build_options.h" +#include "xla/client/xla_computation.h" +#include "xla/service/backend.h" +#include "xla/service/compiler.h" +#include "xla/service/executable.h" +#include "xla/service/service.h" +#include "xla/service/shaped_buffer.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 { + +// Service implementation that extends the XLA Service to leverage running +// in the same process as the client. +class LocalService : public Service { + public: + // Factory for creating a LocalService. + static StatusOr> NewService( + const ServiceOptions& options); + + // Builds Executables with the given XlaComputation, argument layouts and + // options. If result_layout is non-null, then the executable is compiled to + // produce a result of the given layout. If device_allocator is non-null, + // then the compiler may use it to allocate temp space on the device. The + // compiler is responsible for freeing any memory it allocates this way. + StatusOr>> CompileExecutables( + const XlaComputation& computation, + const absl::Span argument_layouts, + const ExecutableBuildOptions& build_options); + + // Same as CompileExecutables() above, but return AotCompilationResult objects + // (instead of Executable objects), which can be persisted to later load + // Executable objects. + StatusOr>> + CompileAotResults(const XlaComputation& computation, + const absl::Span argument_layouts, + const ExecutableBuildOptions& build_options); + + // 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); + + // 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); + + // Registers a vector of shaped buffers of device memory, one per replica, and + // returns a corresponding handle that can be used for talking to XLA clients. + StatusOr RegisterReplicatedBuffers( + std::vector replicated_buffers, + const std::string& tag); + + private: + explicit LocalService(const ServiceOptions& options, + std::unique_ptr backend); + LocalService(const LocalService&) = delete; + void operator=(const LocalService&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LOCAL_SERVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/local_service_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/local_service_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..e71f4605aec2e8e9beeddcb1f7ee3abe915ceb78 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/local_service_utils.h @@ -0,0 +1,38 @@ +/* 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_SERVICE_LOCAL_SERVICE_UTILS_H_ +#define XLA_SERVICE_LOCAL_SERVICE_UTILS_H_ + +#include + +#include "absl/types/span.h" +#include "xla/client/executable_build_options.h" +#include "xla/client/xla_computation.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/backend.h" +#include "xla/service/service.h" + +namespace xla { +// Validates the computation argument layouts, and returns the corresponding +// HloModuleConfig. +StatusOr> GetHloModuleConfig( + const XlaComputation& computation, + absl::Span argument_layouts, + const ExecutableBuildOptions& build_options, + ServiceOptions* options = nullptr, Backend* backend = nullptr); +} // namespace xla + +#endif // XLA_SERVICE_LOCAL_SERVICE_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logical_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logical_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..8666d6d62614f7109037f2e73377b0f13a8df3c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logical_buffer.h @@ -0,0 +1,60 @@ +/* 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_SERVICE_LOGICAL_BUFFER_H_ +#define XLA_SERVICE_LOGICAL_BUFFER_H_ + +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_value.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/lib/gtl/int_type.h" + +namespace xla { + +// TuplePointsToAnalysis uses this subclass of BufferValue. +class LogicalBuffer : public BufferValue { + public: + LogicalBuffer(HloInstruction* instruction, const ShapeIndex& index, Id id); + + // Return the instruction that defines the buffer. + HloInstruction* instruction() const override { return instruction_; } + + // Return the index within the output of the instruction where the buffer is + // defined. Index used defined as in ShapeUtil::GetSubshape() + const ShapeIndex& index() const override { return index_; } + + // Return the shape of the buffer. This reference points into the shape field + // of the instruction defining the buffer. Therefore, the returned shape will + // contain the layout of instruction, if any. + const Shape& shape() const override { + return ShapeUtil::GetSubshape(instruction_->shape(), index_); + } + + std::string ToString() const override; + + private: + HloInstruction* instruction_; + ShapeIndex index_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LOGICAL_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logical_buffer_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logical_buffer_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..ce86d5a2adc434d5c3bb3f7bd870f99ec16da896 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logical_buffer_analysis.h @@ -0,0 +1,89 @@ +/* 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_SERVICE_LOGICAL_BUFFER_ANALYSIS_H_ +#define XLA_SERVICE_LOGICAL_BUFFER_ANALYSIS_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/logical_buffer.h" +#include "xla/statusor.h" + +namespace xla { +// A class to create all the logical buffers defined by the HLO ops in a module. +class LogicalBufferAnalysis : public DfsHloVisitorWithDefault { + public: + // Runs points-to analysis on 'module'. + static StatusOr> Run( + const HloModule* module); + + // Returns the logical buffer with the given ID. + LogicalBuffer& GetBuffer(LogicalBuffer::Id id) const; + + // Returns the logical buffer that represents the output of a given HLO + // at a given index. + LogicalBuffer& GetBuffer(HloInstruction* instruction, + const ShapeIndex& index) const; + + const std::vector>& logical_buffers() const { + return logical_buffers_; + } + size_t num_logical_buffers() const { return logical_buffers_.size(); } + + private: + explicit LogicalBufferAnalysis(const HloModule* module) : module_(module) {} + Status Analyze(); + + // The module this analysis is performed on. + const HloModule* module_; + + // Create a new logical buffer and return a reference to it. The newly created + // buffer is stored in an internal vector of LogicalBuffers and can be + // accessed with GetBuffer. + void NewLogicalBuffer(HloInstruction* instruction, const ShapeIndex& index); + + Status DefaultAction(HloInstruction* hlo_instruction) override; + Status HandleTuple(HloInstruction* tuple) override; + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + Status HandleBitcast(HloInstruction* bitcast) override; + Status HandleDomain(HloInstruction* domain) override; + Status HandleCopy(HloInstruction* copy) override; + Status HandleCopyStart(HloInstruction* copy_start) override; + Status HandleCopyDone(HloInstruction* copy_done) override; + Status HandleRecvDone(HloInstruction* recv_done) override; + Status HandleSend(HloInstruction* send) override; + Status HandleAddDependency(HloInstruction* add_dependency) override; + Status HandleCustomCall(HloInstruction* custom_call) override; + Status HandleFusion(HloInstruction* fusion) override; + + // A map from the buffer ID to the logical buffer + std::vector> logical_buffers_; + + // A map from an hlo + shape index to the logical buffer representing + // the appropriate output. + absl::flat_hash_map, + LogicalBuffer*> + output_buffers_; + // Whether to alias buffers defined by dataflow relations. This aliasing + // relation should not be recognized if copies can be inserted to break up + // the dataflow relation-induced aliasing. + const bool alias_buffer_across_dataflow_ = false; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LOGICAL_BUFFER_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logistic_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logistic_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..b754b71266d1fbd007fdf6f59f012d05cbbf3a0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/logistic_expander.h @@ -0,0 +1,46 @@ +/* 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_SERVICE_LOGISTIC_EXPANDER_H_ +#define XLA_SERVICE_LOGISTIC_EXPANDER_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// A pass which performs expansion of the logistic function. +class LogisticExpander : public OpExpanderPass { + public: + LogisticExpander() = default; + ~LogisticExpander() override = default; + absl::string_view name() const override { return "logistic-expander"; } + + private: + // Returns `true` if `instruction` should be expanded by this pass. + bool InstructionMatchesPattern(HloInstruction* instruction) override; + // Returns a replacement for `instruction`, or nullptr if no replacement is + // needed (e.g. only the to_apply subcomputation of the instruction was + // modified). + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LOGISTIC_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/loop_schedule_linearizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/loop_schedule_linearizer.h new file mode 100644 index 0000000000000000000000000000000000000000..a3a1b9e4beb151ed247d10dca91f2e512138394c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/loop_schedule_linearizer.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_LOOP_SCHEDULE_LINEARIZER_H_ +#define XLA_SERVICE_LOOP_SCHEDULE_LINEARIZER_H_ + +#include "xla/hlo/ir/hlo_computation.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_pass_interface.h" + +namespace xla { + +// Adds control dependency edges from instructions which "write" values inside +// the loop, to instructions which "read" those same values, in order to avoid +// extraneous copies. This is not always possible with our buffer layout +// constraints (that is, assuming that every element of the tuple the while loop +// operates upon gets the same buffer) as it may create cycles (an easiest +// example of a dependency cycle is a loop doing `(a, b) = (b, a)`). Thus we +// take a best-effort approach instead: add dependency edges only if we can show +// they don't create a cycle. +class LoopScheduleLinearizer : public HloModulePass { + public: + absl::string_view name() const override { return "loop-schedule-linearizer"; } + + explicit LoopScheduleLinearizer( + const HloDataflowAnalysis::CanShareBuffer& can_share_buffer = nullptr) + : can_share_buffer_(can_share_buffer) {} + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Backend specific function that decides whether an instruction can share + // buffer with its operand. + HloDataflowAnalysis::CanShareBuffer can_share_buffer_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LOOP_SCHEDULE_LINEARIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/map_inliner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/map_inliner.h new file mode 100644 index 0000000000000000000000000000000000000000..ebb10cdf3d87d02c3ec3462840f0eea053c4d661 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/map_inliner.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_MAP_INLINER_H_ +#define XLA_SERVICE_MAP_INLINER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which performs map inlining. This replaces kMap instructions with +// their equivalent sequence of array operations. For example: +// map({X, Y}, add) -> add(X, Y)). +class MapInliner : public HloModulePass { + public: + ~MapInliner() override = default; + absl::string_view name() const override { return "map-inline"; } + + // Run map inlining on the given computation. Returns whether the computation + // was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_MAP_INLINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/mapped_ptr_container_sorter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/mapped_ptr_container_sorter.h new file mode 100644 index 0000000000000000000000000000000000000000..262f5d455f9c05494d054d7e618bba137fee7352 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/mapped_ptr_container_sorter.h @@ -0,0 +1,457 @@ +/* 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. +==============================================================================*/ + +// Below, we specify an example usage, in which clone is sorted according to +// original, using map_fn to map from pointers in original to pointers in clone. +// +// std::vector> original = ...; +// std::vector> clone = ...; +// HloCloneContext* ctx = ...; +// using Sorter = MappedPtrContainerSorter; +// Sorter::MappedPtrFn map_fn = [ctx](const HloInstruction* i) { +// return ctx->FindInstruction(i); +// }; +// +// auto status = Sorter::Sort(map_fn, Sorter::IndexAfterMappedElementsFn(), +// original, clone); + +#ifndef XLA_SERVICE_MAPPED_PTR_CONTAINER_SORTER_H_ +#define XLA_SERVICE_MAPPED_PTR_CONTAINER_SORTER_H_ + +#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/str_cat.h" +#include "absl/strings/str_join.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/util.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/logging.h" +#include "tsl/platform/statusor.h" + +namespace xla { + +// A class for sorting an unordered container of pointers according to the sort +// order of an ordered container of pointers. Sorting is stable. +// +// Terminology: +// - unmapped element: An element from the unordered container that does not +// have a corresponding element in the ordered container. +template +class MappedPtrContainerSorter { + public: + // A function to map elements from an ordered container to elements in an + // unordered container. Not every element in ordered_container need map to an + // element in unordered_container and vice versa. + using MapPtrFn = absl::FunctionRef; + + // A function that maps unmapped elements (from an unordered container) to an + // index in the final sorted result. The returned index indicates that the + // unmapped element should be placed just after the mapped element at that + // index, in the result without unmapped elements. See + // IndexBeforeMappedElementsFn() and IndexAfterMappedElementsFn() for how to + // indicate that an unmapped element should be placed before or after all + // mapped elements, respectively. Unmapped elements destined for the same + // index will retain their order from the unordered container. + using UnmappedPtrIndexFn = absl::FunctionRef; + + // Functions that return an UnmappedElementIndexFn that indicates that + // ummapped elements (from an unordered container) should be placed before or + // after all mapped elements, respectively. + static UnmappedPtrIndexFn IndexBeforeMappedElementsFn(); + static UnmappedPtrIndexFn IndexAfterMappedElementsFn(); + + // Returned function always returns an error. + static UnmappedPtrIndexFn InvalidIndexFn(); + + // Sorts an unordered container of pointers according to the order of an + // ordered container of pointers. Sorting is stable. Works with POD pointers, + // const POD pointers, and unique_ptrs. If an error is returned, + // unordered_container is not modified. Returns an error status if: + // - unmapped_index() returns an invalid index + // - An internal error occurs. (This should theoretically not happen.) + template + static Status Sort(MapPtrFn map_ptr, UnmappedPtrIndexFn unmapped_index, + const OrderedTy& ordered_container, + UnorderedTy& unordered_container); + + private: + // A class for sorting the indices of the unordered_container. + class SortedIndices { + public: + // max_partial_order_exclusive is 1 greater than the maximum partial order + // value allowed to be sent to AddMappedElement(). + SortedIndices(size_t max_partial_order_exclusive, + size_t unordered_container_size) + : max_partial_order_exclusive_(max_partial_order_exclusive), + unordered_container_size_(unordered_container_size), + mapped_element_indices_by_partial_order_( + max_partial_order_exclusive) {} + + // Specify the partial ordering value of a mapped element from the + // unordered container. The partial ordering is amongst other mapped + // elements. + Status AddMappedElement(size_t unordered_container_index, + size_t partial_order); + + // Specify the index (amongst mapped elements), where an unmapped element + // should be inserted. The unmapped element is inserted just after the + // mapped element with index target_index_amongst_mapped_elements. + void AddUnmappedElement(size_t unordered_container_index, + size_t target_index_amongst_mapped_elements); + + std::string ToString() const; + + // The result maps each element in the unordered_container to the target + // index that it will occupy in the sorted result. + StatusOr> Flatten() const; + + private: + SortedIndices() = delete; + + size_t max_partial_order_exclusive_; + size_t unordered_container_size_; + std::vector> mapped_element_indices_by_partial_order_; + absl::flat_hash_map> + target_index_to_unmapped_element_index_; + }; + + static size_t IndexBeforeMappedElements() { + return std::numeric_limits::max() - 2; + } + + static size_t IndexAfterMappedElements() { + return std::numeric_limits::max() - 1; + } + + static size_t InvalidIndex() { return std::numeric_limits::max(); } + + // Returns a mapping in which the element at index i indicates the target + // index that unordered_container[i] should occupy in the sorted result. + template + static StatusOr> ComputeNewIndices( + MapPtrFn map_ptr, UnmappedPtrIndexFn unmapped_index, + const OrderedTy& ordered_container, + const UnorderedTy& unordered_container); + + // Reorders unordered_container according to the indices in new_indices. See + // ComputeNewIndices() for how to interpret new_indices. + template + static void Reorder(std::vector new_indices, + UnorderedTy& unordered_container); +}; + +///// Template implementation below ///// + +namespace mapped_ptr_container_sorter_internal { + +template +struct PtrGetter { + // Extracts a pointer of type O from i. + static O Get(I i); +}; + +template +struct PtrGetter { + static const T* Get(T* const& p) { return p; } +}; + +template +struct PtrGetter { + static const T* Get(T const* const& p) { return p; } +}; + +template +struct PtrGetter { + static T* Get(T*& p) { return p; } +}; + +template +struct PtrGetter&, const T*> { + static const T* Get(const std::unique_ptr& p) { return p.get(); } +}; + +template +struct PtrGetter&, T*> { + static T* Get(std::unique_ptr& p) { return p.get(); } +}; + +} // namespace mapped_ptr_container_sorter_internal + +template +typename MappedPtrContainerSorter::UnmappedPtrIndexFn +MappedPtrContainerSorter::IndexBeforeMappedElementsFn() { + static const auto fn = [](const PointedToTy*) { + return IndexBeforeMappedElements(); + }; + return fn; +} + +template +typename MappedPtrContainerSorter::UnmappedPtrIndexFn +MappedPtrContainerSorter::IndexAfterMappedElementsFn() { + static const auto fn = [](const PointedToTy*) { + return IndexAfterMappedElements(); + }; + return fn; +} + +template +typename MappedPtrContainerSorter::UnmappedPtrIndexFn +MappedPtrContainerSorter::InvalidIndexFn() { + static const auto fn = [](const PointedToTy*) { return InvalidIndex(); }; + return fn; +} + +template +Status MappedPtrContainerSorter::SortedIndices::AddMappedElement( + size_t unordered_container_index, size_t partial_order) { + if (partial_order >= mapped_element_indices_by_partial_order_.size()) { + return InternalErrorStrCat( + "invalid partial order: ", partial_order, " v max(", + mapped_element_indices_by_partial_order_.size(), ")"); + } + + mapped_element_indices_by_partial_order_[partial_order].push_back( + unordered_container_index); + return OkStatus(); +} + +template +void MappedPtrContainerSorter::SortedIndices::AddUnmappedElement( + size_t unordered_container_index, + size_t target_index_amongst_mapped_elements) { + target_index_to_unmapped_element_index_[target_index_amongst_mapped_elements] + .push_back(unordered_container_index); +} + +template +std::string MappedPtrContainerSorter::SortedIndices::ToString() + const { + std::vector mapped_element_strs; + mapped_element_strs.reserve(mapped_element_indices_by_partial_order_.size()); + for (const auto& indices : mapped_element_indices_by_partial_order_) { + mapped_element_strs.push_back( + absl::StrCat("[", absl::StrJoin(indices, ", "), "]")); + } + std::vector unmapped_element_strs; + unmapped_element_strs.reserve(target_index_to_unmapped_element_index_.size()); + for (const auto& kv : target_index_to_unmapped_element_index_) { + std::string key = absl::StrCat(kv.first); + if (kv.first == IndexBeforeMappedElements()) { + key = "before_mapped"; + } + if (kv.first == IndexAfterMappedElements()) { + key = "after_mapped"; + } + if (kv.first == InvalidIndex()) { + key = "invalid"; + } + unmapped_element_strs.push_back( + absl::StrCat(key, ": [", absl::StrJoin(kv.second, ", "), "]")); + } + + return absl::StrCat( + "max_partial_order_exclusive_: ", max_partial_order_exclusive_, "\n", + "unordered_container_size_: ", unordered_container_size_, "\n", + "mapped_element_indices_by_partial_order_: [", + absl::StrJoin(mapped_element_strs, ", "), "]\n", + "target_index_to_unmapped_element_index_: {", + absl::StrJoin(unmapped_element_strs, ", "), "}\n"); +} + +template +StatusOr> +MappedPtrContainerSorter::SortedIndices::Flatten() const { + std::vector result(unordered_container_size_, InvalidIndex()); + size_t next_available_index = 0; + auto next_index_fn = [&]() -> StatusOr { + if (next_available_index >= unordered_container_size_) { + return InternalErrorStrCat( + "invalid unordered_container index: ", next_available_index, + " v size(", unordered_container_size_, ")"); + } + return next_available_index++; + }; + + if (target_index_to_unmapped_element_index_.contains( + IndexBeforeMappedElements())) { + const auto& indices = + target_index_to_unmapped_element_index_.at(IndexBeforeMappedElements()); + for (size_t index : indices) { + TF_ASSIGN_OR_RETURN(result[index], next_index_fn()); + } + } + size_t num_inserted_mapped_elements = 0; + for (const auto& mapped_element_indices : + mapped_element_indices_by_partial_order_) { + for (size_t mapped_element_index : mapped_element_indices) { + TF_ASSIGN_OR_RETURN(result[mapped_element_index], next_index_fn()); + ++num_inserted_mapped_elements; + if (target_index_to_unmapped_element_index_.contains( + num_inserted_mapped_elements - 1)) { + const auto& unmapped_element_indices = + target_index_to_unmapped_element_index_.at( + num_inserted_mapped_elements - 1); + for (size_t unmapped_element_index : unmapped_element_indices) { + TF_ASSIGN_OR_RETURN(result[unmapped_element_index], next_index_fn()); + } + } + } + } + if (target_index_to_unmapped_element_index_.contains( + IndexAfterMappedElements())) { + const auto& indices = + target_index_to_unmapped_element_index_.at(IndexAfterMappedElements()); + for (size_t index : indices) { + TF_ASSIGN_OR_RETURN(result[index], next_index_fn()); + } + } + + // Ensure that every element in unordered_container has a valid new index. + absl::flat_hash_set used_indices; + for (size_t index : result) { + if (used_indices.contains(index)) { + return InternalErrorStrCat( + "2 elements in unordered_container are destined for the same " + "index: ", + index); + } + if (index >= unordered_container_size_) { + return InvalidArgumentStrCat("invalid unordered_container index: ", index, + " v size(", unordered_container_size_, ")"); + } + } + + return result; +} + +template +template +StatusOr> +MappedPtrContainerSorter::ComputeNewIndices( + MapPtrFn map_ptr, UnmappedPtrIndexFn unmapped_index, + const OrderedTy& ordered_container, + const UnorderedTy& unordered_container) { + using UnorderedPtrGetter = mapped_ptr_container_sorter_internal::PtrGetter< + typename UnorderedTy::const_reference, const PointedToTy*>; + using OrderedPtrGetter = mapped_ptr_container_sorter_internal::PtrGetter< + typename OrderedTy::const_reference, const PointedToTy*>; + + if (unordered_container.size() >= IndexBeforeMappedElements()) { + return InvalidArgumentStrCat("Unordered container is too large to sort."); + } + + // Step 1: build a set of the ptrs in unordered_container + absl::flat_hash_set unordered_ptrs; + for (const auto& unordered_element : unordered_container) { + const PointedToTy* ptr = UnorderedPtrGetter::Get(unordered_element); + unordered_ptrs.insert(ptr); + } + + // Step 2: for mapped elements (in unordered_container), create a map from + // mapped ptr -> partial ordering + absl::flat_hash_map> + mapped_ptr_to_partial_order; + size_t next_partial_order_value = 0; + for (const auto& ordered_element : ordered_container) { + const PointedToTy* ordered_ptr = OrderedPtrGetter::Get(ordered_element); + const PointedToTy* unordered_ptr = map_ptr(ordered_ptr); + if (!unordered_ptr) { + // A corresponding unordered element does not exist. + continue; + } + if (!unordered_ptrs.contains(unordered_ptr)) { + // A pointer exists that maps to the ordered element, but it's not in our + // unordered_container. + continue; + } + mapped_ptr_to_partial_order[unordered_ptr].push_back( + next_partial_order_value); + ++next_partial_order_value; + } + + // Step 3: create sorted unordered element indices + SortedIndices result(next_partial_order_value, unordered_container.size()); + for (size_t i = 0; i < unordered_container.size(); ++i) { + const PointedToTy* ptr = UnorderedPtrGetter::Get(unordered_container[i]); + if (!mapped_ptr_to_partial_order.contains(ptr)) { + // ptr is unmapped + result.AddUnmappedElement(i, unmapped_index(ptr)); + continue; + } + + // ptr is mapped + // + // Potentially, several elements in ordered_container map to ptr. + // We assign ptr theindex corresponding to the next such ordered element. + auto& index_list = mapped_ptr_to_partial_order[ptr]; + TF_RETURN_IF_ERROR(result.AddMappedElement(i, index_list.front())); + // Do not map more than one unordered element to the same index, unless we + // have no choice. + if (index_list.size() > 1) { + // We never remove the last ordered index, in case ptr appears in the + // unordered_container more times than the ordered container. + index_list.pop_front(); + } + } + + VLOG(5) << "Pre flatten unordered_container result:\n" << result.ToString(); + return result.Flatten(); +} + +template +template +void MappedPtrContainerSorter::Reorder( + std::vector new_indices, UnorderedTy& unordered_container) { + size_t old_pos = 0; + while (old_pos < new_indices.size()) { + size_t new_pos = new_indices[old_pos]; + if (old_pos == new_pos) { + ++old_pos; + continue; + } + std::swap(new_indices[old_pos], new_indices[new_pos]); + std::swap(unordered_container[old_pos], unordered_container[new_pos]); + } +} + +template +template +Status MappedPtrContainerSorter::Sort( + MapPtrFn map_ptr, UnmappedPtrIndexFn unmapped_index, + const OrderedTy& ordered_container, UnorderedTy& unordered_container) { + std::vector indices; + TF_ASSIGN_OR_RETURN( + indices, ComputeNewIndices(map_ptr, unmapped_index, ordered_container, + unordered_container)); + Reorder(std::move(indices), unordered_container); + return OkStatus(); +} + +} // namespace xla + +#endif // XLA_SERVICE_MAPPED_PTR_CONTAINER_SORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/maybe_owning_device_memory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/maybe_owning_device_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..7ca8666611bf982e0cff7bbaaeb361b9ed870b6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/maybe_owning_device_memory.h @@ -0,0 +1,76 @@ +/* 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_SERVICE_MAYBE_OWNING_DEVICE_MEMORY_H_ +#define XLA_SERVICE_MAYBE_OWNING_DEVICE_MEMORY_H_ + +#include + +#include "absl/types/variant.h" +#include "xla/stream_executor/device_memory_allocator.h" + +namespace xla { + +// MaybeOwningDeviceMemory represents either an owned or unowned device memory. +// Like std::variant. When the object goes +// output of scope, it will free the underlying memory if it owns it. +class MaybeOwningDeviceMemory { + public: + MaybeOwningDeviceMemory() = default; + explicit MaybeOwningDeviceMemory(tensorflow::se::OwningDeviceMemory owned) + : mem_(std::move(owned)) {} + explicit MaybeOwningDeviceMemory(tensorflow::se::DeviceMemoryBase unowned) + : mem_(unowned) {} + MaybeOwningDeviceMemory(MaybeOwningDeviceMemory&&) = default; + ~MaybeOwningDeviceMemory() = default; + + MaybeOwningDeviceMemory& operator=(tensorflow::se::DeviceMemoryBase unowned) { + mem_ = unowned; + return *this; + } + + MaybeOwningDeviceMemory& operator=(tensorflow::se::OwningDeviceMemory owned) { + mem_ = std::move(owned); + return *this; + } + + MaybeOwningDeviceMemory& operator=(MaybeOwningDeviceMemory&&) = default; + + // Fetches the underlying DeviceMemoryBase from a MaybeOwningDeviceMemory. The + // caller of this function is *not* responsible for freeing the memory. + tensorflow::se::DeviceMemoryBase AsDeviceMemoryBase() const; + + // Release the tensorflow::se::OwningDeviceMemory without freeing it, and + // moves the ownership of the memory buffer from the object to the caller. + // + // A nullopt is returned if the HasOwnership() == false; + std::optional Release(); + + // If the device memory is owned, returns a pointer to the internal + // OwningDeviceMemory, otherwise nullptr is returned. + const tensorflow::se::OwningDeviceMemory* AsOwningDeviceMemory() const; + + // Returns true if the device_memory has ownership over underlying memory. + bool HasOwnership() const; + + private: + std::variant + mem_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_MAYBE_OWNING_DEVICE_MEMORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..384c5bc46d985bf293aaa57080e94561c9fdc397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.h @@ -0,0 +1,2670 @@ +/* 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_SERVICE_MEMORY_SPACE_ASSIGNMENT_MEMORY_SPACE_ASSIGNMENT_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_MEMORY_SPACE_ASSIGNMENT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// TODO(b/210891274): Use btree_map after build issue in Windows is resolved. +#if defined(__GNUC__) || defined(__clang__) +#include "absl/container/btree_map.h" +#endif +#include "absl/container/flat_hash_map.h" +#include "absl/functional/function_ref.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/heap_simulator.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_value.h" +#include "xla/service/memory_space_assignment/memory_space_assignment.pb.h" +#include "xla/service/memory_space_assignment/repacking.h" +#include "xla/shape.h" +#include "xla/statusor.h" + +namespace xla { + +namespace memory_space_assignment { +// Forward Declaration of Options. +class Options; + +inline constexpr char kConcatBitcastCustomCall[] = "ConcatBitcast"; + +// This class contains pre-set assignments determined by memory space +// assignment. It contains two data structures: (1) a chunks vector that maps a +// defining HloPosition to a Chunk (offset and size), and (2) an assignment_info +// vector that maps the memory space to information like its allocated size and +// heap memory trace. If there is only one alternate memory space like there is +// currently, there will be one entry in assignment_info. +class PresetAssignments { + public: + // Contains per-memory-space information like the allocated size and heap + // simulator trace. + struct AssignmentInformation { + int64_t size; + HeapSimulatorTrace heap_simulator_trace; + }; + + PresetAssignments() = default; + + void add_chunk(const HloPosition& position, + const HeapSimulator::Chunk& chunk) { + chunks_.emplace_back(position, chunk); + } + + void add_scoped_allocation_chunk(HloInstruction* instruction, + const HeapSimulator::Chunk& chunk) { + scoped_allocation_chunks_.emplace_back(instruction, chunk); + } + + AssignmentInformation* assignment_information_for_space( + int64_t memory_space) { + for (auto& space_and_info : assignment_info_) { + if (space_and_info.first == memory_space) { + return &space_and_info.second; + } + } + assignment_info_.emplace_back(memory_space, AssignmentInformation()); + return &assignment_info_.back().second; + } + + absl::Span> chunks() + const { + return chunks_; + } + + absl::Span> + scoped_allocation_chunks() const { + return scoped_allocation_chunks_; + } + + absl::Span> + assignment_informations() const { + return assignment_info_; + } + + // Get debugging information. + std::string buffer_info_str() const { return buffer_info_str_; } + std::string allocation_info_str() const { return allocation_info_str_; } + std::string instruction_schedule_str() const { + return instruction_schedule_str_; + } + + private: + std::vector> chunks_; + std::vector> + scoped_allocation_chunks_; + std::vector> assignment_info_; + std::string buffer_info_str_; + std::string allocation_info_str_; + std::string instruction_schedule_str_; +}; + +// A wrapper class around HloCostAnalysis with additional knowledge about the +// bandwidths of different memory spaces. +class MemorySpaceAssignmentCostAnalysis { + public: + // An optional Cache object may be provided to some of the methods below to + // speed up the lookup. + struct Cache { + absl::flat_hash_map while_nest_multiplier; + absl::flat_hash_map memory_boundedness; + }; + + // Function type that can be used to indicate which input/output values are in + // the alternate memory. + using IsInAlternateMemoryFun = absl::FunctionRef /*operand_num*/, const ShapeIndex& /*index*/, + const Shape& /*shape*/)>; + + virtual ~MemorySpaceAssignmentCostAnalysis() = default; + + static StatusOr> Create( + const HloCostAnalysis& cost_analysis, const Options& options, + const HloModule& module); + + const HloCostAnalysis& cost_analysis() const { return cost_analysis_; } + + // Returns a heuristic value that captures how much putting this tensor to the + // alternate memory would help if the op is memory bound, or otherwise how far + // off is the op to memory boundedness. The larger this number, the higher + // priority it will be placed in the alternate memory. + float GetAlternateMemoryBenefit(const HloInstruction& instruction, + float elapsed_time_due_to_alternate_mem, + Cache* cache = nullptr) const; + // Like above, return the benefit of putting the output tensor in the + // alternate memory. + float GetAlternateMemoryBenefit(const HloPosition& position, + Cache* cache = nullptr) const; + // Like above, return the benefit of putting the input tensor in the alternate + // memory. + float GetAlternateMemoryBenefit(const HloUse& use, + Cache* cache = nullptr) const; + + // Returns a heuristic value of memory boundedness for the given + // BufferInterval. The larger this number, the higher priority it will be + // placed in the alternate memory. + float GetMemoryBoundedness( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& interval, + Cache* cache = nullptr) const; + + // If enabled in Options::pipeline_overhead_window_size_mib, returns the + // overhead of accessing the default memory, in seconds. The source of the + // overhead is the software pipelining ovehead. The lowering of the operations + // typically use tiling to copy one window at a time from default memory, and + // perform compute: + // + // Pipeline overhead: <-> + // +----+----+----+----+ + // Copy from default mem: | | | | | + // +----+----+----+----+ + // \ \ \ \ + // \ \ \ \ + // V V V V + // +--+ +--+ +--+ +--+ + // Compute: | | | | | | | | + // +--+ +--+ +--+ +--+ + float GetDefaultMemoryAccessOverhead( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Returns the amount of time the default memory bandwidth is idle, while + // executing this instruction, in seconds. This value can be multiplied with + // the default memory bandwidth to get the amount of bytes that are available + // to be copied to/from default memory during the execution of this + // instruction. + float GetDefaultMemoryBandwidthIdleTime( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Returns the bytes accessed from alternate memory. + float GetBytesAccessedFromAlternateMemory( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Returns the elapsed time in seconds due to compute only. + float GetInstructionElapsedDueToCompute( + const HloInstruction& instruction) const; + + // Returns the elapsed time in seconds due to memory only. If + // operands_in_alternate_mem or outputs_in_alternate_mem is provided, it will + // assume that the corresponding operands or output will be in the alternate + // memory space. This is useful for calculating the benefit of placing the + // buffer in alternate memory. + float GetInstructionElapsedDueToMemory( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Like above, only the inputs/outputs indicated by is_in_alternate_mem are in + // the alternate memory. + float GetInstructionElapsedDueToMemory( + const HloInstruction& instruction, + IsInAlternateMemoryFun is_in_alternate_mem) const; + + // Returns the estimated elapsed duration of the instruction in seconds. It + // assumes all operands and outputs of the instruction are in the default + // memory. + virtual float GetInstructionElapsed(const HloInstruction& instruction) const; + + // Returns the estimated elapsed duration of the instruction in seconds. It + // assumes all operands and outputs of the instruction are in the default + // memory, except for the operands and outputs specified to be in the + // alternate memory. + virtual float GetInstructionElapsedInAlternateMemory( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem, + absl::Span outputs_in_alternate_mem) const; + + // Like above, only the inputs/outputs indicated by is_in_alternate_mem are in + // the alternate memory. + float GetInstructionElapsedInAlternateMemory( + const HloInstruction& instruction, + IsInAlternateMemoryFun is_in_alternate_mem) const; + + // Returns the elapsed time it would take to asynchronously copy the shape + // from default to alternate memory space (or vice versa). + virtual float GetAsyncCopyElapsed(const Shape& shape) const; + + int64_t GetScheduleEndTime() const; + + // Returns the number of nested computation levels this instruction resides + // in. If while_only is true, it returns the while loop nest level and 0 + // means the instruction is not in a while loop. + int CalculateComputationNestLevel(const HloInstruction* instruction, + bool while_only) const; + + const HloLiveRange& hlo_live_range() const { return *hlo_live_range_; } + const Options& options() const { return options_; } + + protected: + MemorySpaceAssignmentCostAnalysis( + const HloCostAnalysis& cost_analysis, const Options& options, + std::unique_ptr alias_analysis, + std::unique_ptr hlo_live_range, + std::unique_ptr call_graph) + : cost_analysis_(cost_analysis), + options_(options), + alias_analysis_(std::move(alias_analysis)), + hlo_live_range_(std::move(hlo_live_range)), + call_graph_(std::move(call_graph)) {} + + private: + const HloCostAnalysis& cost_analysis_; + const Options& options_; + std::unique_ptr alias_analysis_; + std::unique_ptr hlo_live_range_; + std::unique_ptr call_graph_; +}; + +// Abstract base class that memory space assignment uses to pick prefetch +// intervals. +class PrefetchIntervalPicker { + public: + PrefetchIntervalPicker() = default; + virtual ~PrefetchIntervalPicker() = default; + + // Returns true if the buffer can be allocated in alternate memory space + // without any copies (prefetches). + virtual bool CanAllocateInAlternateMemoryNoCopy(const Shape& shape, + int64_t start_time, + int64_t end_time) const = 0; + + // Returns the preferred end time for an eviction that starts at a given time + // and must end by the given end time. + virtual int64_t PreferredEvictionEndTime(const Shape& shape, + int64_t start_time, + int64_t latest_end_time) const = 0; + + // Returns the latest time that a prefetch can start. + virtual int64_t LatestPrefetchStartTime(const Shape& shape, + int64_t start_time, int64_t end_time, + const HloUse* use) const = 0; + + // Returns the preferred time that a prefetch can start. + virtual int64_t PreferredPrefetchStartTime( + const Shape& shape, int64_t earliest_prefetch_start_time, + int64_t latest_prefetch_start_time, int64_t prefetch_end_time) const = 0; + + // Returns the latest time that a prefetch can end that is less than or equal + // to proposed_prefetch_end_time. + virtual int64_t LatestPrefetchEndTime( + int64_t original_prefetch_end_time, + int64_t proposed_prefetch_end_time) const { + return proposed_prefetch_end_time; + } + + // Returns the estimated end time of a prefetch that starts at the given time. + virtual int64_t EstimatedPrefetchEndTime(const Shape& shape, + int64_t start_time, + int64_t end_time) const = 0; + + // Returns the elapsed time in seconds between the logical interval that + // corresponds to the instruction schedule. + virtual float GetLogicalIntervalElapsed(int64_t start_time, + int64_t end_time) const = 0; + + // Begins the iterator for the first start time of the prefetch. + virtual void Begin(const HloUse& use, int64_t start_time, int64_t end_time, + std::optional preferred_time) = 0; + + // Advances the start time of the prefetch and returns that value. + virtual int64_t Next() = 0; + + // Returns true if the available prefetch intervals have been exhausted. + virtual bool Done() const = 0; + + // Returns the latest time the prefetch interval picker will have pick. + virtual int64_t latest_time() const = 0; + + // The retry number can be used to modify the interval picking policies. The + // first attempt will have a retry_number of 0, then 1, etc. + virtual void SetRetryNumber(int retry_number) { + retry_number_ = retry_number; + } + int retry_number() const { return retry_number_; } + + // Returns a debug string for the current state of the prefetch interval + // picker. + virtual std::string ToDebugString() const = 0; + + // Returns a debug string for no-copy allocation. + virtual std::string ToNoCopyDebugString(const Shape& shape, + int64_t start_time, + int64_t end_time) const = 0; + + // Prefetch interval pickers may return a value corresponding to the benefit + // of placing the BufferInterval in the alternate memory. The larger value, + // the more beneficial. + virtual std::optional BufferIntervalAlternateMemoryBenefit( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& interval) + const { + return std::nullopt; + } + + protected: + const absl::flat_hash_map* + instruction_schedule_ = nullptr; + int retry_number_ = 0; +}; + +// Prefetch interval picker that uses instruction count to overlap asynchronous +// copies with independent computation. The min and max overlap counts describe +// the number of independent HLOs overlapped while a value is being prefetched +// into the alternate memory (between CopyStart and CopyDone HLO instructions). +// max_overlap_count attempts to prevent bringing tensors into the alternate +// memory too eagerly and hence occupying the space for other tensors which +// might use it. min_overlap_count attempts to prevent cases where tensors are +// prefetched into the alternate memory without sufficient time for the copy to +// take place. In those cases, it's just better to keep the tensor in the +// default memory instead of hurting the critical path with this copy that +// likely won't finish in time. +class InstructionCountPrefetchIntervalPicker : public PrefetchIntervalPicker { + public: + InstructionCountPrefetchIntervalPicker(int64_t min_overlap_count, + int64_t max_overlap_count) + : min_overlap_count_(min_overlap_count), + max_overlap_count_(max_overlap_count) {} + + bool CanAllocateInAlternateMemoryNoCopy(const Shape& shape, + int64_t start_time, + int64_t end_time) const override; + + int64_t PreferredEvictionEndTime(const Shape& shape, int64_t start_time, + int64_t latest_end_time) const override; + + int64_t LatestPrefetchStartTime(const Shape& shape, int64_t start_time, + int64_t end_time, + const HloUse* use) const override; + + int64_t PreferredPrefetchStartTime(const Shape& shape, + int64_t earliest_prefetch_start_time, + int64_t latest_prefetch_start_time, + int64_t prefetch_end_time) const override; + + int64_t EstimatedPrefetchEndTime(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + float GetLogicalIntervalElapsed(int64_t start_time, + int64_t end_time) const override; + + void Begin(const HloUse& use, int64_t start_time, int64_t end_time, + std::optional preferred_time) override; + + int64_t Next() override; + bool Done() const override; + + int64_t latest_time() const override; + + std::string ToDebugString() const override; + std::string ToNoCopyDebugString(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + + private: + int64_t min_overlap_count_; + int64_t max_overlap_count_; + int64_t end_time_; + int64_t current_prefetch_time_; +}; + +// Forward Declaration of MemorySpaceAssignmentCostAnalysis +class MemorySpaceAssignmentCostAnalysis; +// Prefetch interval picker that uses cost analysis to overlap asynchronous +// copies with independent computation. It uses min (independent computation +// duration) / (asynchronous copy duration) ratio to guide whether the prefetch +// is within the lower bound. For the upper bound, it restricts the maximum +// duration that a buffer may occupy the alternate memory space as a multiple of +// the time it would take to copy a buffer that is the size of the alternate +// memory. It starts with the preferred ratio in Begin() and works its way for +// alternately earlier and later prefetches until hitting min and max ratios. +// The value for buffer size for max async copy is a mechanism to prevent +// copying small buffers between the two memories unnecessarily. For calculating +// the max time that the buffer can reside in alternate memory, we use the +// larger of this value and the actual size of the buffer. A shape override can +// also be provided which causes the interval picker to use that shape for async +// copy durations instead of the actual shape of the copy. +class CostAnalysisPrefetchIntervalPicker : public PrefetchIntervalPicker { + public: + CostAnalysisPrefetchIntervalPicker( + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + float min_overlap_to_async_copy_ratio, + float preferred_overlap_to_async_copy_ratio, + float max_overlap_to_mem_size_async_copy_ratio, int64_t mem_size_bytes, + const Shape* shape_override = nullptr); + + bool CanAllocateInAlternateMemoryNoCopy(const Shape& shape, + int64_t start_time, + int64_t end_time) const override; + + int64_t PreferredEvictionEndTime(const Shape& shape, int64_t start_time, + int64_t latest_end_time) const override; + + int64_t LatestPrefetchEndTime( + int64_t original_prefetch_end_time, + int64_t proposed_prefetch_end_time) const override; + + int64_t LatestPrefetchStartTime(const Shape& shape, int64_t start_time, + int64_t end_time, + const HloUse* use) const override; + + int64_t PreferredPrefetchStartTime(const Shape& shape, + int64_t earliest_prefetch_start_time, + int64_t latest_prefetch_start_time, + int64_t prefetch_end_time) const override; + + int64_t EstimatedPrefetchEndTime(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + float GetLogicalIntervalElapsed(int64_t start_time, + int64_t end_time) const override; + + void Begin(const HloUse& use, int64_t start_time, int64_t end_time, + std::optional preferred_time) override; + + int64_t Next() override; + bool Done() const override; + + int64_t latest_time() const override; + + void SetRetryNumber(int retry_number) override; + + std::string ToDebugString() const override; + std::string ToNoCopyDebugString(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + + std::optional BufferIntervalAlternateMemoryBenefit( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& interval) + const override; + + private: + // Finds the minimum nest level in the given interval. + int GetMinWhileNestLevel(int64_t start_time, int64_t end_time) const; + + // Given the elapsed time to copy this buffer to the alternate memory, returns + // the longest time that this buffer may reside in the alternate memory space. + float GetMaxElapsedInAlternateMemory(float async_copy_elapsed) const; + + // For each instruction in the flattened schedule, maintain their elapsed time + // (in cumulative sum) and while nesting level. + std::vector elapsed_time_cumsum_; + std::vector while_nest_level_; + std::vector computation_nest_level_; + // Maintain the index of the most recent (before this instruction) nest level + // change in order to efficiently determine the minimum nest level in an + // interval. + std::vector while_nest_level_change_; + + const MemorySpaceAssignmentCostAnalysis& cost_analysis_; + float min_overlap_to_async_copy_ratio_; + float preferred_overlap_to_async_copy_ratio_; + float max_async_copy_elapsed_; + float max_overlap_multiplier_ = 1.0; + + float async_copy_elapsed_; + float inst_elapsed_reduction_; + int64_t end_logical_time_; + int64_t earliest_prefetch_time_; + int64_t latest_prefetch_time_; + bool using_increasing_prefetch_time_iterator_ = true; + int64_t increasing_prefetch_time_iterator_; + int64_t decreasing_prefetch_time_iterator_; + + std::vector while_execution_counts_; + // Shape override is used to override the shape of the shape of the async copy + // to treat all async copies the same duration. Having an override forces + // prefetches to be scheduled roughly in FIFO order. + std::optional shape_override_; +}; + +// MemorySpaceAssignment assigns memory spaces (default or alternate) to each +// instruction in the module. It will greedily try placing as as many values in +// the alternate memory space as possible. It uses the heap simulator to +// determine the actual allocation offsets of values in the alternate memory +// space to account for fragmentation. The default memory space is assumed to be +// large enough to hold the values that could not be placed in the alternate +// memory space. +class MemorySpaceAssignment { + public: + using Chunk = HeapSimulator::Chunk; + using BufferInterval = + GlobalDecreasingSizeBestFitHeap::BufferInterval; + using BufferIntervalCompare = + GlobalDecreasingSizeBestFitHeap::BufferIntervalCompare; + using IsAllowedInAlternateMemoryFunction = + std::function; + using IsUseAllowedInAlternateMemoryFunction = + std::function; + using IsPositionAllowedInAlternateMemoryFunction = + std::function; + using ReservedScopedMemoryFunction = std::function>& /*operands_in_alternate_memory*/, + const absl::flat_hash_set& /*outputs_in_alternate_memory*/)>; + using UpdateLayoutFunction = std::function; + + // MemorySpaceAssignment uses a notion of a slow and large default memory + // space and a fast and small alternate memory space. + enum class MemorySpace { kDefault, kAlternate }; + + // Forward declaration for Allocation. + class Allocation; + class ParentAllocation; + + // This class represents an allocation that might either be in the default or + // alternate memory. An HloValue might live in multiple different allocations + // over its lifetime. The lifetimes of the allocations are defined using + // start_time and end_time, which corresponds to the instruction indexes in + // the flattened schedule. Each of these allocations might partially overlap + // with each other. CopyAllocation defined below represents asynchronous + // copies between Allocations. + // + // Consider an instruction Foo, and its users Bar and Baz, and the times given + // in terms of the flattened schedule of the entire module: + // + // Foo:10 + // / \ + // Bar:14 \ + // Baz:25 + // + // A valid memory space assignment could be like the following: + // + // Time: 10 ... 14 ... 25 + // Foo Bar Baz + // Alternate +-------+ +-----+ + // Default +---------------------+ + // ^ ^ ^ ^ + // | | | | + // evict evict prefetch prefetch + // start end start end + // + // This would be represented with: + // - Allocation(memory_space=kAlternate, start_time=10, end_time=14) + // - CopyAllocation(memory_space=kDefault, start_time=12, end_time=25) + // - CopyAllocation(memory_space=kAlternate, start_time=22, end_time=25) + class Allocation { + friend class ParentAllocation; + + public: + Allocation(HloPosition defining_position, MemorySpace memory_space, + std::optional chunk, int64_t start_time, int64_t end_time, + bool is_scoped_allocation) + : defining_position_(defining_position), + memory_space_(memory_space), + chunk_(chunk), + start_time_(start_time), + end_time_(end_time), + is_scoped_allocation_(is_scoped_allocation) { + CHECK(!is_scoped_allocation || defining_position.index == ShapeIndex({})); + } + virtual ~Allocation() = default; + + // True if the allocation is for a copy or a sliced-copy. + bool is_copy_like_allocation() const; + + virtual bool is_copy_allocation() const { return false; } + virtual bool is_sliced_copy_allocation() const { return false; } + + // Adds a use to this allocation. + void AddUse(HloUse use); + + // Extends the end time of this allocation. + void Extend(int64_t end_time) { end_time_ = std::max(end_time_, end_time); } + + // After all of the time ranges for the allocations have been assigned, + // Process morphs the instructions affected to assign the memory spaces and + // insert asynchronous copy instructions if necessary. + virtual Status Process(); + + // An optional post-process step that will be called after all allocations + // have been processed. + virtual Status PostProcess() { return OkStatus(); } + + // Marks (adds this allocation to needed_allocations) if this allocation is + // needed. Allocation and CopyAllocations are always needed and + // ParentAllocations are needed if they have any uses or if other + // CopyAllocation or ParentAllocations depend on them. + virtual void MarkIfNeeded( + absl::flat_hash_set& needed_allocations) const; + + // Marks this allocation as needed. + virtual void MarkNeeded( + absl::flat_hash_set& needed_allocations) const; + + // Returns the defining position for this allocation. + virtual HloPosition defining_position() const { return defining_position_; } + + // Returns the time the buffer is first available to be used. For + // Allocation, this is start_time. + virtual int64_t earliest_available_time() const { return start_time_; } + + const std::vector& uses() const { return uses_; } + void clear_uses() { uses_.clear(); } + MemorySpace memory_space() const { return memory_space_; } + // Returns the associated chunk that may be a nullopt if the allocation is + // in the default memory space. + std::optional maybe_chunk() const { return chunk_; } + // Returns the associated chunk. The caller should ensure that the chunk is + // defined (the allocation should be in the alternate memory space). + Chunk chunk() const { + CHECK(chunk_.has_value()); + return *chunk_; + } + Chunk* mutable_chunk() { return &*chunk_; } + void set_offset(int64_t offset); + void set_start_time(int64_t start_time) { start_time_ = start_time; } + void set_end_time(int64_t end_time) { end_time_ = end_time; } + int64_t start_time() const { return start_time_; } + int64_t end_time() const { return end_time_; } + bool is_scoped_allocation() const { return is_scoped_allocation_; } + virtual std::optional cross_program_prefetch_index() const { + return std::nullopt; + } + + bool operator==(const Allocation& other) const; + virtual std::string ToString() const; + + bool is_in_alternate_mem() const { + return memory_space_ == MemorySpace::kAlternate; + } + bool is_in_default_mem() const { + return memory_space_ == MemorySpace::kDefault; + } + + protected: + // Recursively create kGetTupleElement instructions if the defining position + // shape is not an array. Returns the new instruction that has array shape. + HloInstruction* AddGetTupleElements() const; + + HloPosition defining_position_; + std::vector uses_; + MemorySpace memory_space_; + std::optional chunk_; + int64_t start_time_; + int64_t end_time_; + const bool is_scoped_allocation_; + }; + + // This class represents an allocation as a result of an asynchronous copy. + // Note: CopyStart instructions are inserted after `start_time` or later, + // while CopyDone instructions are inserted before + // `copy_done_schedule_before_time` or earlier. + class CopyAllocation : public Allocation { + public: + CopyAllocation( + Allocation& prev_allocation, MemorySpace memory_space, + std::optional chunk, int64_t start_time, int64_t end_time, + int64_t copy_done_schedule_before_time, + std::optional cross_program_prefetch_index = std::nullopt) + : Allocation(/*defining_position=*/{nullptr, {}}, memory_space, chunk, + start_time, end_time, /*is_scoped_allocation=*/false), + prev_allocation_(prev_allocation), + copy_start_schedule_after_(start_time), + copy_done_schedule_before_(copy_done_schedule_before_time), + cross_program_prefetch_index_(cross_program_prefetch_index) {} + + bool is_copy_allocation() const override { return true; } + + Status Process() override; + + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + HloPosition defining_position() const override { + // Unless explicitly set, the defining position of a copy allocation in + // retrieved from the previous allocation. This is because we don't create + // new CopyStart/CopyDone instructions until later and the position should + // point to the previous (copy or otherwise) allocation's position for the + // original defining position. + if (defining_position_.instruction == nullptr) { + return prev_allocation_.defining_position(); + } + return defining_position_; + } + + HloInstruction* copy_start() const { return copy_start_; } + HloInstruction* copy_done() const { return copy_done_; } + + // Returns the time the buffer is first available to be used. For + // CopyAllocation, this is when the copy ends, which is + // copy_done_schedule_before. + int64_t earliest_available_time() const override { + return copy_done_schedule_before_; + } + + int64_t copy_start_schedule_after() const { + return copy_start_schedule_after_; + } + int64_t copy_done_schedule_before() const { + return copy_done_schedule_before_; + } + + void set_copy_start_schedule_after(int64_t copy_start_schedule_after) { + copy_start_schedule_after_ = copy_start_schedule_after; + } + + void set_copy_done_schedule_before(int64_t copy_done_schedule_before) { + copy_done_schedule_before_ = copy_done_schedule_before; + } + + std::optional cross_program_prefetch_index() const override { + return cross_program_prefetch_index_; + } + + bool operator==(const CopyAllocation& other) const; + std::string ToString() const override; + + const Allocation& prev_allocation() { return prev_allocation_; } + Allocation& mutable_prev_allocation() { return prev_allocation_; } + + private: + Allocation& prev_allocation_; + // These variables define the scheduling boundaries where CopyStart and + // CopyDone can be scheduled. The earliest CopyStart can be scheduled is + // after copy_start_schedule_after_ and the latest CopyDone can be scheduled + // is before copy_done_schedule_before_. + int64_t copy_start_schedule_after_; + int64_t copy_done_schedule_before_; + HloInstruction* copy_start_; + HloInstruction* copy_done_; + std::optional cross_program_prefetch_index_; + }; + + // The parameters for slicing a single dimension of a tensor. + struct SliceParam { + std::string ToString() const; + bool operator==(const SliceParam& other) const; + + int64_t start_inclusive; + int64_t end_exclusive; + }; + + // A proposed way to slice a buffer. + struct SliceProposal { + std::string ToString() const; + friend std::ostream& operator<<(std::ostream& os, + const SliceProposal& proposal); + std::tuple&, int64_t> + ToTuple() const; + bool operator==(const SliceProposal& other) const; + + // Shape resulting from the slice. + Shape slice_shape; + + // slice_params map to the parameters that would be passed to a slice + // instruction. Thus: + // * There should be a slice parameter for every dimension in the shape of + // the tensor being sliced. + // * The ith slice_param applies to the ith logical dimension in the shape + // being sliced. + // * If a dimension is not being sliced, it should have a SliceParam of + // {0, dim size}. + std::vector slice_params; + + // The size to be allocated for the slice. Note, this may be > the size of + // the slice shape, due to additional padding that may occur when the slices + // are concatenated back together. + int64_t slice_size; + }; + + // A SliceProposalCollection proposes a way to to slice an AllocationRequest. + // A SliceProposalCollection is generated from a SliceProposalFunction and is + // used when we want to slice a prefetch. + using SliceProposalCollection = std::vector; + using SliceProposalFunction = std::function( + const Shape& shape, const SlicedPrefetchOptions& options)>; + + // A SliceDecision is a SliceProposal that we've determined where and when to + // allocate. + struct SliceDecision { + std::string ToString() const; + bool operator==(const SliceDecision& other) const; + + Chunk chunk; + int64_t start_time; + SliceProposal sizing; + float copy_resource_consumed; + }; + + // This class represents an allocation resulting from asynchronous sliced + // copies. + // + // Let the sliced allocation be represented as follows, and imagine that t3 + // is the time when the entire buffer [p0, p3) is available for use + // + // space + // ^ + // p3 | +-----------+ + // | | | + // p2 | +---+ | + // | | | + // p1 | +-------+ | + // | | | + // p0 | +-------+ + // +---|---|---|---|---|----> time + // t0 t1 t2 t3 t4 + // + // The Allocation underlying the SlicedCopyAllocation will use the following + // dimensions: + // - chunk = [p0, p3) + // - start time = t2 + // - earliest_available_time = t3 + // - end_time = t4 + class SlicedCopyAllocation : public Allocation { + public: + // Full details about a slice in the sliced allocation. + struct SliceDetail { + std::string ToString() const; + std::tuple + ToTuple() const; + bool operator==(const SliceDetail& other) const; + + // Create the instructions to copy the slice. This method updates + // copy_start and copy_done. Given a Shape, the hardware may have + // constraints on how the shape is physically laid out in memory. + // update_layout_fn updates a Shape's layout in accordance with those + // constraints. + Status CreateAsyncSlice(const Shape& original_shape, + HloInstruction& producer, HloComputation& parent, + absl::FunctionRef update_layout_fn); + + SliceDecision slice_decision; + int64_t copy_start_after_time = -1; + int64_t copy_done_before_time = -1; + HloInstruction* copy_start = nullptr; + HloInstruction* copy_done = nullptr; + }; + + // REQUIRES: + // - slice_decisions_sorted_by_start_time.size() >= 2, otherwise, + // CopyAllocation should be used. + SlicedCopyAllocation( + const Allocation& prev_allocation, MemorySpace memory_space, + std::vector slice_decisions_sorted_by_start_time, + int64_t end_time, int64_t copy_done_schedule_before_time, + absl::FunctionRef update_layout_fn); + + bool is_sliced_copy_allocation() const override { return true; } + + // MemorySpaceAssignment::Process() calls Process() to create asynchronous + // slice copies, and a bitcast-concat call to glue the slices back together. + Status Process() override; + + // Marks the allocation as needed. + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + // Returns the defining position for this allocation. + HloPosition defining_position() const override; + + // Returns the time the buffer is first available to be used. For + // SlicedCopyAllocation, this is when all copies have ended. + int64_t earliest_available_time() const override; + + std::vector SliceOffsetsSortedByStartTime() const; + void AddDiffToAllSliceOffsets(int64_t diff); + + // Used to update offsets and start times after repacking. + void ImportRepackedSliceData( + const MemorySpaceAssignmentRepacker::SlicedAllocationData& data); + + const std::vector& slice_details_sorted_by_start_time() const; + std::vector& mutable_slice_details_sorted_by_start_time(); + HloInstruction* concat() const { return concat_; } + + std::tuple&, + const HloInstruction*> + ToTuple() const; + bool operator==(const SlicedCopyAllocation& other) const; + std::string ToString() const override; + + private: + SlicedCopyAllocation() = delete; + + // Create an instruction to concatenate the slices. Populates concat_. + Status CreateBitcastConcat(const Shape& shape, + absl::Span slices); + + Shape original_shape_to_slice_; + const Allocation& prev_allocation_; + // REQUIRES: + // - sorted_segments_[i].copy_start_after_time <= + // sorted_segments_[i+j].copy.start_after_time + // - sorted_segments_[i].copy_done_before_time <= + // sorted_segments_[i+j].copy.start_before_time + std::vector slice_details_sorted_by_start_time_; + HloInstruction* concat_ = nullptr; + absl::FunctionRef update_layout_fn_; + }; + + // An allocation in the default memory space that mirrors another Allocation + // object. This is useful to model an eviction that happens before a while op + // so that we don't need to redundantly evict the buffer after the while op as + // well. + class MirroredAllocation : public Allocation { + public: + MirroredAllocation(const Allocation& original_allocation, int64_t time) + : Allocation(original_allocation.defining_position(), + MemorySpace::kDefault, original_allocation.maybe_chunk(), + /*start_time=*/time, + /*end_time=*/time, /*is_scoped_allocation=*/false), + original_allocation_(original_allocation) {} + + Status Process() override; + + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + std::string ToString() const override; + + private: + const Allocation& original_allocation_; + }; + + // An allocation in default memory space that is defined in the parent + // computation. If a value has a copy in the default memory space in the + // parent computation, we don't need to evict this buffer in a while loop. + class ParentAllocation : public Allocation { + public: + ParentAllocation(const Allocation& original_allocation, + HloInstruction* calling_instruction, HloPosition position, + int64_t time) + : Allocation(position, MemorySpace::kDefault, + original_allocation.maybe_chunk(), /*start_time=*/time, + /*end_time=*/time, /*is_scoped_allocation=*/false), + original_allocation_(original_allocation), + calling_instruction_(calling_instruction) {} + + Status Process() override; + Status PostProcess() override; + + void MarkIfNeeded(absl::flat_hash_set& + needed_allocations) const override; + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + std::string ToString() const override; + + private: + const Allocation& original_allocation_; + HloInstruction* calling_instruction_; + }; + + using AllocationSequence = std::vector>; + // AllocationValue is used to break up HloValues for each non-trivial position + // (trivial positions are considered Tuple, GetTupleElement, and Bitcast). An + // HloValue may include positions and uses that alias with each other across + // multiple computations. We use this class to break these HloValues such that + // every AllocationValue has one defining position (that may alias with other + // AllocationValues). The uses field of the AllocationValue contains only the + // direct uses of the AllocationValue's defining position. + // + // For example, consider the following HLO snippet: + // + // Body { + // body_param = (f32[4,3]{1,0}, f32[]) parameter(0) + // get-tuple-element.3 = f32[4,3]{1,0} get-tuple-element(body_param), + // index=0 + // ... + // ROOT tuple = (f32[4,3]{1,0}, f32[]) tuple(get-tuple-element.3, ...) + // } + // + // Cond { + // cond_param = (f32[4,3]{1,0}, f32[]) parameter(0) + // ... + // } + // + // add.4 = f32[4,3]{1,0} add(...) + // tuple.1 = (f32[4,3]{1,0}, f32[]) tuple(add.4, ...) + // while = (f32[4,3]{1,0}, f32[]) while(tuple.1), body=Body, condition=Cond + // get-tuple-element.5 = f32[4,3]{1,0} get-tuple-element(while), index=0 + // add.5 = f32[4,3]{1,0} add(get-tuple-element.5, ...) + // + // This contains an HloValue that looks like the following: + // positions: + // add.4 + // body_param {0} + // get-tuple-element.3 + // tuple {0} + // cond_param {0} + // tuple.1 {0} + // while {0} + // get-tuple-element.5 + // uses: + // add.1, operand 0 + // tuple, operand 0 + // while, operand 0 {0} + // add.5, operand 0 + // + // We break this HloValue up into the following AllocationValues for each + // non-trivial position: + // AllocationValue1: computation = Entry + // position: + // add.4 + // uses: + // while, operand 0 {0} + // AllocationValue2: computation = Cond + // position: + // cond_param {0} + // uses: + // AllocationValue3: computation = Body + // position: + // body_param {0} + // uses: + // add.1, operand 0 + // tuple, operand 0 + // AllocationValue4: computation = Entry + // position: + // while {0} + // uses: + // add.5, operand 0 + class AllocationValue { + public: + // This data structure wraps an HloUse and adds additional metadata that are + // useful for allocation. + struct Use { + // The wrapped HloUse object. + HloUse hlo_use; + // The logical time this use is scheduled. + int64_t time; + // All the positions where this use aliases with. The aliased positions + // must get the same allocation. + std::vector aliases; + + bool operator==(const Use& other) const { + return hlo_use == other.hlo_use && time == other.time && + aliases == other.aliases; + } + + template + friend H AbslHashValue(H h, const Use& s) { + return H::combine(std::move(h), s.hlo_use, s.time, s.aliases); + } + }; + + AllocationValue(const HloValue* value, const HloPosition& position, + int64_t size) + : value_(value), + defining_position_(position), + size_(size), + requires_contiguous_allocation_(false) {} + + const HloPosition& defining_position() const { return defining_position_; } + const HloInstruction* defining_instruction() const { + return defining_position().instruction; + } + int64_t size() const { return size_; } + const std::vector& uses() const { return uses_; } + std::vector& uses() { return uses_; } + const HloValue* value() const { return value_; } + const HloComputation* computation() const { + return defining_instruction()->parent(); + } + AllocationSequence* mutable_allocation_sequence() { + return &allocation_sequence_; + } + const AllocationSequence* allocation_sequence() const { + return &allocation_sequence_; + } + + // Sets/gets whether this AllocationValue requires allocating it + // contiguously throughout its live range (without any copies). + bool requires_contiguous_allocation() const { + return requires_contiguous_allocation_; + } + void set_requires_contiguous_allocation( + bool requires_contiguous_allocation) { + requires_contiguous_allocation_ = requires_contiguous_allocation; + } + + void AddUse(const HloUse& use, int64_t use_time) { + uses_.push_back({use, use_time, {}}); + } + + std::string ToString() const; + std::string ToShortString() const; + + private: + const HloValue* value_; + HloPosition defining_position_; + int64_t size_; + // If true, there must be a contiguous allocation for this buffer without + // any copies. + bool requires_contiguous_allocation_; + std::vector uses_; + AllocationSequence allocation_sequence_; + }; + + // Statistics of asynchronous copies. + struct AsyncCopyStats { + // Includes both async copies and async sliced copies. + int64_t max_outstanding_async_copies = 0; + // Includes both async copies and async sliced copies. + int64_t num_prefetches = 0; + int64_t num_sliced_prefetches = 0; + int64_t num_sliced_prefetch_slices = 0; + int64_t prefetch_bytes = 0; + int64_t num_evictions = 0; + int64_t eviction_bytes = 0; + }; + + virtual ~MemorySpaceAssignment() = default; + + // Runs the MemorySpaceAssignment pass. + static StatusOr> Run( + HloModule* module, const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis, const Options& options); + + // Calculates asynchronous copy statistics. + StatusOr CalculateAsyncCopyStats() const; + + static BufferIntervalCompare GetMemoryBoundednessBufferIntervalCompare( + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + MemorySpaceAssignmentCostAnalysis::Cache* cache = nullptr); + + // Verify that the memory space assignment is free of overlapping buffers and + // export heap simulator trace to be used by buffer_assignment. + Status VerifyAndExportHeapSimulatorTrace(); + + protected: + // Main driver of the memory space assignment pass. + virtual StatusOr> RunMemorySpaceAssignment( + const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis); + + // Finds an AllocationSequence for placing buffers in alternate memory using + // the AlternateMemoryBestFitHeap algorithm. Must be set before Process() is + // called. + virtual Status FindAllocationSequence(const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis); + + const Options& options() const { return options_; } + + MemorySpaceAssignment(HloModule* module, const Options& options, + const HloLiveRange& hlo_live_range) + : module_(module), + options_(options), + flattened_instructions_(hlo_live_range.flattened_instruction_sequence() + .instructions() + .begin(), + hlo_live_range.flattened_instruction_sequence() + .instructions() + .end()), + computations_in_schedule_(), + preset_assignments_(std::make_unique()) { + for (const auto& computation_and_bound : + hlo_live_range.computation_span_times()) { + computations_in_schedule_.insert(computation_and_bound.first); + } + } + + AllocationSequence allocations_; + + HloModule* module() { return module_; } + + private: + // Process calls Process methods of the allocations after the allocations have + // been finalized. + Status Process(const HloLiveRange& hlo_live_range); + + // Process() might have altered the computation graph by inserting kTuple and + // kGetTupleElement instructions. SimplifyGraph performs a simple DCE and + // tuple simplification operation (e.g., given GetTupleElement(Tuple(a, b), + // 1), simply forwards b). Runs to fixed point. + Status SimplifyGraph(); + + // FixSchedule inserts asynchronous copies in the schedule. + Status FixSchedule(); + + // Export the alternate memory assignments to the PresetAssignments and color + // the HLO graph with the determined memory spaces. + Status ExportAndColorBuffers(); + + // Schedules asynchronous copies and ensures that the CopyStarts and their + // corresponding CopyDones follow the same order. + void ScheduleAsynchronousCopies(); + + // Remove the positions and chunks associated with the instruction from + // alternate_memory_assignments_. + void RemoveAssignmentForInstruction(const HloInstruction* instruction); + + // Returns the estimated elapsed duration of the hlo module in seconds. It + // uses the 'allocations' argument to determine the location (default memory + // or alternate memory) of each operand and output of an instruction. + float ComputeEstimatedElapsedTime(const HloLiveRange& hlo_live_range, + const AllocationSequence& allocations); + + HloModule* module_; + const Options& options_; + std::vector flattened_instructions_; + absl::flat_hash_set computations_in_schedule_; + std::unique_ptr preset_assignments_; + std::vector> alternate_memory_assignments_; + std::vector> scoped_memory_assignments_; + int64_t alternate_memory_size_ = 0; + + // These maps hold vectors of new instructions that need to be scheduled after + // (or before) the instruction index in the key. FixSchedule uses these maps + // to modify and fix the schedule. + absl::flat_hash_map> schedule_after_; + absl::flat_hash_map> schedule_before_; +}; + +// Filters prefetches by matching against multiple filters and overrides the +// preferred prefetch time for matching prefetches by the provided override +// strategy. +class FilterUpdatePreferredPrefetch { + public: + // Supported filters for prefetch filtering by operand size, instruction name, + // operand number and operand index matching. + enum class FilterType { + OP_SIZE_LTE, // sting value: op_size_lte, filter value type: integer + OP_SIZE_GTE, // sting value: op_size_gte, filter value type: integer + INSTRUCTION_NAME_EXACT, // sting value: instruction_name_exact, + // filter value type: string + OP_NUMBER_EXACT, // sting value: op_number_exact, + // filter value type: integer + OP_INDEX_EXACT // sting value: op_index_exact, filter value type: string + // (empty string for {}, 1 for {1} and 1#2 for {1,2}) + }; + // Strategies to compute new perferred prefetch time. Prefetch eagerness + // sets prefetch time to a time within the live-range depending on a value, + // e.g. 0.5 sets it exactly in the middle of the live-range. Put after + // instruction or put before instruction finds an instruction in the schedule + // and puts the preferred prefetch time before or after the found instruction. + enum class OverrideType { + PREFETCH_EAGERNESS, // sting value: prefetch_eagerness, + // override value type : float + PUT_AFTER_INSTRUCTION, // sting value: put_after_instruction, + // override value type: string + PUT_BEFORE_INSTRUCTION // sting value: put_before_instruction, + // override value type: string + }; + std::vector> filter_list_; + OverrideType override_type_; + std::string override_value_; + + std::string ToString() const { return config_string_; } + + static StatusOr> + ParseFilterUpdatePreferredPrefetches(std::string config); + + static StatusOr IsOpSizeGte(int64_t operand_size, std::string config); + + static StatusOr IsOpSizeLte(int64_t operand_size, std::string config); + + static StatusOr IsInstructionNameExact( + absl::string_view instruction_name, std::string config); + + static StatusOr IsOpNumberExact(int64_t operand_number, + std::string config); + + static StatusOr IsOpIndexExact(const ShapeIndex& operand_index, + std::string config); + + StatusOr> GetPrefetchByEagerness( + int64_t earliest_prefetch_time, int64_t latest_prefetch_time) const; + + StatusOr> GetPrefetchTimeAfterInstruction( + const absl::flat_hash_map& schedule) + const; + + StatusOr> GetPrefetchTimeBeforeInstruction( + const absl::flat_hash_map& schedule) + const; + + private: + std::string config_string_; + StatusOr GetScheduleTimeFromInstructionName( + const absl::flat_hash_map& schedule) + const; + + static StatusOr ParseFilterType(std::string config); + + static StatusOr ParseOverrideType(std::string config); + + static StatusOr ParseOperandIndex(std::string config); + + static StatusOr + ParseFilterUpdatePreferredPrefetch(std::string config); +}; + +// The different options to be passed to the Run() API. +struct Options { + // Backend-specific integer value that describes the alternate memory. + int64_t alternate_memory_space = 0; + + // Maximum size of the alternate memory space. + int64_t max_size_in_bytes = 0; + + // Memory alignment of the alternate memory space. + int64_t alignment_in_bytes = 1; + + // If provided, we sort the buffers using this comparison function + // otherwise, we use GlobalDecreasingSizeBestFitHeap::kSpatial. + std::optional + buffer_interval_compare = std::nullopt; + + // This object determines how early and how late prefetches can occur. + PrefetchIntervalPicker* prefetch_interval_picker = nullptr; + + // This object is used to determine the benefit of a particular allocation. + MemorySpaceAssignmentCostAnalysis* cost_analysis = nullptr; + + // Size function for buffer values. + BufferValue::SizeFunction size_fn; + + // This function can be used to prevent certain HloValues (e.g., based on + // the opcode) to be placed on the alternate memory. + MemorySpaceAssignment::IsAllowedInAlternateMemoryFunction + is_allowed_in_alternate_mem_fn; + + // This function can be used to prevent certain HloUses (e.g., based on + // the opcode) to be placed on the alternate memory. + MemorySpaceAssignment::IsUseAllowedInAlternateMemoryFunction + is_use_allowed_in_alternate_mem_fn = [](const HloUse&) { return true; }; + + // Specifies if the given position is allowed in the alternate memory. + MemorySpaceAssignment::IsPositionAllowedInAlternateMemoryFunction + is_position_allowed_in_alternate_mem_fn = + [](const HloPosition&) { return true; }; + + // This function returns the amount of scoped memory in bytes that should be + // reserved during the execution of this instruction. + MemorySpaceAssignment::ReservedScopedMemoryFunction + reserved_scoped_memory_fn = + [](const HloInstruction*, + const absl::flat_hash_set< + std::pair>& /*operands_in_alternate_memory*/, + const absl::flat_hash_set< + ShapeIndex>& /*outputs_in_alternate_memory*/) { return 0; }; + + // If true, we will try to reduce scoped allocation buffer size for all + // instructions if their operand/output has been allocated in alternate + // memory. + bool reduce_scoped_memory_limit = false; + + // If true, we allocate the reserved scoped memory at the same offset. This + // is useful to enable more deduplication between HLOs that have reserved + // scoped memories, but may result in less efficient memory packing. + bool allocate_reserved_scoped_memory_at_same_offset = true; + + // Specifies the upper bound for number of outstanding prefetches and + // evictions, -1 for unlimited. + int64_t max_outstanding_prefetches = -1; + int64_t max_outstanding_evictions = -1; + + // Extra outstanding prefetch limit for while uses (in addition to + // max_outstanding_prefetches). + int64_t while_use_extra_outstanding_prefetch_limit = 0; + + // Specifies the maximum number of retries that will be performed for each + // value in case prefetching failed due to running out of asynchronous + // copies or asynchronous copy resource. + int64_t max_retries = 1; + + // The maximum number of repacks that we are willing to perform in case we + // can't allocate a buffer due to running out of memory. If this value is + // greater than 0, repacker must be non-nullptr. + int64_t max_repacks = 0; + + // This variable is used by the cost analysis in estimating how many times + // each while loop will execute. Nested loops will be assumed to have + // executed pow(while_execution_count, nesting_level) times. + uint64_t xla_tpu_memory_space_assignment_while_execution_count = 5ULL; + + // This variable is used to scale the alternate memory benefit factor for + // large buffers. The default scaling function is sqrt. + std::string + xla_tpu_alternate_memory_benefit_scaling_factor_for_large_buffers = + "SQRT"; + + float async_copy_bandwidth_bytes_per_second = 0.0f; + + float alternate_mem_bandwidth_bytes_per_second = 0.0f; + + // The repacking algorithm to reduce fragmentation. Must be non-null if + // max_repacks is greater than 0. + MemorySpaceAssignmentRepacker* repacker = nullptr; + + // This is only useful for testing, repack after every allocation. + bool repack_after_every_allocation = false; + + // If true, tries allocating buffers across (e.g., before and inside a while + // loop body) sequential calls (kWhile, kCall, and kConditional). + bool allocate_across_sequential_calls = false; + + // If true, verifies the memory space assignment against overlapping + // buffers. + bool verify = false; + + // If not nullptr, this function is called to dump debugging information. + // The first argument is appended to the file name and the second argument + // is the contents of the file. + std::function dump_fn = nullptr; + + // Enable prefetching buffers into preferred memory across program + // boundaries + bool enable_cross_program_prefetch = true; + + // If true, use buffer_interval_compare to determine which buffers to + // prefetch across program boundaries. + bool default_cross_program_prefetch_heuristic = false; + + // Enable cross-program prefetch freeing optimization where the + // cross-program-prefetched buffer can be reused. + bool enable_cross_program_prefetch_freeing = true; + + // The maximum number of cross program prefetches. + // TODO(tjablin): Use a heuristic to determine this automatically. + int max_cross_program_prefetches = 1; + + // Enable redundant eviction optimization in/around while loops. If enabled, + // this optimization would keep a copy of the buffer in the default memory in + // addition to alternate memory to eliminate redundant evictions. + bool enable_while_redundant_eviction_elimination = true; + + // An optional memory space assignment autotuning config, which is used + // to sort allocated buffers. + std::optional> autotuning_config = std::nullopt; + + // Scales effective bandwidth for async copies. Valid range is (0, 1]. + float async_copy_bandwidth_scaling_factor = 1.0; + + // If true, uses the earlier instance of the same instruction to use as + // preferred prefetch start time. + bool use_repeated_instance_for_preferred_prefetch_time = false; + + // If true, enforces the FIFO order for prefetches. + bool enforce_prefetch_fifo_order = false; + + // The ratio of use bytes to copy bytes for a given allocation site below + // which we consider the site to be inefficient. A value of 0 would treat all + // sites as efficient and a value of 1 would require the amount of bytes used + // at the site to be at least as much as the async copy bytes. There are two + // factors that determine the copy and use bytes: + // - Some uses don't actually access the entire tensor, e.g. in + // dynamic-update-slice. + // - copy_bytes may be larger than the size of the tensor as well. An + // example is a tensor may be prefetched, used, and then evicted. In that + // case copy_bytes would be twice the size of the tensor. + float inefficient_use_to_copy_ratio = 0.0; + + // This is mostly used for testing, it allows a test case to inject its own + // logic for AlternateMemoryBestFitHeap::GetInefficientAllocationSites. + std::function>( + absl::Span)> + get_inefficient_allocation_sites_fn = nullptr; + + // The window size used to calculate the pipeline overhead when HLO accesses + // the default memory, in MiB. + float pipeline_overhead_window_size_mib = 0; + + // Config to filter prefetches and update preferred prefetch times for the + // filtered prefetches according to an update config. + std::vector filter_update_preferred_prefetches; + + // Options for slicing prefetches into smaller asynchronously copied pieces. + SlicedPrefetchOptions sliced_prefetch_options; + + // Options for the memory-bound loop optimizer feature. + MemoryBoundLoopOptimizerOptions memory_bound_loop_optimizer_options; + + // A function for updating shape layouts. + MemorySpaceAssignment::UpdateLayoutFunction update_layout_fn = [](Shape*) {}; + + MemorySpaceAssignment::SliceProposalFunction propose_slice_fn = + [](const Shape&, const SlicedPrefetchOptions&) + -> xla::StatusOr { + return UnimplementedStrCat("Generation of SliceProposals unimplemented"); + }; + + // Option to always spill buffers from alternate memory to default memory + // and prefetching back to alternate memory(if needed) just in time for use. + bool always_spill_to_default_memory = false; +}; + +// A struct representing an asynchronous copy with its logical start and end +// time (time that copy done is scheduled), the resource this copy would use, +// its destination memory space, and a unique ID. +struct AsynchronousCopy { + int64_t start_time; + int64_t end_time; + float resource; + MemorySpaceAssignment::MemorySpace destination; + int64_t id; + + std::tuple + AsTuple() const { + return std::make_tuple(start_time, end_time, resource, destination, id); + } +}; + +// Compare asynchronous copies such that an earlier start time has the same or +// earlier end time and an earlier end time has the same or earlier start time. +bool operator<(const AsynchronousCopy& a, const AsynchronousCopy& b); + +bool operator==(const AsynchronousCopy& a, const AsynchronousCopy& b); +bool operator!=(const AsynchronousCopy& a, const AsynchronousCopy& b); + +// Helper class to enforce asynchronous copy ordering. If the appropriate option +// is enabled, we only allow asynchronous copies that are pipelined: if an +// asynchronous copy ends earlier than another asynchronous copy, it must start +// the same time or earlier than the other asynchronous copy; and if an +// asynchronous copy starts earlier than another asynchronous copy, it must end +// the same time or earlier than the other asynchronous copy. +class AsynchronousCopyOrdering { + public: + AsynchronousCopyOrdering() = default; + + // Adds an asynchronous copy. + void AddCopy(const AsynchronousCopy& copy); + + // Removes an asynchronous copy. CHECKs that it is removed. + void RemoveCopy(const AsynchronousCopy& copy); + + // Returns true if the addition of an asynchronous copy in the given time + // interval would violate the asynchronous copy ordering. E.g., consider the + // following scenario: + // CS CD + // already committed async copy: +-----------+ + // new async copy: +--------+ + // + // The new asynchronous copy would violate the ordering guarantee because the + // copy start is after an already committed asynchronous copy while its copy + // done is before the committed copy. + bool ViolatesOrdering(int64_t start_time, int64_t end_time) const; + + private: + // We use this data structure for keys into the map that has a custom + // comparator for the ordering guarantees. + struct Interval { + int64_t start_time; + int64_t end_time; + + // We allow multiple prefetches that have one or both of the same start and + // end times. std::map considers two values as equal if neither are less + // than the other. Using this comparator, we can ensure that the only + // intervals that evaluate to be equal are those with the same start and end + // times or those with intervals that violate the FIFO order. + bool operator<(const Interval& other) const { + return (start_time < other.start_time && end_time <= other.end_time) || + (start_time <= other.start_time && end_time < other.end_time); + } + }; + // Stores asynchronous copies in a tree set respecting the pipelining order. + std::map> ranges_; +}; + +// Helper class to enforce asynchronous copy resources by keeping track of +// available copy bandwidth and elapsed times of overlapped operations. It +// maintains a list of initial resources that correspond to the elapsed times of +// overlapped operations. As asynchronous copies are added, the available +// resource is subtracted to keep track of the current state. +class AsynchronousCopyResource { + public: + // A specification of needed asynchronous copy resources. + struct ResourceSpec { + int64_t start_time; + int64_t end_time; + float resource; + }; + + AsynchronousCopyResource() = default; + + // The constructor needs the initial resources. + explicit AsynchronousCopyResource(absl::Span initial_resources) + : initial_resources_(initial_resources.begin(), initial_resources.end()), + delay_(initial_resources.size(), 0) {} + + // Adds the given asynchronous copy and updates the current resources. CHECK + // fails if there aren't enough resources to satisfy this copy (the caller + // should use HasEnoughResource first to ensure there is enough resource). + void AddCopy(const AsynchronousCopy& copy); + + // Removes the given copy and frees the resource. + void RemoveCopy(const AsynchronousCopy& copy); + + // Returns true if a copy with the given start and end times and resource can + // be satisfied. + bool HasEnoughResource(int64_t start_time, int64_t end_time, float resource); + + // Returns true if a set of copy specifications can be satisfied in the + // order specified. + bool HasEnoughResourceMultiCheck(const std::vector& specs); + + // This is only used for debugging and testing purposes, it returns the + // currently available resource at each logical time. + std::vector GetCurrentResources() const { + std::vector current_resources(initial_resources_.begin(), + initial_resources_.end()); + for (int i = 0; i < current_resources.size(); ++i) { + current_resources[i] -= std::min(current_resources[i], delay_[i]); + } + return current_resources; + } + + // A useful debugging tool for printing several pieces of information about + // AsynchronousCopyResource. + std::string Dump( + int64_t start_time, int64_t end_time, + MemorySpaceAssignment::MemorySpace memory_space_filter) const; + + private: + // Internal helper method to implement adding/removing/checking resources. + // ConsumeResource() may modify delay_. If delay_change_map is not null, + // for any change to delay_[i], {i, delay_[i]} will be added to + // delay_change_map, allowing callers to undo any modifications. + bool ConsumeResource( + int64_t start_time, int64_t end_time, float resource, + absl::flat_hash_map* delay_change_map = nullptr, + float resource_to_free = 0.0); + + // Same as the public RemoveCopy except it works on the async_copies_ + // iterator. Assumes copy_it points to the last copy for its start time; + // otherwise the public RemoveCopy method is supposed to temporarily remove + // these later copies that share the same start time before removing the + // requested copy. + void RemoveCopy(std::list::iterator& copy_it); + + // We maintain a linked list of asynchronous copies sorted by the start times. + // This allows us to efficiently find the copy that starts right after another + // one because adding a copy might push a copy further into the future. + std::list async_copies_; +// To make the lookups into async_copies_ more efficient, we also maintain a +// binary tree that is indexed by the start time, containing iterators into +// async_copies_. +// TODO(b/210891274): Use btree_map after build issue in Windows is resolved. +#if defined(__GNUC__) || defined(__clang__) + absl::btree_map::iterator> + async_copy_time_map_; +#else + std::map::iterator> async_copy_time_map_; +#endif + std::vector initial_resources_; + std::vector delay_; +}; + +// TODO(b/280618622): Refactor this class out of this file. +// +// An optimizer for unrolled memory-bound loops. It keeps track of alternate +// memory capacity and default memory bandwidth to decide the allocations of +// each tensor within a loop iteration. The assumption is that all of the +// unrolled loop iterations will use the same allocation decisions, so we can +// spend more time to optimize this one iteration as optimally as possible. +// +// To represent instructions, we keep track of three iterations (previous, +// current, and next), as well as the header and footer regions that are before +// and after the loop, respectively. +// +// We classify each tensor used in the current iteration as one of the following +// allocations based on its positions and uses: +// +// Temporary Allocations: These are produced by a producer in the current +// iteration and consumed either in this or the next iteration. For these, we +// try to give them alternate memory allocations for their entire live range. +// +// Case 1: producer and consumer all in the current iteration. +// p-----c--c +// Case 2: producer is in the current iter, consumer is in the next iter. +// p-----c +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +// +// Loop Carried Dependences: This is where the last use is at a larger index +// than the producer. This would require 2X peak buffer consumption because both +// this and next iteration's buffer is alive at the same time. This case is +// currently not supported. +// +// Case 3: producer is in the current iter, consumer is in the next iter +// (consumer idx >= producer idx). +// p-----------------c +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +// +// Pinned Allocations: These are values produced at the header and are used in +// every iteration at the same indices. For these, we just allocate the buffer +// for the duration of the loop: +// +// Case 4: producer: kHead, consumer: kCurrent +// p---------------c--------------c--------------c-------- +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +// +// Prefetch Allocations: These are values produced at the header and are used in +// the current (and possibly next) iteration. We will try to prefetch these +// values into the alternate memory: +// +// Case 5: producer: kHead, consumer: kCurrent +// p---------------------------------c--------c +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +class MemoryBoundLoopOptimizer { + public: + // We represent each tensor used in the current iteration as a LoopValue, + // wrapping the relevant information such as its HLO value, indices and + // pointers to its use and position sites in different iterations. + struct LoopValue { + // An enum that encodes the allocation type that is suitable for this + // LoopValue. See the comment above on what each of these mean. + enum class AllocationType { + kTemporary, + kLoopCarriedDependence, + kPinned, + kPrefetch, + kUnsupported + }; + + // ToString methods for logging/debugging. + static std::string AllocationTypeToString(AllocationType allocation_type); + std::string ToString() const; + + // The HloValues that correspond to this LoopValue. + std::vector hlo_values; + // The position in the header, if any. + std::optional header_position; + // The loop index and position in the previous and current iterations. + std::vector> prev_iteration_positions; + std::vector> loop_positions; + // The loop index and use in the current and next iterations. + std::vector> loop_uses; + std::vector> next_iteration_uses; + // The allocation type. + AllocationType allocation_type; + // Size of this tensor. + int64_t size; + // The default memory bandwidth savings were we to successfully put this in + // the alternate memory using the allocation type, in bytes. + float savings; + // The savings divided by the size. This is typically 2 for temporary + // allocations (skip a write and a read to the default memory). More complex + // production/consumption patterns may result in higher or lower values. We + // use this value to sort LoopValues so that the algorithm can prioritize + // allocating the buffers with the highest savings per byte to the alternate + // memory. + float savings_per_byte; + // The optimized AllocationSequence. + MemorySpaceAssignment::AllocationSequence allocations; + }; + + // Factory method to create and initialize a MemoryBoundLoopOptimizer. + static StatusOr> Create( + int loop_start, int loop_end, uint64_t alternate_memory_size, + const MemoryBoundLoopOptimizerOptions& options, + const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis_, + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + const BufferValue::SizeFunction& size_function); + + // Optimize the loop. Initialize must be called first. + void Optimize(); + + // Calculate the steady-state execution time of one loop iteration using the + // allocation decisions so far. + float CalculateExecutionTime() const; + + // Return the LoopValues. + const std::vector& loop_values() const { return loop_values_; } + std::vector& loop_values() { return loop_values_; } + + // Return the remaining memory vector for each point in time in the loop using + // the allocation decisions so far. + const std::vector& remaining_memory() const { + return remaining_memory_; + } + + // The loop start, end, and size accessors. + int loop_start() const { return loop_start_; } + int loop_end() const { return loop_end_; } + int loop_size() const { return loop_size_; } + + private: + // Temporary data structures used by the AllocatePrefetch function. + struct AllocatePrefetchesContext { + // The values that are requested to be prefetched. + absl::Span values; + + // A list of indices into values array, sorted by the start time of the + // first use. + std::vector value_indices; + + // Default memory remaining bandwidths assuming all prefetches succeeded. + std::vector bandwidth_idle_times; + + // Additional memory used while performing prefetching. + std::vector additional_memory_used; + }; + + MemoryBoundLoopOptimizer( + int loop_start, int loop_end, uint64_t alternate_memory_size, + const MemoryBoundLoopOptimizerOptions& options, + const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis_, + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + const BufferValue::SizeFunction& size_function); + + // Initializes the data structures used by the optimizer. + Status Initialize(); + + // Given an HloBuffer object, determines if this buffer represents a LoopValue + // that can be optimized by the optimizer, and if so it adds a LoopValue to + // the back of loop_values_ that represents the HloBuffer. Otherwise, no new + // LoopValue is added to loop_values_. + void MaybeCreateLoopValue(const HloBuffer& buffer, + const HloComputation* loop_computation); + + // Sort LoopValues by savings_per_byte. + void SortLoopValues(); + + // After allocation finishes, we fix up by creating Allocation objects to any + // LoopValues that didn't get alternate memory allocations. + void PostProcess(); + + // Allocate LoopValues by dispatching to the correct Allocate method. + void AllocateLoopValues(); + + // Allocate and reserve memory between the given indices. + bool AllocateBetween(int64_t begin_idx, int64_t end_idx, int64_t size); + + // Perform allocation type kTemporary. Return true if successful. + bool AllocateTemporary(LoopValue& value); + + // Perform allocation type kPinned. Return true if successful. + bool AllocatePinned(LoopValue& value); + + // Perform allocation type kPrefetch. Unlike the other Allocate methods, this + // performs allocation of multiple LoopValues in order to consider the effect + // of remaining bandwidth assuming the other prefetches were successful. + // Return true if successful. + bool AllocatePrefetches(absl::Span values); + + // Allocate one prefetch for the loop value index that corresponds to + // context.context.values. Returns true if successful. + bool AllocatePrefetch(int value_index, AllocatePrefetchesContext& context); + + // Keeps track of successful allocation of all uses and positions of this + // LoopValue. + void AddAllLoopPositionsAndUses(LoopValue& value, + bool allocate_next_iteration_uses); + + // Returns the default memory bandwidth idle time at the index. + float GetBandwidthIdleTime(int idx) const; + + // Returns the default memory bandwidth idle time at the index assuming the + // given uses and positions got alternate memory allocations. + float GetBandwidthIdleTime( + int idx, + const absl::flat_hash_map>>& + additional_uses_in_alternate_mem, + const absl::flat_hash_map>& + additional_positions_in_alternate_mem) const; + + // Returns the instruction elapsed at the index. + float GetInstructionElapsed(int idx) const; + + int loop_start_; + int loop_end_; + int loop_size_; + uint64_t alternate_memory_size_; + MemoryBoundLoopOptimizerOptions options_; + const HloLiveRange& hlo_live_range_; + const HloAliasAnalysis& alias_analysis_; + const MemorySpaceAssignmentCostAnalysis& cost_analysis_; + BufferValue::SizeFunction size_function_; + + absl::flat_hash_map instructions_in_loop_; + absl::flat_hash_map + instructions_in_prev_iteration_; + absl::flat_hash_map + instructions_in_next_iteration_; + std::vector loop_values_; + std::vector remaining_memory_; + absl::flat_hash_map>> + uses_in_alternate_mem_; + absl::flat_hash_map> + positions_in_alternate_mem_; +}; + +// This class inherits from GlobalDecreasingSizeBestFitHeap with a notion of +// maximum size. +class AlternateMemoryBestFitHeap + : public GlobalDecreasingSizeBestFitHeap { + public: + using MemorySpace = MemorySpaceAssignment::MemorySpace; + using AllocationValue = MemorySpaceAssignment::AllocationValue; + using HloPositionOrUse = std::variant; + + AlternateMemoryBestFitHeap( + MemorySpaceAssignment::AllocationSequence* allocations, + const Options& options, const HloAliasAnalysis& alias_analysis, + const HloLiveRange& hlo_live_range); + + // Allocates a buffer in preferred memory with whole program lifetime and + // enables prefetching prefetch_candidate from default memory across program + // boundaries. + void AllocateCrossProgramPrefetchBuffer( + HloModule* module, const BufferInterval& prefetch_candidate); + + HeapSimulator::Result Finish() override; + + protected: + // Given a buffer interval, returns the colocated intervals. Unlike the + // similar GlobalDecreasingSizeBestFitHeap::GetTransitiveColocations, it + // returns the colocated intervals sorted by scheduled time. + std::vector GetSortedColocatedIntervals( + const BufferInterval& interval) const; + + // Given a BufferInterval, creates AllocationValue objects and corresponding + // AllocationSequences and appends them into allocation_sequence_list_. + void CreateAllocationValues( + const BufferInterval& buffer_interval, + std::vector& allocation_values) const; + + // Given colocated intervals, populates allocation_values with the + // corresponding AllocationValue objects. + virtual void CreateAllocationValuesFromColocatedIntervals( + absl::Span + colocated_intervals, + std::vector& allocation_values); + + // Go through all the uses in the AllocationValues and find the aliasing + // positions. + void FindAliases(std::vector* allocation_values) const; + + MemorySpaceAssignment::AllocationSequence* allocations() { + return allocations_; + } + const Options& options() const { return options_; } + const HloAliasAnalysis& alias_analysis() { return alias_analysis_; } + const HloLiveRange& hlo_live_range() { return hlo_live_range_; } + + private: + // We inherit AllocationBlock struct to attach the Allocation information to + // make importing repacked offsets easier. + struct RepackAllocationBlock + : MemorySpaceAssignmentRepacker::AllocationBlock { + MemorySpaceAssignment::Allocation* allocation; + }; + + // A data structure we use to associate Allocation objects that are aliased + // and must get the same offset. + struct AliasedOffset { + int64_t offset; + absl::flat_hash_set allocations; + }; + + // An allocation request for a use segment. A use segment is the time segment + // between the definition and the first use, and the time segment between the + // uses of a buffer. For example, the time between the definition and Use1, is + // the first segment, and the time between Use1 and Use2 is the second segment + // and so on: + // + // +------+----------+-------+ + // / \ \ \ + // / v v v + // Def Use1 Use2 Use3 + // <----------> <--------> <-----> + // Segment Segment Segment + // + // start_time and end_time are the start and end logical times of the segment. + // use_times is a sorted sequence of the times of all uses. + // latest_prefetch_time is the latest time we can schedule the CopyDone for a + // prefetch. + // If allow_no_copy_alternate_mem_allocation is false, an eviction is forced. + // If earliest_prefetch_time is set, prefetches cannot start before this + // value. + struct AllocationRequest { + int64_t start_time; + int64_t end_time; + int64_t latest_prefetch_time; + int64_t size; + bool prefer_no_copy_alternate_mem_allocation; + bool allow_no_copy_alternate_mem_allocation; + bool allow_prefetch; + std::optional earliest_prefetch_time; + std::optional preferred_prefetch_time; + AliasedOffset* preferred_offset; + const MemorySpaceAssignment::AllocationValue::Use* use; + MemorySpaceAssignment::AllocationValue* allocation_value; + absl::Span all_use_times; + }; + + // This struct contains mandatory memory assignments at a given time. E.g., an + // input's required memory assignment time would correspond to the definition + // time of the parameter instruction, and an output's time would correspond to + // the time of last use. + struct RequiredMemoryAssignment { + MemorySpaceAssignment::MemorySpace memory_space; + int64_t time; + AliasedOffset* offset; + + bool equals_ignoring_time(const RequiredMemoryAssignment& other) const { + return memory_space == other.memory_space && offset == other.offset; + } + + bool operator==(const RequiredMemoryAssignment& other) const { + return memory_space == other.memory_space && time == other.time && + offset == other.offset; + } + + bool operator!=(const RequiredMemoryAssignment& other) const { + return !(*this == other); + } + }; + + // A struct that contains a pointer to loop-optimized allocation along with + // essential data about the loop itself. + struct LoopOptimizedAllocationInfo { + // The use_idx is the instruction index of the use within the loop. + int64_t use_index; + // The number of instructions in one iteration of the loop. We use use_index + // and loop_size to calculate when exactly to schedule a prefetch + // instruction. + int64_t loop_size; + // A pointer into an Allocation in loop_optimized_allocations_. + const MemorySpaceAssignment::Allocation* loop_optimized_allocation; + }; + + // A context object that is used to share state amongst the methods that + // implement Prefetch(). Prefetch tries to find both a sliced solution and an + // unsliced solution at the same time. We store both in this structure. + struct PrefetchContext { + // Prefetching is designed to operate on a SlicedBufferInterval that is + // backed by a standard BufferInterval, even if the number of slices == 1. + // WorkingIntervals is used to store a SlicedBufferInterval and its backing + // BufferInterval. + struct WorkingIntervals { + BufferInterval full; + // sliced is a unique_ptr because it won't necessarily be initialized + // when the WorkingBufferIntervals are created, and there is no way to + // create an empty SlicedBufferInterval. + std::unique_ptr sliced; + }; + + struct SlicedSolution { + // When we talk about a slice, we think of spatial slices, where each + // slice is allocated at different times. The following example shows + // 3 slices that are used to form a contiguous buffer from [p0, p3] + // + // space + // ^ + // p3 | +-----------+ + // | | s2 | + // p2 | +---+-----------+ + // | | s1 | + // p1 | +-------+-------+ + // | | s0 | + // p0 | +-------+ + // +---|---|---|---|---|----> time + // t0 t1 t2 t3 t4 + std::vector + slice_decisions_sorted_by_start_time; + + // In order to support colocated buffer calculations, we need to add a + // BufferInterval-Chunk pair to pending_chunks_, such that: + // - The duration of the BufferInterval is non-zero. + // - All slices have been allocated by the start of the BufferInterval. + // - The BufferInterval ends at the end time for all slices. + // - The Chunk covers the space allocated for all slices. + // + // In order to meet that requirement, + // we create BufferInterval-Chunk pairs from + // slice_decisions_sorted_by_start_time that meet those requirement but do + // not cause any memory to be allocated in more than one Chunk at a time. + // The result is stored in slices_for_pending_chunks. + // + // The illustration below demonstrates how we would construct such + // BufferInterval-Chunk pairs from the + // slice_decisions_sorted_by_start_time example above. + // + // space + // ^ + // p3 | +---+---+---+ + // | |c2 | | + // p2 | +---+---+ | + // | | c0 | c2 | + // p1 | +-------+ | + // | | | + // p0 | +-------+ + // +---|---|---|---|---|----> time + // t0 t1 t2 t3 t4 + std::vector> slices_for_pending_chunks; + + // The prefetch_picker_debug_string will only be set with the appropriate + // VLOG level. + std::string prefetch_picker_debug_string; + }; + + struct UnslicedSolution { + Chunk chunk_candidate; // The chunk chosen for the solution. + float prefetch_resource; // The amount of required prefetch resource. + // The prefetch_picker_debug_string will only be set with the appropriate + // VLOG level. + std::string prefetch_picker_debug_string; + }; + + WorkingIntervals& GetMutableWorkingIntervals(bool for_sliced_solution) { + if (for_sliced_solution) { + return sliced_solution_intervals; + } + return unsliced_solution_intervals; + } + + const WorkingIntervals& GetWorkingIntervals( + bool for_sliced_solution) const { + if (for_sliced_solution) { + return sliced_solution_intervals; + } + return unsliced_solution_intervals; + } + + // Parameters to Prefetch(). + const AllocationRequest* request; + MemorySpaceAssignment::Allocation* prev_allocation_in_default_mem; + + // Intermediate calculations common to both the sliced and unsliced + // solutions. + int64_t prefetch_start_time = -1; + int64_t prefetch_end_time = -1; + const Shape* full_shape; + int64_t extra_async_copy_limit = 0; + // As a compilation time optimization, store the prefetch start time where + // we have first seen out of memory. There is no point of exploring prefetch + // start times earlier than this point. + std::optional out_of_mem_start = std::nullopt; + + // Data structures used to compute and store the sliced solution. + std::optional + slice_proposal_collection = std::nullopt; + WorkingIntervals sliced_solution_intervals; + std::optional sliced_solution; + + // Data structures used to compute and store the unsliced solution. + WorkingIntervals unsliced_solution_intervals; + std::optional unsliced_solution; + }; + + // Result of an allocation, prefetch, eviction etc. request. The result is + // either kSuccess or a bitwise OR of one or more failures. The values are + // unique powers of two. To check if a result contains a particular failure, + // use the result_is method. To add a new failure to a result, use the + // result_mark method. + enum class Result { + // Successful allocation. + kSuccess = 0, + // Allocation failed because we ran out of alternate memory. + kFailOutOfMemory = 1, + // A no-copy allocation couldn't be performed because the previous + // allocation wasn't in the alternate memory space. + kFailPrevAllocationNotInAlternateMem = 2, + // A no-copy allocation couldn't be performed because the live range was too + // long. + kFailLiveRangeTooLong = 4, + // A prefetching couldn't be performed because the live range was too short. + kFailLiveRangeTooShort = 8, + // Ran out of outstanding asynchronous copy limit either during prefetching + // or eviction. + kFailOutOfAsyncCopies = 16, + // A prefetching couldn't be performed because the asynchronous copy + // resource was violated. + kFailViolatesAsyncCopyResource = 32, + // An allocation failure happened that requires uncommitting all the pending + // allocations. Usually this is due to a situation requiring an eviction but + // the eviction couldn't be performed. + kFailRequiresUncommit = 64, + // For prefetching, indicates that all slices have the same start time, in + // which case, we fallback to an unsliced solution. + kAllSlicesHaveTheSameStartTime = 128 + }; + + // Return true if the result belongs to a failure. + static bool result_is(Result result, Result failure) { + return static_cast(result) & static_cast(failure); + } + + // Mark (bitwise OR) a failure to the result. + static Result result_mark(Result failure, Result& result) { + result = static_cast(static_cast(result) | + static_cast(failure)); + return result; + } + + // Return true if the result is a failure that requires us to uncommit pending + // chunks. + static bool result_requires_uncommit(Result result) { + return result_is(result, Result::kFailRequiresUncommit); + } + + // Return true if the result is a failure either due to running out of + // outstanding asynchronous copies or due to violating asynchronous copy + // ordering. + static bool result_failed_because_of_async_copy(Result result) { + return result_is(result, Result::kFailOutOfAsyncCopies) || + result_is(result, Result::kFailViolatesAsyncCopyResource); + } + + // For the given loop with the start and end index and loop size, run the + // MemoryBoundLoopOptimizer and record its outputs into + // optimized_allocations_map_. + Status OptimizeMemoryBoundLoop(int loop_start_idx, int loop_end_idx, + int loop_size); + + // Identify memory-bound loops in the graph and call OptimizeMemoryBoundLoop + // for the found loops. + void IdentifyAndOptimizeMemoryBoundLoops(); + + // Allocates buffers for instructions that need reserved scoped allocations in + // the alternate memory space. + void AllocateReservedScopedAllocations(); + + // Returns the AliasedOffset object associated with the allocation. + AliasedOffset* GetAliasedOffset( + const MemorySpaceAssignment::Allocation& allocation); + + // If aliased_offset is non-null, this method adds the allocation to + // aliased_offset. Otherwise, it creates a new AliasedOffset object and adds + // the allocation to this new AliasedOffset. + void CreateOrAddToAliasedOffset( + const MemorySpaceAssignment::Allocation& allocation, + AliasedOffset* aliased_offset); + + // Given an allocation sequence, returns the live allocation at time with a + // preference towards allocations in alternate memory. Returns nullptr if no + // allocation is alive at that time. + static MemorySpaceAssignment::Allocation* GetLiveAllocationAt( + const MemorySpaceAssignment::AllocationSequence& allocations, + int64_t time); + + // Returns true if the use is allowed in the alternate memory. + bool IsUseAllowedInAlternateMemory(const AllocationValue& value, + const HloUse& use) const; + + // Finds allocations for allocation values generated from colocated intervals. + // All of the allocation values have a must-alias relationship with each + // other. Returns either kSuccess if all of the sites could be placed in the + // alternate memory or a bitwise OR of failure reasons why they couldn't + Result AllocateAllocationValues( + absl::Span allocation_values); + + // Finds an allocation for an allocation request for a segment (see the + // documentation for AllocationRequest above how a segment is defined). + // + // It performs three things in the following order: + // 1- Allocate the allocation request entirely in the alternate memory, if + // there is enough space and if the prefetch interval picker allows. + // 2- If (1) was unsuccessful, and the only allocation for + // this buffer was in the alternate memory, we try to perform a prefetch. + // 3- If (1) was unsuccessful, prefetch the buffer into the alternate memory, + // if there is enough space and if the prefetch interval picker allows. + // + // If an eviction (2) was requested and was unsuccessful, this method returns + // Result::kFailRequiresUncommit. This means we could not find a suitable + // allocation, so all previous allocations for this buffer must be removed and + // allocated in the default memory. Otherwise, this method may return + // Result::kSuccess if the buffer could be placed in alternate memory or some + // other Result with an OR of reasons why the buffer couldn't be placed in + // alternate memory. + Result AllocateSegment(const AllocationRequest& request); + + // Try allocating in alternate memory without any copies. + Result AllocateInAlternateMemoryNoCopy(const AllocationRequest& request); + + // Try evicting to default memory space. + Result Evict(const AllocationRequest& request); + + // Returns the time a copy done of a prefetch should be scheduled. + int64_t FindPrefetchEndTime(const AllocationRequest& request, + int64_t earliest_prefetch_time) const; + + // Try prefetching to alternate memory space. + Result Prefetch( + const AllocationRequest& request, + MemorySpaceAssignment::Allocation& prev_allocation_in_default_mem); + + // Helper methods used to implement Prefetch(). + // + // Generates a SliceProposal in context, if options dictate and one can be + // constructed. + void GenerateSliceProposal(PrefetchContext& context) const; + // Calls GenerateSliceProposal to potentially create a SliceProposal, and + // sets up WorkingIntervals for a sliced and unsliced solution. Updates + // context. + void SetupPrefetchWorkingIntervalsAndSliceProposal( + PrefetchContext& context) const; + // Initializes the PrefetchIntervalPicker and associated data structures in + // context. + Result InitializePrefetchIntervalPicker(PrefetchContext& context); + // As a compile time optimization, try a prefetch allocation that is as late + // as possible. If this is not able to find a solution, none of the + // earlier tries will succeed either. + Result EnsureSomeSpatialPrefetchFitExists(PrefetchContext& context) const; + // Check if for the specified type of solution, using the parameters in + // context. If we find a solution, it will be stored in context. + Result CheckPrefetchFit(bool for_sliced_solution, PrefetchContext& context); + // Given a specified number of slices, start times, and end times, pick times + // to start each slice. + std::vector PickSliceStartTimes(int64_t num_slices, + int64_t prefetch_start_time, + int64_t prefetch_end_time) const; + // Creates a debugging string describing the timing of the prefetch solution + // we are currently attempting (as dictated by for_sliced_solution and + // context). + std::string AlternateMemoryAllocationAttemptToString( + bool for_sliced_solution, const PrefetchContext& context) const; + + // Find the best possible chunk candidate, where it has the longest possible + // availability if no preferred offset is given, or at the preferred_offset if + // it is given. + std::optional FindBestChunkCandidate( + const AllocationRequest& request, const AliasedOffset* preferred_offset, + BufferInterval* alternate_mem_interval) const; + // The same as FindBestChunkCandidate() but allocates the request in slices. + // The ith returned chunk should be allocated at slice time i. + std::vector FindBestChunkCandidates( + const AllocationRequest& request, const AliasedOffset* preferred_offset, + SlicedBufferInterval* alternate_mem_interval) const; + + // Returns the required assignment at a particular time, if available. + std::optional RequiredMemoryAssignmentAt( + const HloValue* buffer, int64_t time) const; + + // Searches for aliases in the use for a required assignment, and returns it + // if found. + std::optional AliasedRequiredAssignmentForUse( + const AllocationValue::Use& use) const; + + // Goes through the colocated intervals and adds any required assignment. + void AddRequiredAssignmentsForColocatedIntervals( + absl::Span + colocated_intervals); + + // Propagates aliased required assignment for a given position. + void AddAliasedRequiredAssignment( + const HloInstruction* instruction, ShapeIndex index, + const MemorySpaceAssignment::Allocation* aliased_allocation); + + // This sets a required assignment. CHECK fails if there is a conflicting + // required assignment at the same time. + void AddRequiredAssignment(const HloValue* value, + const HloInstruction* instruction, + MemorySpace memory_space, int64_t time, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + void AddRequiredAssignment(const HloInstruction* instruction, + ShapeIndex index, MemorySpace memory_space, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + void AddRequiredAssignment(const HloPosition& position, + MemorySpace memory_space, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + void AddRequiredAssignment(const HloUse& use, MemorySpace memory_space, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + + // Adds input and outputs as required assignments. + void AddInputAndOutputRequiredAssignments(); + + // Returns a list of "linked" allocations in the alternate memory. Linked + // allocations all share a common allocation site (a use or position) with + // each other. This can be used to determine if a group of linked allocations + // are considered efficient or not. + std::vector> + GetLinkedAllocationsInAlternateMemory( + absl::Span allocation_values) const; + + // Returns allocation sites (use or position) that are allocated in the + // alternate memory, but is considered inefficient. These arise in the + // context of in-place operation like dynamic-update-slice. We will typically + // have an allocation that has the DUS as a use, and another allocation that + // has the DUS as a defining position. These two allocation will be part of + // the same linked allocation group. + // + // One reason why an allocation site could be inefficient is because the + // amount of data that is asynchronously copied (prefetch and eviction) is + // much larger than the amount of data that is used by the HLOs. If we find + // inefficient allocation sites, we can require these sites default memory + // allocations and allocate them again. + std::vector GetInefficientAllocationSites( + absl::Span allocation_values) const; + + // Returns true if the colocated intervals in the argument are in a parameter + // or root instruction of the entry computation and are reserved by the user + // to be in the alternate memory space. + bool AreIntervalsReservedInAlternateMemory( + absl::Span colocated_intervals) const; + + // Since the allocations are recorded to the AllocationSequence, we don't + // maintain result_ in GlobalDecreasingSizeBestFitHeap. Override AddToChunkMap + // to avoid unnecessarily adding the chunk to the chunk map. + // + // Sliced prefetching requires that we override this method because we + // associate more than one chunk with a buffer (i.e., 1 chunk per slice), + // which would cause the original implementation of this method to CHECK fail. + void AddToChunkMap(const HloValue* buffer, Chunk chunk) override {} + + // Returns true if the addition of num_additional_copies asynchronous copies + // in the given time interval would violate the maximum number of asynchronous + // copies. An extra async copy limit can be provided to increase the limit of + // asynchronous copies for this instance. + bool ViolatesMaximumOutstandingAsyncCopies( + int64_t start_time, int64_t end_time, bool is_prefetch, + int64_t extra_async_copy_limit = 0, + int64_t num_additional_copies = 1) const; + + // Exports the allocations for repacking and puts them into the vector in the + // parameter. + void ExportAllocationsForRepacking( + std::vector& + allocations); + + // Update reserved scoped allocation size for instructions when their + // operand/output has been allocated in alternate memory by invoking + // reserved_scoped_memory_fn + void UpdateReservedScopedAllocationSize(); + + // Imports repacked allocations and updates the internal data structures + // consistent with the new packing. + void ImportRepackedAllocations(); + // Helper functions to implement ImportRepackedAllocations. + void ImportRepackedNonSlicedAllocation(RepackAllocationBlock& block); + void ImportRepackedSlicedAllocation(RepackAllocationBlock& block); + + // Adds an asynchronous copy to allocations. + void AddAsyncCopy( + MemorySpaceAssignment::Allocation& prev_allocation, + MemorySpace memory_space, std::optional chunk, int64_t start_time, + int64_t end_time, int64_t copy_done_schedule_before_time, + MemorySpaceAssignment::AllocationSequence* allocations, + AliasedOffset* aliased_offset, float resource, + std::optional cross_program_prefetch_index = std::nullopt); + + // For prefetching, adds a SlicedCopyAllocation to allocations. Also updates + // asynchronous copy data structures, prefetch_interval_tree_, and aliasing + // data structures + void AddAsyncSlicesForPrefetch( + const MemorySpaceAssignment::Allocation& prev_allocation, + MemorySpaceAssignment::AllocationSequence* allocations, + AliasedOffset* aliased_offset, + const std::vector& + slice_decisions_sorted_by_start_time, + int64_t prefetch_end_time, int64_t allocation_end_time); + + // This method is used for committing the chunk candidate but adding it to + // pending_chunks_ so that we can "uncommit" them in case we need to roll back + // this allocation sequence. + void AddToPendingChunks(const BufferInterval& buffer_interval, + const Chunk& chunk); + // If we need to remove the allocations for this allocation sequence, this + // removes pending chunks and asynchronous copies in the respective pending + // buffers from the interval trees. If an allocation request returns + // kFailRequiresUncommit, this method must be called. + void UncommitPendingChunks(absl::Span allocation_values); + + // Finalizes the allocations where they can no longer be uncommitted. + void FinalizeAllocations(absl::Span allocation_values); + + // Clears all pending chunks and asynchronous copies. + void ClearPendingChunks(); + + // Append buffer and allocation infos for debugging and dump it into a file, + // if enabled. + void AppendBufferInfoDebugString(const BufferInterval& interval, + std::string* debug_str) const; + void AppendScopedAllocationBufferInfoDebugString( + const HloInstruction* instruction, int64_t time, int64_t size, + std::string& debug_str) const; + void AppendAllocationInfoDebugString( + const MemorySpaceAssignment::Allocation& allocation, + std::string& debug_str) const; + void DumpDebugStringsIfEnabled() const; + + // Returns the available heap size in the alternate memory. + int64_t available_heap_size() const { + return options_.max_size_in_bytes - reserved_in_bytes_; + } + + // Returns the earliest time in the [start_time, end_time] range that a new + // allocation with the given size would fit in the alternate memory. If it + // doesn't fit, it returns nullopt. + std::optional FindEarliestTimeToSatisfyPeakMemory(int start_time, + int end_time, + int64_t size) const; + + // Creates and returns a RepackAllocationBlock. + static RepackAllocationBlock MakeRepackAllocationBlock( + int64_t start_time, int64_t end_time, int64_t size, + int64_t initial_offset, int64_t id, + MemorySpaceAssignment::Allocation* allocation) { + RepackAllocationBlock allocation_block; + allocation_block.start_time = start_time; + allocation_block.end_time = end_time; + allocation_block.size = size; + allocation_block.offset = -1; + allocation_block.initial_offset = initial_offset; + allocation_block.id = id; + allocation_block.colocations = {}; + allocation_block.allocation = allocation; + return allocation_block; + } + + // Returns a vector of instructions that have the same fingerprint as this + // instruction. + const std::vector* GetRepeatedInstructionList( + const HloInstruction* instruction) const; + + MemorySpaceAssignment::AllocationSequence* allocations_; + const Options& options_; + const HloAliasAnalysis& alias_analysis_; + const HloLiveRange& hlo_live_range_; + std::unique_ptr call_graph_; + // We use a interval tree to keep track of the number of outstanding + // prefetches and evictions. + BufferIntervalTree prefetch_interval_tree_; + BufferIntervalTree eviction_interval_tree_; + AsynchronousCopyOrdering async_copy_ordering_; + AsynchronousCopyResource prefetch_async_copy_resource_; + AsynchronousCopyResource eviction_async_copy_resource_; + // A list of RepackAllocationBlock objects that mirrors allocation sequences, + // used for repacking. We use a list here because we need pointer stability + // for aliased allocations. + std::list repack_allocation_blocks_; + int64_t num_repacks_ = 0; + std::vector> pending_chunks_; + std::vector pending_async_copies_; + std::vector> + pending_required_assignments_; + // A cache to keep the peak memory usage at each point in the graph. We use + // this to see if the proposed allocation in the alternate memory would fit + // ignoring fragmentation, and if not, we can skip the more expensive lookup + // in the BufferIntervalTree, which also considers fragmentation. + std::vector peak_memory_usage_; + // The data structure that contains AliasedOffset objects and Allocation to + // AliasedOffset map for efficient lookup. + std::list aliased_offsets_; + absl::flat_hash_map + aliased_offset_map_; + // This map contains required memory assignments for HloValues (e.g., input + // and outputs). + absl::flat_hash_map> + required_assignments_; + // Number of bytes reserved in alternate memory space. + int64_t reserved_in_bytes_ = 0; + // A rough measure of the memory pressure of the model, in bytes. Note that + // this is pressure for memory capacity (and not accessed bytes), and for + // alternate memory (not default memory). + int64_t memory_pressure_ = 0; + int64_t next_async_copy_id_ = 0; + // Fingerprint cache. + absl::flat_hash_map fingerprint_map_; + // Vector of repeated instructions (that have the same fingerprint) indexed by + // fingerprint. + absl::flat_hash_map> + repeated_inst_map_; + + // Loop-optimized allocations found by MemoryBoundLoopOptimizer. These + // allocation objects describe the allocations for one iteration of the loop, + // so we translate them into the program-level Allocation objects in + // allocations_. + std::vector + loop_optimized_allocations_; + // A map to look up the loop-optimized allocation info by use. + absl::flat_hash_map + loop_optimized_allocations_map_; + // A map to look the operands of each instruction that are assigned in + // alternate memory. + absl::flat_hash_map>> + operands_in_alternate_memory_map_; + // A map to look the outputs of each instruction that are assigned in + // alternate memory. + absl::flat_hash_map> + outputs_in_alternate_memory_map_; + // Debug strings. + std::string buffer_info_str_; + std::string allocation_info_str_; + std::string instruction_schedule_str_; +}; +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_MEMORY_SPACE_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..7d4d597a213719076e19ba910ccac3ef46a49144 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/memory_space_assignment.pb.h @@ -0,0 +1,590 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/memory_space_assignment/memory_space_assignment.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_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_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto; +namespace xla { +namespace memory_space_assignment { +class MemoryBoundLoopOptimizerOptions; +struct MemoryBoundLoopOptimizerOptionsDefaultTypeInternal; +extern MemoryBoundLoopOptimizerOptionsDefaultTypeInternal _MemoryBoundLoopOptimizerOptions_default_instance_; +class SlicedPrefetchOptions; +struct SlicedPrefetchOptionsDefaultTypeInternal; +extern SlicedPrefetchOptionsDefaultTypeInternal _SlicedPrefetchOptions_default_instance_; +} // namespace memory_space_assignment +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::memory_space_assignment::MemoryBoundLoopOptimizerOptions* Arena::CreateMaybeMessage<::xla::memory_space_assignment::MemoryBoundLoopOptimizerOptions>(Arena*); +template<> ::xla::memory_space_assignment::SlicedPrefetchOptions* Arena::CreateMaybeMessage<::xla::memory_space_assignment::SlicedPrefetchOptions>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace memory_space_assignment { + +// =================================================================== + +class SlicedPrefetchOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.memory_space_assignment.SlicedPrefetchOptions) */ { + public: + inline SlicedPrefetchOptions() : SlicedPrefetchOptions(nullptr) {} + ~SlicedPrefetchOptions() override; + explicit PROTOBUF_CONSTEXPR SlicedPrefetchOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + SlicedPrefetchOptions(const SlicedPrefetchOptions& from); + SlicedPrefetchOptions(SlicedPrefetchOptions&& from) noexcept + : SlicedPrefetchOptions() { + *this = ::std::move(from); + } + + inline SlicedPrefetchOptions& operator=(const SlicedPrefetchOptions& from) { + CopyFrom(from); + return *this; + } + inline SlicedPrefetchOptions& operator=(SlicedPrefetchOptions&& 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 SlicedPrefetchOptions& default_instance() { + return *internal_default_instance(); + } + static inline const SlicedPrefetchOptions* internal_default_instance() { + return reinterpret_cast( + &_SlicedPrefetchOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(SlicedPrefetchOptions& a, SlicedPrefetchOptions& b) { + a.Swap(&b); + } + inline void Swap(SlicedPrefetchOptions* 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(SlicedPrefetchOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + SlicedPrefetchOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const SlicedPrefetchOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const SlicedPrefetchOptions& from) { + SlicedPrefetchOptions::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(SlicedPrefetchOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.memory_space_assignment.SlicedPrefetchOptions"; + } + protected: + explicit SlicedPrefetchOptions(::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 { + kMinBytesFieldNumber = 2, + kMaxSlicesFieldNumber = 1, + kFailOnNonAlignmentBoundarySliceProposalFieldNumber = 3, + }; + // uint64 min_bytes = 2; + void clear_min_bytes(); + uint64_t min_bytes() const; + void set_min_bytes(uint64_t value); + private: + uint64_t _internal_min_bytes() const; + void _internal_set_min_bytes(uint64_t value); + public: + + // uint32 max_slices = 1; + void clear_max_slices(); + uint32_t max_slices() const; + void set_max_slices(uint32_t value); + private: + uint32_t _internal_max_slices() const; + void _internal_set_max_slices(uint32_t value); + public: + + // bool fail_on_non_alignment_boundary_slice_proposal = 3; + void clear_fail_on_non_alignment_boundary_slice_proposal(); + bool fail_on_non_alignment_boundary_slice_proposal() const; + void set_fail_on_non_alignment_boundary_slice_proposal(bool value); + private: + bool _internal_fail_on_non_alignment_boundary_slice_proposal() const; + void _internal_set_fail_on_non_alignment_boundary_slice_proposal(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.memory_space_assignment.SlicedPrefetchOptions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + uint64_t min_bytes_; + uint32_t max_slices_; + bool fail_on_non_alignment_boundary_slice_proposal_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto; +}; +// ------------------------------------------------------------------- + +class MemoryBoundLoopOptimizerOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions) */ { + public: + inline MemoryBoundLoopOptimizerOptions() : MemoryBoundLoopOptimizerOptions(nullptr) {} + ~MemoryBoundLoopOptimizerOptions() override; + explicit PROTOBUF_CONSTEXPR MemoryBoundLoopOptimizerOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + MemoryBoundLoopOptimizerOptions(const MemoryBoundLoopOptimizerOptions& from); + MemoryBoundLoopOptimizerOptions(MemoryBoundLoopOptimizerOptions&& from) noexcept + : MemoryBoundLoopOptimizerOptions() { + *this = ::std::move(from); + } + + inline MemoryBoundLoopOptimizerOptions& operator=(const MemoryBoundLoopOptimizerOptions& from) { + CopyFrom(from); + return *this; + } + inline MemoryBoundLoopOptimizerOptions& operator=(MemoryBoundLoopOptimizerOptions&& 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 MemoryBoundLoopOptimizerOptions& default_instance() { + return *internal_default_instance(); + } + static inline const MemoryBoundLoopOptimizerOptions* internal_default_instance() { + return reinterpret_cast( + &_MemoryBoundLoopOptimizerOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(MemoryBoundLoopOptimizerOptions& a, MemoryBoundLoopOptimizerOptions& b) { + a.Swap(&b); + } + inline void Swap(MemoryBoundLoopOptimizerOptions* 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(MemoryBoundLoopOptimizerOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + MemoryBoundLoopOptimizerOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const MemoryBoundLoopOptimizerOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const MemoryBoundLoopOptimizerOptions& from) { + MemoryBoundLoopOptimizerOptions::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(MemoryBoundLoopOptimizerOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions"; + } + protected: + explicit MemoryBoundLoopOptimizerOptions(::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 { + kDesiredCopyRatioFieldNumber = 2, + kEnabledFieldNumber = 1, + kAllowUnsatisfiedFullyPipelinedPrefetchFieldNumber = 3, + }; + // optional float desired_copy_ratio = 2; + bool has_desired_copy_ratio() const; + private: + bool _internal_has_desired_copy_ratio() const; + public: + void clear_desired_copy_ratio(); + float desired_copy_ratio() const; + void set_desired_copy_ratio(float value); + private: + float _internal_desired_copy_ratio() const; + void _internal_set_desired_copy_ratio(float value); + public: + + // optional bool enabled = 1; + bool has_enabled() const; + private: + bool _internal_has_enabled() const; + public: + void clear_enabled(); + bool enabled() const; + void set_enabled(bool value); + private: + bool _internal_enabled() const; + void _internal_set_enabled(bool value); + public: + + // optional bool allow_unsatisfied_fully_pipelined_prefetch = 3; + bool has_allow_unsatisfied_fully_pipelined_prefetch() const; + private: + bool _internal_has_allow_unsatisfied_fully_pipelined_prefetch() const; + public: + void clear_allow_unsatisfied_fully_pipelined_prefetch(); + bool allow_unsatisfied_fully_pipelined_prefetch() const; + void set_allow_unsatisfied_fully_pipelined_prefetch(bool value); + private: + bool _internal_allow_unsatisfied_fully_pipelined_prefetch() const; + void _internal_set_allow_unsatisfied_fully_pipelined_prefetch(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + float desired_copy_ratio_; + bool enabled_; + bool allow_unsatisfied_fully_pipelined_prefetch_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// SlicedPrefetchOptions + +// uint32 max_slices = 1; +inline void SlicedPrefetchOptions::clear_max_slices() { + _impl_.max_slices_ = 0u; +} +inline uint32_t SlicedPrefetchOptions::_internal_max_slices() const { + return _impl_.max_slices_; +} +inline uint32_t SlicedPrefetchOptions::max_slices() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.SlicedPrefetchOptions.max_slices) + return _internal_max_slices(); +} +inline void SlicedPrefetchOptions::_internal_set_max_slices(uint32_t value) { + + _impl_.max_slices_ = value; +} +inline void SlicedPrefetchOptions::set_max_slices(uint32_t value) { + _internal_set_max_slices(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.SlicedPrefetchOptions.max_slices) +} + +// uint64 min_bytes = 2; +inline void SlicedPrefetchOptions::clear_min_bytes() { + _impl_.min_bytes_ = uint64_t{0u}; +} +inline uint64_t SlicedPrefetchOptions::_internal_min_bytes() const { + return _impl_.min_bytes_; +} +inline uint64_t SlicedPrefetchOptions::min_bytes() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.SlicedPrefetchOptions.min_bytes) + return _internal_min_bytes(); +} +inline void SlicedPrefetchOptions::_internal_set_min_bytes(uint64_t value) { + + _impl_.min_bytes_ = value; +} +inline void SlicedPrefetchOptions::set_min_bytes(uint64_t value) { + _internal_set_min_bytes(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.SlicedPrefetchOptions.min_bytes) +} + +// bool fail_on_non_alignment_boundary_slice_proposal = 3; +inline void SlicedPrefetchOptions::clear_fail_on_non_alignment_boundary_slice_proposal() { + _impl_.fail_on_non_alignment_boundary_slice_proposal_ = false; +} +inline bool SlicedPrefetchOptions::_internal_fail_on_non_alignment_boundary_slice_proposal() const { + return _impl_.fail_on_non_alignment_boundary_slice_proposal_; +} +inline bool SlicedPrefetchOptions::fail_on_non_alignment_boundary_slice_proposal() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.SlicedPrefetchOptions.fail_on_non_alignment_boundary_slice_proposal) + return _internal_fail_on_non_alignment_boundary_slice_proposal(); +} +inline void SlicedPrefetchOptions::_internal_set_fail_on_non_alignment_boundary_slice_proposal(bool value) { + + _impl_.fail_on_non_alignment_boundary_slice_proposal_ = value; +} +inline void SlicedPrefetchOptions::set_fail_on_non_alignment_boundary_slice_proposal(bool value) { + _internal_set_fail_on_non_alignment_boundary_slice_proposal(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.SlicedPrefetchOptions.fail_on_non_alignment_boundary_slice_proposal) +} + +// ------------------------------------------------------------------- + +// MemoryBoundLoopOptimizerOptions + +// optional bool enabled = 1; +inline bool MemoryBoundLoopOptimizerOptions::_internal_has_enabled() const { + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + return value; +} +inline bool MemoryBoundLoopOptimizerOptions::has_enabled() const { + return _internal_has_enabled(); +} +inline void MemoryBoundLoopOptimizerOptions::clear_enabled() { + _impl_.enabled_ = false; + _impl_._has_bits_[0] &= ~0x00000002u; +} +inline bool MemoryBoundLoopOptimizerOptions::_internal_enabled() const { + return _impl_.enabled_; +} +inline bool MemoryBoundLoopOptimizerOptions::enabled() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.enabled) + return _internal_enabled(); +} +inline void MemoryBoundLoopOptimizerOptions::_internal_set_enabled(bool value) { + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.enabled_ = value; +} +inline void MemoryBoundLoopOptimizerOptions::set_enabled(bool value) { + _internal_set_enabled(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.enabled) +} + +// optional float desired_copy_ratio = 2; +inline bool MemoryBoundLoopOptimizerOptions::_internal_has_desired_copy_ratio() const { + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; + return value; +} +inline bool MemoryBoundLoopOptimizerOptions::has_desired_copy_ratio() const { + return _internal_has_desired_copy_ratio(); +} +inline void MemoryBoundLoopOptimizerOptions::clear_desired_copy_ratio() { + _impl_.desired_copy_ratio_ = 0; + _impl_._has_bits_[0] &= ~0x00000001u; +} +inline float MemoryBoundLoopOptimizerOptions::_internal_desired_copy_ratio() const { + return _impl_.desired_copy_ratio_; +} +inline float MemoryBoundLoopOptimizerOptions::desired_copy_ratio() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.desired_copy_ratio) + return _internal_desired_copy_ratio(); +} +inline void MemoryBoundLoopOptimizerOptions::_internal_set_desired_copy_ratio(float value) { + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.desired_copy_ratio_ = value; +} +inline void MemoryBoundLoopOptimizerOptions::set_desired_copy_ratio(float value) { + _internal_set_desired_copy_ratio(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.desired_copy_ratio) +} + +// optional bool allow_unsatisfied_fully_pipelined_prefetch = 3; +inline bool MemoryBoundLoopOptimizerOptions::_internal_has_allow_unsatisfied_fully_pipelined_prefetch() const { + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; + return value; +} +inline bool MemoryBoundLoopOptimizerOptions::has_allow_unsatisfied_fully_pipelined_prefetch() const { + return _internal_has_allow_unsatisfied_fully_pipelined_prefetch(); +} +inline void MemoryBoundLoopOptimizerOptions::clear_allow_unsatisfied_fully_pipelined_prefetch() { + _impl_.allow_unsatisfied_fully_pipelined_prefetch_ = false; + _impl_._has_bits_[0] &= ~0x00000004u; +} +inline bool MemoryBoundLoopOptimizerOptions::_internal_allow_unsatisfied_fully_pipelined_prefetch() const { + return _impl_.allow_unsatisfied_fully_pipelined_prefetch_; +} +inline bool MemoryBoundLoopOptimizerOptions::allow_unsatisfied_fully_pipelined_prefetch() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.allow_unsatisfied_fully_pipelined_prefetch) + return _internal_allow_unsatisfied_fully_pipelined_prefetch(); +} +inline void MemoryBoundLoopOptimizerOptions::_internal_set_allow_unsatisfied_fully_pipelined_prefetch(bool value) { + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.allow_unsatisfied_fully_pipelined_prefetch_ = value; +} +inline void MemoryBoundLoopOptimizerOptions::set_allow_unsatisfied_fully_pipelined_prefetch(bool value) { + _internal_set_allow_unsatisfied_fully_pipelined_prefetch(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.allow_unsatisfied_fully_pipelined_prefetch) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace memory_space_assignment +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/repacking.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/repacking.h new file mode 100644 index 0000000000000000000000000000000000000000..0379fc794832303147b4532219711141f4b1a603 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/repacking.h @@ -0,0 +1,165 @@ +/* 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_SERVICE_MEMORY_SPACE_ASSIGNMENT_REPACKING_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_REPACKING_H_ + +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/types/span.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { +namespace memory_space_assignment { + +// An interface to define allocation repacking algorithms. +class MemorySpaceAssignmentRepacker { + public: + MemorySpaceAssignmentRepacker(int64_t max_size, int64_t alignment) + : max_size_(max_size), alignment_(alignment) {} + virtual ~MemorySpaceAssignmentRepacker() = default; + + // Data about a slice in a sliced allocation. + struct Slice { + int64_t size; + int64_t offset; + int64_t start_time; + + std::string ToString() const { + return absl::StrCat("{ size: ", size, ", offset: ", offset, + ", start_time: ", start_time, " }"); + } + + std::tuple ToTuple() const { + return std::make_tuple(size, offset, start_time); + } + + bool operator==(const Slice& rhs) const { + return ToTuple() == rhs.ToTuple(); + } + }; + + // Slice data about a sliced allocation. + struct SlicedAllocationData { + std::vector slices_sorted_by_offset; + + std::vector SizesSortedByOffset() const { + std::vector sizes_sorted_by_offset; + sizes_sorted_by_offset.reserve(slices_sorted_by_offset.size()); + absl::c_for_each(slices_sorted_by_offset, + [&sizes_sorted_by_offset](const Slice& slice) { + sizes_sorted_by_offset.push_back(slice.size); + }); + return sizes_sorted_by_offset; + } + + std::vector SortedStartTimes() const { + std::vector sorted_start_times; + sorted_start_times.reserve(slices_sorted_by_offset.size()); + absl::c_for_each(slices_sorted_by_offset, + [&sorted_start_times](const Slice& slice) { + sorted_start_times.push_back(slice.start_time); + }); + absl::c_sort(sorted_start_times); + return sorted_start_times; + } + + std::string ToString() const { + return absl::StrCat( + "{ slices_sorted_by_offset: [ ", + absl::StrJoin(slices_sorted_by_offset, ", ", + [](std::string* out, const Slice& slice) { + absl::StrAppend(out, slice.ToString()); + }), + " ] }"); + } + + bool operator==(const SlicedAllocationData& rhs) const { + return slices_sorted_by_offset == rhs.slices_sorted_by_offset; + } + }; + + // A contiguous block of allocation consisting of start and end (logical) + // times, size, and the initial offset. After repacking, if the repacking was + // successful and the allocations were modified, the offset field holds the + // new offset. To support aliased allocations, AllocationBlock also includes a + // vector of AllocationBlock pointers, called colocations. All AllocationBlock + // objects within the colocations must get the same offset. The id should be + // unique and is used to ensure determinism for comparison tie-breaker. + // + // Each AllocationBlock can be treated as an allocation that requires size + // space from start_time to end_time. However, some allocations are really + // composed of slices. In such cases, the repacker can utilize + // the information in the original_slice_data field to achieve an even more + // efficient repacking. + struct AllocationBlock { + int64_t start_time; + int64_t end_time; + int64_t size; + int64_t offset; + int64_t initial_offset; + int64_t id; + std::vector colocations; + + // Optional data structures that are used to improve repacking, when an + // allocation is sliced, e.g., from a sliced prefetch. + std::optional original_slice_data; + std::optional repacked_slice_data; + + std::string ToString() const { + std::string original_slicing_str; + if (original_slice_data.has_value()) { + original_slicing_str = absl::StrCat("; original_slice_data: ", + original_slice_data->ToString()); + } + std::string repacked_slicing_str; + if (repacked_slice_data.has_value()) { + repacked_slicing_str = absl::StrCat("; repacked_slice_data: ", + repacked_slice_data->ToString()); + } + return absl::StrCat("[", start_time, ", ", end_time, "]; size: ", size, + "; offset: ", offset, + "; initial offset: ", initial_offset, + "; # colocations: ", colocations.size(), + original_slicing_str, repacked_slicing_str); + } + + // This is required by BufferIntervalCompare as a tie breaker. Use a unique + // and deterministic id. + bool operator<(const AllocationBlock& other) const { return id < other.id; } + }; + + // Repack the AllocationBlocks provided in the parameter. Returns true if + // allocations have been modified and false if not. Returns a non-ok status if + // there was an error. + virtual StatusOr Repack(absl::Span allocations) = 0; + + protected: + int64_t max_size_; + int64_t alignment_; +}; + +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_REPACKING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/tuning_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/tuning_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..749b4445e4be9afbd187115e3ee16711e4155b39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/tuning_utils.h @@ -0,0 +1,38 @@ +/* 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_SERVICE_MEMORY_SPACE_ASSIGNMENT_TUNING_UTILS_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_TUNING_UTILS_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/heap_simulator.h" + +namespace xla { + +namespace memory_space_assignment { + +using BufferInterval = + GlobalDecreasingSizeBestFitHeap::BufferInterval; + +// This function converts sorted_buffer_intervals to order-customized buffer +// intervals respecting a given memory space assignment autotuning config. +void CustomizeSortedBufferInterval( + std::optional> memory_space_assignment_config, + std::vector& sorted_buffer_intervals); + +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_TUNING_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..c2d76208a28e188c222031fd2e15031aaef9f392 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/memory_space_assignment/utils.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_MEMORY_SPACE_ASSIGNMENT_UTILS_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_UTILS_H_ + +#include "xla/service/heap_simulator.h" + +namespace xla { +namespace memory_space_assignment { + +// Encapsulates common utility methods for memory space assignment. +class MemorySpaceAssignmentUtils { + public: + // Returns true if this buffer is allowed to be placed in the alternate + // memory. + static bool IsIntervalAllowedInAlternateMemory( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& + interval); + + // Returns true if the HloValue is allowed to be placed in alternate memory. + static bool IsValueAllowedInAlternateMemory(const HloValue* value); +}; + +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/metrics.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/metrics.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..98ddf56e93b4a8b35579bf1849d5e2ec10125e9e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/metrics.pb.h @@ -0,0 +1,974 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/metrics.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmetrics_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmetrics_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 +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fmetrics_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fmetrics_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fmetrics_2eproto; +namespace xla { +class CompilationLogEntry; +struct CompilationLogEntryDefaultTypeInternal; +extern CompilationLogEntryDefaultTypeInternal _CompilationLogEntry_default_instance_; +class PassMetrics; +struct PassMetricsDefaultTypeInternal; +extern PassMetricsDefaultTypeInternal _PassMetrics_default_instance_; +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::CompilationLogEntry* Arena::CreateMaybeMessage<::xla::CompilationLogEntry>(Arena*); +template<> ::xla::PassMetrics* Arena::CreateMaybeMessage<::xla::PassMetrics>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { + +enum CompilationLogEntry_CompilationStage : int { + CompilationLogEntry_CompilationStage_UNSPECIFIED = 0, + CompilationLogEntry_CompilationStage_END_TO_END = 1, + CompilationLogEntry_CompilationStage_HLO_PASSES = 2, + CompilationLogEntry_CompilationStage_CODE_GENERATION = 3, + CompilationLogEntry_CompilationStage_BACKEND_PASSES = 4, + CompilationLogEntry_CompilationStage_CompilationLogEntry_CompilationStage_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + CompilationLogEntry_CompilationStage_CompilationLogEntry_CompilationStage_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool CompilationLogEntry_CompilationStage_IsValid(int value); +constexpr CompilationLogEntry_CompilationStage CompilationLogEntry_CompilationStage_CompilationStage_MIN = CompilationLogEntry_CompilationStage_UNSPECIFIED; +constexpr CompilationLogEntry_CompilationStage CompilationLogEntry_CompilationStage_CompilationStage_MAX = CompilationLogEntry_CompilationStage_BACKEND_PASSES; +constexpr int CompilationLogEntry_CompilationStage_CompilationStage_ARRAYSIZE = CompilationLogEntry_CompilationStage_CompilationStage_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CompilationLogEntry_CompilationStage_descriptor(); +template +inline const std::string& CompilationLogEntry_CompilationStage_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CompilationLogEntry_CompilationStage_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + CompilationLogEntry_CompilationStage_descriptor(), enum_t_value); +} +inline bool CompilationLogEntry_CompilationStage_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CompilationLogEntry_CompilationStage* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + CompilationLogEntry_CompilationStage_descriptor(), name, value); +} +// =================================================================== + +class PassMetrics final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.PassMetrics) */ { + public: + inline PassMetrics() : PassMetrics(nullptr) {} + ~PassMetrics() override; + explicit PROTOBUF_CONSTEXPR PassMetrics(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + PassMetrics(const PassMetrics& from); + PassMetrics(PassMetrics&& from) noexcept + : PassMetrics() { + *this = ::std::move(from); + } + + inline PassMetrics& operator=(const PassMetrics& from) { + CopyFrom(from); + return *this; + } + inline PassMetrics& operator=(PassMetrics&& 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 PassMetrics& default_instance() { + return *internal_default_instance(); + } + static inline const PassMetrics* internal_default_instance() { + return reinterpret_cast( + &_PassMetrics_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(PassMetrics& a, PassMetrics& b) { + a.Swap(&b); + } + inline void Swap(PassMetrics* 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(PassMetrics* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + PassMetrics* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const PassMetrics& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const PassMetrics& from) { + PassMetrics::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(PassMetrics* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.PassMetrics"; + } + protected: + explicit PassMetrics(::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 { + kPassNameFieldNumber = 2, + kPassDurationFieldNumber = 3, + kModuleIdFieldNumber = 1, + }; + // string pass_name = 2; + void clear_pass_name(); + const std::string& pass_name() const; + template + void set_pass_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_pass_name(); + PROTOBUF_NODISCARD std::string* release_pass_name(); + void set_allocated_pass_name(std::string* pass_name); + private: + const std::string& _internal_pass_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_pass_name(const std::string& value); + std::string* _internal_mutable_pass_name(); + public: + + // .google.protobuf.Duration pass_duration = 3; + bool has_pass_duration() const; + private: + bool _internal_has_pass_duration() const; + public: + void clear_pass_duration(); + const ::PROTOBUF_NAMESPACE_ID::Duration& pass_duration() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::Duration* release_pass_duration(); + ::PROTOBUF_NAMESPACE_ID::Duration* mutable_pass_duration(); + void set_allocated_pass_duration(::PROTOBUF_NAMESPACE_ID::Duration* pass_duration); + private: + const ::PROTOBUF_NAMESPACE_ID::Duration& _internal_pass_duration() const; + ::PROTOBUF_NAMESPACE_ID::Duration* _internal_mutable_pass_duration(); + public: + void unsafe_arena_set_allocated_pass_duration( + ::PROTOBUF_NAMESPACE_ID::Duration* pass_duration); + ::PROTOBUF_NAMESPACE_ID::Duration* unsafe_arena_release_pass_duration(); + + // int64 module_id = 1; + void clear_module_id(); + int64_t module_id() const; + void set_module_id(int64_t value); + private: + int64_t _internal_module_id() const; + void _internal_set_module_id(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.PassMetrics) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr pass_name_; + ::PROTOBUF_NAMESPACE_ID::Duration* pass_duration_; + int64_t module_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fmetrics_2eproto; +}; +// ------------------------------------------------------------------- + +class CompilationLogEntry final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.CompilationLogEntry) */ { + public: + inline CompilationLogEntry() : CompilationLogEntry(nullptr) {} + ~CompilationLogEntry() override; + explicit PROTOBUF_CONSTEXPR CompilationLogEntry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CompilationLogEntry(const CompilationLogEntry& from); + CompilationLogEntry(CompilationLogEntry&& from) noexcept + : CompilationLogEntry() { + *this = ::std::move(from); + } + + inline CompilationLogEntry& operator=(const CompilationLogEntry& from) { + CopyFrom(from); + return *this; + } + inline CompilationLogEntry& operator=(CompilationLogEntry&& 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 CompilationLogEntry& default_instance() { + return *internal_default_instance(); + } + static inline const CompilationLogEntry* internal_default_instance() { + return reinterpret_cast( + &_CompilationLogEntry_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(CompilationLogEntry& a, CompilationLogEntry& b) { + a.Swap(&b); + } + inline void Swap(CompilationLogEntry* 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(CompilationLogEntry* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CompilationLogEntry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CompilationLogEntry& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CompilationLogEntry& from) { + CompilationLogEntry::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(CompilationLogEntry* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.CompilationLogEntry"; + } + protected: + explicit CompilationLogEntry(::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 CompilationLogEntry_CompilationStage CompilationStage; + static constexpr CompilationStage UNSPECIFIED = + CompilationLogEntry_CompilationStage_UNSPECIFIED; + static constexpr CompilationStage END_TO_END = + CompilationLogEntry_CompilationStage_END_TO_END; + static constexpr CompilationStage HLO_PASSES = + CompilationLogEntry_CompilationStage_HLO_PASSES; + static constexpr CompilationStage CODE_GENERATION = + CompilationLogEntry_CompilationStage_CODE_GENERATION; + static constexpr CompilationStage BACKEND_PASSES = + CompilationLogEntry_CompilationStage_BACKEND_PASSES; + static inline bool CompilationStage_IsValid(int value) { + return CompilationLogEntry_CompilationStage_IsValid(value); + } + static constexpr CompilationStage CompilationStage_MIN = + CompilationLogEntry_CompilationStage_CompilationStage_MIN; + static constexpr CompilationStage CompilationStage_MAX = + CompilationLogEntry_CompilationStage_CompilationStage_MAX; + static constexpr int CompilationStage_ARRAYSIZE = + CompilationLogEntry_CompilationStage_CompilationStage_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + CompilationStage_descriptor() { + return CompilationLogEntry_CompilationStage_descriptor(); + } + template + static inline const std::string& CompilationStage_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CompilationStage_Name."); + return CompilationLogEntry_CompilationStage_Name(enum_t_value); + } + static inline bool CompilationStage_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + CompilationStage* value) { + return CompilationLogEntry_CompilationStage_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kPassMetricsFieldNumber = 5, + kTimestampFieldNumber = 1, + kDurationFieldNumber = 3, + kStageFieldNumber = 2, + kTaskIndexFieldNumber = 4, + }; + // repeated .xla.PassMetrics pass_metrics = 5; + int pass_metrics_size() const; + private: + int _internal_pass_metrics_size() const; + public: + void clear_pass_metrics(); + ::xla::PassMetrics* mutable_pass_metrics(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::PassMetrics >* + mutable_pass_metrics(); + private: + const ::xla::PassMetrics& _internal_pass_metrics(int index) const; + ::xla::PassMetrics* _internal_add_pass_metrics(); + public: + const ::xla::PassMetrics& pass_metrics(int index) const; + ::xla::PassMetrics* add_pass_metrics(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::PassMetrics >& + pass_metrics() const; + + // .google.protobuf.Timestamp timestamp = 1; + bool has_timestamp() const; + private: + bool _internal_has_timestamp() const; + public: + void clear_timestamp(); + const ::PROTOBUF_NAMESPACE_ID::Timestamp& timestamp() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::Timestamp* release_timestamp(); + ::PROTOBUF_NAMESPACE_ID::Timestamp* mutable_timestamp(); + void set_allocated_timestamp(::PROTOBUF_NAMESPACE_ID::Timestamp* timestamp); + private: + const ::PROTOBUF_NAMESPACE_ID::Timestamp& _internal_timestamp() const; + ::PROTOBUF_NAMESPACE_ID::Timestamp* _internal_mutable_timestamp(); + public: + void unsafe_arena_set_allocated_timestamp( + ::PROTOBUF_NAMESPACE_ID::Timestamp* timestamp); + ::PROTOBUF_NAMESPACE_ID::Timestamp* unsafe_arena_release_timestamp(); + + // .google.protobuf.Duration duration = 3; + bool has_duration() const; + private: + bool _internal_has_duration() const; + public: + void clear_duration(); + const ::PROTOBUF_NAMESPACE_ID::Duration& duration() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::Duration* release_duration(); + ::PROTOBUF_NAMESPACE_ID::Duration* mutable_duration(); + void set_allocated_duration(::PROTOBUF_NAMESPACE_ID::Duration* duration); + private: + const ::PROTOBUF_NAMESPACE_ID::Duration& _internal_duration() const; + ::PROTOBUF_NAMESPACE_ID::Duration* _internal_mutable_duration(); + public: + void unsafe_arena_set_allocated_duration( + ::PROTOBUF_NAMESPACE_ID::Duration* duration); + ::PROTOBUF_NAMESPACE_ID::Duration* unsafe_arena_release_duration(); + + // .xla.CompilationLogEntry.CompilationStage stage = 2; + void clear_stage(); + ::xla::CompilationLogEntry_CompilationStage stage() const; + void set_stage(::xla::CompilationLogEntry_CompilationStage value); + private: + ::xla::CompilationLogEntry_CompilationStage _internal_stage() const; + void _internal_set_stage(::xla::CompilationLogEntry_CompilationStage value); + public: + + // int32 task_index = 4; + void clear_task_index(); + int32_t task_index() const; + void set_task_index(int32_t value); + private: + int32_t _internal_task_index() const; + void _internal_set_task_index(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.CompilationLogEntry) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::PassMetrics > pass_metrics_; + ::PROTOBUF_NAMESPACE_ID::Timestamp* timestamp_; + ::PROTOBUF_NAMESPACE_ID::Duration* duration_; + int stage_; + int32_t task_index_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fmetrics_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// PassMetrics + +// int64 module_id = 1; +inline void PassMetrics::clear_module_id() { + _impl_.module_id_ = int64_t{0}; +} +inline int64_t PassMetrics::_internal_module_id() const { + return _impl_.module_id_; +} +inline int64_t PassMetrics::module_id() const { + // @@protoc_insertion_point(field_get:xla.PassMetrics.module_id) + return _internal_module_id(); +} +inline void PassMetrics::_internal_set_module_id(int64_t value) { + + _impl_.module_id_ = value; +} +inline void PassMetrics::set_module_id(int64_t value) { + _internal_set_module_id(value); + // @@protoc_insertion_point(field_set:xla.PassMetrics.module_id) +} + +// string pass_name = 2; +inline void PassMetrics::clear_pass_name() { + _impl_.pass_name_.ClearToEmpty(); +} +inline const std::string& PassMetrics::pass_name() const { + // @@protoc_insertion_point(field_get:xla.PassMetrics.pass_name) + return _internal_pass_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void PassMetrics::set_pass_name(ArgT0&& arg0, ArgT... args) { + + _impl_.pass_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.PassMetrics.pass_name) +} +inline std::string* PassMetrics::mutable_pass_name() { + std::string* _s = _internal_mutable_pass_name(); + // @@protoc_insertion_point(field_mutable:xla.PassMetrics.pass_name) + return _s; +} +inline const std::string& PassMetrics::_internal_pass_name() const { + return _impl_.pass_name_.Get(); +} +inline void PassMetrics::_internal_set_pass_name(const std::string& value) { + + _impl_.pass_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* PassMetrics::_internal_mutable_pass_name() { + + return _impl_.pass_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* PassMetrics::release_pass_name() { + // @@protoc_insertion_point(field_release:xla.PassMetrics.pass_name) + return _impl_.pass_name_.Release(); +} +inline void PassMetrics::set_allocated_pass_name(std::string* pass_name) { + if (pass_name != nullptr) { + + } else { + + } + _impl_.pass_name_.SetAllocated(pass_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.pass_name_.IsDefault()) { + _impl_.pass_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.PassMetrics.pass_name) +} + +// .google.protobuf.Duration pass_duration = 3; +inline bool PassMetrics::_internal_has_pass_duration() const { + return this != internal_default_instance() && _impl_.pass_duration_ != nullptr; +} +inline bool PassMetrics::has_pass_duration() const { + return _internal_has_pass_duration(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Duration& PassMetrics::_internal_pass_duration() const { + const ::PROTOBUF_NAMESPACE_ID::Duration* p = _impl_.pass_duration_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_Duration_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::Duration& PassMetrics::pass_duration() const { + // @@protoc_insertion_point(field_get:xla.PassMetrics.pass_duration) + return _internal_pass_duration(); +} +inline void PassMetrics::unsafe_arena_set_allocated_pass_duration( + ::PROTOBUF_NAMESPACE_ID::Duration* pass_duration) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.pass_duration_); + } + _impl_.pass_duration_ = pass_duration; + if (pass_duration) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.PassMetrics.pass_duration) +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* PassMetrics::release_pass_duration() { + + ::PROTOBUF_NAMESPACE_ID::Duration* temp = _impl_.pass_duration_; + _impl_.pass_duration_ = 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* PassMetrics::unsafe_arena_release_pass_duration() { + // @@protoc_insertion_point(field_release:xla.PassMetrics.pass_duration) + + ::PROTOBUF_NAMESPACE_ID::Duration* temp = _impl_.pass_duration_; + _impl_.pass_duration_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* PassMetrics::_internal_mutable_pass_duration() { + + if (_impl_.pass_duration_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Duration>(GetArenaForAllocation()); + _impl_.pass_duration_ = p; + } + return _impl_.pass_duration_; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* PassMetrics::mutable_pass_duration() { + ::PROTOBUF_NAMESPACE_ID::Duration* _msg = _internal_mutable_pass_duration(); + // @@protoc_insertion_point(field_mutable:xla.PassMetrics.pass_duration) + return _msg; +} +inline void PassMetrics::set_allocated_pass_duration(::PROTOBUF_NAMESPACE_ID::Duration* pass_duration) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.pass_duration_); + } + if (pass_duration) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(pass_duration)); + if (message_arena != submessage_arena) { + pass_duration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, pass_duration, submessage_arena); + } + + } else { + + } + _impl_.pass_duration_ = pass_duration; + // @@protoc_insertion_point(field_set_allocated:xla.PassMetrics.pass_duration) +} + +// ------------------------------------------------------------------- + +// CompilationLogEntry + +// .google.protobuf.Timestamp timestamp = 1; +inline bool CompilationLogEntry::_internal_has_timestamp() const { + return this != internal_default_instance() && _impl_.timestamp_ != nullptr; +} +inline bool CompilationLogEntry::has_timestamp() const { + return _internal_has_timestamp(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Timestamp& CompilationLogEntry::_internal_timestamp() const { + const ::PROTOBUF_NAMESPACE_ID::Timestamp* p = _impl_.timestamp_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::Timestamp& CompilationLogEntry::timestamp() const { + // @@protoc_insertion_point(field_get:xla.CompilationLogEntry.timestamp) + return _internal_timestamp(); +} +inline void CompilationLogEntry::unsafe_arena_set_allocated_timestamp( + ::PROTOBUF_NAMESPACE_ID::Timestamp* timestamp) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.timestamp_); + } + _impl_.timestamp_ = timestamp; + if (timestamp) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.CompilationLogEntry.timestamp) +} +inline ::PROTOBUF_NAMESPACE_ID::Timestamp* CompilationLogEntry::release_timestamp() { + + ::PROTOBUF_NAMESPACE_ID::Timestamp* temp = _impl_.timestamp_; + _impl_.timestamp_ = 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::Timestamp* CompilationLogEntry::unsafe_arena_release_timestamp() { + // @@protoc_insertion_point(field_release:xla.CompilationLogEntry.timestamp) + + ::PROTOBUF_NAMESPACE_ID::Timestamp* temp = _impl_.timestamp_; + _impl_.timestamp_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Timestamp* CompilationLogEntry::_internal_mutable_timestamp() { + + if (_impl_.timestamp_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Timestamp>(GetArenaForAllocation()); + _impl_.timestamp_ = p; + } + return _impl_.timestamp_; +} +inline ::PROTOBUF_NAMESPACE_ID::Timestamp* CompilationLogEntry::mutable_timestamp() { + ::PROTOBUF_NAMESPACE_ID::Timestamp* _msg = _internal_mutable_timestamp(); + // @@protoc_insertion_point(field_mutable:xla.CompilationLogEntry.timestamp) + return _msg; +} +inline void CompilationLogEntry::set_allocated_timestamp(::PROTOBUF_NAMESPACE_ID::Timestamp* timestamp) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.timestamp_); + } + if (timestamp) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(timestamp)); + if (message_arena != submessage_arena) { + timestamp = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, timestamp, submessage_arena); + } + + } else { + + } + _impl_.timestamp_ = timestamp; + // @@protoc_insertion_point(field_set_allocated:xla.CompilationLogEntry.timestamp) +} + +// .xla.CompilationLogEntry.CompilationStage stage = 2; +inline void CompilationLogEntry::clear_stage() { + _impl_.stage_ = 0; +} +inline ::xla::CompilationLogEntry_CompilationStage CompilationLogEntry::_internal_stage() const { + return static_cast< ::xla::CompilationLogEntry_CompilationStage >(_impl_.stage_); +} +inline ::xla::CompilationLogEntry_CompilationStage CompilationLogEntry::stage() const { + // @@protoc_insertion_point(field_get:xla.CompilationLogEntry.stage) + return _internal_stage(); +} +inline void CompilationLogEntry::_internal_set_stage(::xla::CompilationLogEntry_CompilationStage value) { + + _impl_.stage_ = value; +} +inline void CompilationLogEntry::set_stage(::xla::CompilationLogEntry_CompilationStage value) { + _internal_set_stage(value); + // @@protoc_insertion_point(field_set:xla.CompilationLogEntry.stage) +} + +// .google.protobuf.Duration duration = 3; +inline bool CompilationLogEntry::_internal_has_duration() const { + return this != internal_default_instance() && _impl_.duration_ != nullptr; +} +inline bool CompilationLogEntry::has_duration() const { + return _internal_has_duration(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Duration& CompilationLogEntry::_internal_duration() const { + const ::PROTOBUF_NAMESPACE_ID::Duration* p = _impl_.duration_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_Duration_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::Duration& CompilationLogEntry::duration() const { + // @@protoc_insertion_point(field_get:xla.CompilationLogEntry.duration) + return _internal_duration(); +} +inline void CompilationLogEntry::unsafe_arena_set_allocated_duration( + ::PROTOBUF_NAMESPACE_ID::Duration* duration) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.duration_); + } + _impl_.duration_ = duration; + if (duration) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.CompilationLogEntry.duration) +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* CompilationLogEntry::release_duration() { + + ::PROTOBUF_NAMESPACE_ID::Duration* temp = _impl_.duration_; + _impl_.duration_ = 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* CompilationLogEntry::unsafe_arena_release_duration() { + // @@protoc_insertion_point(field_release:xla.CompilationLogEntry.duration) + + ::PROTOBUF_NAMESPACE_ID::Duration* temp = _impl_.duration_; + _impl_.duration_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* CompilationLogEntry::_internal_mutable_duration() { + + if (_impl_.duration_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Duration>(GetArenaForAllocation()); + _impl_.duration_ = p; + } + return _impl_.duration_; +} +inline ::PROTOBUF_NAMESPACE_ID::Duration* CompilationLogEntry::mutable_duration() { + ::PROTOBUF_NAMESPACE_ID::Duration* _msg = _internal_mutable_duration(); + // @@protoc_insertion_point(field_mutable:xla.CompilationLogEntry.duration) + return _msg; +} +inline void CompilationLogEntry::set_allocated_duration(::PROTOBUF_NAMESPACE_ID::Duration* duration) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.duration_); + } + if (duration) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(duration)); + if (message_arena != submessage_arena) { + duration = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, duration, submessage_arena); + } + + } else { + + } + _impl_.duration_ = duration; + // @@protoc_insertion_point(field_set_allocated:xla.CompilationLogEntry.duration) +} + +// int32 task_index = 4; +inline void CompilationLogEntry::clear_task_index() { + _impl_.task_index_ = 0; +} +inline int32_t CompilationLogEntry::_internal_task_index() const { + return _impl_.task_index_; +} +inline int32_t CompilationLogEntry::task_index() const { + // @@protoc_insertion_point(field_get:xla.CompilationLogEntry.task_index) + return _internal_task_index(); +} +inline void CompilationLogEntry::_internal_set_task_index(int32_t value) { + + _impl_.task_index_ = value; +} +inline void CompilationLogEntry::set_task_index(int32_t value) { + _internal_set_task_index(value); + // @@protoc_insertion_point(field_set:xla.CompilationLogEntry.task_index) +} + +// repeated .xla.PassMetrics pass_metrics = 5; +inline int CompilationLogEntry::_internal_pass_metrics_size() const { + return _impl_.pass_metrics_.size(); +} +inline int CompilationLogEntry::pass_metrics_size() const { + return _internal_pass_metrics_size(); +} +inline void CompilationLogEntry::clear_pass_metrics() { + _impl_.pass_metrics_.Clear(); +} +inline ::xla::PassMetrics* CompilationLogEntry::mutable_pass_metrics(int index) { + // @@protoc_insertion_point(field_mutable:xla.CompilationLogEntry.pass_metrics) + return _impl_.pass_metrics_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::PassMetrics >* +CompilationLogEntry::mutable_pass_metrics() { + // @@protoc_insertion_point(field_mutable_list:xla.CompilationLogEntry.pass_metrics) + return &_impl_.pass_metrics_; +} +inline const ::xla::PassMetrics& CompilationLogEntry::_internal_pass_metrics(int index) const { + return _impl_.pass_metrics_.Get(index); +} +inline const ::xla::PassMetrics& CompilationLogEntry::pass_metrics(int index) const { + // @@protoc_insertion_point(field_get:xla.CompilationLogEntry.pass_metrics) + return _internal_pass_metrics(index); +} +inline ::xla::PassMetrics* CompilationLogEntry::_internal_add_pass_metrics() { + return _impl_.pass_metrics_.Add(); +} +inline ::xla::PassMetrics* CompilationLogEntry::add_pass_metrics() { + ::xla::PassMetrics* _add = _internal_add_pass_metrics(); + // @@protoc_insertion_point(field_add:xla.CompilationLogEntry.pass_metrics) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::PassMetrics >& +CompilationLogEntry::pass_metrics() const { + // @@protoc_insertion_point(field_list:xla.CompilationLogEntry.pass_metrics) + return _impl_.pass_metrics_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace xla + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::xla::CompilationLogEntry_CompilationStage> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::xla::CompilationLogEntry_CompilationStage>() { + return ::xla::CompilationLogEntry_CompilationStage_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmetrics_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/metrics_hook_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/metrics_hook_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..bf364611373765bc4d996970ed5b14a74658952d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/metrics_hook_interface.h @@ -0,0 +1,58 @@ +/* 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_SERVICE_METRICS_HOOK_INTERFACE_H_ +#define XLA_SERVICE_METRICS_HOOK_INTERFACE_H_ + +#include "absl/strings/string_view.h" +#include "absl/time/time.h" +#include "xla/service/metrics.pb.h" + +namespace xla { + +// MetricsHookInterface is an abstract interface for compiler backends to record +// stages of their compilation process. + +class MetricsHookInterface { + public: + virtual ~MetricsHookInterface() = default; + // Used to record instance of a successful XLA compilation pass happening + // under a stage + virtual void RecordStagePassCount(absl::string_view stage, + absl::string_view pass) const = 0; + + // Used to record instance of an error with error_status happening under an + // XLA compilation stage and pass + virtual void RecordStagePassError(absl::string_view stage, + absl::string_view pass, + absl::string_view error_status) const = 0; + + // Used to record instance of a successful XLA compilation stage that does not + // encompass its own passes (empty pass field). + virtual void RecordStageCount(absl::string_view stage) const = 0; + + // Used to record instance of an error with error_status happening under an + // XLA compilation stage (empty pass field) + virtual void RecordStageError(absl::string_view stage, + absl::string_view error_status) const = 0; + + // Captures metrics for a given XLA compilation stage. The `pass_metrics` can + // be empty if no pass specific metrics are available. + virtual void RecordCompilationMetrics( + CompilationLogEntry::CompilationStage stage, absl::Duration latency, + absl::Span pass_metrics) const = 0; +}; +} // namespace xla +#endif // XLA_SERVICE_METRICS_HOOK_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/name_uniquer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/name_uniquer.h new file mode 100644 index 0000000000000000000000000000000000000000..88adc5ce0b6a36a8198aab89f1abde29716e6477 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/name_uniquer.h @@ -0,0 +1,88 @@ +/* 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_SERVICE_NAME_UNIQUER_H_ +#define XLA_SERVICE_NAME_UNIQUER_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/types.h" + +namespace xla { + +// Simple stateful class that helps generate "unique" names. To use it, simply +// call GetUniqueName as many times as needed. The names returned by +// GetUniqueName are guaranteed to be distinct for this instance of the class. +// Note that the names will be sanitized to match regexp +// "[a-zA-Z_][a-zA-Z0-9_.-]*". +class NameUniquer { + public: + // The separator must contain allowed characters only: "[a-zA-Z0-9_.-]". + explicit NameUniquer(const std::string& separator = "__"); + + // Get a sanitized unique name in a string, with an optional prefix for + // convenience. + std::string GetUniqueName(absl::string_view prefix = ""); + + // Sanitizes and returns the name. Unallowed characters will be replaced with + // '_'. The result will match the regexp "[a-zA-Z_][a-zA-Z0-9_.-]*". + static std::string GetSanitizedName(absl::string_view name); + + private: + // Used to track and generate new identifiers for the same instruction name + // root. + class SequentialIdGenerator { + public: + SequentialIdGenerator() = default; + + // Tries to register id as used identifier. If id is not already used, the + // id itself will be returned. Otherwise a new one will be generated, and + // returned. + int64_t RegisterId(int64_t id) { + if (used_.insert(id).second) { + return id; + } + while (!used_.insert(next_).second) { + ++next_; + } + return next_++; + } + + private: + // The next identifier to be tried. + int64_t next_ = 0; + + // Set of all the identifiers which has been used. + absl::flat_hash_set used_; + }; + + // The string to use to separate the prefix of the name from the uniquing + // integer value. + std::string separator_; + + // Map from name prefix to the generator data structure which tracks used + // identifiers and generates new ones. + absl::flat_hash_map generated_names_; + + NameUniquer(const NameUniquer&) = delete; + NameUniquer& operator=(const NameUniquer&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_NAME_UNIQUER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/op_expander_pass.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/op_expander_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..ff99b1dd51b91a45529e8975def3ef46a42516d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/op_expander_pass.h @@ -0,0 +1,55 @@ +/* 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_SERVICE_OP_EXPANDER_PASS_H_ +#define XLA_SERVICE_OP_EXPANDER_PASS_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This pass is an abstract superclass for passes that replace operations that +// match a pattern. It is intended to be subclassed, not used directly. +// +// This pass is useful for legalizing HLO instructions that a particular backend +// does not support into other HLO instructions. +class OpExpanderPass : public HloModulePass { + public: + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // extra_filter: Optional extra filtering criteria for matching instructions, + // used in conjunction with InstructionMatchesPattern. + explicit OpExpanderPass(HloPredicate extra_filter = nullptr) + : extra_filter_(std::move(extra_filter)) {} + + protected: + // Returns `true` if `instruction` should be expanded by this pass. + virtual bool InstructionMatchesPattern(HloInstruction* instruction) = 0; + + // Returns a replacement for `instruction`, or nullptr if no replacement is + // needed (e.g. only the to_apply subcomputation of the instruction was + // modified). + virtual StatusOr ExpandInstruction( + HloInstruction* instruction) = 0; + + HloPredicate extra_filter_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_OP_EXPANDER_PASS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/operand_upcaster.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/operand_upcaster.h new file mode 100644 index 0000000000000000000000000000000000000000..8261ae2987f3929dfb7a8b89c0dbda6cfa3901a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/operand_upcaster.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_OPERAND_UPCASTER_H_ +#define XLA_SERVICE_OPERAND_UPCASTER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// Inserts Convert to operands of instructions that allows result accumulation +// as wider integral types. +class OperandUpcaster : public OpExpanderPass { + public: + explicit OperandUpcaster(HloPredicate extra_filter = nullptr) + : OpExpanderPass(std::move(extra_filter)) {} + + absl::string_view name() const override { return "operand_upcaster"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_OPERAND_UPCASTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/optimization_barrier_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/optimization_barrier_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..50c148dfc0da7a13fc55e53c0ba9bc46c8ec5140 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/optimization_barrier_expander.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_OPTIMIZATION_BARRIER_EXPANDER_H_ +#define XLA_SERVICE_OPTIMIZATION_BARRIER_EXPANDER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// This pass removes the opt-barrier operation which is functionally a no-op. +class OptimizationBarrierExpander : public HloModulePass { + public: + OptimizationBarrierExpander() = default; + + absl::string_view name() const override { return "cse_barrier_expander"; } + + protected: + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_OPTIMIZATION_BARRIER_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/p2p_schedule_preparation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/p2p_schedule_preparation.h new file mode 100644 index 0000000000000000000000000000000000000000..d0823224eb9d06e7a94c09463d6f2e31b25192d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/p2p_schedule_preparation.h @@ -0,0 +1,174 @@ +/* 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_SERVICE_P2P_SCHEDULE_PREPARATION_H_ +#define XLA_SERVICE_P2P_SCHEDULE_PREPARATION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// P2PSchedulePreparation is a pass to linearize point-to-point operation chain +// to prepare for any HLO scheduler. In particular, this pass currently does the +// following: +// (1) For an unpipelined P2P Send-Recv chain, add control dependence to +// express this ordering: +// recv => send => recv-done => send-done +// +// (2) For a pipelined P2P Send-Recv chain, add control dependence to the +// while-body to express this ordering: +// send => recv +// No control dependence are added to a pipelined Send-Recv in the +// computation with the while-loop as the data dependence already expresses +// this ordering: +// recv => recv-done => while-loop => send => send-done. +// +// (3) For a pipelined P2P Send-Recv chain, if the while-body has other P2P +// chains, we need to add control dependence to ensure that the pipelined +// Send-done is ordered before other P2P chains while the pipelined +// Recv-done is ordered after other P2P chains. In particular, we make the +// pipelined Send-done the control predecessor of other Recv and the pipelined +// Recv the control successor of other Send-done. Here is an example to +// illustrate the problem we address: +// +// Assume a while-body with the following HLO collective-permute operations: +// collective-permute-start-1 = (u32[2], u32[2]) +// collective-permute-start(data), channel_id=1... +// collective-permute-done-1 = u32[2], channel_id=1 +// use of collective-permute-done-1 result +// collective-permute-start-2 = (u32[2], u32[2]) +// collective-permute-start(data), channel_id=2... +// collective-permute-done-2 = u32[2], channel_id=2 +// use of collective-permute-done-2 result +// +// Now assume we transform the collective-permute operations into two P2P +// Send-Recv chains, the block of code will become something like this: +// after-all-1 = token[] after-all() +// recv-1 = (u32[2], token[]) recv(after-all-1), channel_id=1 ... +// send-1 = (u32[2], token[]) send(data, after-all-1), channel_id=1 ... +// recv-done-1 = (u32[2], token[]) recv-done(recv-1), channel_id=1 ... +// send-done-1 = token[] send-done(send-1), channel_id=1 ... +// use of recv-done-1 result +// after-all-2 = token[] after-all() +// recv-2 = (u32[2], token[]) recv(after-all-2), channel_id=2 ... +// send-2 = (u32[2], token[]) send(data, after-all-2), channel_id=2 ... +// recv-done-2 = (u32[2], token[]) recv-done(recv-2), channel_id=2 ... +// send-done-2 = token[] send-done(send-2), channel_id=2 ... +// use of recv-done-2 result +// +// If the while-loop is not pipelined, this pass adds control dependence to +// make sure the first Send-Recv chain finish before the second Send-Recv +// starts. +// +// If the while-loop is pipelined for the first Send-Recv chain, then the +// first Recv and the last Send of the chain are moved to the computation +// that calls the while-loop, and the block of code in the while-body will +// become something like this: + +// after-all-1 = token[] after-all() +// send-1 = (u32[2], token[]) send(data, after-all-1), channel_id=1 ... +// send-done-1 = token[] send-done(send-1), channel_id=1 ... +// use of recv-done-1 result from the previous iteration or the computation +// that calls the while-loop (for the first iteration) +// +// after-all-2 = token[] after-all() +// recv-2 = (u32[2], token[]) recv(after-all-2), channel_id=2 ... +// send-2 = (u32[2], token[]) send(data, after-all-2), channel_id=2 ... +// recv-done-2 = (u32[2], token[]) recv-done(recv-2), channel_id=2 ... +// send-done-2 = token[] send-done(send-2), channel_id=2 ... +// use of recv-done-2 result +// +// recv-1 = (u32[2], token[]) recv(after-all-1), channel_id=1 ... +// recv-done-1 = (u32[2], token[]) recv-done(recv-1), channel_id=1 ... +// +// In this case, we make send-done-1 the control predecessor of recv-2 and +// send-done-2 the control predecessor of recv-1 to ensure that the second +// Send-Recv chain is executed after the Send for the first chain finishes and +// before the Recv for the first chain starts. +// +// (4) Adds control prececessors/successors to ensure that a P2P Send-Recv +// sequence on a non-host device will be scheduled before other operations that +// use the Recv result and may also invoke P2P operations indirectly. Here is an +// example to illustrate the problem we address: +// +// Assume a computation with the following HLO instructions, where while-body +// invokes collective-permute operations: +// collective-permute-start = (u32[2], u32[2]) +// collective-permute-start(data) ... +// collective-permute-done = u32[2] +// collective-permute-done(collective-permute-start) +// while-init = (u32[], u32[2]) tuple(c0, collective-permute-done) +// while-result = (u32[], u32[2]) while(while-init), +// body=while-body, condition=while-cond +// +// Without collective-permute-decomposer transformation, LHS will Schedule +// while-result after collective-permute-start without any problem. +// +// Now assume we transform the collective-permute operations in the computation +// as well as inside the while-body into a sequence of P2P Send-Recv sequence, +// the computation will become something like this: +// after-all = token[] after-all() +// recv = (u32[2], token[]) recv(after-all) ... +// send = (u32[2], token[]) send(data, after-all), +// control-predecessors={recv} ... +// recv-done = (u32[2], token[]) recv-done(recv), +// control-predecessors={send} ... +// send-done = token[] send-done(send), +// control-predecessors={recv-done} ... +// recv-data = u32[2] get-tuple-element(recv-done), index=0 +// while-init = (u32[], u32[2]) tuple(c0, recv-data) +// while-result = (u32[], u32[2]) while(while_init), +// body=while_body, condition=while_cond +// +// When scheduling this computation in a bottom up fashion, the LHS will reach a +// point where both while-result and send-done are in the ready queue. If LHS +// picks send-done over while-result, the scheduler is stuck because +// while-result can't be scheduled when the Send-Recv chain is holding the +// resources for P2P operations and recv-done cannot be scheduled as well +// because while-result depends on while-init which depends on recv-done. To +// avoid this deadlock, we make send-done a control predecessor of recv-data +// in this pass. +// +// Note that instead of making send-done a control predecessor of recv-data, we +// may make send-done a control predecessor of the instruction that contains +// the nested P2P operations, which is while-result in this example. This allows +// recv-data and while-init to be scheduled before send-done. However, doing so +// would complicate the implementation. We leave this to future improvement if +// we will find out it can actually help performance in real practice. +// +// (4) Similar to case (3), if the result of the while-loop with pipelined P2P +// chain is used by an instruction with nested P2P chains, we meed to schedule +// send-done of the pipelined while-loop before the instruction to avoid +// deadlock. We express this by making the send-done a control predecessor of +// the get-tuple-element instruction that retrieve the while-loop result. +// +class P2PSchedulePreparation : public HloModulePass { + public: + absl::string_view name() const override { + return "latency-hiding-scheduler-preparation"; + } + + using HloPassInterface::Run; + // Runs P2PSchedulePreparation pass on computations in 'module'. + // Returns whether the 'module' was changed. + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_P2P_SCHEDULE_PREPARATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/pattern_matcher.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/pattern_matcher.h new file mode 100644 index 0000000000000000000000000000000000000000..041d500006ad53b543ffe1ec0d2075bedea4624e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/pattern_matcher.h @@ -0,0 +1,2989 @@ +/* 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_SERVICE_PATTERN_MATCHER_H_ +#define XLA_SERVICE_PATTERN_MATCHER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/strings/str_replace.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "absl/utility/utility.h" +#include "xla/hlo/ir/hlo_casting_utils.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/layout_util.h" +#include "xla/literal_util.h" +#include "xla/service/hlo_parser.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// A pattern matcher for HloInstructions, Shapes, and Layouts. +// +// The Match function's first argument must be HloInstruction*, Shape*, or +// Layout*. The second argument is a pattern that will be matched against the +// first argument, as described below. +// +// Patterns are constructed using the match::Op, match::Shape, or match::Layout +// functions. By default, the returned patterns will match any HloInstruction, +// Shape, or Layout, respectively. However the match can be made more specific +// by using the pattern's modifier methods, for example: +// +// match::Op().WithOpcode(HloOpcode::kAdd).WithOperand( +// 0, match::Op().WithOpcode(HloOpcode::kConstant)) +// +// This pattern will match Add instructions whose first operand is a constant. +// +// Each pattern type has the following modifiers, which are described where +// nontrivial. +// +// Op(): +// - Is: is the given HloInstruction* (i.e. pointer equality) +// - WithName +// - WithOpcode +// - WithoutOpcode: anything other than the given opcode +// - WithShape: instr's shape matches the given pattern +// - WithShapeEqualTo: instr's shape is equal to the given Shape +// - WithShapeCompatibleTo: instr's shape is compatible with the given Shape +// - WithElementType: instr.shape().element_type() matches the given type +// - WithNumOperands +// - WithOperand: operand at the given index matches the given pattern +// - WithOperandIfPresent: instr has fewer than i operands or the i'th one +// matches the given pattern +// - IsConstant +// - IsNonConstant +// - IsConstantScalar/IsEffectiveConstantScalar: Optionally accepts a value, +// e.g. IsConstantScalar() or IsConstantScalar(42). +// - WithFusionKind +// - WithTupleIndex: get-tuple-element operations with the given tuple index +// - WithOneUse: Instruction is used as an operand exactly once. +// - WithOneUser: Instruction is used by exactly one other instruction, but +// is possibly used more than once as an operand (e.g. multiply(x,x)). +// - WithComparisonDirection: instr has the given direction +// - WithConvDnums(string or proto): checks convolution_dimension_numbers(). +// - WithPredicate: Instruction matches an arbitrary function you pass. +// Function must have signature `bool(const HloInstruction*)`. +// - WithContractingDims: Dot instruction with specific LHS and RHS +// contracting dimensions. +// - WithReplicaGroups: Collective instruction's replica groups matches the +// given pattern. +// +// Shape(): +// - EqualTo +// - CompatibleTo +// - IsScalar/IsEffectiveScalar/IsArray/IsTuple +// - IsDenseArray +// - WithLayout: layout shape's layout matches the given pattern (e.g. +// - WithLayoutEqualTo: shape's layout equals the argument (i.e. another +// Layout, but not the result of Layout().foo()) +// - WithSubshape: shape is a tuple whose subshape matches the given pattern +// (e.g. Shape().IsScalar()). +// - WithSubshapeEqualTo: shape is a tuple with a subshape equal to the arg +// (i.e. another Shape, but not the result of Shape().foo()) +// - WithElementType: shape is an array/scalar with the given elem type +// - WithRank: shape is an array/scalar with the given rank +// +// Layout(): +// - EqualTo +// - WithMinorToMajor: minor to major dimension ordering matches the given +// pattern +// +// Op(), Shape(), and Layout() may be passed an argument of type +// HloInstruction**, Shape**, or Layout**, respectively, or const versions of +// these pointers. If the pattern is matched, the address of the matched value +// will be "captured" and stored at this location. +// +// For example: +// HloInstruction* foo = ...; +// HloInstruction* matched_operand; +// CHECK(Match(foo, +// match::Op().WithOperand(0, match::Op(&matched_operand)))); +// +// Helpers are provided for most HLO instructions. These helpers can be called +// with no arguments, in which case they will match any instruction matching the +// opcode. They may also be called with matches for the operands and with an +// optional capture. (The capture must be the first argument.) Some examples of +// these helpers and their equivalents are provided below. + +// Example nullary instruction: +// Parameter() == Op().WithOpcode(HloOpcode::kParameter) +// Parameter(&a) == Op(&a).WithOpcode(HloOpcode::kParameter) +// +// Example unary instruction: +// Abs() == Op().WithOpcode(HloOpcode::kAbs) +// Abs(Op(&a)) == Op().WithOpcode(HloOpcode::kAbs) +// .WithOperand(0, Op(&a))) +// Abs(&a, Op(&b)) == Op(&a).WithOpcode(HloOpcode::kAbs) +// .WithOperand(0, Op(&b)) +// +// Commutative binary instructions have a special form that accepts either order +// of args, e.g.: +// +// AddAnyOrder(Parameter(1), Abs()) == +// Op().WithOpcode(HloOpcode::kAdd) +// .WithBinaryOperandsAnyOrder(Op().WithParameterNum(1), Abs()); +// +// MultiplyAnyOrder(&a, Parameter(), Abs()) // Captures the mul in `a`. +// +// The following additional helpers are provided. In all cases, `&a` is +// optional. +// +// ConstantScalar(&a) == Op(&a).IsConstantScalar(); +// ConstantScalar(&a, v) == Op(&a).IsConstantScalar(v); +// ConstantEffectiveScalar(&a) == Op(&a).IsConstantEffectiveScalar(); +// ConstantEffectiveScalar(&a, v) == Op(&a).IsConstantEffectiveScalar(&a, v) +// NonConstant(&a) == Op(&a).IsNonConstant() +// GetTupleElement(&a, b, index) == Op(&a).WithTupleIndex(index) +// .WithOperand(0, b); +// Parameter(&a, n) == Op(&a).WithParameterNum(n); + +struct MatchOption { + // If true, actually capture matched item into the user pointer. + bool capture; + + // If true, require all operands prescribed in pattern to have one user. + bool single_user_only; + + // An explanation for why we failed to match is streamed here, if not-null. + std::ostream* explain_os; +}; + +template +bool Match(Value* value, const Pattern& pattern, + MatchOption option = {/*.capture=*/true, + /*.single_user_only=*/false, + /*.explain_os=*/nullptr}) { + if (option.capture) { + auto new_option = option; + new_option.capture = false; + if (!pattern.Match(value, new_option)) { + return false; + } + } + return pattern.Match(value, option); +} + +// Recursively requires all operands of the top-level operation prescribed in +// pattern (but not the top-level operation itself) to have one user. The +// behavior is identical to calling Match(value, pattern) with WithOneUser() +// applied to all prescribed operands at all levels in pattern. +// +// Example: +// p0 = parameter(0) +// add = add(p0, p0) +// mul = multiply(p0, p0) +// +// MatchSingleUserOnly(p0, m::Op()) -> true +// (Top-level operation in the pattern is not required to have one user). +// +// MatchSingleUserOnly(add, m::Add()) -> true +// (Only operands prescribed in the pattern are required to have one user). +// +// MatchSingleUserOnly(add, m::Add(m::Op(), m::Op()) -> false +// (Operands prescribed in the pattern have two users). +// +// The previous line is equivalent to: +// Match(add, m::Add(m::Op().WithOneUser(), m::Op().WithOneUser()) -> false. +template +bool MatchSingleUserOnly(Value* value, const Pattern& pattern) { + MatchOption option = {/*.capture=*/true, /*.single_user_only=*/true, + /*.explain_os=*/nullptr}; + return Match(value, pattern, option); +} + +// If `enable_logging` is false, this is identical to Match(instr, pattern). +// +// If `enable_logging` is true and the match fails, we try to +// Match(instr, filter_pattern). If this is true, then we log an explanation for +// why the original Match(instr, pattern) failed. +// +// This function can be used aid in debugging passes with complex matchers. +// For example, in the following snippet we're trying to match +// m::Slice(m::Reshape(m::Pad())). Every time we encounter a slice that +// doesn't match the larger pattern, we will log an explanation for why it +// didn't match the larger pattern. +// +// if (MatchAndLogIfFailed(instr, "slice of reshape of pad", +// m::Slice(m::Reshape(m::Pad())), +// VLOG_IS_ON(3), m::Slice()) +// +// TODO(jlebar): Log the caller's absl::SourceLocation once that's in OSS. +template +bool MatchAndLogIfFailed(HloInstruction* instr, absl::string_view desc, + const Pattern& pattern, bool enable_logging, + const FilterPattern& filter_pattern) { + bool matched = Match(instr, pattern); + if (matched || !enable_logging || !Match(instr, filter_pattern)) { + return matched; + } + std::stringstream os; + CHECK(!Match( + instr, pattern, + {/*capture=*/false, /*.single_user_only=*/false, /*explain_os=*/&os})); + LOG(ERROR) << "Failed to match " << desc << ":\n" << os.str(); + return false; +} + +namespace match { + +namespace detail { + +// Macro for streaming to option.explain_os if it's not null. +// +// EXPLAIN << "value of foo(): " << foo() +// +#pragma push_macro("EXPLAIN") +#define EXPLAIN \ + if (option.explain_os) *option.explain_os + +// kIndentInc is the additional number of spaces that we indent by when we +// increase the indent "by one". +enum { + kIndentInc = 2, +}; + +// Writes a newline and then `indent` spaces. +// +// We follow an unintuitive convention in this file's pretty-printers: Indents +// are performed by the caller, not the callee. For example, if you want to +// print +// +// foo: +// - bar +// +// you'd do: +// +// Foo::DescribeTo(std::ostream* os, int64_t indent) { +// *os << "foo:"; +// Indent(os, indent) // Create a newline at the *current* indent level. +// *os << " - "; +// bar.DescribeTo(os, indent + 3); // + 3 because strlen(" * ") == 3. +// } +// +// Bar::DescribeTo(std::ostream* os, int64_t indent) { *os << "bar"; } +// +// Notice that Bar::DescribeTo() does not call Indent; the indenting is +// performed by Foo. This convention allows the caller to decide whether a +// matcher is preceded by a newline, which is important e.g. for the AllOf +// matcher. +// +// (Incidentally, indenting in Match's explanations is handled differently. +// Indents are a common case in DescribeTo [we're printing a whole tree], but +// they're a special case in Match [we're printing only a path through the tree +// that encounters a failing node]. Indents in Match only appear when we +// encounter a failing disjunction, so we just handle them as a special case +// there.) +inline void Indent(std::ostream* os, int64_t indent) { + *os << "\n"; + for (int64_t i = 0; i < indent; ++i) { + *os << " "; + } +} + +// SFINAE template that determines whether T declares a static member +// kIsTrivialMatcher. +// +// Trivial matchers get special treatment. For example, when printing +// a conjunction of matchers, we don't print "and" after a trivial matcher. This +// yields e.g. +// "a shape compatible with f32[1,2]" +// rather than +// "a shape AND compatible with f32[1,2]" +template +struct IsTrivialMatcher { + static constexpr bool value = false; +}; +template +struct IsTrivialMatcher::type> { + static constexpr bool value = true; +}; + +template +class AllOfPattern { + public: + explicit AllOfPattern(const Patterns&... patterns) : patterns_(patterns...) {} + + bool Match(const Item* item, MatchOption option) const { + bool matched = MatchImpl(item, option, std::integral_constant()); + // This invariant is guaranteed by the top-level Match and AnyOf. + DCHECK(matched || !option.capture); + return matched; + } + + bool Match(Item* item, MatchOption option) const { + bool matched = MatchImpl(item, option, std::integral_constant()); + // This invariant is guaranteed by the top-level Match and AnyOf. + DCHECK(matched || !option.capture); + return matched; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + DescribeToImpl(os, std::integral_constant(), indent); + } + + // Accessor for patterns_. Please don't use this outside of this file. + const std::tuple& patterns() const { return patterns_; } + + private: + template + bool MatchImpl(ItemType* item, MatchOption option, + std::integral_constant) const { + // We don't need to do any EXPLAINing here; it's all correctly handled by + // our sub-matchers (if any fail). + return std::get(patterns_).Match(item, option) && + MatchImpl(item, option, std::integral_constant()); + } + + template + bool MatchImpl(ItemType* item, MatchOption option, + std::integral_constant) const { + return true; + } + + // Pretty-printing a conjunction has some special cases to make it easy to + // read in the simple (common) case. + // + // If sizeof...(Patterns) == 1, prints as e.g. + // + // a shape + // + // If sizeof...(Patterns) == 2 and patterns_[0] is a trivial matcher (e.g. "a + // shape") prints as + // + // a shape compatible with f32[1,2] + // + // If sizeof...(Patterns) > 2 and patterns_[0] is a trivial matcher, prints as + // + // a shape: + // * compatible with f32[1,2] AND + // * that represents a scalar + // + // Otherwise prints as: + // + // all of: + // * foo AND + // * bar + // + template + void DescribeToImpl(std::ostream* os, std::integral_constant, + int64_t indent) const { + constexpr bool first_is_trivial = + IsTrivialMatcher( + patterns_))>::type>::value; + constexpr bool is_last = index == sizeof...(Patterns) - 1; + const auto& submatcher = std::get(patterns_); + + auto print_bulleted_item = [&] { + *os << " * "; + submatcher.DescribeTo(os, indent + 3); + if (!is_last) { + *os << " AND"; + Indent(os, indent); + } + }; + + if (index == 0) { + if (first_is_trivial || is_last) { + submatcher.DescribeTo(os, indent + kIndentInc); + if (sizeof...(Patterns) > 2) { + *os << ":"; + Indent(os, indent); + } + } else { + *os << "all of:"; + Indent(os, indent); + print_bulleted_item(); + } + } else if (first_is_trivial && index == 1 && sizeof...(Patterns) == 2) { + *os << " "; + submatcher.DescribeTo(os, indent); + } else { + print_bulleted_item(); + } + DescribeToImpl(os, std::integral_constant(), indent); + } + + void DescribeToImpl(std::ostream* os, + std::integral_constant, + int64_t indent) const {} + + std::tuple patterns_; +}; + +} // namespace detail + +// Returns a pattern that represents the conjunction of all input patterns. All +// patterns need to match in order to have the AllOf pattern match. +template +auto AllOf(const Patterns&... patterns) { + return detail::AllOfPattern::type, + Patterns...>(patterns...); +} + +// AllOf, X, Y, ...> => AllOf. +// +// This transformation is necessary for good pretty-printing. +template +auto AllOf(const detail::AllOfPattern& inner_p, + const OuterPs&... outer_ps) { + // Invoke constructor of AllOfPattern. + auto make_all_of = [](const InnerPs&... inner_ps, + const OuterPs&... outer_ps) { + return detail::AllOfPattern::type, + InnerPs..., OuterPs...>(inner_ps..., + outer_ps...); + }; + return absl::apply(make_all_of, std::tuple_cat(inner_p.patterns(), + std::make_tuple(outer_ps...))); +} + +namespace detail { + +template +class LayoutPattern; + +// The base LayoutPattern implementation. Matches only if the layout is not +// nullptr. +class LayoutPatternBaseImpl { + public: + bool Match(const ::xla::Layout* layout, MatchOption option) const { + if (layout == nullptr) { + EXPLAIN << "Layout is null"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "a layout"; + } + + static constexpr bool kIsTrivialMatcher = true; +}; + +// A LayoutPattern implementation that matches only if the layout equals a +// Layout proto. +class LayoutPatternEqualImpl { + public: + explicit constexpr LayoutPatternEqualImpl(const ::xla::Layout* layout) + : layout_(layout) {} + + bool Match(const ::xla::Layout* layout, MatchOption option) const { + if (!LayoutUtil::Equal(*layout_, *layout)) { + EXPLAIN << "Layout " << LayoutUtil::HumanString(*layout) + << " is not equal to expected " + << LayoutUtil::HumanString(*layout_); + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "equal to " << LayoutUtil::HumanString(*layout_); + } + + private: + const ::xla::Layout* layout_; +}; + +class LayoutPatternMinorToMajorImpl { + public: + explicit LayoutPatternMinorToMajorImpl( + absl::Span minor_to_major) + : minor_to_major_(minor_to_major.begin(), minor_to_major.end()) {} + + bool Match(const ::xla::Layout* layout, MatchOption option) const { + if (layout->minor_to_major() != minor_to_major_) { + EXPLAIN << "Layout does not have minor to major [" + << absl::StrJoin(minor_to_major_, ",") << "]"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with minor to major [" << absl::StrJoin(minor_to_major_, ",") + << "]"; + } + + private: + absl::InlinedVector minor_to_major_; +}; + +// A pattern that matches Layouts. +template +class LayoutPattern { + private: + template + auto AppendImpl(NewImpl new_impl) const { + auto new_allof = AllOf<::xla::Layout>(impl_, std::move(new_impl)); + return LayoutPattern(std::move(new_allof), + matched_layout_); + } + + public: + explicit constexpr LayoutPattern(const Impl& impl, + LayoutType** matched_layout) + : impl_(impl), matched_layout_(matched_layout) {} + + // Returns true and captures the layout iff it matches the pattern. + bool Match(const ::xla::Layout* layout, MatchOption option) const { + if (impl_.Match(layout, option)) { + if (option.capture && matched_layout_) { + *matched_layout_ = layout; + } + return true; + } + return false; + } + + // Returns true and captures the layout iff it matches the pattern. + bool Match(::xla::Layout* layout, MatchOption option) const { + if (impl_.Match(layout, option)) { + if (option.capture && matched_layout_) { + *matched_layout_ = layout; + } + return true; + } + return false; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + impl_.DescribeTo(os, indent); + } + + // Modifies the pattern to match only if the layout equals the given proto. + // The layout must outlive the returned pattern. + constexpr auto EqualTo(const ::xla::Layout* layout) const { + return AppendImpl(LayoutPatternEqualImpl(layout)); + } + + constexpr auto WithMinorToMajor( + absl::Span minor_to_major) const { + return AppendImpl(LayoutPatternMinorToMajorImpl(minor_to_major)); + } + + private: + Impl impl_; + LayoutType** matched_layout_; +}; + +template +class AnyOfPattern { + public: + explicit AnyOfPattern(const Patterns&... patterns) : patterns_(patterns...) {} + + bool Match(const Item* item, MatchOption option) const { + return MatchImpl(item, option); + } + + bool Match(Item* item, MatchOption option) const { + return MatchImpl(item, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "any of:"; + Indent(os, indent); + DescribeToImpl(os, std::integral_constant(), indent); + } + + private: + template + bool MatchImpl(ItemType* item, MatchOption option) const { + // If we're generating an explanation, buffer it until we know we failed. + std::optional explanation; + MatchOption new_option = option; + if (option.explain_os) { + new_option.explain_os = &explanation.emplace(); + } + bool rv = MatchRecursiveImpl(item, new_option, + std::integral_constant()); + if (!rv && option.explain_os) { + EXPLAIN << "None of the following matchers succeeded:"; + EXPLAIN << explanation->str(); + } + return rv; + } + + template + bool MatchRecursiveImpl(ItemType* item, MatchOption option, + std::integral_constant) const { + auto new_option = option; + new_option.capture = false; + + std::optional explanation; + if (option.explain_os) { + new_option.explain_os = &explanation.emplace(); + } + + // Try to match the sub-pattern without capturing behavior. + if (std::get(patterns_).Match(item, new_option)) { + // Capture the branch. + if (option.capture) { + // TODO(timshen): Currently the behavior can be exponential. Optimize it + // with memoization or recording the matched sub-pattern index, if it + // takes too long to run. + // + // Specifically, the "memoization" approach is to create an empty + // container with the key (pattern, instruction), and value as whether + // matched or not. + // + // Alternatively, we may run the pattern matching with captures off, but + // instead record a "trace" somewhere, indicating how exactly the + // pattern matches the input. For example, the trace information for + // AnyOf will be a runtime number indicate which sub-pattern is matched. + // Then we run another pass to do captures only with the help of the + // trace. + bool matched = std::get(patterns_).Match(item, option); + DCHECK(matched); + } + return true; + } + if (option.explain_os) { + EXPLAIN << "\nMatcher #" << index + 1; + EXPLAIN << "\n - "; + std::get(patterns_).DescribeTo(option.explain_os, /*indent=*/3); + EXPLAIN << "\nfailed with"; + EXPLAIN << "\n - "; + EXPLAIN << absl::StrReplaceAll(explanation->str(), {{"\n", "\n "}}); + } + return MatchRecursiveImpl(item, option, + std::integral_constant()); + } + + template + bool MatchRecursiveImpl( + ItemType* item, MatchOption option, + std::integral_constant) const { + return false; + } + + template + void DescribeToImpl(std::ostream* os, std::integral_constant, + int64_t indent) const { + *os << " - "; + std::get(patterns_).DescribeTo(os, indent + 3); + if (index != sizeof...(Patterns) - 1) { + *os << " OR"; + Indent(os, indent); + } + DescribeToImpl(os, std::integral_constant(), indent); + } + + void DescribeToImpl(std::ostream* os, + std::integral_constant, + int64_t indent) const {} + + std::tuple patterns_; +}; + +} // namespace detail + +// Creates a layout pattern that will capture the matched layout in the +// argument. +inline constexpr auto Layout(const ::xla::Layout** matched_layout = nullptr) { + return detail::LayoutPattern( + detail::LayoutPatternBaseImpl(), matched_layout); +} + +// Creates a layout pattern that will capture the matched layout in the +// argument. +inline constexpr auto Layout(::xla::Layout** matched_layout) { + return detail::LayoutPattern<::xla::Layout, detail::LayoutPatternBaseImpl>( + detail::LayoutPatternBaseImpl(), matched_layout); +} + +namespace detail { + +template +class ShapePattern; + +// The base ShapePattern implementation. Matches only if the shape is not +// nullptr. +class ShapePatternBaseImpl { + public: + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (shape == nullptr) { + EXPLAIN << "Shape is null"; + } + return shape != nullptr; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "a shape"; + } + + static constexpr bool kIsTrivialMatcher = true; +}; + +// A ShapePattern implementation that matches only if the shape equals a Shape +// proto. +class ShapePatternEqualImpl { + public: + explicit constexpr ShapePatternEqualImpl(const ::xla::Shape* shape) + : shape_(shape) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!ShapeUtil::Equal(*shape_, *shape)) { + EXPLAIN << "Shape not equal to " + << ShapeUtil::HumanStringWithLayout(*shape_); + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "equal to " << ShapeUtil::HumanStringWithLayout(*shape_); + } + + private: + const ::xla::Shape* shape_; +}; + +// A ShapePattern implementation that matches only if the shape is compatible to +// a Shape proto. +class ShapePatternCompatibleImpl { + public: + explicit constexpr ShapePatternCompatibleImpl(const ::xla::Shape* shape) + : shape_(shape) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!ShapeUtil::Compatible(*shape_, *shape)) { + EXPLAIN << "Shape not compatible with " + << ShapeUtil::HumanString(*shape_); + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "compatible with " << ShapeUtil::HumanString(*shape_); + } + + private: + const ::xla::Shape* shape_; +}; + +// A ShapePattern implementation that matches only if the shape has a given +// element type. +class ShapePatternElementTypeImpl { + public: + explicit constexpr ShapePatternElementTypeImpl(PrimitiveType element_type) + : element_type_(element_type) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (shape->element_type() != element_type_) { + EXPLAIN << "Shape does not have element type " + << PrimitiveType_Name(element_type_); + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with element type " << PrimitiveType_Name(element_type_); + } + + private: + PrimitiveType element_type_; +}; + +// A ShapePattern implementation that matches only if the shape has a given +// list of dimensions. +class ShapePatternDimsImpl { + public: + explicit ShapePatternDimsImpl(absl::Span dims) + : dims_(dims.begin(), dims.end()) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (shape->dimensions() != dims_) { + EXPLAIN << "Shape does not have dimensions [" << absl::StrJoin(dims_, ",") + << "]"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with dimensions [" << absl::StrJoin(dims_, ",") << "]"; + } + + private: + absl::InlinedVector dims_; +}; + +// A ShapePattern implementation that matches only if the shape is scalar. +class ShapePatternIsScalarImpl { + public: + explicit constexpr ShapePatternIsScalarImpl() = default; + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!ShapeUtil::IsScalar(*shape)) { + EXPLAIN << "Shape is not a scalar"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "that represents a scalar"; + } +}; + +// A ShapePattern implementation that matches only if the shape is an array +class ShapePatternIsArrayImpl { + public: + explicit constexpr ShapePatternIsArrayImpl() = default; + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!shape->IsArray()) { + EXPLAIN << "Shape is not an array"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "that represents an array"; + } +}; + +// A ShapePattern implementation that matches only if the shape is an array +class ShapePatternIsDenseArrayImpl { + public: + explicit constexpr ShapePatternIsDenseArrayImpl() = default; + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!LayoutUtil::IsDenseArray(*shape)) { + EXPLAIN << "Shape is not a dense array"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "that represents a dense array"; + } +}; + +// A ShapePattern implementation that matches only if the shape is a tuple. +class ShapePatternIsTupleImpl { + public: + explicit constexpr ShapePatternIsTupleImpl() = default; + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!shape->IsTuple()) { + EXPLAIN << "Shape is not a tuple"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "that represents a tuple"; + } +}; + +// A ShapePattern implementation that matches only if the shape is an effective +// scalar. +class ShapePatternEffectiveScalarImpl { + public: + explicit constexpr ShapePatternEffectiveScalarImpl() = default; + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (!ShapeUtil::IsEffectiveScalar(*shape)) { + EXPLAIN << "Shape is not an effective scalar"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "that is an effective scalar"; + } +}; + +// A ShapePattern implementation that matches only if the shape has a given +// rank. +class ShapePatternRankImpl { + public: + explicit constexpr ShapePatternRankImpl(int64_t rank) : rank_(rank) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (shape->rank() != rank_) { + if (rank_ == 0) { + EXPLAIN << "Shape is not a scalar"; + } else { + EXPLAIN << "Shape does not have rank " << rank_; + } + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + if (rank_ == 0) { + *os << "that is a scalar"; + } else { + *os << "that has " << rank_ << " dimension" << (rank_ != 1 ? "s" : ""); + } + } + + private: + int64_t rank_; +}; + +// A ShapePattern implementation that matches only if the shape has a layout +// that matches a given pattern. +template +class ShapePatternLayoutImpl { + public: + explicit constexpr ShapePatternLayoutImpl( + const LayoutPattern& layout) + : layout_(layout) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + return LayoutUtil::HasLayout(*shape) && + layout_.Match(&shape->layout(), option); + } + + bool Match(::xla::Shape* shape, MatchOption option) const { + if (!LayoutUtil::HasLayout(*shape)) { + EXPLAIN << "Shape does not have a layout"; + return false; + } + if (!layout_.Match(shape->mutable_layout(), option)) { + EXPLAIN << "\nin layout"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with"; + Indent(os, indent + kIndentInc); + layout_.DescribeTo(os, indent + kIndentInc); + } + + private: + LayoutPattern layout_; +}; + +// A ShapePattern implementation that matches only if the shape has a subshape +// that matches a given pattern. +template +class ShapePatternSubshapeImpl { + public: + explicit ShapePatternSubshapeImpl( + ShapeIndexView index, + const ShapePattern& subshape) + : index_(index), subshape_(subshape) {} + + bool Match(const ::xla::Shape* shape, MatchOption option) const { + return MatchImpl(shape, option); + } + + bool Match(::xla::Shape* shape, MatchOption option) const { + return MatchImpl(shape, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with subshape at index " << ShapeIndex(index_) << " which is"; + Indent(os, indent + kIndentInc); + subshape_.DescribeTo(os, indent + kIndentInc); + } + + private: + ::xla::Shape* GetSubshape(::xla::Shape* shape) const { + return ShapeUtil::GetMutableSubshape(shape, index_); + } + const ::xla::Shape* GetSubshape(const ::xla::Shape* shape) const { + return &ShapeUtil::GetSubshape(*shape, index_); + } + + template + bool MatchImpl(ShapeType* shape, MatchOption option) const { + if (!ShapeUtil::IndexIsValid(*shape, index_)) { + EXPLAIN << "No subshape at " << ShapeIndex(index_); + return false; + } + if (!subshape_.Match(GetSubshape(shape), option)) { + EXPLAIN << "\nin subshape at " << ShapeIndex(index_); + return false; + } + return true; + } + + ShapeIndexView index_; + ShapePattern subshape_; +}; + +// A pattern that matches Shapes. +template +class ShapePattern { + private: + template + auto AppendImpl(NewImpl new_impl) const { + auto new_all_of = AllOf<::xla::Shape>(impl_, std::move(new_impl)); + return ShapePattern(std::move(new_all_of), + matched_shape_); + } + + public: + explicit constexpr ShapePattern(const Impl& impl, ShapeType** matched_shape) + : impl_(impl), matched_shape_(matched_shape) {} + + // Returns true and captures the shape iff it matches the pattern. + bool Match(const ::xla::Shape* shape, MatchOption option) const { + if (impl_.Match(shape, option)) { + if (option.capture && matched_shape_) { + *matched_shape_ = shape; + } + return true; + } + if (shape) { + EXPLAIN << "\nin " + << (shape->has_layout() ? ShapeUtil::HumanStringWithLayout(*shape) + : ShapeUtil::HumanString(*shape)); + } + return false; + } + + // Returns true and captures the shape iff it matches the pattern. + bool Match(::xla::Shape* shape, MatchOption option) const { + if (impl_.Match(shape, option)) { + if (option.capture && matched_shape_) { + *matched_shape_ = shape; + } + return true; + } + EXPLAIN << "\nin " + << (shape->has_layout() ? ShapeUtil::HumanStringWithLayout(*shape) + : ShapeUtil::HumanString(*shape)); + return false; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + return impl_.DescribeTo(os, indent); + } + + // Modifies the pattern to match only if the shape equals the given proto. + // The layout must outlive the returned pattern. + constexpr auto EqualTo(const ::xla::Shape* shape) const { + return AppendImpl(ShapePatternEqualImpl(shape)); + } + + // Modifies the pattern to match only if the shape is compatible to the given + // proto. The layout must outlive the returned pattern. + constexpr auto CompatibleTo(const ::xla::Shape* shape) const { + return AppendImpl(ShapePatternCompatibleImpl(shape)); + } + + // Modifies the pattern to match only if the shape has the given element type. + constexpr auto WithElementType(PrimitiveType element_type) const { + return AppendImpl(ShapePatternElementTypeImpl(element_type)); + } + + constexpr auto WithDims(absl::Span dims) const { + return AppendImpl(ShapePatternDimsImpl(dims)); + } + + // Modifies the pattern to match only if the shape is scalar. + constexpr auto IsScalar() const { + return AppendImpl(ShapePatternIsScalarImpl()); + } + + // Modifies the pattern to match only if the shape is an array. + constexpr auto IsArray() const { + return AppendImpl(ShapePatternIsArrayImpl()); + } + + // Modifies the pattern to match only if the shape is a tuple. + constexpr auto IsTuple() const { + return AppendImpl(ShapePatternIsTupleImpl()); + } + + constexpr auto IsEffectiveScalar() const { + return AppendImpl(ShapePatternEffectiveScalarImpl()); + } + + // Modifies the pattern to match only if the shape has the given rank. + constexpr auto WithRank(int64_t rank) const { + return AppendImpl(ShapePatternRankImpl(rank)); + } + + // Modifies the pattern to match only if the shape has a layout that matches + // the given pattern. + template + auto WithLayout(const LayoutPattern& layout) const { + return AppendImpl(ShapePatternLayoutImpl(layout)); + } + + constexpr auto WithLayout(absl::Span minor_to_major) const { + return WithLayout(Layout().WithMinorToMajor(minor_to_major)); + } + + constexpr auto WithLayoutEqualTo(const ::xla::Layout* layout) const { + return WithLayout(Layout().EqualTo(layout)); + } + + // Modifies the pattern to match only if the shape is a dense array. + constexpr auto IsDenseArray() const { + return AppendImpl(ShapePatternIsDenseArrayImpl()); + } + + // Modifies the pattern to match only if the shape has a subshape that matches + // the given pattern. + template + auto WithSubshape( + ShapeIndexView index, + const ShapePattern& subshape) const { + return AppendImpl( + ShapePatternSubshapeImpl(index, subshape)); + } + + ShapePattern>>> + WithSubshapeEqualTo(ShapeIndexView index, const ::xla::Shape* shape) const { + return WithSubshape(index, + ShapePattern( + ShapePatternBaseImpl(), nullptr) + .EqualTo(shape)); + } + + ShapePattern>>> + WithSubshapeCompatibleTo(ShapeIndexView index, + const ::xla::Shape* shape) const { + return WithSubshape(index, + ShapePattern( + ShapePatternBaseImpl(), nullptr) + .CompatibleTo(shape)); + } + + private: + Impl impl_; + ShapeType** matched_shape_; +}; + +} // namespace detail + +// Creates a shape pattern that will capture the matched layout in the argument. +inline constexpr auto Shape(const ::xla::Shape** matched_shape = nullptr) { + return detail::ShapePattern( + detail::ShapePatternBaseImpl(), matched_shape); +} + +// Creates a shape pattern that will capture the matched layout in the argument. +inline constexpr auto Shape(::xla::Shape** matched_shape) { + return detail::ShapePattern<::xla::Shape, detail::ShapePatternBaseImpl>( + detail::ShapePatternBaseImpl(), matched_shape); +} + +namespace detail { + +// Overloads to get a const or non-const operand out of an instruction. +inline HloInstruction* HloOperand(HloInstruction* instr, int64_t idx) { + return instr->mutable_operand(idx); +} +inline const HloInstruction* HloOperand(const HloInstruction* instr, + int64_t idx) { + return instr->operand(idx); +} + +// Pretty-printer for HloInstruction. Sort of like ToShortString, but with +// fewer %s and more shapes. +inline std::string InstToString(const HloInstruction* inst) { + return inst->ToString( + HloPrintOptions().set_print_metadata(false).set_print_percent(false)); +} + +template +class HloInstructionPattern; + +// The base HloInstructionPattern implementation. Matches only if the +// instruction is not nullptr. +class HloInstructionPatternBaseImpl { + public: + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (inst == nullptr) { + EXPLAIN << "HloInstruction* is null"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "an HloInstruction"; + } + + static constexpr bool kIsTrivialMatcher = true; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// has a given name. +class HloInstructionPatternNameImpl { + public: + explicit HloInstructionPatternNameImpl(absl::string_view name) + : name_(name) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (inst->name() != name_) { + EXPLAIN << "HloInstruction not named \"" << name_ << "\""; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "named \"" << name_ << "\""; + } + + private: + absl::string_view name_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// equals a particular pointer. +class HloInstructionIsImpl { + public: + explicit HloInstructionIsImpl(const HloInstruction* inst) : inst_(inst) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (inst != inst_) { + EXPLAIN << "HloInstruction " << std::hex << std::nouppercase + << std::showbase << reinterpret_cast(inst) << " is not " + << reinterpret_cast(inst_) << " (" + << InstToString(inst_) << ")"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which is " << std::hex << std::nouppercase << std::showbase + << reinterpret_cast(inst_) << " (" << InstToString(inst_) + << ")"; + } + + private: + const HloInstruction* inst_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// has a given opcode. +class HloInstructionPatternOpcodeImpl { + public: + explicit constexpr HloInstructionPatternOpcodeImpl(HloOpcode opcode, + bool invert) + : opcode_(opcode), invert_(invert) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (invert_ && inst->opcode() == opcode_) { + EXPLAIN << "HloInstruction has opcode " << opcode_ + << ", expected anything else"; + return false; + } + if (!invert_ && inst->opcode() != opcode_) { + EXPLAIN << "HloInstruction doesn't have opcode " << opcode_; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + if (!invert_) { + *os << "with opcode " << opcode_; + } else { + *os << "with any opcode other than " << opcode_; + } + } + + private: + HloOpcode opcode_; + bool invert_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// has one of a given list of custom call targets. +class HloInstructionCustomCallTargetImpl { + public: + explicit HloInstructionCustomCallTargetImpl( + absl::Span custom_call_targets) + : custom_call_targets_(custom_call_targets.begin(), + custom_call_targets.end()) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kCustomCall || + !absl::c_linear_search(custom_call_targets_, + inst->custom_call_target())) { + if (custom_call_targets_.size() == 1) { + EXPLAIN << "HloInstruction is not a custom call with a target '" + << custom_call_targets_.front() << "'"; + } else { + EXPLAIN << "HloInstruction is not a custom call with a target in {" + << absl::StrJoin(custom_call_targets_, ", ") << "}"; + } + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + if (custom_call_targets_.size() == 1) { + *os << "custom call with target '" << custom_call_targets_.front() << "'"; + } else { + *os << "custom call with target in {" + << absl::StrJoin(custom_call_targets_, ", ") << "}"; + } + } + + private: + absl::InlinedVector custom_call_targets_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// has the given number of operands. +class HloInstructionPatternNumOperandsImpl { + public: + explicit constexpr HloInstructionPatternNumOperandsImpl(int64_t num_operands) + : num_operands_(num_operands) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (inst->operand_count() != num_operands_) { + EXPLAIN << "HloInstruction doesn't have " << num_operands_ << " operands"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with " << num_operands_ << " operand" + << (num_operands_ != 1 ? "s" : ""); + } + + private: + int64_t num_operands_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// has a shape that matches a given pattern. +template +class HloInstructionPatternShapeImpl { + public: + explicit constexpr HloInstructionPatternShapeImpl( + const ShapePattern& shape) + : shape_(shape) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (!shape_.Match(&inst->shape(), option)) { + EXPLAIN << "\nin output shape"; + return false; + } + return true; + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + if (!shape_.Match(inst->mutable_shape(), option)) { + EXPLAIN << "\nin output shape"; + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "outputting"; + Indent(os, indent + kIndentInc); + shape_.DescribeTo(os, indent + kIndentInc); + } + + private: + ShapePattern shape_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// has an operand that matches a given pattern. +template +class HloInstructionPatternOperandImpl { + public: + explicit constexpr HloInstructionPatternOperandImpl( + int64_t operand_index, + const HloInstructionPattern& operand) + : operand_index_(operand_index), operand_(operand) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with operand " << operand_index_ << " which is:"; + Indent(os, indent + kIndentInc); + operand_.DescribeTo(os, indent + kIndentInc); + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (operand_index_ >= inst->operand_count()) { + EXPLAIN << "desired operand index " << operand_index_ + << " is out of bounds"; + return false; + } + if (!operand_.Match(HloOperand(inst, operand_index_), option)) { + EXPLAIN << "\nin operand " << operand_index_; + return false; + } + if (option.single_user_only && + inst->operand(operand_index_)->user_count() != 1) { + EXPLAIN << "Operand " << operand_index_ << " of HloInstruction has " + << inst->operand(operand_index_)->user_count() + << " users. Expected 1."; + return false; + } + return true; + } + + int64_t operand_index_; + HloInstructionPattern operand_; +}; + +// An HloInstructionPattern implementation that matches if the instruction has +// fewer than i+1 operands, or if the i'th operand matches a given pattern. +template +class HloInstructionPatternOperandIfPresentImpl { + public: + explicit constexpr HloInstructionPatternOperandIfPresentImpl( + int64_t operand_index, + const HloInstructionPattern& operand) + : operand_index_(operand_index), operand_(operand) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "either with fewer than " << operand_index_ + 1 << " operand" + << (operand_index_ + 1 != 1 ? "s" : "") << ", or with an operand " + << operand_index_ << " which is:"; + Indent(os, indent + kIndentInc); + operand_.DescribeTo(os, indent + kIndentInc); + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (operand_index_ >= inst->operand_count()) { + return true; + } + if (!operand_.Match(HloOperand(inst, operand_index_), option)) { + EXPLAIN << "\nin operand " << operand_index_; + return false; + } + return true; + } + + int64_t operand_index_; + HloInstructionPattern operand_; +}; + +// Matches a binary instruction whose operands come in any order. +template +class HloInstructionPatternBinaryOperandsAnyOrderImpl { + public: + explicit constexpr HloInstructionPatternBinaryOperandsAnyOrderImpl( + const HloInstructionPattern& op1, + const HloInstructionPattern& op2) + : op1_(op1), op2_(op2) {} + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with two operands in either order:"; + Indent(os, indent); + *os << " - "; + op1_.DescribeTo(os, indent + 3); + Indent(os, indent); + *os << " - "; + op2_.DescribeTo(os, indent + 3); + } + + private: + HloInstruction* operand(HloInstruction* inst, int64_t idx) const { + return inst->mutable_operand(idx); + } + const HloInstruction* operand(const HloInstruction* inst, int64_t idx) const { + return inst->operand(idx); + } + + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + // We could implement this using AnyOf and AllOf matchers, but the templates + // get pretty difficult to debug, since any compile error herein becomes + // not-an-error via SFINAE. Also this way lets us give better messages on + // failure. + if (inst->operand_count() != 2) { + EXPLAIN << "HloInstruction did not have two operands"; + return false; + } + + if (option.single_user_only) { + for (int i = 0; i < 2; ++i) { + if (inst->operand(i)->user_count() != 1) { + EXPLAIN << "Operand " << i << " of HloInstruction has " + << inst->operand(i)->user_count() << " users. Expected 1."; + return false; + } + } + } + + // If we're not generating explanations, this is pretty simple. + if (!option.explain_os) { + auto try_match = [&](int64_t idx1, int64_t idx2) { + MatchOption new_option = option; + new_option.capture = false; + if (op1_.Match(operand(inst, idx1), new_option) && + op2_.Match(operand(inst, idx2), new_option)) { + if (option.capture) { + bool matched = op1_.Match(operand(inst, idx1), option) && + op2_.Match(operand(inst, idx2), option); + DCHECK(matched); + } + return true; + } + return false; + }; + return try_match(0, 1) || try_match(1, 0); + } + + // If we are generating explanations, we have some work to do in order to + // generate a helpful error. + // + // First, try all four operand/matcher combinations, recording the + // failure explanations separately from option.explain_os. matches[i][j] + // tells us if matcher_i matches operand j. + bool matches[/*matcher*/ 2][/*operand*/ 2]; + std::stringstream explanations[/*matcher*/ 2][/*operand*/ 2]; + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 2; ++j) { + MatchOption new_option = option; + new_option.capture = false; + new_option.explain_os = &explanations[i][j]; + matches[i][j] = i == 0 ? op1_.Match(operand(inst, j), new_option) + : op2_.Match(operand(inst, j), new_option); + } + } + + // Check if the match succeeded. + for (int i = 0; i < 2; ++i) { + if (matches[0][i] && matches[1][(i + 1) % 2]) { + // Rerun the matches with capture enabled if necessary. + if (option.capture) { + auto* operand1 = operand(inst, i); + auto* operand2 = operand(inst, (i + 1) % 2); + bool matched = + op1_.Match(operand1, option) && op2_.Match(operand2, option); + DCHECK(matched); + } + return true; + } + } + + auto describe_matcher = [&](int matcher_idx) { + EXPLAIN << "\n - "; + if (matcher_idx == 0) { + op1_.DescribeTo(option.explain_os, /*indent=*/3); + } else { + CHECK_EQ(matcher_idx, 1); + op2_.DescribeTo(option.explain_os, /*indent=*/3); + } + for (int i = 0; i < 2; ++i) { + if (matches[matcher_idx][/*operand*/ i]) { + continue; + } + EXPLAIN << "\ndoes not match " << (i == 0 ? "LHS" : "RHS") << ":\n"; + EXPLAIN << " - "; + EXPLAIN << absl::StrReplaceAll( + explanations[matcher_idx][/*operand*/ i].str(), {{"\n", "\n "}}); + } + }; + + // If we failed to match, one of the following is true: + // 1. op1 (op2) matches neither LHS nor RHS, or + // 2. op1 and op2 both match LHS (RHS), but neither matches RHS (LHS). + // We print different explanations depending on which case we're in. + + // Case 1. + bool wrote_explanation = false; + for (int i = 0; !wrote_explanation && i < 2; ++i) { + if (!matches[i][0] && !matches[i][1]) { + EXPLAIN << "HloInstruction's operands (ignoring order) did not match " + << (i == 0 ? "first" : "second") << " matcher. Specifically,"; + describe_matcher(i); + wrote_explanation = true; + } + } + + // Case 2. + for (int i = 0; !wrote_explanation && i < 2; ++i) { + if (matches[/*matcher*/ 0][/*operand*/ i] && + matches[/*matcher*/ 1][/*operand*/ i]) { + CHECK(!matches[0][(i + 1) % 2]); + CHECK(!matches[1][(i + 1) % 2]); + CHECK(!wrote_explanation); + EXPLAIN << "HloInstruction's " << (i == 1 ? "LHS" : "RHS") + << " operand did not match either of the two matchers. " + "Specifically,"; + describe_matcher(0); + EXPLAIN << "\nand"; + describe_matcher(1); + wrote_explanation = true; + } + } + + CHECK(wrote_explanation); + return false; + } + + HloInstructionPattern op1_; + HloInstructionPattern op2_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// is a fusion node with a particular kind. +class HloInstructionPatternFusionKindImpl { + public: + explicit constexpr HloInstructionPatternFusionKindImpl( + ::xla::HloInstruction::FusionKind kind) + : kind_(kind) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with fusion kind " << ToString(kind_); + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kFusion) { + EXPLAIN << "HloInstruction does not have fusion kind " << ToString(kind_) + << "; it's not a fusion"; + return false; + } + if (inst->fusion_kind() != kind_) { + EXPLAIN << "HloInstruction does not have fusion kind " << ToString(kind_); + return false; + } + return true; + } + + ::xla::HloInstruction::FusionKind kind_; +}; + +// An HloInstructionPattern implementation that matches only if the instruction +// is a kGetTupleElement with a particular tuple index. +class HloInstructionPatternTupleIndexImpl { + public: + explicit constexpr HloInstructionPatternTupleIndexImpl(int64_t tuple_index) + : tuple_index_(tuple_index) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which is a GTE with index " << tuple_index_; + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kGetTupleElement) { + EXPLAIN << "HloInstruction is not a GTE with index " << tuple_index_ + << "; it's not a GTE at all"; + return false; + } + if (inst->tuple_index() != tuple_index_) { + EXPLAIN << "HloInstruction is not a GTE with index " << tuple_index_; + return false; + } + return true; + } + + int64_t tuple_index_; +}; + +class HloInstructionPatternParameterNumImpl { + public: + explicit constexpr HloInstructionPatternParameterNumImpl( + int64_t parameter_num) + : parameter_num_(parameter_num) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which is parameter " << parameter_num_; + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kParameter || + inst->parameter_number() != parameter_num_) { + EXPLAIN << "HloInstruction is not parameter " << parameter_num_; + return false; + } + return true; + } + + int64_t parameter_num_; +}; + +// Superclass that contains common code used by Op::WithOneUse() and +// Op::WithOneUser(). +class HloInstructionPatternOneUseOrUserImpl { + protected: + bool MatchOneUser(const HloInstruction* inst, MatchOption option) const { + if (inst->user_count() != 1) { + EXPLAIN << "HloInstruction has " << inst->user_count() + << " users, but expected exactly one."; + if (inst->user_count() > 1) { + EXPLAIN << "\nAll users:"; + for (const HloInstruction* user : inst->users()) { + EXPLAIN << "\n - " << InstToString(user); + } + } + return false; + } + return true; + } +}; + +class HloInstructionPatternOneUseImpl + : public HloInstructionPatternOneUseOrUserImpl { + public: + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (!MatchOneUser(inst, option)) { + return false; + } + + int64_t use_count = absl::c_count_if( + inst->users()[0]->operands(), + [&](const HloInstruction* operand) { return operand == inst; }); + if (use_count != 1) { + EXPLAIN << "HloInstruction is used " << use_count + << " times by its user, but is expected to be used just once: " + << InstToString(inst->users()[0]); + return false; + } + return true; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which has exactly one use"; + } +}; + +class HloInstructionPatternOneUserImpl + : public HloInstructionPatternOneUseOrUserImpl { + public: + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchOneUser(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which has exactly one user (but possibly is used multiple times by " + "that instruction)"; + } +}; + +class HloInstructionPatternComparisonDirectionImpl { + public: + explicit constexpr HloInstructionPatternComparisonDirectionImpl( + ComparisonDirection direction) + : direction_(direction) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which has comparison direction " + << ComparisonDirectionToString(direction_); + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kCompare || + inst->comparison_direction() != direction_) { + EXPLAIN << "HloInstruction is not comparison " + << ComparisonDirectionToString(direction_); + return false; + } + return true; + } + + ComparisonDirection direction_; +}; + +class HloInstructionPatternConvDnumsImpl { + public: + explicit HloInstructionPatternConvDnumsImpl(absl::string_view dnums) + : HloInstructionPatternConvDnumsImpl( + ParseConvolutionDimensionNumbers(dnums).value()) {} + + explicit HloInstructionPatternConvDnumsImpl(ConvolutionDimensionNumbers dnums) + : dnums_(std::move(dnums)) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which has convolution dimension numbers " + << ConvolutionDimensionNumbersToString(dnums_); + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kConvolution && + inst->opcode() != HloOpcode::kCustomCall) { + EXPLAIN << "HloInstruction is not convolution or custom-call and so " + "can't have convolution_dimension_numbers"; + return false; + } + + const ConvolutionDimensionNumbers& actual_dnums = + inst->convolution_dimension_numbers(); + if (!tsl::protobuf::util::MessageDifferencer::Equals(dnums_, + actual_dnums)) { + EXPLAIN << "convolution_dimension_numbers " + << ConvolutionDimensionNumbersToString(actual_dnums) + << " don't match expected " + << ConvolutionDimensionNumbersToString(dnums_); + return false; + } + return true; + } + + ConvolutionDimensionNumbers dnums_; +}; + +class HloInstructionPredicateImpl { + public: + explicit HloInstructionPredicateImpl(HloPredicate fn) : fn_(std::move(fn)) {} + + bool Match(const HloInstruction* inst, MatchOption option) const { + bool match = fn_(inst); + if (!match) { + EXPLAIN << "HloInstruction does not match user-specified predicate"; + } + return match; + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which matches a user-specified predicate"; + } + + private: + HloPredicate fn_; +}; + +class HloInstructionContractingDimsImpl { + public: + explicit HloInstructionContractingDimsImpl( + absl::Span lhs_contracting_dims, + absl::Span rhs_contracting_dims) + : lhs_contracting_dims_(lhs_contracting_dims.begin(), + lhs_contracting_dims.end()), + rhs_contracting_dims_(rhs_contracting_dims.begin(), + rhs_contracting_dims.end()) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "with lhs_contracting_dims {" + << absl::StrJoin(lhs_contracting_dims_, ",") + << "} and rhs_contracting_dims {" + << absl::StrJoin(rhs_contracting_dims_, ",") << "}"; + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (inst->opcode() != HloOpcode::kDot) { + EXPLAIN << "HloInstruction is not dot so " + "can't have dot_dimension_numbers"; + return false; + } + + const DotDimensionNumbers& dnums = inst->dot_dimension_numbers(); + if (absl::MakeSpan(dnums.lhs_contracting_dimensions()) != + lhs_contracting_dims_) { + EXPLAIN << "lhs_contracting_dimensions {" + << absl::StrJoin(dnums.lhs_contracting_dimensions(), ",") + << "} don't match expected {" + << absl::StrJoin(lhs_contracting_dims_, ",") << "}"; + return false; + } + + if (absl::MakeSpan(dnums.rhs_contracting_dimensions()) != + rhs_contracting_dims_) { + EXPLAIN << "rhs_contracting_dimensions {" + << absl::StrJoin(dnums.rhs_contracting_dimensions(), ",") + << "} don't match expected {" + << absl::StrJoin(rhs_contracting_dims_, ",") << "}"; + return false; + } + return true; + } + + absl::InlinedVector lhs_contracting_dims_; + absl::InlinedVector rhs_contracting_dims_; +}; + +class HloInstructionReplicaGroupsImpl { + public: + explicit HloInstructionReplicaGroupsImpl( + std::vector> replica_groups) + : replica_groups_(std::move(replica_groups)) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + std::vector replica_group_strs; + replica_group_strs.reserve(replica_groups_.size()); + for (const std::vector& replica_group : replica_groups_) { + replica_group_strs.push_back( + absl::StrCat("{", absl::StrJoin(replica_group, ","), "}")); + } + *os << "with replica_group {" << absl::StrJoin(replica_group_strs, ",") + << "}"; + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + const HloCollectiveInstruction* collective = + DynCast(inst); + if (!collective) { + EXPLAIN << "HloInstruction is not a collective"; + return false; + } + + if (absl::c_equal(collective->replica_groups(), replica_groups_, + [](const ReplicaGroup& a, const std::vector& b) { + return absl::c_equal(a.replica_ids(), b); + })) { + return true; + } + + std::ostringstream desc_stream; + DescribeTo(&desc_stream); + + std::vector replica_group_strs; + replica_group_strs.reserve(replica_groups_.size()); + for (const ReplicaGroup& replica_group : collective->replica_groups()) { + replica_group_strs.push_back(absl::StrCat( + "{", absl::StrJoin(replica_group.replica_ids(), ","), "}")); + } + EXPLAIN << "replica_group {" << absl::StrJoin(replica_group_strs, ",") + << "} don't match expected " << desc_stream.str(); + return false; + } + + std::vector> replica_groups_; +}; + +class HloInstructionShardingImpl { + public: + explicit HloInstructionShardingImpl( + const std::optional& sharding) + : sharding_(sharding) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + if (sharding_.has_value()) { + *os << "with sharding " << sharding_->ToString(); + } else { + *os << "with no sharding"; + } + } + + private: + template + bool MatchImpl(HloInstructionType* inst, MatchOption option) const { + if (!sharding_.has_value()) { + if (!inst->has_sharding()) { + return true; + } + EXPLAIN << "HloInstruction is expected to have no sharding."; + return false; + } + if (inst->has_sharding()) { + if (inst->sharding() == sharding_.value()) { + return true; + } + EXPLAIN << "sharding " << inst->sharding().ToString() + << " don't match expected " << sharding_->ToString(); + return false; + } else { + EXPLAIN << "HloInstruction has no sharding. Expected: " + << sharding_->ToString(); + return false; + } + } + + std::optional sharding_; +}; + +// Matches a constant scalar or effective scalar, optionally with a given value. +template +class HloConstantScalarImpl { + public: + explicit constexpr HloConstantScalarImpl(bool match_effective_scalar) + : val_(std::nullopt), match_effective_scalar_(match_effective_scalar) {} + + constexpr HloConstantScalarImpl(ScalarTy val, bool match_effective_scalar) + : val_(val), match_effective_scalar_(match_effective_scalar) {} + + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + bool Match(::xla::HloInstruction* inst, MatchOption option) const { + return MatchImpl(inst, option); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + *os << "which is a constant " + << (match_effective_scalar_ ? "effective " : "") << "scalar"; + if (val_.has_value()) { + *os << " with value " << *val_; + } + } + + private: + template + bool MatchImpl(InstTy* inst, MatchOption option) const { + const auto* const_inst = DynCast(inst); + if (!const_inst) { + EXPLAIN << "HloInstruction is not a constant"; + return false; + } + if (match_effective_scalar_ && + !ShapeUtil::IsEffectiveScalar(inst->shape())) { + EXPLAIN << "HloInstruction is not an effective scalar"; + return false; + } + if (!match_effective_scalar_ && !ShapeUtil::IsScalar(inst->shape())) { + EXPLAIN << "HloInstruction is not a scalar"; + return false; + } + if (!val_.has_value()) { + return true; + } + + auto const_inst_scalar_or = const_inst->literal().Reshape({}); + if (!const_inst_scalar_or.ok()) { + EXPLAIN << "could not convert matched literal to effective scalar"; + return false; + } + Literal const_inst_scalar = std::move(const_inst_scalar_or).value(); + if (!const_inst_scalar.IsEqualAt({}, *val_)) { + EXPLAIN << "HloInstruction's constant value " + << const_inst_scalar.ToStringWithoutShape() + << " did not match expected value " << *val_; + return false; + } + return true; + } + + std::optional val_; + bool match_effective_scalar_; +}; + +// A pattern that matches HloInstructions. +template +class HloInstructionPattern { + private: + template + auto AppendImpl(NewImpl new_impl) const { + auto new_allof = AllOf<::xla::HloInstruction>(impl_, std::move(new_impl)); + return HloInstructionPattern( + std::move(new_allof), matched_inst_); + } + + public: + explicit constexpr HloInstructionPattern(const Impl& impl, + HloInstructionType** matched_inst) + : impl_(impl), matched_inst_(matched_inst) {} + + // Returns true and captures the instruction iff it matches the pattern. + bool Match(const ::xla::HloInstruction* inst, MatchOption option) const { + if (impl_.Match(inst, option)) { + if (option.capture && matched_inst_) { + *matched_inst_ = inst; + } + return true; + } + if (inst != nullptr) { + EXPLAIN << "\nin " << InstToString(inst); + } + return false; + } + + // Returns true and captures the instruction iff it matches the pattern. + bool Match(::xla::HloInstruction* inst, MatchOption option, + bool explain_instruction = true) const { + if (impl_.Match(inst, option)) { + if (option.capture && matched_inst_) { + *matched_inst_ = inst; + } + return true; + } + if (explain_instruction) { + EXPLAIN << "\nin " << InstToString(inst); + } + return false; + } + + // Modifies the pattern to match only if the instruction has the given name. + auto WithName(absl::string_view name) const { + return AppendImpl(HloInstructionPatternNameImpl(name)); + } + + // Modifies the pattern to match only if the instruction has the given opcode. + auto WithOpcode(HloOpcode opcode) const { + return AppendImpl(HloInstructionPatternOpcodeImpl(opcode, false)); + } + + // Modifies the pattern to match a custom call with one of the given targets. + auto WithCustomCallTarget( + absl::Span custom_call_targets) const { + return AppendImpl(HloInstructionCustomCallTargetImpl(custom_call_targets)); + } + + auto WithNumOperands(int64_t num_operands) const { + return AppendImpl(HloInstructionPatternNumOperandsImpl(num_operands)); + } + + // Modifies the pattern to match only if the instruction does not have the + // given opcode. + auto WithoutOpcode(HloOpcode opcode) const { + return AppendImpl(HloInstructionPatternOpcodeImpl(opcode, true)); + } + + constexpr auto Is(const HloInstruction* instr) const { + return AppendImpl(HloInstructionIsImpl(instr)); + } + + // Modifies the pattern to match only if the instruction is a constant. + constexpr auto IsConstant() const { return WithOpcode(HloOpcode::kConstant); } + + constexpr auto IsConstantScalar() const { + return AppendImpl( + HloConstantScalarImpl(/*match_effective_scalar=*/false)); + } + + // This does not check that T has the same type as the instruction, so e.g. + // IsConstantScalar(1.0) may match a constant of shape int32_t[]. + template + constexpr auto IsConstantScalar(const ScalarTy& val) const { + return AppendImpl( + HloConstantScalarImpl(val, /*match_effective_scalar=*/false)); + } + + constexpr auto IsConstantEffectiveScalar() const { + return AppendImpl( + HloConstantScalarImpl(/*match_effective_scalar=*/true)); + } + + template + constexpr auto IsConstantEffectiveScalar(const ScalarTy& val) const { + return AppendImpl( + HloConstantScalarImpl(val, /*match_effective_scalar=*/true)); + } + + // Modifies the pattern to match only if the instruction is not a constant. + constexpr auto IsNonConstant() const { + return WithoutOpcode(HloOpcode::kConstant); + } + + // Modifies the pattern to match only if the instruction has a shape that + // matches the given pattern. + template + constexpr auto WithShape( + const ShapePattern& shape) const { + return AppendImpl( + HloInstructionPatternShapeImpl(shape)); + } + + // Because we only specify the shape's element type and dims, this is + // effectivley checking shape-compatible-to, not shape-equal-to. Perhaps this + // function should be called WithShapeCompatibleTo, but the short name is + // nice, and there's no ambiguity because there's no layout in the args! + constexpr auto WithShape(PrimitiveType ty, absl::Span dims) { + return WithShape(Shape().WithElementType(ty).WithDims(dims)); + } + + // Modifies the pattern to match only if the instruction's shape's element + // type, dims and minor to major dimension ordering match the given pattern. + constexpr auto WithShape(PrimitiveType ty, absl::Span dims, + absl::Span minor_to_major) { + return WithShape( + Shape().WithElementType(ty).WithDims(dims).WithLayout(minor_to_major)); + } + // Make this a templated function to work around gcc 4.9.4 template infinite + // recursion bug. + template + constexpr auto WithShapeEqualTo(const ::xla::Shape* shape) const { + return WithShape(Shape().EqualTo(shape)); + } + + // Make this a templated function to work around gcc 4.9.4 template infinite + // recursion bug. + template + constexpr auto WithShapeCompatibleTo(const ::xla::Shape* shape) const { + return WithShape(Shape().CompatibleTo(shape)); + } + + // Modifies the pattern to match only if the instruction's shape's element + // type matches the given pattern. + constexpr auto WithElementType(PrimitiveType ty) { + return WithShape(Shape().WithElementType(ty)); + } + + // Modifies the pattern to match only if the instruction has an operand that + // matches the given pattern. + template + constexpr auto WithOperand( + int64_t operand_index, + const HloInstructionPattern& operand) const { + return AppendImpl( + HloInstructionPatternOperandImpl( + operand_index, operand)); + } + + // Modifies the pattern to match only if + // - the instruction has fewer than i+1 operands, or + // - the i'th operand matches the given pattern. + template + constexpr auto WithOperandIfPresent( + int64_t operand_index, + const HloInstructionPattern& operand) const { + return AppendImpl( + HloInstructionPatternOperandIfPresentImpl( + operand_index, operand)); + } + + template + constexpr auto WithBinaryOperandsAnyOrder( + const HloInstructionPattern& op1, + const HloInstructionPattern& op2) const { + return AppendImpl( + HloInstructionPatternBinaryOperandsAnyOrderImpl< + OperandType1, OperandImpl1, OperandType2, OperandImpl2>(op1, op2)); + } + + // Modifies the pattern to match only if the instruction is a fusion node with + // the given kind. + constexpr auto WithFusionKind(HloInstruction::FusionKind kind) const { + return AppendImpl(HloInstructionPatternFusionKindImpl(kind)); + } + + // Modifies the pattern to match only if the instruction is a + // get-tuple-element with the given tuple index. + constexpr auto WithTupleIndex(int64_t tuple_index) const { + return AppendImpl(HloInstructionPatternTupleIndexImpl(tuple_index)); + } + + // Modifies the pattern to match only if the instruction is a parameter + // with the given parameter number. + constexpr auto WithParameterNum(int64_t parameter_num) const { + return AppendImpl(HloInstructionPatternParameterNumImpl(parameter_num)); + } + + // Modifies the pattern to match if the instruction is used exactly once. + // Does not match if the instruction is used twice by the same user (e.g. + // multiply(x,x)). + constexpr auto WithOneUse() const { + return AppendImpl(HloInstructionPatternOneUseImpl()); + } + + // Modifies the pattern to match if the instruction is used by exactly one + // other instruction. Will match if the instruction is used twice, so long as + // it's by the same user (e.g. multiply(x,x)). + constexpr auto WithOneUser() const { + return AppendImpl(HloInstructionPatternOneUserImpl()); + } + + // Modifies the pattern to match only if the instruction has the given + // comparison direction. + auto WithComparisonDirection(ComparisonDirection direction) const { + return AppendImpl(HloInstructionPatternComparisonDirectionImpl(direction)); + } + + auto WithConvDnums(absl::string_view dnums) const { + return AppendImpl(HloInstructionPatternConvDnumsImpl(dnums)); + } + auto WithConvDnums(ConvolutionDimensionNumbers dnums) const { + return AppendImpl(HloInstructionPatternConvDnumsImpl(dnums)); + } + + auto WithPredicate(HloPredicate fn) const { + return AppendImpl(HloInstructionPredicateImpl(std::move(fn))); + } + + auto WithContractingDims( + absl::Span lhs_contracting_dims, + absl::Span rhs_contracting_dims) const { + return AppendImpl(HloInstructionContractingDimsImpl(lhs_contracting_dims, + rhs_contracting_dims)); + } + + auto WithReplicaGroups( + std::vector> replica_groups) const { + return AppendImpl( + HloInstructionReplicaGroupsImpl(std::move(replica_groups))); + } + + auto WithSharding(absl::string_view sharding) const { + return AppendImpl( + HloInstructionShardingImpl(ParseSharding(sharding).value())); + } + + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + impl_.DescribeTo(os, indent); + } + + private: + Impl impl_; + HloInstructionType** matched_inst_; +}; + +template +struct AnyOfImpl { + auto operator()(const Patterns&... patterns) const { + return AnyOfPattern::type, Patterns...>( + patterns...); + } +}; + +template +struct AnyOfImpl { + auto operator()(const Patterns&... patterns) const { + auto any_of = AnyOfPattern(patterns...); + return HloInstructionPattern( + std::move(any_of), /*matched_inst=*/nullptr); + } +}; + +} // namespace detail + +// Returns a pattern that represents the logical disjunction of the input +// patterns. The returned pattern matches from left to right, and stops on the +// first match. +template +auto AnyOf(const Patterns&... patterns) { + return detail::AnyOfImpl()(patterns...); +} + +// Creates an instruction pattern that will capture the matched instruction in +// the argument. +inline constexpr auto Op(const ::xla::HloInstruction** matched_inst = nullptr) { + return detail::HloInstructionPattern( + detail::HloInstructionPatternBaseImpl(), matched_inst); +} + +// Creates an instruction pattern that will capture the matched instruction in +// the argument. +inline constexpr auto Op(::xla::HloInstruction** matched_inst) { + return detail::HloInstructionPattern<::xla::HloInstruction, + detail::HloInstructionPatternBaseImpl>( + detail::HloInstructionPatternBaseImpl(), matched_inst); +} + +// Helpers for nullary instructions. +#define XLA_NULLOP_PATTERN(NAME) \ + inline auto NAME() { return Op().WithOpcode(HloOpcode::k##NAME); } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst) { \ + return Op(matched_inst).WithOpcode(HloOpcode::k##NAME); \ + } +XLA_NULLOP_PATTERN(Constant) +XLA_NULLOP_PATTERN(Parameter) +XLA_NULLOP_PATTERN(Iota) +XLA_NULLOP_PATTERN(Rng) +XLA_NULLOP_PATTERN(PartitionId) +XLA_NULLOP_PATTERN(ReplicaId) +#undef XLA_NULLOP_PATTERN + +// Helpers for unary instructions. +#define XLA_UNOP_PATTERN(NAME) \ + inline auto NAME() { return Op().WithOpcode(HloOpcode::k##NAME); } \ + \ + template \ + inline auto NAME(Arg&& arg) { \ + return Op() \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithOperand(0, std::forward(arg)); \ + } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst, Arg&& arg) { \ + return Op(matched_inst) \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithOperand(0, std::forward(arg)); \ + } +XLA_UNOP_PATTERN(Abs) +XLA_UNOP_PATTERN(RoundNearestAfz) +XLA_UNOP_PATTERN(Bitcast) +XLA_UNOP_PATTERN(BitcastConvert) +XLA_UNOP_PATTERN(Broadcast) +XLA_UNOP_PATTERN(Ceil) +XLA_UNOP_PATTERN(Convert) +XLA_UNOP_PATTERN(Copy) +XLA_UNOP_PATTERN(Cos) +XLA_UNOP_PATTERN(AllReduceStart) +XLA_UNOP_PATTERN(AllReduceDone) +XLA_UNOP_PATTERN(AllToAll) +XLA_UNOP_PATTERN(CollectivePermute) +XLA_UNOP_PATTERN(CollectivePermuteStart) +XLA_UNOP_PATTERN(CollectivePermuteDone) +XLA_UNOP_PATTERN(Domain) +XLA_UNOP_PATTERN(Exp) +XLA_UNOP_PATTERN(Fft) +XLA_UNOP_PATTERN(Floor) +XLA_UNOP_PATTERN(GetTupleElement) +XLA_UNOP_PATTERN(Imag) +XLA_UNOP_PATTERN(Infeed) +XLA_UNOP_PATTERN(IsFinite) +XLA_UNOP_PATTERN(Log) +XLA_UNOP_PATTERN(Not) +XLA_UNOP_PATTERN(Negate) +XLA_UNOP_PATTERN(Real) +XLA_UNOP_PATTERN(Recv) +XLA_UNOP_PATTERN(RecvDone) +XLA_UNOP_PATTERN(ReducePrecision) +XLA_UNOP_PATTERN(Reshape) +XLA_UNOP_PATTERN(Reverse) +XLA_UNOP_PATTERN(Rsqrt) +XLA_UNOP_PATTERN(SendDone) +XLA_UNOP_PATTERN(Sign) +XLA_UNOP_PATTERN(Sin) +XLA_UNOP_PATTERN(Slice) +XLA_UNOP_PATTERN(Sqrt) +XLA_UNOP_PATTERN(Tan) +XLA_UNOP_PATTERN(Tanh) +XLA_UNOP_PATTERN(Transpose) +#undef XLA_UNOP_PATTERN + +// Helpers for binary instructions. +#define XLA_BINOP_PATTERN(NAME) \ + inline auto NAME() { return Op().WithOpcode(HloOpcode::k##NAME); } \ + \ + template \ + inline auto NAME(Lhs&& lhs, Rhs&& rhs) { \ + return Op() \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithOperand(0, std::forward(lhs)) \ + .WithOperand(1, std::forward(rhs)); \ + } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst, Lhs&& lhs, Rhs&& rhs) { \ + return Op(matched_inst) \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithOperand(0, std::forward(lhs)) \ + .WithOperand(1, std::forward(rhs)); \ + } + +#define XLA_COMMUTATIVE_BINOP_PATTERN(NAME) \ + XLA_BINOP_PATTERN(NAME) \ + \ + template \ + inline auto NAME##AnyOrder(HloInstructionType** matched_inst, Lhs&& lhs, \ + Rhs&& rhs) { \ + return Op(matched_inst) \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithBinaryOperandsAnyOrder(std::forward(lhs), \ + std::forward(rhs)); \ + } \ + template \ + inline auto NAME##AnyOrder(Lhs&& lhs, Rhs&& rhs) { \ + return NAME##AnyOrder( \ + nullptr, std::forward(lhs), std::forward(rhs)); \ + } +XLA_COMMUTATIVE_BINOP_PATTERN(Add) +XLA_BINOP_PATTERN(Atan2) +XLA_BINOP_PATTERN(Divide) +XLA_BINOP_PATTERN(Complex) +XLA_BINOP_PATTERN(Compare) +XLA_BINOP_PATTERN(Convolution) +XLA_BINOP_PATTERN(Dot) +XLA_BINOP_PATTERN(Gather) +XLA_COMMUTATIVE_BINOP_PATTERN(Maximum) +XLA_COMMUTATIVE_BINOP_PATTERN(Minimum) +XLA_COMMUTATIVE_BINOP_PATTERN(Multiply) +XLA_BINOP_PATTERN(Outfeed) +XLA_BINOP_PATTERN(Pad) +XLA_BINOP_PATTERN(Power) +XLA_BINOP_PATTERN(Remainder) +XLA_BINOP_PATTERN(Send) +XLA_BINOP_PATTERN(Subtract) +XLA_COMMUTATIVE_BINOP_PATTERN(And) +XLA_COMMUTATIVE_BINOP_PATTERN(Or) +XLA_BINOP_PATTERN(ShiftLeft) +XLA_BINOP_PATTERN(ShiftRightArithmetic) +XLA_BINOP_PATTERN(ShiftRightLogical) +XLA_COMMUTATIVE_BINOP_PATTERN(Xor) +#undef XLA_COMMUTATIVE_BINOP_PATTERN +#undef XLA_BINOP_PATTERN + +// Helpers for ternary instructions. +#define XLA_TERNOP_PATTERN(NAME) \ + inline auto NAME() { return Op().WithOpcode(HloOpcode::k##NAME); } \ + \ + template \ + inline auto NAME(Arg0&& arg0, Arg1&& arg1, Arg2&& arg2) { \ + return Op() \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithOperand(0, std::forward(arg0)) \ + .WithOperand(1, std::forward(arg1)) \ + .WithOperand(2, std::forward(arg2)); \ + } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst, Arg0&& arg0, \ + Arg1&& arg1, Arg2&& arg2) { \ + return Op(matched_inst) \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithOperand(0, std::forward(arg0)) \ + .WithOperand(1, std::forward(arg1)) \ + .WithOperand(2, std::forward(arg2)); \ + } +XLA_TERNOP_PATTERN(Clamp); +XLA_TERNOP_PATTERN(Select); +XLA_TERNOP_PATTERN(SelectAndScatter); +#undef XLA_TERNOP_PATTERN + +namespace detail { +template +inline auto WithOperands(Matcher&& m, int64_t operand_num, + FirstArg&& first_arg) { + return m.WithOperand(operand_num, std::forward(first_arg)); +} + +template +inline auto WithOperands(Matcher&& m, int64_t operand_num, FirstArg&& first_arg, + Args&&... args) { + return WithOperands( + m.WithOperand(operand_num, std::forward(first_arg)), + operand_num + 1, std::forward(args)...); +} +} // namespace detail + +#define XLA_VARIADIC_OP_PATTERN(NAME) \ + inline auto NAME() { return Op().WithOpcode(HloOpcode::k##NAME); } \ + \ + template \ + inline auto NAME(Args&&... args) { \ + return detail::WithOperands( \ + Op().WithOpcode(HloOpcode::k##NAME).WithNumOperands(sizeof...(Args)), \ + /*operand_num=*/0, std::forward(args)...); \ + } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst, Args&&... args) { \ + return detail::WithOperands(Op(matched_inst) \ + .WithOpcode(HloOpcode::k##NAME) \ + .WithNumOperands(sizeof...(Args)), \ + /*operand_num=*/0, \ + std::forward(args)...); \ + } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst) { \ + return Op(matched_inst).WithOpcode(HloOpcode::k##NAME); \ + } + +// We could implement all ops as "variadic" ops, but it would make the +// already-bad compile errors even worse. +XLA_VARIADIC_OP_PATTERN(AfterAll); +XLA_VARIADIC_OP_PATTERN(AllGather) +XLA_VARIADIC_OP_PATTERN(AllReduce) +XLA_VARIADIC_OP_PATTERN(Concatenate); +XLA_VARIADIC_OP_PATTERN(Conditional); +XLA_VARIADIC_OP_PATTERN(DynamicSlice) +XLA_VARIADIC_OP_PATTERN(DynamicUpdateSlice) +XLA_VARIADIC_OP_PATTERN(Fusion); +XLA_VARIADIC_OP_PATTERN(Map) +XLA_VARIADIC_OP_PATTERN(Reduce); +XLA_VARIADIC_OP_PATTERN(ReduceScatter) +XLA_VARIADIC_OP_PATTERN(ReduceWindow) +XLA_VARIADIC_OP_PATTERN(Scatter); +XLA_VARIADIC_OP_PATTERN(Sort); +XLA_VARIADIC_OP_PATTERN(Tuple); +XLA_VARIADIC_OP_PATTERN(Call); + +// CustomCall doesn't use the XLA_VARIADIC_OP_PATTERN macro so that you can +// optionally pass a string_view for the custom_call_target before the other +// operands. +inline auto CustomCall() { return Op().WithOpcode(HloOpcode::kCustomCall); } + +template +auto CustomCall(HloInstructionType** matched_inst) { + return Op(matched_inst).WithOpcode(HloOpcode::kCustomCall); +} + +template < + typename Arg0, typename... Args, + typename std::enable_if< + !std::is_convertible::value && + !std::is_convertible::value && + !std::is_convertible::value>::type* = + nullptr> +auto CustomCall(Arg0&& arg0, Args&&... args) { + return detail::WithOperands(CustomCall().WithNumOperands(sizeof...(Args) + 1), + /*operand_num=*/0, std::forward(arg0), + std::forward(args)...); +} + +template +auto CustomCall(absl::Span custom_call_targets, + Args&&... args) { + return CustomCall(std::forward(args)...) + .WithCustomCallTarget(custom_call_targets); +} + +template ::value>::type* = nullptr> +auto CustomCall(HloInstructionType** matched_inst, Arg0&& arg0, + Args&&... args) { + return detail::WithOperands( + CustomCall(matched_inst).WithNumOperands(sizeof...(Args) + 1), + /*operand_num=*/0, std::forward(arg0), std::forward(args)...); +} + +template +auto CustomCall(HloInstructionType** matched_inst, + absl::Span custom_call_targets, + Args&&... args) { + return CustomCall(matched_inst, std::forward(args)...) + .WithCustomCallTarget(custom_call_targets); +} + +// Helpers for comparison instructions. +#define XLA_COMPARE_PATTERN(NAME) \ + inline auto NAME() { \ + return Op() \ + .WithOpcode(HloOpcode::kCompare) \ + .WithComparisonDirection(ComparisonDirection::k##NAME); \ + } \ + \ + template \ + inline auto NAME(Lhs&& lhs, Rhs&& rhs) { \ + return Op() \ + .WithOpcode(HloOpcode::kCompare) \ + .WithOperand(0, std::forward(lhs)) \ + .WithOperand(1, std::forward(rhs)) \ + .WithComparisonDirection(ComparisonDirection::k##NAME); \ + } \ + \ + template \ + inline auto NAME(HloInstructionType** matched_inst, Lhs&& lhs, Rhs&& rhs) { \ + return Op(matched_inst) \ + .WithOpcode(HloOpcode::kCompare) \ + .WithOperand(0, std::forward(lhs)) \ + .WithOperand(1, std::forward(rhs)) \ + .WithComparisonDirection(ComparisonDirection::k##NAME); \ + } + +#define XLA_COMMUTATIVE_COMPARE_PATTERN(NAME) \ + XLA_COMPARE_PATTERN(NAME) \ + \ + template \ + inline auto NAME##AnyOrder(HloInstructionType** matched_inst, Lhs&& lhs, \ + Rhs&& rhs) { \ + return Op(matched_inst) \ + .WithOpcode(HloOpcode::kCompare) \ + .WithBinaryOperandsAnyOrder(std::forward(lhs), \ + std::forward(rhs)); \ + } \ + template \ + inline auto NAME##AnyOrder(Lhs&& lhs, Rhs&& rhs) { \ + return NAME##AnyOrder( \ + nullptr, std::forward(lhs), std::forward(rhs)); \ + } + +XLA_COMMUTATIVE_COMPARE_PATTERN(Eq); +XLA_COMMUTATIVE_COMPARE_PATTERN(Ne); +XLA_COMPARE_PATTERN(Ge); +XLA_COMPARE_PATTERN(Gt); +XLA_COMPARE_PATTERN(Le); +XLA_COMPARE_PATTERN(Lt); + +// Helpers for matching non-constant instructions. +inline auto NonConstant() { return Op().IsNonConstant(); } + +template +inline auto NonConstant(HloInstructionType** matched_inst) { + return Op(matched_inst).IsNonConstant(); +} + +// Add overloads for GetTupleElement which take a int64_t specifying which tuple +// element is selected. +template +inline auto GetTupleElement(Arg&& arg, int64_t tuple_index) { + return Op() + .WithOpcode(HloOpcode::kGetTupleElement) + .WithOperand(0, std::forward(arg)) + .WithTupleIndex(tuple_index); +} + +template +inline auto GetTupleElement(HloInstructionType** matched_inst, Arg&& arg, + int64_t tuple_index) { + return Op(matched_inst) + .WithOpcode(HloOpcode::kGetTupleElement) + .WithOperand(0, std::forward(arg)) + .WithTupleIndex(tuple_index); +} + +// Add overloads for Parameter which take an int64_t specifying the parameter +// number. +inline auto Parameter(int64_t parameter_num) { + return Op().WithOpcode(HloOpcode::kParameter).WithParameterNum(parameter_num); +} +template +inline auto Parameter(HloInstructionType** matched_inst, + int64_t parameter_num) { + return Op(matched_inst) + .WithOpcode(HloOpcode::kParameter) + .WithParameterNum(parameter_num); +} + +inline auto ConstantScalar() { return Op().IsConstantScalar(); } + +template +inline auto ConstantScalar(HloInstructionType** matched_inst) { + return Op(matched_inst).IsConstantScalar(); +} + +template +inline auto ConstantScalar(ScalarTy val) { + return Op().IsConstantScalar(val); +} + +template +inline auto ConstantScalar(HloInstructionType** matched_inst, ScalarTy val) { + return Op(matched_inst).IsConstantScalar(val); +} + +inline auto ConstantEffectiveScalar() { + return Op().IsConstantEffectiveScalar(); +} + +template +inline auto ConstantEffectiveScalar(HloInstructionType** matched_inst) { + return Op(matched_inst).IsConstantEffectiveScalar(); +} + +template +inline auto ConstantEffectiveScalar(ScalarTy val) { + return Op().IsConstantEffectiveScalar(val); +} + +template +inline auto ConstantEffectiveScalar(HloInstructionType** matched_inst, + ScalarTy val) { + return Op(matched_inst).IsConstantEffectiveScalar(val); +} + +namespace detail { + +// A helper for the type erasure. +class InstructionPatternInterface { + public: + virtual ~InstructionPatternInterface() = default; + + virtual bool Match(::xla::HloInstruction* instr, + MatchOption option) const = 0; + + virtual void DescribeTo(std::ostream* os, int64_t indent) const = 0; +}; + +// A helper for the type erasure. +template +class TypedInstructionPattern : public InstructionPatternInterface { + public: + explicit TypedInstructionPattern(Pattern pattern) + : pattern_(std::move(pattern)) {} + + bool Match(::xla::HloInstruction* instr, MatchOption option) const override { + return pattern_.Match(instr, option); + } + void DescribeTo(std::ostream* os, int64_t indent) const override { + pattern_.DescribeTo(os, indent); + } + + private: + Pattern pattern_; +}; + +// An Impl class for HloInstructionPattern that stores the inner pattern in a +// type-erased shared_ptr. +class HloInstructionPatternSharedImpl { + public: + template + explicit HloInstructionPatternSharedImpl(Pattern pattern) + // The return type annotation of the lambda is needed for correctness. + : pattern_(std::make_shared>( + std::move(pattern))) {} + + bool Match(::xla::HloInstruction* instr, MatchOption option) const { + return pattern_->Match(instr, option); + } + void DescribeTo(std::ostream* os, int64_t indent = 0) const { + pattern_->DescribeTo(os, indent); + } + + private: + // We use std::shared_ptr to avoid copying the underlying pattern when reusing + // it, thus avoiding exponential memory use. + std::shared_ptr pattern_; +}; + +} // namespace detail + +// Wraps the HloInstructionPattern in a type-erased shared_ptr. +// +// This can be used around repeated subpatterns to avoid exponential code growth +// and compilation time, while keeping memory usage minimal at runtime. This is +// similar to defining a subroutine in imperative programming languages. +// +// If used excessively, this may slightly increase the runtime of the patterns. +// +// Example usage: +// auto shared = m::SharedSubpattern(sub_pattern); +// return m::AnyOf(m::Convert(shared), shared); +template +inline auto SharedSubpattern( + detail::HloInstructionPattern pattern) { + auto impl = detail::HloInstructionPatternSharedImpl(std::move(pattern)); + return detail::HloInstructionPattern( + std::move(impl), /*matched_inst=*/nullptr); +} + +} // namespace match + +} // namespace xla + +#undef EXPLAIN +#pragma pop_macro("EXPLAIN") +#endif // XLA_SERVICE_PATTERN_MATCHER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/platform_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/platform_util.h new file mode 100644 index 0000000000000000000000000000000000000000..57695f6449948268f05906a8537c1f42101e2713 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/platform_util.h @@ -0,0 +1,74 @@ +/* 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_SERVICE_PLATFORM_UTIL_H_ +#define XLA_SERVICE_PLATFORM_UTIL_H_ + +#include +#include +#include + +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" + +namespace xla { + +// Utilities for querying platforms and devices used by XLA. +class PlatformUtil { + public: + // Returns the canonical name of the underlying platform. + // + // This is needed to differentiate if for given platform like GPU or CPU + // there are multiple implementations. For example, GPU platform may be + // cuda(Nvidia) or rocm(AMD) + static StatusOr CanonicalPlatformName( + const std::string& platform_name); + + // Returns the platforms present on the system and supported by XLA. + // + // Note that, even if a platform is present with zero devices, if we *do* have + // compilation support for it, it will be returned in this sequence. + static StatusOr> GetSupportedPlatforms(); + + // Convenience function which returns the default supported platform for + // tests. If exactly one supported platform is present, then this platform is + // the default platform. If exactly two platforms are present and one of them + // is the interpreter platform, then the other platform is the default + // platform. Otherwise returns an error. + static StatusOr GetDefaultPlatform(); + + // Returns the platform according to the given name. Returns error if there is + // no such platform. + static StatusOr GetPlatform(const std::string& platform_name); + + // Returns a vector of StreamExecutors for the given platform. + // If populated, only the devices in allowed_devices will have + // their StreamExecutors initialized, otherwise all StreamExecutors will be + // initialized and returned. + // + // If the platform has no visible devices, a not-found error is returned. + static StatusOr> GetStreamExecutors( + se::Platform* platform, + const std::optional>& allowed_devices = std::nullopt); + + private: + PlatformUtil(const PlatformUtil&) = delete; + PlatformUtil& operator=(const PlatformUtil&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_PLATFORM_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/profile_guided_latency_estimator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/profile_guided_latency_estimator.h new file mode 100644 index 0000000000000000000000000000000000000000..5d71e85751317ab006233314d071cb2cbcc5eb49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/profile_guided_latency_estimator.h @@ -0,0 +1,61 @@ +/* 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_SERVICE_PROFILE_GUIDED_LATENCY_ESTIMATOR_H_ +#define XLA_SERVICE_PROFILE_GUIDED_LATENCY_ESTIMATOR_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/service/latency_hiding_scheduler.h" +#include "tsl/profiler/protobuf/profiled_instructions.pb.h" + +namespace xla { + +// Implementation of LatencyEstimator using a profile to estimate HLO cost and +// latencies between instructions. If a cost is not known, it will forward to +// an underlying estimator. +class ProfileGuidedLatencyEstimator : public LatencyEstimator { + public: + ProfileGuidedLatencyEstimator( + const SchedulerConfig& config, + std::unique_ptr latency_estimator, + const tensorflow::profiler::ProfiledInstructionsProto& proto); + + TimeCost GetLatencyBetween(const HloGraphNode& from, + const HloGraphNode& target) const override; + TimeCost NodeCost(const HloInstruction* instr) const override; + int CyclesPerMicrosecond() const override { + return latency_estimator_->CyclesPerMicrosecond(); + } + + private: + const SchedulerConfig config_; + std::unique_ptr latency_estimator_; + + // Profile info pertaining to a single instruction. + struct ProfileInfo { + std::optional cost; + // Latencies to other instruction with this instruction as source. + absl::flat_hash_map latencies; + }; + absl::flat_hash_map instr_map_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_PROFILE_GUIDED_LATENCY_ESTIMATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/qr_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/qr_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..ab381bc57433d33e56fbe629086c0a419da34d85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/qr_expander.h @@ -0,0 +1,57 @@ +/* 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_SERVICE_QR_EXPANDER_H_ +#define XLA_SERVICE_QR_EXPANDER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/client/lib/qr.h" +#include "xla/client/xla_builder.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +class QrExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "qr_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; + + virtual StatusOr QrBlock( + XlaOp a, PrecisionConfig::Precision precision); + + virtual StatusOr CompactWYRepresentation( + PrimitiveType type, absl::Span batch_dims, XlaOp vs, + XlaOp taus, int64_t m, int64_t n, PrecisionConfig::Precision precision); + + private: + StatusOr BuildQrDecomposition(XlaOp a, int64_t block_size, + PrecisionConfig::Precision precision); + + StatusOr ProductOfElementaryHouseholderReflectors( + XlaOp a, XlaOp taus, int64_t block_size, + PrecisionConfig::Precision precision); + + // Mapping from op signatures to existing computations. + absl::flat_hash_map computation_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_QR_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/real_imag_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/real_imag_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..e5337197e44de556fa71b8e24590591ad6507159 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/real_imag_expander.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. +==============================================================================*/ + +#ifndef XLA_SERVICE_REAL_IMAG_EXPANDER_H_ +#define XLA_SERVICE_REAL_IMAG_EXPANDER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// Expands real/image instructions with non-complex inputs. +class RealImagExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "real_imag_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; + + StatusOr ExpandInstruction(HloInstruction* inst) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_REAL_IMAG_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..1486a3249deee0e26a19bf94a756cec06bf666ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_decomposer.h @@ -0,0 +1,80 @@ +/* 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_SERVICE_REDUCE_DECOMPOSER_H_ +#define XLA_SERVICE_REDUCE_DECOMPOSER_H_ + +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// For each reduction R(I), ensures the postcondition: +// +// !custom_layout_allowed(R) +// => +// layout(R) == layout(I) # modulo removed dimensions +// +// To achieve that, decomposes layout-mutating reductions which do not satisfy +// `custom_layout_allowed` into a reduction and a copy. +// +// For a singular reduction: +// +// -> reduce -> +// +// Gets turned into: +// +// -> reduce -> copy -> +// +// For a variadic recuction, the layout assignment guarantees that the layout +// is the same for all outputs. This pass will transpose the variadic reduction +// inputs which have different physical layout to the first operand. +// +// A{L} \ +// B{L} -> reduce{L'} -> +// C{L} / +// +// Get turned into: +// +// A{L} \ / GTE(1) -> copy{L'} \ +// B{L} -> reduce{E(L)} --- GTE(2) -> copy{L'} - Tuple{L'} +// C{L} / \ GTE(3) -> copy{L'} / +// +// Where E(L) is expected layout of a reduction (original layout with reduce +// dimensions dropped). +// +// PRECONDITION: +// In variadic reduction, all outputs have the same layout +// (enforced by layout assignment). +class ReduceDecomposer : public HloModulePass { + public: + explicit ReduceDecomposer(HloPredicate custom_layout_allowed = nullptr) + : custom_layout_allowed_(custom_layout_allowed) {} + + absl::string_view name() const override { return "reduce-decomposer"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + HloPredicate custom_layout_allowed_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_REDUCE_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_combiner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_combiner.h new file mode 100644 index 0000000000000000000000000000000000000000..d343688d8274abbb8b3f2405e7151108b294f709 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_combiner.h @@ -0,0 +1,51 @@ +/* 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_SERVICE_REDUCE_SCATTER_COMBINER_H_ +#define XLA_SERVICE_REDUCE_SCATTER_COMBINER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Combines small non-dependent ReduceScatter ops into larger combined +// ReduceScatter ops. A typical ReduceScatter implementation has a minimum +// latency-induced time for a ReduceScatter op so a single combined op can be +// more efficient than many small ones. +class ReduceScatterCombiner : public HloModulePass { + public: + ReduceScatterCombiner(int64_t combine_threshold_in_bytes, + int64_t combine_threshold_count); + + absl::string_view name() const override { return "reduce-scatter-combiner"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // Combine reduce-scatter ops up to this threshold. + int64_t combine_threshold_in_bytes_; + + // Combine reduce-scatter ops up to this threshold (number of operands). + int64_t combine_threshold_count_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_REDUCE_SCATTER_COMBINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..2717baa31a18ae4ba67923f855d8c1906403651e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_decomposer.h @@ -0,0 +1,47 @@ +/* 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_SERVICE_REDUCE_SCATTER_DECOMPOSER_H_ +#define XLA_SERVICE_REDUCE_SCATTER_DECOMPOSER_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// A pass that decomposes a reduce-scatter into an all-reduce followed by a +// dynamic-slice. +class ReduceScatterDecomposer : public HloModulePass { + public: + explicit ReduceScatterDecomposer( + std::function update_layout = nullptr) + : update_layout_(update_layout) {} + absl::string_view name() const override { + return "reduce-scatter-decomposer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + std::function update_layout_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_REDUCE_SCATTER_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_reassociate.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_reassociate.h new file mode 100644 index 0000000000000000000000000000000000000000..bc7c92532a41775ddcf10f5dcf256a7a574f6a1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reduce_scatter_reassociate.h @@ -0,0 +1,45 @@ +/* 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_SERVICE_REDUCE_SCATTER_REASSOCIATE_H_ +#define XLA_SERVICE_REDUCE_SCATTER_REASSOCIATE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// A pass that reassociates reduce-scatter feeding into compatible elementwise +// operations. As an example: add(reduce-scatter(x), reduce-scatter(y)) will be +// replaced with reduce_scatter(add(x,y)). +// +// i.e., reassociating the reduce-scatter operation. + +class ReduceScatterReassociate : public HloModulePass { + public: + absl::string_view name() const override { + return "reduce-scatter-reassociate"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_REDUCE_SCATTER_REASSOCIATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rendezvous.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rendezvous.h new file mode 100644 index 0000000000000000000000000000000000000000..a22b491ead581cc4d8cc1da36c63eab814def994 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rendezvous.h @@ -0,0 +1,139 @@ +/* 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_SERVICE_RENDEZVOUS_H_ +#define XLA_SERVICE_RENDEZVOUS_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/functional/function_ref.h" +#include "absl/synchronization/mutex.h" +#include "absl/time/time.h" +#include "absl/types/span.h" + +namespace xla { + +template +class ThreadSafeMap { + public: + V& operator[](const K& key) { + absl::MutexLock lock(&mutex_); + std::unique_ptr& value = map_[key]; + if (value == nullptr) value = std::make_unique(); + return *value; + } + + void ForEachValue(absl::FunctionRef fn) { + absl::MutexLock lock(&mutex_); + for (const auto& [_, value] : map_) fn(*value); + } + + private: + absl::Mutex mutex_; + absl::flat_hash_map> map_ ABSL_GUARDED_BY(mutex_); +}; + +void AwaitAndLogIfStuck(absl::Mutex& mutex, const absl::Condition& condition, + absl::Duration warn_stuck_timeout, + absl::Duration terminate_timeout); + +// A rendezvous for a group of threads. +// +// The group of threads identifies itself with a key that must be unique to the +// the group. When all threads have arrived at the rendezvous, one thread +// executes the given function with the values supplied by each thread, and all +// threads receive the result. +// TODO(cjfj): Replace XLA rendezvous code with this simpler implementation. +template +std::shared_ptr RendezvousSingle( + const K& key, const V& value, size_t num_threads, + absl::FunctionRef)> fn, + absl::Duration warn_stuck_timeout = absl::InfiniteDuration(), + absl::Duration terminate_timeout = absl::InfiniteDuration()) { + // Fast-path (DO NOT REMOVE: the logic below doesn't work for single thread). + if (num_threads == 1) return std::make_shared(fn({&value})); + + struct State { + absl::Mutex mutex; + std::vector values ABSL_GUARDED_BY(mutex); + std::shared_ptr result ABSL_GUARDED_BY(mutex); + }; + + static auto& states = *new ThreadSafeMap; + State& state = states[key]; + + absl::MutexLock lock(&state.mutex); + state.values.push_back(&value); + + std::shared_ptr result; + if (state.values.size() == num_threads) { + // Last thread to arrive executes the function. + CHECK(state.result == nullptr); + result = std::make_shared(fn(state.values)); + state.result = result; + state.values.clear(); + } else { + absl::Condition result_ready( + +[](std::shared_ptr* ptr) { return ptr->get() != nullptr; }, + &state.result); + AwaitAndLogIfStuck(state.mutex, result_ready, warn_stuck_timeout, + terminate_timeout); + + // There is one use of the result in the shared state, plus one use for each + // thread that has already retrieved the result. + if (state.result.use_count() < num_threads) { + result = state.result; + } else { + // Last thread to retrieve the result takes the result from the state, + // allowing the other threads to exit the function. + return std::move(state.result); + } + } + + // Wait for all threads to have retrieved the result. Without this, a thread + // could duplicate or delete its copy of the result, invalidating the use + // count logic above. + absl::Condition result_taken( + +[](std::shared_ptr* ptr) { return ptr->get() == nullptr; }, + &state.result); + AwaitAndLogIfStuck(state.mutex, result_taken, warn_stuck_timeout, + terminate_timeout); + return result; +} + +// A rendezvous for a group of threads. +// +// The group of threads identifies itself with a key that must be unique to the +// the group. When all threads have arrived at the rendezvous, one thread +// executes the given function and all threads receive the result. +// TODO(cjfj): Replace XLA rendezvous code with this simpler implementation. +template +std::shared_ptr RendezvousSingle( + const K& key, size_t num_threads, absl::FunctionRef fn, + absl::Duration warn_stuck_timeout = absl::InfiniteDuration(), + absl::Duration terminate_timeout = absl::InfiniteDuration()) { + // Pass an arbitrary value that is ignored. + return RendezvousSingle( + key, 0, num_threads, [fn](absl::Span) { return fn(); }, + warn_stuck_timeout, terminate_timeout); +} + +} // namespace xla + +#endif // XLA_SERVICE_RENDEZVOUS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reshape_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reshape_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..4b3a8bf9d6aad4caaca94fdd535cbd5edcb6bfb4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reshape_decomposer.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_RESHAPE_DECOMPOSER_H_ +#define XLA_SERVICE_RESHAPE_DECOMPOSER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Decomposes a reshape which does not satisfy the ReshapeIsBitcast precondition +// into a bitcast and a copy (physical transposition). Tries to create only one +// transposition, but when it's not possible, creates two. +// +// Postcondition: All reshapes are turned into bitcasts. +class ReshapeDecomposer : public HloModulePass { + public: + absl::string_view name() const override { return "reshape-decomposer"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_RESHAPE_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reshape_mover.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reshape_mover.h new file mode 100644 index 0000000000000000000000000000000000000000..444457bc49f96f7488f1701bfa4cd6c0bfd3fc15 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/reshape_mover.h @@ -0,0 +1,74 @@ +/* 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_SERVICE_RESHAPE_MOVER_H_ +#define XLA_SERVICE_RESHAPE_MOVER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This pass sinks kReshape and kTranspose operations (known as "rearrange" ops) +// down through elementwise ops: +// +// op(rearrange(x), rearrange(y)) => rearrange(op(x, y)). +// +// We also handle the case where one of the operands is not itself a rearrange +// op but can be trivially rearranged. For example: +// +// op(rearrange(x), broadcast(scalar_y)) => +// rearrange(x, broadcast'(scalar_y)). +// +// This pass should be run to a fixed point. It also expects algsimp to be run +// after each iteration. + +struct ReshapeMoverOptions { + // On some platforms, it's cheap to do `reshape(broadcast(f32[n] x))`. The + // reshape and broadcast can always be fused, and the index calculations are + // not expensive. In such cases it can be beneficial for us to create these + // reshapes eagerly, allowing us to get rid of more expensive ones. + bool reshape_of_1d_broadcast_is_cheap = false; +}; + +class ReshapeMover : public HloModulePass { + public: + explicit ReshapeMover( + const ReshapeMoverOptions& options = ReshapeMoverOptions{}) + : options_(options) {} + + absl::string_view name() const override { return "reshape-mover"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr TryReshapeMoveOnCandidates(HloInstructionSet* candidates); + StatusOr SinkRearrangeOperands(HloInstruction* instruction); + StatusOr ApplyInverseRearrange( + const HloInstruction* rearrange, HloInstruction* operand); + bool IsReshapeMoveCandidate(HloInstruction* instruction); + const HloInstruction* FirstNontrivialRearrange( + absl::Span instrs); + bool CanTriviallyRearrange(const HloInstruction* instr, + const HloInstruction* rearrange); + + ReshapeMoverOptions options_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_RESHAPE_MOVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/result_caster.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/result_caster.h new file mode 100644 index 0000000000000000000000000000000000000000..c5fd47d2c8fa1ccd883aa61ae72203731a5b7458 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/result_caster.h @@ -0,0 +1,43 @@ +/* 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_SERVICE_RESULT_CASTER_H_ +#define XLA_SERVICE_RESULT_CASTER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// Inserts Convert to result of instructions to the preferred element type +// specified by the instructions when direct accumulation of that type isn't +// supported by the backend. This pass should run after OperandUpcaster. +class ResultCaster : public OpExpanderPass { + public: + explicit ResultCaster(HloPredicate extra_filter = nullptr) + : OpExpanderPass(std::move(extra_filter)) {} + + absl::string_view name() const override { return "result_caster"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_RESULT_CASTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rng_bit_generator_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rng_bit_generator_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..b297e8c9b1dc47265bce5ee4a4c7e9b4578c9644 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rng_bit_generator_expander.h @@ -0,0 +1,72 @@ +/* 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_SERVICE_RNG_BIT_GENERATOR_EXPANDER_H_ +#define XLA_SERVICE_RNG_BIT_GENERATOR_EXPANDER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/op_expander_pass.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +class RngBitGeneratorExpander : public OpExpanderPass { + public: + explicit RngBitGeneratorExpander(RandomAlgorithm default_algorithm) + : default_algorithm_(default_algorithm) { + CHECK_NE(default_algorithm_, RandomAlgorithm::RNG_DEFAULT); + } + + absl::string_view name() const override { + return "rng-bit-generator-expander"; + } + + protected: + struct RngGeneratorKey { + Shape data_shape; + Shape state_shape; + RandomAlgorithm algorithm; + HloModule* module; + + template + friend H AbslHashValue(H h, const RngGeneratorKey& c) { + return H::combine(std::move(h), c.state_shape, c.data_shape, c.algorithm, + c.module); + } + + bool operator==(const RngGeneratorKey& o) const { + return data_shape == o.data_shape && state_shape == o.state_shape && + algorithm == o.algorithm && module == o.module; + } + }; + + bool InstructionMatchesPattern(HloInstruction* instruction) override; + StatusOr ExpandInstruction(HloInstruction* hlo) override; + StatusOr GetGeneratorComputation(const Shape& data_shape, + const Shape& state_shape, + RandomAlgorithm algorithm, + HloModule* module); + + const RandomAlgorithm default_algorithm_; + absl::flat_hash_map computation_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_RNG_BIT_GENERATOR_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rng_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rng_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..8ba3ca11cfac8ceef98ea38e68f5260f162e03de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/rng_expander.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_RNG_EXPANDER_H_ +#define XLA_SERVICE_RNG_EXPANDER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +class RngExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "rng-expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction(HloInstruction* rng) override; + + private: + // Cache RNG computations based on the distribution, output shape and shapes + // of the first and second operand. + absl::flat_hash_map, + HloComputation*> + expanded_rng_instructions_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_RNG_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/scatter_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/scatter_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..7e6ae841b0082ed3464aa691f6d5833b0e823000 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/scatter_expander.h @@ -0,0 +1,67 @@ +/* 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_SERVICE_SCATTER_EXPANDER_H_ +#define XLA_SERVICE_SCATTER_EXPANDER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// This pass rewrites scatter operations into (roughly) while loops of +// dynamic-update-slices. +// +// This pass can be used in two ways: +// +// - kEliminateAllScatters: For backends that don't support scatter, this pass +// can convert every scatter into a loop. +// +// - kEliminateSimpleScatters: For backends that *do* support scatter, this +// pass can strength-reduce "simple" scatters -- specifically, scatters that +// can be represented without a loop -- to dynamic-update-slices. +// +// - kEliminateIndeterminisitcScatters: For backends that *do* support +// scatter, this pass converts scatters with potentially indeterminisitc +// behavior, because of non-unique indices or non-associative combiner +// functions. There may be false positives, but no false negatives, i.e. +// some scatters are converted even when deterministic in practice. +// +// Note that even in kEliminateSimpleScatters mode, this pass may still expand a +// scatter into a loop (with a trip-count of 1). It's up to other +// simplification passes to remove the loop. +class ScatterExpander : public OpExpanderPass { + public: + enum Mode { + kEliminateAllScatters, + kEliminateSimpleScatters, + kEliminateIndeterminisitcScatters, + }; + + explicit ScatterExpander(Mode m) : mode_(m) {} + + absl::string_view name() const override { return "scatter_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; + + StatusOr ExpandInstruction(HloInstruction* inst) override; + + private: + Mode mode_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SCATTER_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/scatter_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/scatter_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..c993782cd8f423415ba2d07b05deb88de1c51cf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/scatter_simplifier.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 XLA_SERVICE_SCATTER_SIMPLIFIER_H_ +#define XLA_SERVICE_SCATTER_SIMPLIFIER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// This pass rewrites scatter operations into a combination of transposes, +// reshapes and a simpler scatter. +// +// It implements the first two steps of the algorithm decribed in +// ScatterExpander::ExpandInstruction (scatter_expander.cc). Additionally, it +// transposes updates and operands to transform scatter_dims_to_operand_dims +// into the identity mapping. This is different from the algorithm in +// ScatterExpander, which instead applies the mapping in scatter_indices. +// +// The output scatter's attributes will have the following characteristics: +// - scatter_indices is a two-dimensional tensor +// - index_vector_dim is 1 +// - inserted_window_dims is [] +// - update_window_dims is [0, 1, ...] +// - scatter_dims_to_operand_dims is [0, 1, ...] +// +// The purpose of this pass is to check whether this transformation has any +// performance implications. +class ScatterSimplifier : public OpExpanderPass { + public: + absl::string_view name() const override { return "scatter_simplifier"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; + + StatusOr ExpandInstruction(HloInstruction* inst) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SCATTER_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/select_and_scatter_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/select_and_scatter_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..96161a3f6a8d21de47618c13481fb0c8648f4f79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/select_and_scatter_expander.h @@ -0,0 +1,40 @@ +/* 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_SERVICE_SELECT_AND_SCATTER_EXPANDER_H_ +#define XLA_SERVICE_SELECT_AND_SCATTER_EXPANDER_H_ + +#include "xla/service/op_expander_pass.h" + +namespace xla { + +// This pass rewrites select-and-scatter operations into a window reduction and +// a scatter as described in the conceptual explanation of the "select" and +// "scatter" steps of this operation. +class SelectAndScatterExpander : public OpExpanderPass { + public: + absl::string_view name() const override { + return "select_and_scatter_expander"; + } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; + + StatusOr ExpandInstruction(HloInstruction* inst) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SELECT_AND_SCATTER_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/service.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/service.h new file mode 100644 index 0000000000000000000000000000000000000000..81abbba520b5668542172cef6d35048d24624aa8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/service.h @@ -0,0 +1,315 @@ +/* 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_SERVICE_SERVICE_H_ +#define XLA_SERVICE_SERVICE_H_ + +#include +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/debug_options_flags.h" +#include "xla/executable_run_options.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/allocation_tracker.h" +#include "xla/service/backend.h" +#include "xla/service/channel_tracker.h" +#include "xla/service/compilation_cache.h" +#include "xla/service/executable.h" +#include "xla/service/execution_tracker.h" +#include "xla/service/hlo_execution_profile.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla.pb.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" + +namespace xla { + +// Options to configure the service when it is created. +class ServiceOptions { + public: + // Set the platform backing the service, or nullptr for the default platform. + ServiceOptions& set_platform(se::Platform* platform); + se::Platform* platform() const; + + // Set the default number of replicas to use when compiling replicated + // programs. + ServiceOptions& 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. + ServiceOptions& 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. + ServiceOptions& set_allowed_devices( + const std::optional>& allowed_devices); + const std::optional>& allowed_devices() const; + + private: + se::Platform* platform_ = nullptr; + int number_of_replicas_ = 1; + int intra_op_parallelism_threads_ = -1; + std::optional> allowed_devices_; +}; + +// The XLA service object, which is the same across all platforms. It maintains +// the service state of computations and allocations, and delegates +// target-specific requests to the target-specific infrastructure +// (target-specific compiler, StreamExecutor). +class Service : public ServiceInterface { + public: + // Factory method for creating a new Service. + static StatusOr> NewService( + se::Platform* platform = nullptr); + static StatusOr> NewService( + const ServiceOptions& options); + + // Unregisters a previously-allocated global handle. + // + // If the handle given is not currently allocated, a NOT_FOUND status is + // returned. + Status Unregister(const UnregisterRequest* arg, + UnregisterResponse* result) override; + + // Deconstructs a tuple. Returns a newly created GlobalDataHandle for each + // element in the tuple. + Status DeconstructTuple(const DeconstructTupleRequest* arg, + DeconstructTupleResponse* result) override; + + // Compiles a computation into an executable. The request contains the whole + // computation graph. Returns the handle to the executable. + Status Compile(const CompileRequest* arg, CompileResponse* result) override; + + // Executes an executable with the provided global data passes as immutable + // arguments. The request contains the handle to the executable. Returns + // global data output and execution timing. + Status Execute(const ExecuteRequest* arg, ExecuteResponse* result) override; + + // Executes one or more computations in parallel with the provided global data + // passed as immutable arguments. Returns global data output for each + // computation. + Status ExecuteGraphParallel(const ExecuteGraphParallelRequest* arg, + ExecuteParallelResponse* result) override; + + // Requests one or more device handles from the target. + // + // When N device handles are requested and the number of replicas is R, at + // least N * R devices must be available. The devices are assigned based on + // the device ordinals such that the first R available devices are assigned to + // the first set of replicas, and the next R devices to the second set of + // replicas, etc. Each returned device handle represents the device with the + // replica id 0. + Status GetDeviceHandles(const GetDeviceHandlesRequest* arg, + GetDeviceHandlesResponse* result) override; + + // Waits until the specified execution is complete and returns the result. + // Calling this API multiple times with the same execution handle returns the + // method with an error since the execution handle is destroyed after the + // first call. + Status WaitForExecution(const WaitForExecutionRequest* arg, + WaitForExecutionResponse* result) override; + + // Requests that global data be transferred to the client in literal form. + Status TransferToClient(const TransferToClientRequest* arg, + TransferToClientResponse* result) override; + + // Transfers data from a literal provided by the client, into device memory. + Status TransferToServer(const TransferToServerRequest* arg, + TransferToServerResponse* result) override; + + // Transfers data from a literal provided by the client, into the Infeed + // buffer of the device. + Status TransferToInfeed(const TransferToInfeedRequest* arg, + TransferToInfeedResponse* result) override; + + // Transfers data from the Outfeed othe device to the literal provided by the + // client. + Status TransferFromOutfeed(const TransferFromOutfeedRequest* arg, + TransferFromOutfeedResponse* result) override; + + // Resets devices, clearing all existing state on all the devices associated + // with this service (including memory allocated on the devices). + // + // ResetDevice may only be called where no previous Execution state on the + // device is used by the next Execution. + // + // ResetDevice should be called before an Execution that expect the device to + // be in the reset state. For example, if the prior Execution modifies device + // state (e.g., architectural state) that the next Execution depends on. + Status ResetDevice(const ResetDeviceRequest* arg, + ResetDeviceResponse* result) override; + + Status ComputeConstantGraph(const ComputeConstantGraphRequest* arg, + ComputeConstantResponse* result) override; + + // Returns the shape (with layout) of an array associated with a given data + // handle. + Status GetShape(const GetShapeRequest* arg, + GetShapeResponse* result) override; + + // Retrieves the statistics of a computation. + Status GetComputationGraphStats(const ComputationGraphStatsRequest* arg, + ComputationStatsResponse* result) override; + + // Creates a unique channel handle that can be used for Send/Recv + // instructions. + Status CreateChannelHandle(const CreateChannelHandleRequest* arg, + CreateChannelHandleResponse* result) override; + + // Returns the backend used to execute computations. + const Backend& backend() const { return *execute_backend_; } + Backend* mutable_backend() { return execute_backend_.get(); } + + // Create a Hlo module config for the given program shape and arguments. + // aot_options is optional; if not given a default is used. + StatusOr> CreateModuleConfig( + const ProgramShape& program_shape, + absl::Span argument_shapes, + const ExecutionOptions* execution_options, + const AotCompilationOptions* aot_options = nullptr); + + // Convenience function which checks whether the given client_shape + // (presumably passed by the client to set the result layout) is valid for the + // given computation result shape. + static Status ValidateResultShape(const Shape& client_shape, + const Shape& result_shape); + + private: + // A private overload for Service itself, used by other methods within this + // class. + StatusOr> CreateModuleConfig( + const ProgramShape& program_shape, + absl::Span arguments, + const ExecutionOptions& execution_options, + const AotCompilationOptions* aot_options = nullptr); + + // Prepare the executors for executing parallel. + StatusOr> GetExecutors( + const ExecutionOptions& execution_options, int64_t requests_size, + int64_t request_index) const; + + // Prepare the arguments for executing parallel. + StatusOr>> GetArguments( + const ExecutionOptions& execution_options, + absl::Span arguments) const; + + protected: + friend class LocalExecutable; + + // The constructor is private. Use the NewService factory to create new + // service objects. + Service(const ServiceOptions& options, + std::unique_ptr execute_backend); + + // Resolves the given argument handles in the allocation tracker and returns + // the corresponding allocations for every replica. The function also verifies + // that each allocation matches the execution platform and device ordinal of + // the corresponding replica. + StatusOr>> + ResolveAndValidateArguments( + absl::Span arguments, + absl::Span stream_executors) const; + + // Builds an Executable for the given parameters. + // + // If device_allocator is not null, the compiler may use it to allocate temp + // buffers, which the compiler is responsible for freeing. The allocator + // given here need not match the allocator used when running the executable. + StatusOr> BuildExecutable( + const HloModuleProto& module_proto, + std::unique_ptr module_config, Backend* backend, + se::StreamExecutor* executor, const Compiler::CompileOptions& options, + bool run_backend_only = false); + + // Same as BuildExecutable() above, but builds a list of Executables for the + // given computations that may interact with each other. + StatusOr>> BuildExecutables( + const std::vector& module_protos, + std::vector> module_configs, + Backend* backend, std::vector> executors, + const Compiler::CompileOptions& options, bool run_backend_only = false); + + // Same as BuildExecutable() above, but builds a list of + // AotCompilationResult(s), which can be persisted to later load Executable + // objects. + StatusOr>> BuildAotResults( + const std::vector& module_protos, + std::vector> module_configs, + Backend* backend, std::vector> executors, + const Compiler::CompileOptions& options, bool run_backend_only = false); + + // Runs the given executable with the given arguments and register the result + // in the allocation tracker. The handle of the result from the tracker is + // returned. If the parameter "profile" is not null, it points to an + // ExecutionProfile object which will be filled in with profile data. + StatusOr ExecuteAndRegisterResult( + Executable* executable, + absl::Span> arguments, + Backend* backend, const DeviceHandle& device_handle, + const std::string& result_tag, ExecutionProfile* profile); + + // Runs the given executables with the given arguments and register the result + // from each executable in the allocation tracker. The handles of the result + // from the tracker are returned. + StatusOr> ExecuteParallelAndRegisterResult( + absl::Span executables, + absl::Span>> arguments, + Backend* backend, absl::Span device_handles, + absl::Span result_tags, ExecutionProfile* profile); + + // Returns the stream executors assigned to the replicas represented by the + // given device handle. Each device_handle is a virtual replicated device that + // represents a set of physical devices for the replicas. + StatusOr> Replicas( + const Backend& backend, const DeviceHandle& device_handle) const; + + // Returns the device handle that represents the replicated device for a + // single computation that is not model-parallelized. + DeviceHandle SingleComputationDeviceHandle() const; + + ServiceOptions options_; + + // Cache containing previously built Executables. + CompilationCache compilation_cache_; + + // Tracks channels created via the API. + ChannelTracker channel_tracker_; + + // Tracks allocations made via the API and computation execution. + AllocationTracker allocation_tracker_; + + // Tracks asynchronously launched executions via the API. + ExecutionTracker execution_tracker_; + + // Backend to compile and execute computations on. + std::unique_ptr execute_backend_; + + Service(const Service&) = delete; + Service& operator=(const Service&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SERVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/service_executable_run_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/service_executable_run_options.h new file mode 100644 index 0000000000000000000000000000000000000000..a8c5dc0745f9a35aaf0b0a080fee677189cafa1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/service_executable_run_options.h @@ -0,0 +1,91 @@ +/* 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_SERVICE_SERVICE_EXECUTABLE_RUN_OPTIONS_H_ +#define XLA_SERVICE_SERVICE_EXECUTABLE_RUN_OPTIONS_H_ + +#include +#include +#include + +#include "xla/executable_run_options.h" +#include "xla/service/stream_pool.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { + +// Class containing options for running a LocalExecutable and other auxiliary +// data. +class ServiceExecutableRunOptions { + public: + // Defines the interface of the stream borrower function pointer + // with the first argument being the device ordinal, the second + // argument being the number of streams to borrow, and the third + // argument being the priority of the streams. + using StreamBorrower = std::function>( + int, int, se::StreamPriority)>; + + ServiceExecutableRunOptions() + : ServiceExecutableRunOptions(ExecutableRunOptions()) {} + + explicit ServiceExecutableRunOptions(ExecutableRunOptions run_options, + StreamBorrower stream_borrower = nullptr) + : run_options_(std::move(run_options)), + stream_borrower_(std::move(stream_borrower)) {} + + // Returns reference or pointer to `ExecutableRunOptions` member. + const ExecutableRunOptions& run_options() const { return run_options_; } + ExecutableRunOptions* mutable_run_options() { return &run_options_; } + + // Delegate to `ExecutableRunOptions` member. + se::Stream* stream() const { return run_options_.stream(); } + se::DeviceMemoryAllocator* allocator() const { + return run_options_.allocator(); + } + int device_ordinal() const { return run_options_.device_ordinal(); } + + // Borrows a stream and returns a smart pointer which returns the stream on + // destruction. + StatusOr BorrowStream( + int device_ordinal, + se::StreamPriority priority = se::StreamPriority::Default) const { + if (!stream_borrower_) { + return Status(absl::StatusCode::kUnimplemented, "No stream borrower"); + } + + TF_ASSIGN_OR_RETURN( + std::vector streams, + stream_borrower_(device_ordinal, /*num_streams=*/1, priority)); + StreamPool::Ptr stream = std::move(streams.back()); + return stream; + } + + StatusOr> BorrowStreams( + int device_ordinal, int num_streams, + se::StreamPriority priority = se::StreamPriority::Default) const { + return stream_borrower_ + ? stream_borrower_(device_ordinal, num_streams, priority) + : Status(absl::StatusCode::kUnimplemented, "No stream borrower"); + } + + private: + ExecutableRunOptions run_options_; + StreamBorrower stream_borrower_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SERVICE_EXECUTABLE_RUN_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/shape_inference.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/shape_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..e04a59a2bf53cb2dbd87d1c8e51857a464d44660 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/shape_inference.h @@ -0,0 +1,426 @@ +/* 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. +==============================================================================*/ + +// Shape inference is used by the XLA service as the user builds up +// computation requests. + +#ifndef XLA_SERVICE_SHAPE_INFERENCE_H_ +#define XLA_SERVICE_SHAPE_INFERENCE_H_ + +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// For a given operation and input shapes, infers what the resulting shape is +// for the operation. With this functionality, the user does not need to specify +// the expected result type for computations that are built up via the API -- +// the shape that results from an operation is inferred. Some methods have +// overloads for inferring shape at the HLO level. +// +// TODO(b/73352135): Shape inference does not issue very good error messages, in +// part because HloInstruction::ToString() is not available since shape +// inference runs before the HloInstruction object is created. We need a +// solution for this. +class ShapeInference { + public: + // Infers the shape produced by applying the given unary operation to the + // given input shape. + static StatusOr InferUnaryOpShape(HloOpcode opcode, + const Shape& shape); + static StatusOr InferUnaryOpShape(HloOpcode opcode, + const HloInstruction* operand); + + // Infers the shape produced by applying the given binary operation to the + // given input shapes. + static StatusOr InferBinaryOpShape( + HloOpcode opcode, const Shape& lhs, const Shape& rhs, + absl::Span broadcast_dimensions); + static StatusOr InferBinaryOpShape(HloOpcode opcode, + const HloInstruction* lhs, + const HloInstruction* rhs); + + // Infers the shape produced by applying the given ternary operation to the + // given input shapes. + static StatusOr InferTernaryOpShape(HloOpcode opcode, const Shape& lhs, + const Shape& rhs, + const Shape& ehs); + static StatusOr InferTernaryOpShape(HloOpcode opcode, + const HloInstruction* lhs, + const HloInstruction* rhs, + const HloInstruction* ehs); + + // Infers the shape produced by applying the given variadic operation to the + // given input operand shapes. + static StatusOr InferVariadicOpShape( + HloOpcode opcode, absl::Span operand_shapes); + static StatusOr InferVariadicOpShape( + HloOpcode opcode, absl::Span operands); + + // Infers the shape produced by applying the given mapping computation shape + // to the given operand shapes. + static StatusOr InferMapShape( + absl::Span arg_shapes, const ProgramShape& to_apply, + absl::Span dimensions); + + // Infers the shape produced by InferBatchNormTraining with the given + // operands. + static StatusOr InferBatchNormTrainingShape(const Shape& operand_shape, + const Shape& scale_shape, + const Shape& offset_shape, + int64_t feature_index); + + // Infers the shape produced by InferBatchNormInference with the given + // operands. + static StatusOr InferBatchNormInferenceShape( + const Shape& operand_shape, const Shape& scale_shape, + const Shape& offset_shape, const Shape& mean_shape, + const Shape& variance_shape, int64_t feature_index); + + // Infers the shape produced by InferBatchNormGrad with the given operands. + static StatusOr InferBatchNormGradShape(const Shape& operand_shape, + const Shape& scale_shape, + const Shape& mean_shape, + const Shape& var_shape, + const Shape& output_grad_shape, + int64_t feature_index); + + // Infers the shape produced by applying the given convolutional filter (rhs) + // to lhs in the way specified by the fields on window. An optional + // preferred_element_type can be specified to upcast the element type. + static StatusOr InferConvolveShape( + const Shape& lhs, const Shape& rhs, int64_t feature_group_count, + int64_t batch_group_count, const Window& window, + const ConvolutionDimensionNumbers& dimension_numbers, + std::optional preferred_element_type); + + // Infers the shape produced by the given FFT type on the given operand. + static StatusOr InferFftShape(const Shape& in, FftType fft_type, + absl::Span fft_length); + + // Infers the shape produced by the given triangular solve operation. + static StatusOr InferTriangularSolveShape( + const Shape& a, const Shape& b, const TriangularSolveOptions& options); + + // Infers the shape produced by the given triangular solve operation. + static StatusOr InferCholeskyShape(const Shape& a); + + // Infers the shape produced by an all-gather with the given operand shape, + // concat dimension, and shard count. + static StatusOr InferAllGatherShape( + absl::Span operand_shapes, + int64_t all_gather_dimension, int64_t shard_count); + + // Infers the shape produced by an all-gather-start with the given operand + // shape, concat dimension, and shard count. + static StatusOr InferAllGatherStartShape( + absl::Span operand_shapes, + int64_t all_gather_dimension, int64_t shard_count); + + // Infers the shape produced by an all-gather-done given a certain + // all-gather-start shape. + static StatusOr InferAllGatherDoneShape( + const Shape& all_gather_start_shape); + + // Infers the shape produced by a cross replica sum with the given operand + // shapes. + static StatusOr InferAllReduceShape( + absl::Span operand_shapes); + + // Infers the shape produced by a reduce-scatter with the given operand + // shape, scatter dimension, and shard count. + static StatusOr InferReduceScatterShape( + absl::Span operand_shapes, int64_t scatter_dimension, + int64_t shard_count); + + // Infers the shape produced by a cross replica sum start. + static StatusOr InferAllReduceStartShape( + absl::Span operand_shapes); + + // Infers the shape produced by a cross replica sum done. + static StatusOr InferAllReduceDoneShape(const Shape& operand_shape); + + // Infers final shape of an Alltoall operation that is created by the xla + // builder. + static StatusOr InferAllToAllShape(const Shape& shape, + int64_t split_dimension, + int64_t concat_dimension, + int64_t split_count); + + // Infers the shape of an HLO all-to-all instruction. + static StatusOr InferAllToAllTupleShape( + absl::Span operand_shapes); + + // Infers the shape of a collective permute operation. + static StatusOr InferCollectivePermuteShape( + absl::Span operand_shapes); + + // Infers the shape of a collective permute start operation. + static StatusOr InferCollectivePermuteStartShape( + absl::Span operand_shapes, + absl::Span context_shapes); + + // Infers the shape of a collective permute operation. + static StatusOr InferCollectivePermuteDoneShape( + const Shape& operand_shape); + + // Infers the shape produced by applying the given reduction computation + // shape to the given input operand shape. + // + // If pass_index is true, the reduce function is invoked with the element + // index as the leading parameter, and the program shape should match + // accordingly (or an error will result). + static StatusOr InferReduceShape( + absl::Span arg_shapes, + absl::Span dimensions_to_reduce, + const ProgramShape& to_apply); + + // Infers the shape produced by applying the given computation to the operand + // shape with the given window and stride dimensions. + static StatusOr InferReduceWindowShape( + const Shape& operand_shape, const Shape& init_value, const Window& window, + const ProgramShape& to_apply_shape); + static StatusOr InferReduceWindowShape(const Shape& operand_shape, + const Shape& init_value, + const Window& window); + static StatusOr InferReduceWindowShape( + absl::Span operands, + absl::Span init_values, const Window& window, + const ProgramShape& to_apply_shape); + + static StatusOr InferReduceWindowShape( + absl::Span operands, absl::Span init_values, + const Window& window); + + // Infers the shape produced by scattering the given source shape to the + // selected indices of each window on the operand shape. + static StatusOr InferSelectAndScatterShape( + const Shape& operand_shape, const ProgramShape& select_shape, + const Window& window, const Shape& source_shape, + const Shape& init_value_shape, const ProgramShape& scatter_shape); + + // Infers the shape produced by a reverse operation that reverses the order + // of the elements in the given dimensions. + static StatusOr InferReverseShape( + const Shape& operand_shape, absl::Span dimensions); + + // Infers the shape produced by a slice operation spanning from the starts to + // the limits in the original shape's dimensions. + // + // e.g. slice f32[32x32] 0:16 0:16 -> f32[16x16] + static StatusOr InferSliceShape(const Shape& arg, + absl::Span starts, + absl::Span limits, + absl::Span strides); + + // Infers the shape produced by a dynamic slice operation of size specified + // in 'slice_sizes', with dynamic start indices shape 'start_indices_shape'. + static StatusOr InferDynamicSliceShape( + const Shape& operand_shape, absl::Span start_index_shapes, + absl::Span slice_sizes, bool allow_scalar_indices = true); + + // Infers the shape produced by a dynamic update slice operation based + // on the shape of operand and update. + static StatusOr InferDynamicUpdateSliceShape( + const Shape& operand_shape, const Shape& update_shape, + absl::Span start_index_shapes, + bool allow_scalar_indices = true); + + // Infers the shape produced by doing a compile-time-constant indexing into + // the given input shape. This is essential for operations on tuples, because + // it is impossible to infer the type that comes out of the tuple indexing if + // it is not a compile time constant. + static StatusOr InferGetTupleElementShape(const Shape& arg, + int64_t index); + + // Infers the shape produced from a while node. condition and body are the + // shapes of computations for the condition and the body of a while node, and + // init is the shape of data initially passed in to the body as an argument. + // The shapes must match; condition: T -> PRED, body: T -> T, init: T + static StatusOr InferWhileShape(const ProgramShape& condition, + const ProgramShape& body, + const Shape& init); + + // Infers the shape produced by a predicated or indexed conditional operation. + static StatusOr InferConditionalShape( + const Shape& branch_index, + absl::Span branch_computations, + absl::Span branch_operands); + + // Infers the shape produced by a broadcast operation. + static StatusOr InferBroadcastShape( + const Shape& operand, absl::Span broadcast_sizes); + + // Checks whether the given parameters can form a broadcast. Returns the same + // output_shape if it's legal. + static StatusOr InferBroadcastShape( + const Shape& operand_shape, const Shape& output_shape, + absl::Span broadcast_dimensions); + + // Infers the shape produced by a reshape operation from the element type of + // its operand and the new dimension sizes specified. + static StatusOr InferReshapeShape(const Shape& operand, + absl::Span dimensions, + absl::Span new_sizes, + int64_t inferred_dimension); + + // Infers the shape produced by a dynamic reshape operation from the element + // type of its operand and the new dimension sizes specified. The result shape + // will have dynamic dimensions as specific in `dim_is_dynamic` and bound + // `new_size_bounds`. + static StatusOr InferDynamicReshapeShape( + const Shape& operand, absl::Span dim_size_shapes, + absl::Span new_size_bounds, + const std::vector& dims_are_dynamic); + + // Infers the shape produced by a transpose operation from the element type of + // its operand and its dimensions field. + static StatusOr InferTransposeShape( + const Shape& operand, absl::Span dimensions); + + // Helper that infers the shape produced by performing a concatenate operation + // with the given operand shapes. + static StatusOr InferConcatOpShape( + absl::Span arg_shapes, int64_t dimension); + + // Helper that validates the given operand shape can be converted to the + // target output_shape via a convert instruction -- the requirement is that + // the shape is identical except for the element type. + static StatusOr InferConvertShape(const Shape& operand_shape, + PrimitiveType new_element_type); + + // Helper that validates the given operand shape can be bitcast converted to + // the target output_shape via a bitcast convert instruction -- the + // requirement is that the shape is identical except for the element type and + // the element types have identical bit-widths. + static StatusOr InferBitcastConvertShape( + const Shape& operand_shape, PrimitiveType new_element_type); + + // Helper that validates the given operand shape can be converted to the + // target output_shape via a stochastic convert instruction -- the requirement + // is that the shape is identical except for the element type. + static StatusOr InferStochasticConvertShape( + const Shape& operand_shape, const Shape& random_shape, + PrimitiveType new_element_type); + + // Helper that validates the input data type for a reduce-precision operation, + // and returns the result shape. + static StatusOr InferReducePrecisionShape(const Shape& operand_shape, + const int exponent_bits, + const int mantissa_bits); + + // Helper that infers the shape produced by a pad operation based on the + // padding configuration. + static StatusOr InferPadShape(const Shape& operand_shape, + const Shape& padding_value_shape, + const PaddingConfig& padding_config); + + // Helper that validates the given arg_shapes are compatible with the shape of + // the to_apply parameters, and returns the to_apply result shape. + static StatusOr InferCallShape( + absl::Span arg_shapes, const ProgramShape& to_apply); + + // Helper that infers the shape produced by performing a dot operation with + // the given LHS and RHS shapes. An optional preferred_element_type can be + // specified to upcast the element type. + static StatusOr InferDotOpShape( + const Shape& lhs, const Shape& rhs, + const DotDimensionNumbers& dimension_numbers, + std::optional preferred_element_type); + + // Helper that infers the shape of the tensor produced by a gather operation + // with the given input shape, gather indices shape and gather dimension + // numbers. + static StatusOr InferGatherShape( + const Shape& input_shape, const Shape& start_indices_shape, + const GatherDimensionNumbers& gather_dim_numbers, + absl::Span slice_sizes); + + // Helper that validates the given input shape, scatter indices shape, updates + // shape, and scatter dimension numbers that constitute a scatter operation, + // and returns the result shape of the scatter operation. + static StatusOr InferScatterShape( + absl::Span arg_shapes, + const ProgramShape& to_apply_shape, + const ScatterDimensionNumbers& scatter_dim_numbers); + + // Helper that validates the given input shape to GetDimensionSize. + static StatusOr InferGetDimensionSizeShape(const Shape& shape, + int64_t dimension); + + // Helper that validates the given input shape to SetDimensionSize. + static StatusOr InferSetDimensionSizeShape(const Shape& operand_shape, + const Shape& val_shape, + int64_t dimension); + + static StatusOr InferTopKShape(const Shape& operand_shape, int64_t k); + + // Helper function for creating a Window proto from user-supplied data. + // Returns error if the user-supplied data was invalid. + static StatusOr InferWindowFromDimensions( + absl::Span window_dimensions, + absl::Span window_strides, + absl::Span> padding, + absl::Span lhs_dilation, + absl::Span rhs_dilation, + std::optional> window_reversal = std::nullopt); + + private: + // Helper that infers the shape produced by performing an element-wise binary + // operation with the given LHS and RHS shapes. + // Note: By "element-wise" we mean operations that look at a single element in + // the LHS and a single element in the RHS to produce a single output element, + // even in the presence of broadcasting of one of the operands over the other. + static StatusOr InferElementwiseBinaryOpShape( + HloOpcode operation, const Shape& lhs, const Shape& rhs, + absl::Span broadcast_dimensions); + + // Helper for inferring the shape of Clamp ops. + static StatusOr InferClampShape(const Shape& min, const Shape& operand, + const Shape& max); + + // Helper for inferring the shape of Select ops. + static StatusOr InferSelectShape(const Shape& pred, + const Shape& on_true, + const Shape& on_false); + + // Helper for inferring shapes of binary operations which use degenerate + // dimension broadcasting (a dimension of size 1 in one operand is broadcast + // up to match the size of the dimension in the other operand). + static StatusOr InferDegenerateDimensionBroadcastShape( + HloOpcode operation, const Shape& lhs, const Shape& rhs); + + // Helper for inferring shapes of binary operations using "InDim" + // broadcasting. This is the broadcasting used in the *InDim binary operations + // (for example ComputationBuilder::AddInDim). smaller_shape must be a + // lower-rank shape than larger_shape. Returns the shape that the + // smaller_shape is broadcast to. + static StatusOr InferInDimBroadcastShape( + const Shape& smaller_shape, const Shape& larger_shape, + absl::Span broadcast_dimensions); + + ShapeInference(const ShapeInference&) = delete; + ShapeInference& operator=(const ShapeInference&) = delete; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SHAPE_INFERENCE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/shaped_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/shaped_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..e3e32001d10cda65e89cb06905fb2de3ce16dec1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/shaped_buffer.h @@ -0,0 +1,210 @@ +/* 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_SERVICE_SHAPED_BUFFER_H_ +#define XLA_SERVICE_SHAPED_BUFFER_H_ + +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/shape_tree.h" +#include "xla/shape_util.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 ScopedShapedBuffer; + +// Class which encapsulates a buffer or set of buffers containing data of a +// particular XLA shape. +class ShapedBuffer { + public: + // Construct a ShapedBuffer with null DeviceMemoryBases at each index. The + // shape of the data on the host and the device may differ because the device + // may have a different representation for different data types. Therefore, + // both the on-host and on-device shape are required. The on-device shape + // determines the number of device allocations (DeviceMemoryBase) held by the + // ShapedBuffer. + ShapedBuffer(Shape on_device_shape, int device_ordinal); + + // TODO(b/170310047): remove this overload. + ShapedBuffer(Shape on_host_shape, Shape on_device_shape, int device_ordinal); + + // Movable, but not copyable. + ShapedBuffer(ShapedBuffer&& s); + ShapedBuffer& operator=(ShapedBuffer&&); + ShapedBuffer(const ShapedBuffer&) = delete; + ShapedBuffer& operator=(const ShapedBuffer&) = delete; + + // Prevent (some forms of) accidental object slicing. + ShapedBuffer(const ScopedShapedBuffer&) = delete; + ShapedBuffer& operator=(const ScopedShapedBuffer&) = delete; + + virtual ~ShapedBuffer(); + + // Returns the shape of the on-host representation of the data held by this + // ShapedBuffer. + const Shape& on_host_shape() const { return on_host_shape_; } + + // Returns the shape of the on-device representation of the data held by this + // ShapedBuffer. + const Shape& on_device_shape() const { return on_device_shape_; } + + int device_ordinal() const { return device_ordinal_; } + + // Return the root buffer of the shape (shape index {}). + const se::DeviceMemoryBase& root_buffer() const { + return buffer(/*index=*/{}); + } + + // Returns the buffer at the given shape index where index is defined as in + // ShapeUtil::GetSubshape. + const se::DeviceMemoryBase& buffer(const ShapeIndex& index) const { + return buffers_.element(index); + } + + // Sets the device memory buffer at the given index. + void set_buffer(const se::DeviceMemoryBase& buffer, const ShapeIndex& index) { + *buffers_.mutable_element(index) = buffer; + } + + // Sets all buffers. + // + // Precondition: buffers.shape == on_device_shape_ + void set_buffers(ShapeTree buffers) { + CHECK(ShapeUtil::Equal(buffers.shape(), on_device_shape_)); + buffers_ = std::move(buffers); + buffers_.replace_shape_ptr(on_device_shape_); + } + + // Reset the shape of this shaped buffer and underlying buffer structure. + // + // Precondition: EqualStructure(this->on_device_shape_, on_device_shape). + void set_shapes(const Shape& on_device_shape) { + CHECK(ShapeUtil::EqualStructure(on_device_shape, on_device_shape_)) + << "Structures are not the same. new: " << on_device_shape + << ", old: " << on_device_shape_; + on_host_shape_ = ShapeUtil::DeviceShapeToHostShape(on_device_shape); + on_device_shape_ = on_device_shape; + buffers_.replace_shape_ptr(on_device_shape_); + } + // TODO(b/170310047): remove this overload. + void set_shapes(const Shape& on_host_shape, const Shape& on_device_shape) { + set_shapes(on_device_shape); + } + + // Returns the underlying ShapeTree containing all the device addresses in the + // ShapedBuffer. + const ShapeTree& buffers() const { return buffers_; } + ShapeTree& buffers() { return buffers_; } + + StatusOr SubShapedBuffer(const ShapeIndex& index) const; + + // Set all device memory pointers in the object to null. + void clear(); + + std::string ToString() const; + + protected: + Shape on_host_shape_; + + // The shape of the data on the device. + Shape on_device_shape_; + + // The device the memory is allocated on. + int device_ordinal_; + + // The tree of device buffers. Its shape is on_device_shape(). + ShapeTree buffers_; +}; + +std::ostream& operator<<(std::ostream& out, const ShapedBuffer& buffer); + +// ScopedShapedBuffer takes allocated buffers as inputs, and deallocates on +// destruction. This class represents an owning wrapper around `ShapedBuffer`. +// +// TODO(timshen): Remove inheritance between ScopedShapedBuffer and +// ShapedBuffer. There should never be a need to consider a ScopedShapedBuffer +// as a ShapedBuffer, because in that case we should just be able to pass around +// our ShapeTree. Inheritance only adds complexity. See +// discussion in cl/192849370. +class ScopedShapedBuffer : public ShapedBuffer { + public: + // Creates a ScopedShapedBuffer with null DeviceMemoryBases at each index. + explicit ScopedShapedBuffer(Shape on_device_shape, + se::DeviceMemoryAllocator* allocator, + int device_ordinal); + // TODO(b/170310047): remove this overload. + explicit ScopedShapedBuffer(Shape on_host_shape, Shape on_device_shape, + se::DeviceMemoryAllocator* allocator, + int device_ordinal); + + // Create a ScopedShapedBuffer by taking over the memory from the incoming + // ShapedBuffer. + explicit ScopedShapedBuffer(ShapedBuffer shaped_buffer, + se::DeviceMemoryAllocator* allocator); + + // Movable, but not copyable. + ScopedShapedBuffer(ScopedShapedBuffer&& s); + ScopedShapedBuffer& operator=(ScopedShapedBuffer&&); + ScopedShapedBuffer(const ScopedShapedBuffer&) = delete; + ScopedShapedBuffer& operator=(const ScopedShapedBuffer&) = delete; + + // All buffers in the shape are deallocated on destruction. + ~ScopedShapedBuffer() override; + + // Return the allocator used to allocate the device memory held in this + // ScopedShapedBuffer. + se::DeviceMemoryAllocator* memory_allocator() const { return allocator_; } + + // Sets the device memory buffer at the given index. + // + // If the given buffer's device memory is non-null, its device_ordinal and + // allocator must match those in `this`. + void set_buffer(se::OwningDeviceMemory buffer, const ShapeIndex& index) { + if (!buffer.is_null()) { + CHECK_EQ(buffer.device_ordinal(), device_ordinal()); + CHECK_EQ(buffer.allocator(), allocator_); + *buffers_.mutable_element(index) = buffer.Release(); + } else { + *buffers_.mutable_element(index) = se::DeviceMemoryBase(); + } + } + + // Like unique_ptr::release(), creates and returns a regular ShapedBuffer from + // this ScopedShapedBuffer, without freeing any of the associated memory. + // + // It's the caller's job to ensure that the memory contained therein is freed. + [[nodiscard]] ShapedBuffer release(); + + // Extracts the sub-tree rooted at 'index' and returns a ScopedShapedBuffer + // that holds ownership of the subtree. Sets the buffers corresponding to the + // subtree to null in 'this'. + ScopedShapedBuffer TakeSubTree(ShapeIndexView index); + + protected: + void Deallocate(); + + se::DeviceMemoryAllocator* allocator_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SHAPED_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sharding_propagation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sharding_propagation.h new file mode 100644 index 0000000000000000000000000000000000000000..8fe65ce26277722f3f84e09d38e41b6c7ee39a2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sharding_propagation.h @@ -0,0 +1,161 @@ +/* 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_SERVICE_SHARDING_PROPAGATION_H_ +#define XLA_SERVICE_SHARDING_PROPAGATION_H_ + +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/call_graph.h" +#include "xla/service/custom_call_sharding_helper.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Remove Sharding custom-call instruction by folding the sharding attribute +// to its operand. If the operand already has a different sharding, insert a +// copy node for reshard. Depending on whether propagating the spmd sharding to +// output/parameters is allowed, the existing shardings of output and parameters +// will be saved in saved_root_shardings and saved_parameter_shardings. The user +// can select which sharding(s) to keep and which shardings to allow spmd to +// propagate. saved_parameter_shardings is a map from the operand index to that +// operand's existing sharding. +// unspecified_dims will be populated with the converted copies if the custom +// call is partially specified. +StatusOr ProcessShardingInstruction( + HloModule* module, + const absl::flat_hash_set& execution_threads, + bool replace_sharding_with_copy, + absl::flat_hash_map>* + unspecified_dims, + std::vector* saved_root_shardings, + absl::flat_hash_map* saved_parameter_shardings, + absl::flat_hash_map* + instruction_to_shard_group_id = nullptr, + absl::flat_hash_map>* + shard_group_id_to_shard_as_group = nullptr, + absl::flat_hash_map>* + shard_group_id_to_shard_like_group = nullptr); + +int64_t ComputeNonRootUsers(const HloInstruction* instr); + +// Infers broadcast ops' operand sharding, based on its output sharding. +std::optional InferBroadcastOperandSharding( + const HloInstruction& instruction, bool is_spmd = true); + +bool InferReduceShardingFromOperand(HloInstruction* instruction, + bool may_combine_partial_sharding, + bool is_spmd); + +// Propagates sharding information around the graph. HLOs that have shardings +// are kept as-is, those that do not have shardings are given shardings based on +// a simple local greedy heuristic. +class ShardingPropagation : public HloModulePass { + public: + using ComputationMap = + absl::flat_hash_map; + explicit ShardingPropagation( + bool is_spmd = false, bool propagate_metadata = false, + absl::Span allow_spmd_sharding_propagation_to_output = + {false}, + absl::Span allow_spmd_sharding_propagation_to_parameters = + {false}, + bool cse_prevention_only = false, + std::unique_ptr sharding_helper = nullptr) + : is_spmd_(is_spmd), + propagate_metadata_(propagate_metadata), + allow_spmd_sharding_propagation_to_output_( + absl::c_any_of(allow_spmd_sharding_propagation_to_output, + [](bool v) { return v; })), + allow_spmd_sharding_propagation_to_parameters_( + absl::c_any_of(allow_spmd_sharding_propagation_to_parameters, + [](bool v) { return v; })), + allow_spmd_sharding_propagation_to_output_vector_( + allow_spmd_sharding_propagation_to_output.begin(), + allow_spmd_sharding_propagation_to_output.end()), + allow_spmd_sharding_propagation_to_parameters_vector_( + allow_spmd_sharding_propagation_to_parameters.begin(), + allow_spmd_sharding_propagation_to_parameters.end()), + cse_prevention_only_(cse_prevention_only) { + if (sharding_helper) { + sharding_helper_ = std::move(sharding_helper); + } else { + sharding_helper_ = std::make_unique(); + } + } + absl::string_view name() const override { return "sharding-propagation"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Function which can be used to apply a spatially partitioned sharding onto a + // given domain. It will apply the sharding into the exit edges of the domain + // and then rely on the rest of sharding propagation to ensure that the + // intermediate nodes get the correct sharding. + static Status NormalizeDomain(const DomainMetadata::Domain& domain, + const DomainMetadata* metadata); + + static std::optional GetShardingFromUser( + const HloInstruction& instruction, const HloInstruction& user, + int64_t aggressiveness, bool is_spmd, const CallGraph& call_graph); + + // Canonicalizes entry_computation_layouts by calling + // module.layout_canonicalization_callback(), which gives canolicalized + // argument and result layouts based on current module. Currently used by + // PJRT which assigns layouts based on runtime shapes: see + // DetermineArgumentLayoutsFromCompileOptions() in + // tensorflow/compiler/xla/pjrt/utils.cc + Status CanonicalizeLayouts(HloModule* module); + + private: + bool InferShardingFromShardGroup( + HloInstruction* instruction, const ComputationMap& computation_map, + int64_t aggressiveness, + const absl::flat_hash_set& shard_group); + bool InferShardingFromOperands(HloInstruction* instruction, + const ComputationMap& computation_map, + int64_t aggressiveness, + const CallGraph& call_graph); + bool InferShardingFromUsers( + HloInstruction* instruction, + const ShardingPropagation::ComputationMap& computation_map, + int64_t aggressiveness, bool is_spmd, + const CustomCallShardingHelper* sharding_helper, + const CallGraph& call_graph); + + std::unique_ptr sharding_helper_; + bool is_spmd_; + bool propagate_metadata_; + bool allow_spmd_sharding_propagation_to_output_; + bool allow_spmd_sharding_propagation_to_parameters_; + std::vector allow_spmd_sharding_propagation_to_output_vector_; + std::vector allow_spmd_sharding_propagation_to_parameters_vector_; + // If true, the pass keeps the propagation results only on selected + // instructions to prevent CSE across unrelated subgraphs. (A common case is + // scalar broadcasts). + bool cse_prevention_only_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SHARDING_PROPAGATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sharding_remover.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sharding_remover.h new file mode 100644 index 0000000000000000000000000000000000000000..9a8d0c3f4f661884b50bef3950f7c735176af7d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sharding_remover.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_SHARDING_REMOVER_H_ +#define XLA_SERVICE_SHARDING_REMOVER_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Remove Sharding custom-call instruction by assigning its users to +// to its operand. This is helpful when partition_count == 1. +class ShardingRemover : public HloModulePass { + public: + absl::string_view name() const override { return "sharding-remover"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SHARDING_REMOVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/simplify_fp_conversions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/simplify_fp_conversions.h new file mode 100644 index 0000000000000000000000000000000000000000..3904fa37505a527f37b018c6eaf433f7b4818ac7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/simplify_fp_conversions.h @@ -0,0 +1,58 @@ +/* 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_SERVICE_SIMPLIFY_FP_CONVERSIONS_H_ +#define XLA_SERVICE_SIMPLIFY_FP_CONVERSIONS_H_ + +#include "absl/container/flat_hash_set.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Simplifies chains of floating-point conversions. +// +// The algebraic simplifier will remove convert pairs of the form `X -> Y -> X`, +// only when they are a no-op (e.g. `bf16 -> f32 -> bf16`). This passes does +// similar, but has two scopes: +// - kSimplifyAllConversions: Simplify any chain of float conversions, possibly +// improving accuracy (e.g. `f32 -> bf16 -> f32` is removed). +// - kOnlySimplifyCompilerGeneratedConversions: Only simplify chains of float +// conversions generated by the compiler in one of the previous optimization +// passes. +class SimplifyFPConversions : public HloModulePass { + public: + enum class Scope { + kOnlySimplifyCompilerGeneratedConversions, + kSimplifyAllConversions + }; + + explicit SimplifyFPConversions(Scope scope) : scope_(scope) {} + + absl::string_view name() const override { return "simplify-fp-conversions"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + Scope scope_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SIMPLIFY_FP_CONVERSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/slice_sinker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/slice_sinker.h new file mode 100644 index 0000000000000000000000000000000000000000..4a5e6aa6ac5e4e054ceb24ad281b74077aae5ff5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/slice_sinker.h @@ -0,0 +1,37 @@ +/* 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_SERVICE_SLICE_SINKER_H_ +#define XLA_SERVICE_SLICE_SINKER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// An HLO pass that sinks slice operations used by a group of elementwise +// operations and merges the group of elementwise operations. +class SliceSinker : public HloModulePass { + public: + absl::string_view name() const override { return "slice-sinker"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SLICE_SINKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/slow_operation_alarm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/slow_operation_alarm.h new file mode 100644 index 0000000000000000000000000000000000000000..a9fa35ca9ed36d852e7a9db112c8ba73ae92a89c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/slow_operation_alarm.h @@ -0,0 +1,92 @@ +/* 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_SERVICE_SLOW_OPERATION_ALARM_H_ +#define XLA_SERVICE_SLOW_OPERATION_ALARM_H_ + +#include +#include +#include +#include +#include + +#include "absl/base/attributes.h" +#include "absl/strings/string_view.h" +#include "absl/time/time.h" + +namespace xla { + +// This RAII object asynchronously prints a warning if it's alive for more than +// a certain amount of time. +class SlowOperationAlarm { + public: + // If `counter` is not null, this alarm will throttle itself to logging + // once-every-power-of-two occurrences. The counter must outlive this object. + SlowOperationAlarm(absl::Duration timeout, std::string msg, + std::atomic* counter = nullptr, + absl::string_view context = ""); + SlowOperationAlarm(absl::Duration timeout, + std::function msg_fn, + std::atomic* counter = nullptr, + absl::string_view context = ""); + ~SlowOperationAlarm(); + + // Not copyable or movable, because the constructor stores a pointer to `this` + // into a global variable. + SlowOperationAlarm(const SlowOperationAlarm&) = delete; + SlowOperationAlarm(const SlowOperationAlarm&&) = delete; + SlowOperationAlarm& operator=(const SlowOperationAlarm&) = delete; + SlowOperationAlarm& operator=(const SlowOperationAlarm&&) = delete; + + absl::Time deadline() const { return deadline_; } + std::string msg() const { return msg_fn_(); } + std::atomic* counter() { return counter_; } + void cancel() { UnscheduleAlarm(this); } + // Has the alarm fired? If appropriate, consider cancel()'ing first, to avoid + // a race. + bool fired() const { return fired_.load(); } + + private: + static void AlarmLoop(); + static void ScheduleAlarm(SlowOperationAlarm* alarm); + static void UnscheduleAlarm(const SlowOperationAlarm* alarm); + + absl::Time start_; + absl::Time deadline_; + std::string context_; + std::function msg_fn_; + std::atomic fired_{false}; + // counter_ may be null. If it's not, this alarm prints something only once + // every power of two occurrences. + std::atomic* counter_; +}; + +// Returns an object which prints a warning about slow compilation after a +// certain amount of time. It will also print the total lifetime duration of +// the returned object when it goes out of scope. +// +// In debug builds, recommends building with -c opt. +// +// In opt builds, recommends filing a bug. +// +// This is throttled to once-every-power-of-two occurrences, globally. +// +// `context` is an additional message prepended to the alarm. +[[nodiscard]] std::unique_ptr SlowCompilationAlarm( + absl::string_view context); + +} // namespace xla + +#endif // XLA_SERVICE_SLOW_OPERATION_ALARM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sort_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sort_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..4150848ff73d0644c9f2c6e7a63712f8b3a6523d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sort_simplifier.h @@ -0,0 +1,38 @@ +/* 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_SERVICE_SORT_SIMPLIFIER_H_ +#define XLA_SERVICE_SORT_SIMPLIFIER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass which removes unused operands from sort, where an unused operand is +// defined as an operand at some index 'x' at which the output is not used. +class SortSimplifier : public HloModulePass { + public: + absl::string_view name() const override { return "simplify-sorts"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SORT_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/source_map_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/source_map_util.h new file mode 100644 index 0000000000000000000000000000000000000000..349a3025e923e006e4c51a2e0388493655ebc218 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/source_map_util.h @@ -0,0 +1,63 @@ +/* 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_SERVICE_SOURCE_MAP_UTIL_H_ +#define XLA_SERVICE_SOURCE_MAP_UTIL_H_ + +#include "absl/strings/str_format.h" +#include "xla/service/executable.h" +#include "xla/status.h" + +namespace xla { +namespace source_map_util { + +// Creates an INVALID_ARGUMENT status with the given format string. +template +Status InvalidParameterArgument(const OpMetadata& op_metadata, + const absl::FormatSpec& format, + const Args&... args) { + std::string message = absl::StrFormat(format, args...); + if (!op_metadata.source_file().empty()) { + absl::StrAppendFormat(&message, " (%s:%d)", op_metadata.source_file(), + op_metadata.source_line()); + } + return InvalidArgument("%s", message); +} + +// Creates an INVALID_ARGUMENT status with the given format string. +// +// Also, attempts to extract the OpMetadata for parameter_number on executable +// and append it to the status message for source mapping to user code. +// +// executable may be nullptr, but parameter_number should not be out of bounds +// or a CHECK-failure may occur. +template +Status InvalidParameterArgument(Executable* executable, int parameter_number, + const absl::FormatSpec& format, + const Args&... args) { + if (executable != nullptr && executable->has_module()) { + const HloModule& module = executable->module(); + const HloComputation& computation = *module.entry_computation(); + HloInstruction* param = computation.parameter_instruction(parameter_number); + const OpMetadata& metadata = param->metadata(); + return InvalidParameterArgument(metadata, format, args...); + } + return InvalidArgument(format, args...); +} + +} // namespace source_map_util +} // namespace xla + +#endif // XLA_SERVICE_SOURCE_MAP_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sparse_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sparse_util.h new file mode 100644 index 0000000000000000000000000000000000000000..bcac77f047db1d53c136e6a57f254877dd0a0cea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/sparse_util.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_SERVICE_SPARSE_UTIL_H_ +#define XLA_SERVICE_SPARSE_UTIL_H_ + +namespace xla { +// Forward declarations. +class HloInstruction; + +// Namespaced collection of (static) Sparse utilities. +class SparseUtil { + public: + // Returns true if the instruction takes sparse operands or return sparse + // result. + static bool HasSparseInOut(HloInstruction* instruction); + + private: + SparseUtil(const SparseUtil&) = delete; + SparseUtil& operator=(const SparseUtil&) = delete; +}; +} // namespace xla + +#endif // XLA_SERVICE_SPARSE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/collective_permute_motion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/collective_permute_motion.h new file mode 100644 index 0000000000000000000000000000000000000000..8b35b90b90a257d0017381a0d802fe44900b7cc9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/collective_permute_motion.h @@ -0,0 +1,41 @@ +/* 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_SERVICE_SPMD_COLLECTIVE_PERMUTE_MOTION_H_ +#define XLA_SERVICE_SPMD_COLLECTIVE_PERMUTE_MOTION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This pass moves collective permutes at the end of a loop to the beginning, +// which makes overlapping possible for megascale decomposed ops. +class CollectivePermuteMotion : public HloModulePass { + public: + CollectivePermuteMotion() = default; + absl::string_view name() const override { + return "collective-permute-motion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SPMD_COLLECTIVE_PERMUTE_MOTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/convolution_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/convolution_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..617dbb8aeac6c03552417e78672970a95bade0a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/convolution_handler.h @@ -0,0 +1,43 @@ +/* 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_SERVICE_SPMD_CONVOLUTION_HANDLER_H_ +#define XLA_SERVICE_SPMD_CONVOLUTION_HANDLER_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/service/dot_as_convolution_util.h" +#include "xla/service/spmd/spmd_partitioner.h" + +namespace xla { +namespace spmd { + +// Partition convolution. +StatusOr PartitionConvolution( + PartitionedHlo lhs, PartitionedHlo rhs, const Shape& output_base_shape, + const HloSharding& output_sharding, const DotConvDimsMapping& dims_mapping, + absl::FunctionRef(HloInstruction*, + HloInstruction*, SpmdBuilder*, + const Window& conv_window)> + create_sharded_conv, + const Window& conv_window, HloInstruction* original_hlo, + int64_t num_partitions, const SpmdPartitionerOptions& options, + HloInstruction* partition_id, HloModule* module, SpmdBuilder* b); + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_CONVOLUTION_HANDLER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/custom_call_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/custom_call_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..93c777626301c1bcc003b696d9387ca351615476 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/custom_call_handler.h @@ -0,0 +1,35 @@ +/* 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_SERVICE_SPMD_CUSTOM_CALL_HANDLER_H_ +#define XLA_SERVICE_SPMD_CUSTOM_CALL_HANDLER_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { +namespace spmd { + +// Creators of custom ops defined by the partitioner itself. + +// Creates a custom op that rotates data along `dim` with the given amount. +std::unique_ptr CreateCustomCallSPMDInternal_RotateRight( + HloInstruction* input, int64_t dim, int64_t amount); + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_CUSTOM_CALL_HANDLER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/spmd_partitioner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/spmd_partitioner.h new file mode 100644 index 0000000000000000000000000000000000000000..26d7a5e6b43cbf33ed79abacd5c86af737dd9f1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/spmd_partitioner.h @@ -0,0 +1,670 @@ +/* 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_SERVICE_SPMD_SPMD_PARTITIONER_H_ +#define XLA_SERVICE_SPMD_SPMD_PARTITIONER_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/container/node_hash_map.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.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/hlo/ir/hlo_opcode.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/service/call_graph.h" +#include "xla/service/custom_call_sharding_helper.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace spmd { + +struct SpmdPartitionerOptions { + // Always exchange halo on LHS for all convolutions. If false, backprop filter + // convolution exchanges halo on RHS. + bool conv_halo_exchange_always_on_lhs = true; + + // The number of instructions to be reported for the highest memory profile + // instructions. + int64_t report_instruction_count = 5; + + // The minimum size in MiB of an einsum operand to be considered using + // windowed implementation in an HLO loop. + int64_t threshold_for_windowed_einsum_mib = 256; + + // Whether unroll windowed einsum loop by degree of two. + bool unroll_windowed_einsum = false; + + // Whether doing bidirectional collective permute in windowed einsum loop. + bool bidirectional_windowed_einsum = false; + + // Whether the entry computations' signature could change after partitioning. + bool allow_module_signature_change = false; + + // Whether to use cached all-gather to avoid repeatedly replicate a tiled + // tensor. If it is set to false, the result tends to be more + // memory-efficient, and the compiler can use the ScheduleAwareAllGatherCSE + // pass to CSE some all-gathers which are relatively close to each other. + bool cache_all_gather = true; + + // When making a compromise between windowed einsum speed and memory usage + // prefer the former if true. + bool choose_faster_windowed_einsum_over_mem = false; + + // Whether doing bidirectional communication when decomposing independent + // all-gathers. + bool bidirectional_decomposed_all_gather = false; + + // Whether to skip checking the numbers and shardings of windowed einsum's + // users. + bool skip_checking_windowed_einsum_users = false; +}; + +// Class to wrap the computation builder to capture information during SPMD +// transformation. +class SpmdBuilder : public HloComputation::Builder { + public: + SpmdBuilder(const std::string& name, HloInstruction* hlo) + : HloComputation::Builder(name) { + visiting_hlo_ = hlo; + } + + HloInstruction* AddInstruction( + std::unique_ptr instruction) override; + + const std::vector& derived_instructions( + HloInstruction* hlo) { + return instructions_.at(hlo); + } + + void set_visiting_hlo(HloInstruction* hlo) { + visiting_hlo_ = hlo; + instructions_[hlo]; + } + + HloInstruction* visiting_hlo() const { return visiting_hlo_; } + + // Wrapper of queries to broadcast_dims_. + std::optional*> BroadcastDimsForCreatedHlo( + const HloInstruction* hlo) { + auto it = broadcast_dims_.find(hlo); + if (it == broadcast_dims_.end()) { + return std::nullopt; + } + return &it->second; + } + + private: + // Currently visiting instruction. + HloInstruction* visiting_hlo_; + + // Map from the currently visiting (old) instruction to new instructions + // created during SPMD partitioning. + HloInstructionMap> instructions_; + + // Maps from each created instruction to a set of dimensions that are from + // broadcasts or elementwise ops over broadcasts. This means elements along + // these dimensions have the same value. + absl::flat_hash_map> + broadcast_dims_; +}; + +// A set of functions that create the cross-partition collective ops. +struct SPMDCollectiveOpsCreator { + // Function used to create a partition ID HLO. + std::function create_partition_id; + + // Function used to create a cross-partition all-reduce HLO. + std::function>& partition_subgroups, + int64_t channel_id)> + create_cross_partition_all_reduce; + + // Function used to create a cross-partition collective-permute HLO. + std::function>& src_dst_pairs, + int64_t next_channel_id)> + create_cross_partition_collective_permute; + + // Function used to create a cross-partition all-to-all HLO. + std::function operands, + const std::vector>& partition_subgroups, + int64_t channel_id, std::optional split_dimension)> + create_cross_partition_all_to_all; + + // Function used to create a cross-partition all-gather HLO. This is optional: + // if it is nullptr, the partitioner will use all-reduce instead. + std::function>& partition_subgroups, + int64_t channel_id, int64_t all_gather_dimension)> + create_cross_partition_all_gather; +}; + +// Create a default SPMDCollectiveOpsCreator. +SPMDCollectiveOpsCreator GetDefaultCollectiveOpsCreator(int64_t num_partitions, + int64_t num_replicas); + +// Logger to report memory usage during SPMD partitioning. +class SpmdLogger { + public: + SpmdLogger(int64_t report_instruction_count, bool disabled) + : report_instruction_count_(report_instruction_count), + disabled_(disabled) {} + static std::string ReportBeforePartition(const HloModule& module, + int64_t report_instruction_count); + static std::string ReportAfterPartition(const HloModule& module, + int64_t report_instruction_count); + + // Registers the logging for the groups of instructions created to transform + // the given hlo. + void RegisterLogEntry(HloInstruction* hlo, + const std::vector& group); + + std::string MakeReport(); + + private: + template + static std::string ReportMemoryUsage(const HloModule& module, const F& filter, + int64_t report_instruction_count); + + // A vector of logging messages (one for each original HLO instruction), where + // the first integer of the pair represents the size of the HBM used. + std::vector> entries_; + + int64_t report_instruction_count_; + + // Note that we allow creating a *disabled* logger when logging is not + // enabled, in which case it is supposed to avoid doing any potentially + // expensive work. The logger is still created in this case and passed to the + // users to help avoid changing current call sites. + const bool disabled_; +}; + +class SpmdPartitioningVisitor; + +class SpmdPartitioner : public HloModulePass { + public: + SpmdPartitioner(int64_t num_partitions, int64_t num_replicas, + SpmdPartitionerOptions options); + SpmdPartitioner(int64_t num_partitions, int64_t num_replicas, + SpmdPartitionerOptions options, + SPMDCollectiveOpsCreator collective_ops_creator) + : num_partitions_(num_partitions), + num_replicas_(num_replicas), + options_(std::move(options)), + collective_ops_creator_(std::move(collective_ops_creator)) {} + absl::string_view name() const override { return "spmd-partitioning"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Transforms the given computation with SPMD instructions, replacing it with + // a new computation. + StatusOr PartitionComputation(HloComputation* computation, + const HloSharding& root_sharding, + int64_t* next_channel_id, + SpmdLogger* logger, + const CallGraph& call_graph); + + // Creates all-gather(s) based on HloSharding. Can be overridden to customize. + // The default uses a single all-gather even if there are multiple sharded + // dimensions, and adds potential reshapes and transposes to achieve that. + // If it returns false, the partitioner will fall back to all-reduce. + // `selected_dims` specifies the dimensions along which the all-gather happens + // in the tiled sharding, which allows potentially creating a subgroup + // all-gather. + virtual HloInstruction* AllGatherShards( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator); + + // Creates all-reduce(s) across devices along selected_dims in sharding. Can + // be overridden to customize. + virtual HloInstruction* AllReduceAlongShardingDims( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator, + HloComputation* reduction); + + const SpmdPartitionerOptions& options() { return options_; } + + protected: + virtual std::unique_ptr CreateVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdLogger* logger, + SpmdPartitionerOptions options, const CallGraph& call_graph); + + // This is the internal implementation for AllGatherShards(), returns a pair + // of hlo instructions whose first element is the result of the all-gather + // shard(which might not be the all-gather itself and it could go through + // some other formatting instructions), and the second element is the + // all-gather being generated or nullptr is no all-gather is generated. + std::pair AllGatherShardsInternal( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator, bool per_dim_ag); + + HloInstruction* AllReduceAlongShardingDimsInternal( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator, + HloComputation* reduction, bool per_dim_ar); + + // Verifies that the sharding of instructions in the module are valid, and + // also fill in missing sharding information. + virtual Status PreprocessSharding( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + // Returns if the given side-effecting instruction is allowed to have + // replicated sharding. + virtual bool CanSideEffectingHaveReplicatedSharding( + const HloInstruction* hlo) { + if (hlo->opcode() == HloOpcode::kCustomCall) { + if (auto* partitioner = + GetCustomCallPartitioner(hlo->custom_call_target())) { + return partitioner->CanSideEffectingHaveReplicatedSharding(); + } + } + return hlo->opcode() == HloOpcode::kInfeed || + hlo->opcode() == HloOpcode::kOutfeed; + } + + // Preprocesses the graph to simplify some communication patterns. E.g., merge + // pad->slice into a single pad with potentially negative padding to avoid + // multiple halo exchanges. + Status PreprocessHlos( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + const int64_t num_partitions_; + const int64_t num_replicas_; + + SpmdPartitionerOptions options_; + SPMDCollectiveOpsCreator collective_ops_creator_; + std::vector> device_groups_; +}; + +// Class describes partition state of the data represented by an HLO created +// during SPMD partitioning pass. +// +// Data on some devices may include padding region, if the base (full) shape +// could not be evenly partitioned. +class PartitionedHlo { + public: + // Return value for ReshardAsWindowedInput which describes the resharded HLO, + // the window for the user on the shard, and if necessary, the dynamic slice + // offsets to be applied to the output of the op being sharded. + struct WindowedInputShardReturnValue { + HloInstruction* sharded_input; + Window shard_window; + std::optional> dynamic_slice_index_on_output; + }; + // A cache for resharding each partitioned HLO. + struct ReshardCache { + struct PerHloCache { + absl::flat_hash_map reshard_cache; + std::vector< + std::tuple> + window_reshard_cache; + }; + // Use absl::node_hash_map for pointer stability. + absl::node_hash_map per_hlo_cache; + // Caches for nested partitioning of grouped sharding. Each string key + // represents a unique way of grouping devices. + absl::flat_hash_map> + groupd_caches; + }; + struct PartitioningState { + SpmdBuilder* b; + HloModule* module; + int64_t num_replicas; + HloInstruction* partition_id; + SPMDCollectiveOpsCreator collective_ops_creator; + int64_t* next_channel_id; + ReshardCache* reshard_cache; + SpmdPartitioner* partitioner; + }; + PartitionedHlo(HloInstruction* hlo, Shape base_shape, PartitioningState state) + : hlo_(hlo), base_shape_(base_shape), state_(std::move(state)) { + CHECK(hlo->has_sharding()) + << "PartitionedHlo is missing sharding:" << hlo->ToString(); + } + + PartitionedHlo CloneWithNewHlo(HloInstruction* hlo) const { + PartitionedHlo new_phlo = *this; + new_phlo.hlo_ = hlo; + if (!hlo->has_sharding() && hlo_->has_sharding()) { + hlo->copy_sharding(hlo_); + } + return new_phlo; + } + + // Reshards the current SPMD instruction to a new sharding with optional + // specified pad value used during resharding. Could only modify the reshard + // cache. + PartitionedHlo Reshard(const HloSharding& target, + std::optional pad_value = std::nullopt); + + // Pads the garbage area of the output with the provided value. Normally, + // unevenly partitioned dimensions are padded on the right, but this function + // allows specifying left-padded dimensions, which can be used during the + // handling of kReverse, etc. + PartitionedHlo PadWithValue( + HloInstruction* pad_value, + absl::Span left_padded_dims = {}, + absl::Span skipped_dims = {}) const; + + // Same as PadWithValue but does not create a new PartitionedHlo. + HloInstruction* PadWithValueHlo( + HloInstruction* pad_value, + absl::Span left_padded_dims = {}, + absl::Span skipped_dims = {}) const; + + PartitionedHlo PadWithZero(absl::Span left_padded_dims = {}, + absl::Span skipped_dims = {}) const; + + // Returns the SPMD instruction. + HloInstruction* hlo() const { return hlo_; } + + // Returns the sharding of the SPMD instruction. + const HloSharding& sharding() const { return hlo_->sharding(); } + + // Returns the rank of the SPMD instruction. + const int64_t rank() const { return base_shape_.rank(); } + + // Original full shape of the data. + const Shape& base_shape() const { return base_shape_; } + + int64_t NewChannel() const { return (*state_.next_channel_id)++; } + + // Reshards the HLO to a usable partitioned input for a windowed user. Could + // only modify the reshard cache. + std::optional ReshardAsWindowedInput( + const Window& window, const HloSharding& target, + HloInstruction* pad_value, bool mask_invalid_region = true, + bool force_mask_in_compact = false); + + const PartitioningState& state() const { return state_; } + + // Helper function to replicate the data on all devices. Could only modify + // the reshard cache. + PartitionedHlo Replicate(); + + // Helper function to replicate the data for partitions along the given dims. + HloInstruction* ReplicatePartial(absl::Span dims); + + // Set state of the partitoned HLO. + void set_state(PartitioningState state) { state_ = std::move(state); } + + private: + // Same as Reshard except that it does not explicitly modify the reshard + // cache, although it would indirectly modify by calling Replicate(). + PartitionedHlo ReshardNoCache(const HloSharding& target, + std::optional pad_value = std::nullopt, + bool allow_full_replication = true); + + // Helper function to broadcast data from a single device to all devices. + PartitionedHlo Broadcast() const; + + // Try to perform complicated reshard handling by splitting a big reshard into + // multiple reshards using that can be handled directly. + std::optional TryComplexReshardHandling( + const HloSharding& target); + + // Helper function to reshard the tensor using AllToAll (instead of the + // default of Replicate followed by Slice). + PartitionedHlo ReshardWithAllToAll( + const HloSharding& target, + absl::Span> source_target_dims) const; + + // Helper function to reshard the tensor using CollectivePermute. + PartitionedHlo ReshardWithCollectivePermute(const HloSharding& target) const; + + // Helper function to reshard to partial replicate using AllGather. + std::optional ReshardToPartialReplicateWithAllGather( + const HloSharding& target); + + // Helper function to reshard from partial replicate using DynamicSlice. + std::optional ReshardFromPartialReplicateWithDynamicSlice( + const HloSharding& target); + + // Helper function to reshard from partial replicate using AllToAll. + std::optional ReshardPartialReplicateWithAllToAll( + const HloSharding& target); + + // SPMD instruction. + HloInstruction* hlo_; + + // The original shape of the data before SPMD transformation is applied. + Shape base_shape_; + + PartitioningState state_; +}; + +struct DotConvDimsMapping { + // The dimension numbers for the operands and output corresponding to a + // logical dimension (e.g., batch, contracting, non-contracting). If an + // operand or the output doesn't have the logical dimension, it is set to + // -1. + struct DimsMapping { + int64_t lhs; + int64_t rhs; + int64_t output; + // input mapped to index in input_spatial_dimensions(). + int64_t spatial; + }; + std::vector batch_dims; + std::vector contracting_dims; + std::vector lhs_non_contracting_dims; + std::vector rhs_non_contracting_dims; + std::vector conv_spatial_dims; +}; + +class SpmdPartitioningVisitor : public DfsHloVisitorWithDefault { + public: + SpmdPartitioningVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdLogger* logger, + SpmdPartitionerOptions options, SpmdPartitioner* partitioner, + const CallGraph& call_graph); + + Status DefaultAction(HloInstruction* hlo) override; + Status HandleAllReduce(HloInstruction* hlo) override; + Status HandleBroadcast(HloInstruction* hlo) override; + Status HandleConstant(HloInstruction* hlo) override; + Status HandleCustomCall(HloInstruction* hlo) override; + Status HandleDot(HloInstruction* hlo) override; + Status HandleDynamicSlice(HloInstruction* hlo) override; + Status HandleDynamicUpdateSlice(HloInstruction* hlo) override; + Status HandleFft(HloInstruction* hlo) override; + Status HandleGather(HloInstruction* hlo) override; + Status HandleGetTupleElement(HloInstruction* hlo) override; + Status HandleInfeed(HloInstruction* hlo) override; + Status HandleOptimizationBarrier(HloInstruction* hlo) override; + Status HandleOutfeed(HloInstruction* hlo) override; + Status HandlePad(HloInstruction* hlo) override; + Status HandleParameter(HloInstruction* hlo) override; + Status HandleReduce(HloInstruction* hlo) override; + Status HandleReverse(HloInstruction* hlo) override; + Status HandleWhile(HloInstruction* hlo) override; + Status HandleConditional(HloInstruction* hlo) override; + Status HandleReduceWindow(HloInstruction* hlo) override; + Status HandleSelectAndScatter(HloInstruction* hlo) override; + Status HandleTuple(HloInstruction* hlo) override; + Status HandleRng(HloInstruction* hlo) override; + Status HandleConvolution(HloInstruction* hlo) override; + Status HandleConcatenate(HloInstruction* hlo) override; + Status HandleScatter(HloInstruction* hlo) override; + Status HandleSlice(HloInstruction* hlo) override; + Status HandleSort(HloInstruction* hlo) override; + Status HandleTranspose(HloInstruction* hlo) override; + Status HandleReshape(HloInstruction* hlo) override; + Status HandleIota(HloInstruction* hlo) override; + Status HandlePartitionId(HloInstruction* hlo) override; + + // Implementation of dot partitioning given DotGeneralDimsMapping. + Status HandleDotHelper(HloInstruction* hlo, + const DotConvDimsMapping& dims_mapping, + absl::FunctionRef( + HloInstruction*, HloInstruction*, SpmdBuilder*, + const Window& conv_window)> + create_sharded_dot); + + // Common handle for elementwise HLOs. + Status HandleElementwise(HloInstruction* hlo); + + // Common handle for HLOs that runs on a single device. + Status HandleSingleDevice(const HloInstruction* hlo); + + // CustomCall handlers per call target. + Status HandleCustomCallTopK(HloInstruction* hlo); + // Convenient custom ops defined by the partitioner itself. + Status HandleCustomCallSPMDInternal_RotateRight(HloInstruction* hlo); + + // Returns the PartitionedHlo that corresponds to the original hlo. + PartitionedHlo& GetPartitionedHlo(const HloInstruction* hlo) { + CHECK_EQ(partitioned_instructions_.count(hlo), 1); + return partitioned_instructions_.find(hlo)->second; + } + + // Sets the PartitionedHlo for the original hlo. + void SetPartitionedHlo(const HloInstruction* hlo, + const PartitionedHlo& partitioned_hlo) { + CHECK_EQ(partitioned_instructions_.count(hlo), 0); + partitioned_instructions_.emplace(hlo, partitioned_hlo); + changed_ = true; + } + + // Convenient wrapper that creates PartitionedHlo from the result of the func + // and maps it to the given original hlo. + void SetPartitionedHlo(const HloInstruction* hlo, + absl::FunctionRef func) { + HloInstruction* new_hlo = func(); + new_hlo->set_sharding(hlo->sharding()); + SetPartitionedHlo( + hlo, PartitionedHlo(new_hlo, hlo->shape(), MakePartitioningState())); + changed_ = true; + } + + int64_t NewChannel() { return (*next_channel_id_)++; } + + PartitionedHlo::PartitioningState MakePartitioningState(); + + SpmdBuilder* builder() { return &b_; } + + virtual StatusOr DoPartition(HloComputation* computation, + const HloSharding& root_sharding, + const SpmdPartitionerOptions& options); + + virtual double GetComputationTimeInMilliSec(HloInstruction* hlo) { + return 0.0; + } + + virtual double GetCommunicationTimeInMilliSec( + int64_t bytes, absl::Span device_groups) { + return 0.0; + } + + virtual int GetCommunicationMultiplier( + absl::Span device_groups) { + return 1; + } + + std::vector CreateReplicaGroups( + std::vector>& groups); + + const CallGraph& call_graph() { return call_graph_; } + + // Information about a loop created for windowed dot-general. Used when + // DoCodeMotionForWindowedDotGeneralLoops() executes after the visitor + // finishes traversing the graph. + struct WindowedDotGeneralLoop { + HloInstruction* while_loop; + int64_t windowed_operand; + bool windowed_in_contracting_dims; + bool windowed_in_batch_dims; + bool operands_sharded_at_contracting_dims; + int64_t num_partitions; + std::vector loop_replica_groups; + }; + + protected: + Status Preprocess(HloInstruction* hlo) override; + Status Postprocess(HloInstruction* hlo) override; + + // Performs code motion for windowed dot-general loops in + // windowed_dot_general_loops_. Invoked after the visitor finishes traversing + // the graph. + Status DoCodeMotionForWindowedDotGeneralLoops( + HloComputation* computation, const SpmdPartitionerOptions& options); + + bool changed_; + HloModule* module_; + int64_t num_partitions_; + int64_t num_replicas_; + + SPMDCollectiveOpsCreator collective_ops_creator_; + + // Tracks the next channel id to use for cross-partition all-reduce. + int64_t* next_channel_id_; + SpmdBuilder b_; + + std::vector windowed_dot_general_loops_; + + HloInstruction* partition_id_; + + private: + PartitionedHlo::ReshardCache reshard_cache_; + + // Mapping from the instruction in the original computation to the new SPMD + // partitioned instruction. + ConstHloInstructionMap partitioned_instructions_; + + HloInstruction* visiting_hlo_; + SpmdLogger* logger_; + const SpmdPartitionerOptions options_; + SpmdPartitioner* partitioner_; + std::vector visiting_hlo_operand_shardings_; + std::optional visiting_hlo_sharding_; + std::optional visiting_num_partitions_; + std::optional visiting_collective_ops_creator_; + std::optional visiting_partition_id_; + std::vector visiting_state_; + std::vector> device_groups_; + const CallGraph& call_graph_; +}; + +} // namespace spmd +} // namespace xla +#endif // XLA_SERVICE_SPMD_SPMD_PARTITIONER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/spmd_partitioner_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/spmd_partitioner_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0bb05c96577394322d134e169da15751ab1e5f4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/spmd_partitioner_util.h @@ -0,0 +1,568 @@ +/* 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_SERVICE_SPMD_SPMD_PARTITIONER_UTIL_H_ +#define XLA_SERVICE_SPMD_SPMD_PARTITIONER_UTIL_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_casting_utils.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_sharding.h" +#include "xla/hlo/utils/hlo_sharding_util.h" +#include "xla/literal_util.h" +#include "xla/service/spmd/spmd_partitioner.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace spmd { + +template +using IsCompOrCompBuilder = + typename std::enable_if_t::value || + std::is_same::value || + std::is_same::value>; + +struct GatherScatterParallelDimSharding { + HloSharding indices_sharding; + HloSharding operand_sharding; +}; + +// Returns true if the given sharding contains any replicated sharding. +bool HasReplicatedSharding(const HloSharding& sharding); + +// Base for creating constants. +template > +HloInstruction* CreateConstantBase(const Shape& shape, Literal value, T* b, + Literal (*literal_creator)(Literal, + PrimitiveType)) { + if (shape.IsTuple()) { + std::vector elements; + for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { + elements.push_back( + CreateConstantBase(ShapeUtil::GetTupleElementShape(shape, i), + value.Clone(), b, literal_creator)); + } + return b->AddInstruction(HloInstruction::CreateTuple(elements)); + } + + if (shape.IsToken()) { + return b->AddInstruction(HloInstruction::CreateToken()); + } + auto c = b->AddInstruction(HloInstruction::CreateConstant( + literal_creator(std::move(value), shape.element_type()))); + if (shape.rank() == 0) { + return c; + } + return b->AddInstruction(HloInstruction::CreateBroadcast(shape, c, {})); +} + +// Creates constant value instructions of the given shape. The literal must be a +// scalar shape and is broadcast to the given shape. +template > +HloInstruction* CreateConstant(const Shape& shape, Literal value, T* b) { + auto identity = [](Literal value, PrimitiveType primitive_type) { + CHECK(ShapeUtil::IsScalarWithElementType(value.shape(), primitive_type)); + return value; + }; + return CreateConstantBase(shape, std::move(value), b, identity); +} + +// Creates zero value instructions of the given shape. +template > +HloInstruction* CreateZero(const Shape& shape, T* b) { + auto zero = [](Literal /*unused*/, PrimitiveType primitive_type) { + return LiteralUtil::Zero(primitive_type); + }; + return CreateConstantBase(shape, /*unused*/ Literal(), b, zero); +} + +// Creates one value instructions of the given shape. +template > +HloInstruction* CreateOne(const Shape& shape, T* b) { + auto one = [](Literal /*unused*/, PrimitiveType primitive_type) { + return LiteralUtil::One(primitive_type); + }; + return CreateConstantBase(shape, /*unused*/ Literal(), b, one); +} + +template > +HloInstruction* CreateR0WithType(PrimitiveType type, NativeT value, T* b) { + auto literal = LiteralUtil::CreateR0(value) + .ConvertToShape(ShapeUtil::MakeShape(type, {})) + .value(); + return b->AddInstruction(HloInstruction::CreateConstant(std::move(literal))); +} + +template > +inline HloInstruction* CreateFirstWithType(PrimitiveType type, T* b) { + if (type == F32) { + auto float_pad_value = std::numeric_limits::quiet_NaN(); + return CreateR0WithType(type, -float_pad_value, b); + } + auto literal = LiteralUtil::MinValue(type); + return b->AddInstruction(HloInstruction::CreateConstant(std::move(literal))); +} + +template > +inline HloInstruction* CreateLastWithType(PrimitiveType type, T* b) { + if (type == F32) { + auto float_pad_value = std::numeric_limits::quiet_NaN(); + return CreateR0WithType(type, float_pad_value, b); + } + auto literal = LiteralUtil::MaxValue(type); + return b->AddInstruction(HloInstruction::CreateConstant(std::move(literal))); +} + +// Create a binary add computation of the given type and add to the module. +HloComputation* MakeBinaryAdd(PrimitiveType type, HloModule* module); + +// Returns true if the shape can be evenly partitioned for the given sharding. +// All tile sharded dimensions should be evenly divisible and there should be no +// single-device sharding. Replicate sharding is considered even partition. +bool EvenlyPartitions(const Shape& shape, const HloSharding& sharding); + +// Returns the shard shape of the given shape when it is partitioned for the +// target sharding. +Shape MakePartitionedShape(const Shape& shape, const HloSharding& sharding); + +// Similar to ShapeUtil::ByteSizeOf(), but does not check it has dense layout +// since this can be before layout assignment. +int64_t ShapeSizeInBytes(const Shape& shape); + +// Creates a table lookup HLO using the ordinal as the offset. +template +HloInstruction* TableLookup(absl::Span table, PrimitiveType type, + HloInstruction* ordinal, SpmdBuilder* b) { + HloInstruction* table_hlo = b->AddInstruction( + HloInstruction::CreateConstant(LiteralUtil::CreateR1(table))); + HloInstruction* value = b->AddInstruction(HloInstruction::CreateDynamicSlice( + ShapeUtil::MakeShape(type, {1}), table_hlo, {ordinal}, {1})); + return b->AddInstruction( + HloInstruction::CreateReshape(ShapeUtil::MakeShape(type, {}), value)); +} + +// Returns the shard shape for a partition without padding due to uneven +// sharding. +Shape MakeNonPaddedShapeForGivenPartition(const Shape& shape, + const HloSharding& sharding, + int64_t partition_id); + +// Generates the HLO instructions that represent the dimension offsets on any +// device. The size of the returned vector is the rank of the given shape. +// If `dims` is non-empty, the generated offsets will only be non-zero for those +// dimensions. +std::vector MakePartitionOffsets( + const Shape& shape, const HloSharding& sharding, + HloInstruction* partition_id, SpmdBuilder* b, + absl::Span dims = {}); + +// Returns the offsets of the partition in the tile assignment. +std::vector MakeTiledPartitionOrdinals( + const HloSharding& sharding, HloInstruction* partition_id, SpmdBuilder* b); + +// Pads hlo to the desired shape using high padding. Either a builder or a +// computation needs to be supplied, but not both. +template > +HloInstruction* PadToShape(HloInstruction* hlo, const Shape& padded_shape, T* b, + std::optional value = std::nullopt) { + if (ShapeUtil::Compatible(hlo->shape(), padded_shape)) { + return hlo; + } + PaddingConfig padding_config; + for (int64_t i = 0; i < padded_shape.rank(); ++i) { + auto padding_config_dim = padding_config.add_dimensions(); + padding_config_dim->set_edge_padding_low(0); + padding_config_dim->set_interior_padding(0); + padding_config_dim->set_edge_padding_high(padded_shape.dimensions(i) - + hlo->shape().dimensions(i)); + } + const Shape padding_shape = + ShapeUtil::MakeScalarShape(hlo->shape().element_type()); + HloInstruction* padding = + value.has_value() ? CreateConstant(padding_shape, std::move(*value), b) + : CreateZero(padding_shape, b); + return b->AddInstruction( + HloInstruction::CreatePad(padded_shape, hlo, padding, padding_config)); +} + +// Returns the padded shape when combining all partitions. +Shape GetPaddedShapeForUnevenPartitioning(const Shape& base_shape, + const HloSharding& sharding); + +// Pads the HLO (with base shape) for uneven tiled partition to make it evenly +// partitionable. +template > +HloInstruction* PadBaseShapeBeforeUnevenTiledSharding( + HloInstruction* hlo, const HloSharding& sharding, T* b, + std::optional value = std::nullopt) { + auto padded_base_shape = + GetPaddedShapeForUnevenPartitioning(hlo->shape(), sharding); + if (ShapeUtil::Compatible(padded_base_shape, hlo->shape())) { + return hlo; + } + return PadToShape(hlo, padded_base_shape, b, std::move(value)); +} + +// Returns the index of the unique tile dimension. Returns std::nullopt if the +// given sharding is not tiled or tiled along multiple dimensions. +std::optional UniqueTiledDim(const HloSharding& sharding); + +// Utilities for symbolic offset calculation and halo exchange. +class OffsetCalculation; + +// Represents a calculation over integers: +// (shard_ordinal * multiplier + offset) / divisor +class MultiplyAddDivideOffsetCalculation { + public: + MultiplyAddDivideOffsetCalculation() + : multiplier_(0), offset_(0), divisor_(1) {} + MultiplyAddDivideOffsetCalculation(int64_t multiplier, int64_t offset, + int64_t divisor); + + OffsetCalculation operator-( + const MultiplyAddDivideOffsetCalculation& other) const; + OffsetCalculation operator+( + const MultiplyAddDivideOffsetCalculation& other) const; + + bool operator==(const MultiplyAddDivideOffsetCalculation& other) const { + return multiplier_ == other.multiplier_ && offset_ == other.offset_ && + divisor_ == other.divisor_; + } + + bool IsConstant() const { return multiplier_ == 0; } + void Simplify(); + int64_t Calculate(int64_t shard_ordinal) const; + HloInstruction* Calculate(HloInstruction* shard_ordinal, + SpmdBuilder* b) const; + + // Returns the maximum result for shard ordinals in the range + // [start_ordinal, limit_ordinal). + int64_t MaxInRange(int64_t start_ordinal, int64_t limit_ordinal) const; + + private: + int64_t multiplier_; + int64_t offset_; + int64_t divisor_; +}; + +// Represents a calculation over integers based on results of other calculations +// defined by an opcode. If the opcode is kCopy, it simply wraps an +// MultiplyAddDivideOffsetCalculation. +class OffsetCalculation { + public: + OffsetCalculation() : opcode_(HloOpcode::kCopy), copy_from_() {} + explicit OffsetCalculation( + const MultiplyAddDivideOffsetCalculation& copy_from) + : opcode_(HloOpcode::kCopy), copy_from_(copy_from) {} + OffsetCalculation(const OffsetCalculation& copy_from) { *this = copy_from; } + OffsetCalculation(HloOpcode opcode, + const MultiplyAddDivideOffsetCalculation& lhs, + const MultiplyAddDivideOffsetCalculation& rhs) + : opcode_(opcode), + lhs_(std::make_unique(lhs)), + rhs_(std::make_unique(rhs)) {} + OffsetCalculation(HloOpcode opcode, const OffsetCalculation& lhs, + const OffsetCalculation& rhs) + : opcode_(opcode), + lhs_(std::make_unique(lhs)), + rhs_(std::make_unique(rhs)) {} + + OffsetCalculation& operator=(const OffsetCalculation& other); + + // Returns whether the calculation returns the same value for all shards. This + // is conservative and could return false even if it is actually constant. + bool IsConstant() const; + + OffsetCalculation operator-(const OffsetCalculation& other) const; + OffsetCalculation operator+(const OffsetCalculation& other) const; + bool operator==(const OffsetCalculation& other) const; + int64_t Calculate(int64_t shard_ordinal) const; + HloInstruction* Calculate(HloInstruction* shard_ordinal, + SpmdBuilder* b) const; + + // Returns the maximum result for shard ordinals in the range + // [start_ordinal, limit_ordinal). + int64_t MaxInRange(int64_t start_ordinal, int64_t limit_ordinal) const; + + private: + HloOpcode opcode_; + std::unique_ptr lhs_; + std::unique_ptr rhs_; + MultiplyAddDivideOffsetCalculation copy_from_; +}; + +// Performs halo exchange on the given dimension based on the provided +// left/right halo size functions. Returns nullopt if the halo is beyond the +// direct neighbor of the shard. +std::optional ExchangeHalo( + HloInstruction* hlo, const OffsetCalculation& left_halo_size_function, + const OffsetCalculation& right_halo_size_function, int64_t dim, + const HloSharding& target, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b); + +// Exchange halo on all dimensions of the HLO. Returns nullopt if any one of the +// dimensions fails to exchange halo (halo is beyond the neighbor shard). +std::optional ExchangeHalo( + HloInstruction* hlo, + std::vector left_halo_size_functions, + std::vector right_halo_size_functions, + const HloSharding& target, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b); + +// A compact version of halo exchange, which generates fewer collective permutes +// when the halo ranges are far from the current shard while the final result +// size is small. It tries to reuse the same collective permute to do as many +// disjoint communications as possible. It also includes data masking. pad_value +// can be nullptr, which means the value in padding regions doesn't matter. +HloInstruction* ExchangeHaloCompact( + HloInstruction* hlo, const Shape& base_shape, + const OffsetCalculation& left_halo_size_function, + const OffsetCalculation& right_halo_size_function, + HloInstruction* pad_value, int64_t dim, const HloSharding& sharding, + HloInstruction* shard_ordinal, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b); + +// Exchanges halos and performs pad/dynamic-slice on the concatenated data such +// that the result starts with the first needed element on each shard. It also +// masks off invalid data due to padding. +// Arguments: +// hlo: the HLO op before halo exchange +// explicit_left_padding_on_full_shape: the amount of left padding to be added +// explicitly by this function on the base shape before partitioning. Without +// base dilation, this is usually set to the window's padding_low so that the +// sharded op do not need to add padding_low on the window; however, with base +// dilation, this could only be set to a custom size. +// padded_full_shape_size: the size of the padded full shape on the given +// dimension, which includes explicit_left_padding_on_full_shape and required +// right padding to make the shape evenly shardable. +// shard_size_with_halo: the shard size on the dimension after halo exchange. +// If different shards have different sizes, use the maximum size. +// offset_on_padded_shape: the offset HLO (S32) that represents the start of +// each shard on the padded full shape. +// pad_value: the padding value used on the full shape. +// force_mask_in_compact: If true, masking is always applied if it uses +// ExchangeHaloCompact. An example is that certain cases in pad can skip +// masking in non-compact halo exchange, but not in compact ones. +std::optional ExchangeHaloAndGetValidData( + HloInstruction* hlo, const Shape& base_shape, + const OffsetCalculation& left_halo_size_function, + const OffsetCalculation& right_halo_size_function, + int64_t explicit_left_padding_on_full_shape, int64_t padded_full_shape_size, + int64_t shard_size_with_halo, int64_t dim, const HloSharding& target, + HloInstruction* offset_on_padded_shape, HloInstruction* pad_value, + HloInstruction* partition_ordinal, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b, bool mask_invalid_region = true, + bool force_mask_in_compact = false); + +// Uses halo exchange to change from right-padding to left-padding for uneven +// tiled sharding on the given dimensions. Tiled sharding always pads uneven +// partitioned data on the right, but we need to swap it to the left for +// kReverse or kConvolution with window reversal. +HloInstruction* HaloExchangeToPadOnLeft(PartitionedHlo& original, + absl::Span dims); + +// Check if the computation is GT comparison and safe for NaNs. +bool IsNanSafeGt(HloComputation* computation); + +// Return k in TopK when input value is parttioned in the sort dimension. +std::optional GetKValueInTopKWhenPartitionSortDim(HloInstruction* hlo); + +// Slices the first k elements at slice dimension. +HloInstruction* SliceFirstK(HloInstruction* hlo, SpmdBuilder* builder, + int64_t slice_dim, int64_t k); + +// Check if a dimension is sharded. +int64_t ShardCountAtDim(const HloSharding& sharding, int64_t dim); + +// Returns the list of source-target pairs of dimensions to swap during +// resharding via all-to-all. Reshard can be done by swapping each pair at a +// time. +std::optional>> +GetReshardAllToAllSourceTargetDims(const HloSharding& source, + const HloSharding& target); + +// Returns whether the resharding can be done via collective-permute. +bool CanReshardWithCollectivePermute(const HloSharding& source, + const HloSharding& target); + +// Returns a new GroupedSharding that has the same group definition of +// `reference`. +hlo_sharding_util::GroupedSharding AlignGroupsWith( + hlo_sharding_util::GroupedSharding grouped_sharding, + const hlo_sharding_util::GroupedSharding& reference, + bool ignore_group_order = false); + +// Align device groups between the two shardings. Equivalent in calling +// GroupShardingOnDims on the two sharding AlignGroupsWith and then +// UngroupSharding +HloSharding AlignShardingOnDims(const HloSharding& sharding, + absl::Span sharding_dims, + const HloSharding& reference, + absl::Span reference_dims); + +// AlignShardingOnDims only if it doesn't change the sharding when ungrouped. +std::optional AlignGroupsWithIfCompatible( + hlo_sharding_util::GroupedSharding grouped_sharding, + const hlo_sharding_util::GroupedSharding& reference); + +// Returns the per-group base shape, i.e., before applying the in-group +// sharding. +Shape GetPerGroupBaseShape( + const hlo_sharding_util::GroupedSharding& grouped_sharding, + const Shape& original_base_shape); + +// Returns the partition id within a group. +HloInstruction* GetInGroupPartitionId( + HloInstruction* partition_id, + const std::vector>& device_groups, SpmdBuilder* b); + +// Creates the nested partitioner state for in-group partitioning. +PartitionedHlo::PartitioningState CreatePerGroupPartitioningState( + const PartitionedHlo::PartitioningState& state, + const std::vector>& device_groups, SpmdBuilder* b); + +// Partially shards a replicated HLO into groups along the group dimensions, and +// within each group data is still replicated. +HloInstruction* PerGroupSliceFromReplicated( + HloInstruction* replicated, HloInstruction* partition_id, + const std::vector>& device_groups, + absl::Span group_dims, + absl::Span group_dim_sizes, SpmdBuilder* b); + +// Pad the shape from partial replicate shape for `dst_sharding`. +// If dst_sharding needs more padding and per_shard_size increased in +// dst_sharding, halo exchange on the right side is needed. +std::optional PadFromPartialReplicateShape( + HloInstruction* hlo, const Shape& base_shape, + const HloSharding& src_sharding, const HloSharding& dst_sharding, + const std::vector& expand_tile_dims, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, HloInstruction* partition_id, SpmdBuilder* b); + +// Get the compatible sharding from a partial replicate sharding to a desired +// target tiled sharding. +// Compatible means replicate sharding can transform to the target tile +// dimensions by dynamic slice. +// For example, if partial_sharding is +// {devices=[1,2,2]0,1,2,3 last_tile_dim_replicate} +// Target sharding is {devices=[2,2]0,1,2,3}, the returned compatible sharding +// will be sharding={devices=[2,2]0,2,1,3}. +// If patial replicate sharding is not partial replicate or can't reshard to +// target_tile_dims by dynamic slice, return std::nullopt. +// If target_sharding is already compatible, returns it. +std::optional PartialReplicateReshardCompatibleSharding( + const HloSharding& partial_sharding, const HloSharding& target_sharding); + +// Do left halo exchange if all-reduce directly from tile sharding to partial +// replicate sharding will remove useful data from the source. +std::optional TileToPartialReplicateHaloExchange( + HloInstruction* hlo, const Shape& base_shape, + const HloSharding& src_sharding, const HloSharding& dst_sharding, + const std::vector& replicate_dims, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, HloInstruction* partition_id, SpmdBuilder* b); + +// Finds a list of dimensions that can be grouped on such that it will have the +// specified device groups. Group order and dimension order are ignored. +std::optional> FindMatchingPartitionedDimsForGrouping( + const HloSharding& sharding, + const std::vector>& device_groups); + +// Create a sharding that matches the provided source sharding on the +// specified dimensions. 'target_dims' and 'source_dims' represent the +// dimensions for which the sharding should match in their respective shape. +// If some devices from the source sharding are left over (because not all the +// devices are allocated to 'source_dims' dimensions) then partial replication +// is employed to make sure the number of devices for the two sharding match. +HloSharding CreateMatchingShardingOnDims(const Shape& target_shape, + const HloSharding& source_sharding, + absl::Span target_dims, + absl::Span source_dims); + +// Returns if the sharding across operand and indices of a gather/scatter is +// across parallel dimensions and matches what SPMD partitioner supports. +std::optional +GatherScatterOperandsShardedAcrossParallelDims( + const HloInstruction& operand, const HloInstruction& indices, + const hlo_sharding_util::GatherScatterParallelDims& parallel_dims); + +// Pattern rewrite preprocessing utilities. + +// Returns rotate_amount if the concat(lhs, rhs) is equivalent to rotating the +// elements along the concat dimension to the right by rotate_amount, where the +// input of rotation is the shard operand of lhs and rhs. Returns -1 if the +// pattern is not found. +int64_t FindRotateRightPattern(const HloInstruction* concat, + const HloInstruction* lhs, + const HloInstruction* rhs); + +// Describes the pad with wrap pattern. +struct PadWithWrapPattern { + int64_t lhs_slice_start; + int64_t rhs_slice_start; + std::vector lhs_modifiers; + std::vector rhs_modifiers; +}; + +// Returns the `PadWithWrapPattern` if the concat(lhs,mid,rhs) is equivalent to +// padding mid with wrapping (i.e., padding mid with slices of itself). Return +// std::nullopt if the pattern is not found. +std::optional FindPadWithWrapPattern( + const HloInstruction* concat, const HloInstruction* lhs, + const HloInstruction* mid, const HloInstruction* rhs); + +// Reshards data for a slice to be happening on such data with the passed +// parameters. +std::optional +ReshardDataForSlicing(absl::Span strides, + absl::Span starts, + absl::Span limits, + PartitionedHlo to_reshard, + const HloSharding& target_sharding, SpmdBuilder* b); + +// Performs slicing of data based on the windowed sharding passed as input. +HloInstruction* SliceDataFromWindowReshard( + const PartitionedHlo::WindowedInputShardReturnValue& reshard_operand, + absl::Span strides, const Shape& base_shape, + const HloSharding& target_sharding, SpmdBuilder* b); + +// Reshards data for a pad to be happening on such data with the passed +// parameters. +std::optional ReshardDataForPad( + HloInstruction* pad_value, PaddingConfig pc, PartitionedHlo to_reshard, + const HloSharding& target_sharding, SpmdBuilder* b); + +// Performs padding of data based on the windowed sharding passed as input. +HloInstruction* PadDataFromWindowReshard( + const PartitionedHlo::WindowedInputShardReturnValue& reshard_operand, + HloInstruction* pad_value, SpmdBuilder* b); + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_SPMD_PARTITIONER_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/stateful_rng_spmd_partitioner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/stateful_rng_spmd_partitioner.h new file mode 100644 index 0000000000000000000000000000000000000000..76ef60a3c3178a689a07c40299a28364a88e616f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/spmd/stateful_rng_spmd_partitioner.h @@ -0,0 +1,80 @@ +/* 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_SERVICE_SPMD_STATEFUL_RNG_SPMD_PARTITIONER_H_ +#define XLA_SERVICE_SPMD_STATEFUL_RNG_SPMD_PARTITIONER_H_ + +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/spmd/spmd_partitioner.h" + +namespace xla { +namespace spmd { + +class StatefulRngSpmdPartitioningVisitor + : public spmd::SpmdPartitioningVisitor { + public: + StatefulRngSpmdPartitioningVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const spmd::SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, spmd::SpmdLogger* logger, + spmd::SpmdPartitionerOptions options, spmd::SpmdPartitioner* partitioner, + const CallGraph& call_graph) + : spmd::SpmdPartitioningVisitor(computation, num_partitions, num_replicas, + collective_ops_creator, next_channel_id, + logger, std::move(options), partitioner, + call_graph) {} + Status HandleRngGetAndUpdateState(HloInstruction* hlo) override; +}; + +class StatefulRngSpmdPartitioner : public spmd::SpmdPartitioner { + public: + StatefulRngSpmdPartitioner(int64_t num_partitions, int64_t num_replicas) + : spmd::SpmdPartitioner(num_partitions, num_replicas, + GetSpmdPartitionerOptions()) {} + + protected: + std::unique_ptr CreateVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const spmd::SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, spmd::SpmdLogger* logger, + spmd::SpmdPartitionerOptions options, + const CallGraph& call_graph) override; + + Status PreprocessSharding( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + bool CanSideEffectingHaveReplicatedSharding( + const HloInstruction* hlo) override; + + private: + static spmd::SpmdPartitionerOptions GetSpmdPartitionerOptions() { + spmd::SpmdPartitionerOptions options; + options.allow_module_signature_change = true; + // Setting windowed einsum threshold to be large to disable it for GPU by + // default. + options.threshold_for_windowed_einsum_mib = 100000; + return options; + } +}; + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_STATEFUL_RNG_SPMD_PARTITIONER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stable_sort_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stable_sort_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..e5896a8e2ab497063214cb3d7fcd2db98dde740d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stable_sort_expander.h @@ -0,0 +1,42 @@ +/* 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_SERVICE_STABLE_SORT_EXPANDER_H_ +#define XLA_SERVICE_STABLE_SORT_EXPANDER_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/op_expander_pass.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass which expands Sort ops that have the is_stable field set to true +// into equivalent Sort ops which guarantee stable sorting without relying on +// the is_stable field. +class StableSortExpander : public OpExpanderPass { + public: + absl::string_view name() const override { return "stable-sort-expander"; } + + private: + bool InstructionMatchesPattern(HloInstruction* instruction) override; + StatusOr ExpandInstruction( + HloInstruction* instruction) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_STABLE_SORT_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stochastic_convert_decomposer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stochastic_convert_decomposer.h new file mode 100644 index 0000000000000000000000000000000000000000..1292e625caa5a2d20303c0e12be5481fb2a2e4e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stochastic_convert_decomposer.h @@ -0,0 +1,39 @@ +/* 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_SERVICE_STOCHASTIC_CONVERT_DECOMPOSER_H_ +#define XLA_SERVICE_STOCHASTIC_CONVERT_DECOMPOSER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// StochasticConvertDecomposer is a pass which replaces unsupported +// stochastic-convert with multiple hlos. +class StochasticConvertDecomposer : public HloModulePass { + public: + absl::string_view name() const override { + return "stochastic_convert_decomposer"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_STOCHASTIC_CONVERT_DECOMPOSER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stream_pool.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stream_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..32204daa3dcc7f7c806cffcbe8d67dfb92df703d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/stream_pool.h @@ -0,0 +1,68 @@ +/* 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_SERVICE_STREAM_POOL_H_ +#define XLA_SERVICE_STREAM_POOL_H_ + +#include +#include +#include + +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace se = ::stream_executor; + +// Pool of stream_executor::Streams, which are created as needed and +// destroyed when the pool is destroyed. +class StreamPool { + public: + struct PtrDeleter { + void operator()(se::Stream* stream) { pool->ReturnStream(stream); } + StreamPool* pool; + }; + + // Stream pointer type returned by BorrowStream, which returns the + // stream to the pool on destruction. + using Ptr = std::unique_ptr; + + StreamPool() = default; + + // Returns a pointer to a stream in the pool, creating a new stream + // if none are available in the pool. The returned smart pointer + // returns the stream to the pool on destruction. + // + // This method is thread-safe. + Ptr BorrowStream(se::StreamExecutor* executor, + se::StreamPriority priority = se::StreamPriority::Default); + + private: + // Puts a pointer to a stream back into the pool, leaving it free + // for future use. Streams that have previously encountered errors + // are deleted, and not returned to the pool. + // + // This method is thread-safe. + void ReturnStream(se::Stream* stream); + + absl::Mutex mu_; + // This stores streams with user-specified priority. + std::unordered_map>> + streams_with_pri_ ABSL_GUARDED_BY(mu_); +}; + +} // namespace xla + +#endif // XLA_SERVICE_STREAM_POOL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/topk_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/topk_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..21f96c01002521e489059096dda92f8487ecaad0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/topk_rewriter.h @@ -0,0 +1,82 @@ +/* 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_SERVICE_TOPK_REWRITER_H_ +#define XLA_SERVICE_TOPK_REWRITER_H_ + +#include +#include +#include +#include + +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This pass pattern-matches soups of HLOs executing a TopK operation and +// replaces them with a TopK CustomCall when the given values are supported by +// the CustomCall and it is more efficient to use that implementation. +class TopkRewriter : public HloModulePass { + public: + explicit TopkRewriter(std::function + is_profitable_to_convert) + : is_profitable_to_convert_(std::move(is_profitable_to_convert)) {} + + absl::string_view name() const override { return "topk-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + protected: + // Check if the sort instruction is in TopK. + std::optional SortIsInTopK(HloInstruction* inst); + + // Transform to CustomCall. + StatusOr TransformToCustomCall( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + private: + // Predicate that returns true if a sort instruction is profitable to be + // converted into a custom call. + std::function + is_profitable_to_convert_; +}; + +class TopkDecomposer : public HloModulePass { + public: + absl::string_view name() const override { return "topk-decomposer"; } + + explicit TopkDecomposer(HloPredicate should_decompose = {}) + : should_decompose_(should_decompose) {} + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + HloPredicate should_decompose_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_TOPK_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/transfer_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/transfer_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..e2b8a15d8c7c7a1eafe04a29e0ff063394406219 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/transfer_manager.h @@ -0,0 +1,332 @@ +/* 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_SERVICE_TRANSFER_MANAGER_H_ +#define XLA_SERVICE_TRANSFER_MANAGER_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "xla/literal.h" +#include "xla/service/executable.h" +#include "xla/service/shaped_buffer.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// The TransferManager interface lets backends provide platform-specific +// mechanisms for constructing literals from given device memory handles. +// This lets each platform customize how literals are transferred to/from the +// device in terms of padding, leading dimension, etc. +class TransferManager { + public: + virtual ~TransferManager() = default; + + // Returns the ID of the platform that this transfer manager acts on. + virtual se::Platform::Id PlatformId() const = 0; + + // Returns the shape of the on-device representation for the given shape on + // the host. This is intended for use with ShapedBuffer where buffers are + // pre-allocated by the host, e.g. TransferLiteralToDevice, without the user + // needing to consider device-specific behaviors. + virtual Shape HostShapeToDeviceShape(const Shape& host_shape) const { + // Strips off any preexisting tiling or memory space information. + // TODO(phawkins): fix clients not to including tiling or memory space + // information in shapes passed to this function and turn this into an + // assertion. + return ShapeUtil::DeviceShapeToHostShape(host_shape); + } + + // Base class for specifying platform specific transfer metadata that can be + // used to tell the underlying implementation to perform specific optimization + // to a transfer. Actual metadata passed to supported transfer methods should + // subclass this class. + class TransferMetadata { + public: + virtual ~TransferMetadata() = default; + }; + // Returns a literal containing the data held in the given ShapedBuffer + // using the provided executor. This operation is performed synchronously + // without waiting for any other operation on a stream to complete. + // + // This function should be avoided in favor of the asynchronous version below. + // + // Optionally caller can specify platform-specific transfer metadata that + // tells the actual implementation to do something special. + StatusOr TransferLiteralFromDevice( + se::Stream* stream, const ShapedBuffer& device_buffer, + const TransferMetadata* transfer_metadata = nullptr); + + Status TransferLiteralFromDevice( + se::Stream* stream, const ShapedBuffer& device_buffer, + const MutableBorrowingLiteral& literal, + const TransferMetadata* transfer_metadata = nullptr); + + // Begins transferring a literal containing the data held in the given + // ShapedBuffer using the provided executor. + // + // This operation is performed asynchronously on the given stream. It returns + // once the transfer is enqueued. 'done' is invoked with the result when + // complete. + // + // device_buffer is copied by reference and must live at least until done() is + // invoked. + // + // Optionally caller can specify platform-specific transfer metadata that + // tells the actual implementation to do something special. + virtual void TransferLiteralFromDevice( + se::Stream* stream, const ShapedBuffer& device_buffer, + MutableBorrowingLiteral literal, std::function done, + const TransferMetadata* transfer_metadata) = 0; + + void TransferLiteralFromDevice(se::Stream* stream, + const ShapedBuffer& device_buffer, + MutableBorrowingLiteral literal, + std::function done) { + return TransferLiteralFromDevice(stream, device_buffer, literal, done, + nullptr); + } + + // Transfers the given literal into the previously allocated device memory + // represented by the given ShapedBuffer using the given executor. The shape + // of the ShapedBuffer and DeviceShape(literal.shape()) must be compatible, + // but need not have the same layout. + // + // This operation is performed synchronously without waiting for any other + // operation on a stream to complete. This function should be avoided in favor + // of the asynchronous version below. + // + // Optionally caller can specify platform-specific transfer metadata that + // tells the actual implementation to do something special. + Status TransferLiteralToDevice( + se::Stream* stream, const LiteralSlice& literal, + const ShapedBuffer& device_buffer, + const TransferMetadata* transfer_metadata = nullptr); + + // Transfers the given literal into the previously allocated device memory + // represented by the given ShapedBuffer using the given executor. The shape + // of the ShapedBuffer and DeviceShape(literal.shape()) must be compatible, + // but need not have the same layout. + // + // This operation is performed asynchronously on the given stream. It returns + // once the transfer is enqueued, and may return before the transfer has + // completed. + // + // The caller may free the data structures 'literal' and 'device_buffer' + // immediately after this function returns, however their constituent buffers + // on both host and device must remain valid until the enqueued transfer has + // completed on 'stream'. + // + // Optionally caller can specify platform-specific transfer metadata that + // tells the actual implementation to do something special. + virtual Status TransferLiteralToDeviceAsync( + se::Stream* stream, const LiteralSlice& literal, + const ShapedBuffer& device_buffer, + const TransferMetadata* transfer_metadata) = 0; + + Status TransferLiteralToDeviceAsync(se::Stream* stream, + const LiteralSlice& literal, + const ShapedBuffer& device_buffer) { + return TransferLiteralToDeviceAsync(stream, literal, device_buffer, + nullptr); + } + + // Convenience methods for transferring an array to or from the device at a + // known address. This avoids having to construct a ShapedBuffer just to + // transfer an array at a known address. + // + // Optionally caller can specify platform-specific transfer metadata that + // tells the actual implementation to do something special. + Status TransferArrayToDevice( + se::Stream* stream, const LiteralSlice& literal, + const se::DeviceMemoryBase& dest, + const TransferMetadata* transfer_metadata = nullptr); + + Status TransferArrayToDeviceAsync( + se::Stream* stream, const LiteralSlice& literal, + const se::DeviceMemoryBase& dest, + const TransferMetadata* transfer_metadata = nullptr); + + StatusOr TransferArrayFromDevice( + se::Stream* stream, const Shape& shape, + const se::DeviceMemoryBase& source, + const TransferMetadata* transfer_metadata = nullptr); + + // Read from a device buffer and update the dynamic dimension sizes of + // `host_shape` and `device_shape`. The function takes in bounded dynamic + // shapes, and returns static shapes with dynamic shapes updated. + // The shape of the buffer also have to be compatible with the host shape and + // device shape. + virtual Status ReadDynamicShapes(se::Stream* stream, + const ShapedBuffer* device_buffer, + Shape* device_shape); + + // Transfers the given literal into the Infeed interface of the device, + // using the given executor. + virtual Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal) = 0; + + // Transfers the given literal from the Outfeed interface of the device, + // using the given executor. The shape and layout are determined by the + // shape and layout of `literal`. + virtual Status TransferLiteralFromOutfeed( + se::StreamExecutor* executor, MutableBorrowingLiteral literal) = 0; + + // Resets the devices associated with this transfer manager. + virtual Status ResetDevices( + absl::Span executor) = 0; + + // Given an allocated ShapedBuffer, constructs the tuple index table(s) in + // each buffer of the given ShapedBuffer corresponding to tuple shapes. If the + // ShapedBuffer is array-shaped this method does nothing. + Status WriteTupleIndexTables(se::Stream* stream, + const ShapedBuffer& device_buffer); + Status WriteTupleIndexTablesAsync(se::Stream* stream, + const ShapedBuffer& device_buffer); + + // Writes a tuple index buffer for the root of 'device_buffer', which must + // be a tuple. Unlike WriteTupleIndexTables, only writes the root buffer, + // rather than writing all subbuffers. This method is always asynchronous. + Status WriteRootTupleIndexTable(se::Stream* stream, + const ShapedBuffer& device_buffer); + Status WriteRootTupleIndexTable( + se::Stream* stream, + const ShapeTree& buffer_tree); + + // Determines the byte size requirement for the given shape on the underlying + // architecture. This will be used to allocate an appropriately sized memory + // region for a host-to-device transfer. + virtual int64_t GetByteSizeRequirement(const Shape& shape) const = 0; + + // Chooses a compact layout for 'shape', ignoring any existing layout on + // 'shape'. What "reasonable" means is left up to the backend. The + // intended use case is to choose a layout that avoids excessive padding on + // devices that have tiled memory architectures. + // The default implementation always picks a default (major-to-minor) layout. + // Fails if 'shape' cannot be represented by the device. + virtual StatusOr ChooseCompactLayoutForShape( + const Shape& host_shape) const; + + // For the given shape, chooses a layout for infeed. The returned shape + // has the same dimensions as the original shape, and only the layout is + // changed. + virtual Shape ChooseGoodInfeedLayout(const Shape& shape) const; + + typedef std::function DeviceShapeRepresentationFn; + + // Allocates a ScopedShapedBuffer which can hold data with the given on-host + // shape. The on-device shape may be different as indicated by + // HostShapeToDeviceShape. + StatusOr AllocateScopedShapedBuffer( + const Shape& on_host_shape, se::DeviceMemoryAllocator* allocator, + int device_ordinal, + DeviceShapeRepresentationFn shape_representation_fn = nullptr); + + // The given ShapedBuffer holds a handle to allocated memory, but it is not + // in the general case legal to immediately copy or access that allocated + // memory because queued operations on the device may alias that memory. + // Memory ordering is enforced by the Stream's happens-before relationship + // which allows eager deallocation and reallocation of buffers host-side even + // if the device hasn't finished with them. + // + // In certain cases, it can be known that a ShapedBuffer does not have any + // conflicting accesses on the device and thus is eligible to be accessed at + // any time from the host. + // + // This function returns true if device_buffer can be accessed immediately + // without waiting for the Stream's previously enqueued items. This only + // returns true if all subbuffers in device_buffer can be accessed + // immediately. + virtual bool CanShapedBufferBeAccessedNow( + se::StreamExecutor* executor, const ShapedBuffer& device_buffer) const { + return false; + } + + // Equivalent to CanShapedBufferBeAccessedNow but for a single device buffer. + virtual bool CanBufferBeAccessedNow( + se::StreamExecutor* executor, + const se::DeviceMemoryBase& device_buffer) const { + return false; + } + + ///// + // The TransferManager class also serves as a point to register objects for + // the various platforms. + + // Registers the TransferManager singleton for the platform kind. This is + // assumed to be a singleton, so no ownership is transferred. + // + // Precondition: a platform kind must not be registered more than once. + typedef std::unique_ptr (*TransferManagerCreationFunction)(); + static void RegisterTransferManager( + se::Platform::Id platform_id, + TransferManagerCreationFunction transfer_manager); + + // Returns the transfer manager singleton pointer if it is available for the + // given platform, or an error status if it is not. + static StatusOr GetForPlatform( + const se::Platform* platform); + + // Writes the given device-memory pointers in 'elements' to the given region + // to construct a tuple index table in the platform-specific tuple + // representation. + virtual Status WriteSingleTupleIndexTable( + se::Stream* stream, absl::Span elements, + const Shape& shape, se::DeviceMemoryBase* region) = 0; + + protected: + // Transfer a memory block of the given size from the device source into the + // 'destination' buffer. + // + // size is the size to transfer to destination in bytes. + virtual Status TransferBufferFromDevice(se::Stream* stream, + const se::DeviceMemoryBase& source, + int64_t size, void* destination); + + // Transfer a memory block of the given size from 'source' buffer to the given + // destination of the device. + // + // size is the size to transfer from source in bytes. + virtual Status TransferBufferToDevice(se::Stream* stream, int64_t size, + const void* source, + se::DeviceMemoryBase* destination); + + private: + // The mutex that guards the platform-to-transfer manager map. + static absl::Mutex platform_transfer_manager_mutex_; + + // State kept for each kind of TransferManager. Registration functions + // set up creation_function, and then we use that to lazily create + // "manager" the first time GetForPlatform is invoked for a particular id. + struct State { + std::unique_ptr manager; + TransferManagerCreationFunction creation_function = nullptr; + }; + + // Map from platform kind to transfer manager singleton. + static absl::flat_hash_map* + GetPlatformTransferManagers(); +}; + +} // namespace xla + +#endif // XLA_SERVICE_TRANSFER_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/transpose_folding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/transpose_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..c83c959f9201df20dff0b30425047b1c3f0d24c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/transpose_folding.h @@ -0,0 +1,80 @@ +/* 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_SERVICE_TRANSPOSE_FOLDING_H_ +#define XLA_SERVICE_TRANSPOSE_FOLDING_H_ + +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// HLO pass that folds transpose operators into Dot operators, where the Dot +// operator is implemented by a GEMM kernel that can transpose its inputs. +class TransposeFolding : public HloModulePass { + public: + using OperandIndices = std::vector; + + // Returns the set of foldable operands for a given HLO and some candidate + // operands. + using TransposableConvOperandsFn = std::function; + + using CanFoldTransposeOperand = std::function( + const HloInstruction&, int64_t /*operand_idx*/)>; + + // Helper function to explicitly not fold transposes. + static OperandIndices NeverFoldTranspose(const HloInstruction&, + const OperandIndices&) { + return {}; + } + + // Helper function to always fold transposes. + static OperandIndices AlwaysFoldTranspose(const HloInstruction&, + const OperandIndices& ids) { + return ids; + } + + // `dot_can_fold_transpose_operand` returns whether the dot operation can fold + // in the given transpose operand. + // + // transposable_conv_operands returns the set of operands it wants to fold if + // the instruction argument is implemented as a convolution that supports + // transposing its arguments. + explicit TransposeFolding( + CanFoldTransposeOperand dot_can_fold_transpose_operand = + IsRowColumnTransposeDotOperand, + TransposableConvOperandsFn transposable_conv_operands = + AlwaysFoldTranspose); + absl::string_view name() const override { return "transpose-folding"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + static StatusOr IsRowColumnTransposeDotOperand( + const HloInstruction& dot, int64_t operand_idx); + + private: + CanFoldTransposeOperand dot_can_fold_transpose_operand_; + TransposableConvOperandsFn transposable_conv_operands_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_TRANSPOSE_FOLDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tree_reduction_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tree_reduction_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..f66d113ca47e17d615f863860044db2358234b23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tree_reduction_rewriter.h @@ -0,0 +1,61 @@ +/* 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_SERVICE_TREE_REDUCTION_REWRITER_H_ +#define XLA_SERVICE_TREE_REDUCTION_REWRITER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Increase precision for the reduction operation by applying the reduce-window +// first. +// +// E.g. suppose we want to reduce f32[1024] to a scalar. This pass first applies +// a reduce-window (with kSame padding) of size `reduce_window_size`, and then +// reduces the resulting array f32[32]. The rewrite is not applied if any of the +// reduced dimensions is smaller than the `reduce_window_size`. +// +// Applying this pass until a fixed point performs a variant of pairwise +// summation (https://en.wikipedia.org/wiki/Pairwise_summation), which is +// guaranteed to have an asymptotically smaller error bound provided that +// intermediate roundoff errors are random and have random sign. +// +// If this pass lowers the performance too much, the window size can always be +// increased to a larger value. +class TreeReductionRewriter : public HloModulePass { + public: + explicit TreeReductionRewriter(int64_t reduce_window_size = 32) + : reduce_window_size_(reduce_window_size) {} + ~TreeReductionRewriter() override = default; + absl::string_view name() const override { return "tree_reduction_rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + int64_t reduce_window_size_; +}; + +} // end namespace xla + +#endif // XLA_SERVICE_TREE_REDUCTION_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/triangular_solve_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/triangular_solve_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..1767e1b57d3da1f40fcd10f078c47be5cbd629bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/triangular_solve_expander.h @@ -0,0 +1,73 @@ +/* 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_SERVICE_TRIANGULAR_SOLVE_EXPANDER_H_ +#define XLA_SERVICE_TRIANGULAR_SOLVE_EXPANDER_H_ + +#include "absl/container/flat_hash_map.h" +#include "xla/client/xla_builder.h" +#include "xla/service/op_expander_pass.h" + +namespace xla { + +class TriangularSolveExpander : public OpExpanderPass { + public: + explicit TriangularSolveExpander(int64_t block_size = 128); + + absl::string_view name() const override { + return "triangular_solve_expander"; + } + + protected: + // Should we use direct solves for batched inputs? + virtual bool UseDirectSolves() const { return true; } + + bool InstructionMatchesPattern(HloInstruction* instruction) override; + + StatusOr ExpandInstruction( + HloInstruction* instruction) override; + + // Performs a triangular solve using an algorithm from MAGMA, which inverts + // diagonal blocks and multiplies them using matrix multiplications. + XlaOp SolveByInvertingDiagonalBlocks(XlaOp a, XlaOp b, bool left_side, + bool lower, bool transpose_a, + bool conjugate_a, bool unit_diagonal, + PrecisionConfig::Precision precision); + + // Helper function used by SolveByInvertingDiagonalBlocks + virtual XlaOp InvertDiagonalBlocks(XlaOp diag_blocks, bool lower_triangular, + PrecisionConfig::Precision precision); + + // Performs a direct triangular solve, suitable for case with small matrices + // or with large batch. + XlaOp SolveDirectly(XlaOp a, XlaOp b, bool left_side, bool lower, + bool transpose_a, bool conjugate_a, bool unit_diagonal, + PrecisionConfig::Precision precision); + + XlaOp BuildTriangularSolve(XlaOp a, XlaOp b, bool left_side, bool lower, + bool transpose_a, bool conjugate_a, + bool unit_diagonal, int64_t block_size, + PrecisionConfig::Precision precision); + + private: + // Block size for BuildTriangularSolve + const int64_t block_size_; + // Mapping from op signatures to existing computations. + absl::flat_hash_map computation_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_TRIANGULAR_SOLVE_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_points_to_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_points_to_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..9985b2ae17c72db8878f39fd1aefcf196e0eab8d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_points_to_analysis.h @@ -0,0 +1,369 @@ +/* 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_SERVICE_TUPLE_POINTS_TO_ANALYSIS_H_ +#define XLA_SERVICE_TUPLE_POINTS_TO_ANALYSIS_H_ + +#include + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/logical_buffer.h" +#include "xla/service/logical_buffer_analysis.h" +#include "xla/shape_tree.h" +#include "xla/statusor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/lib/gtl/compactptrset.h" +#include "tsl/platform/status.h" + +namespace xla { + +// A class describing the source(s) of the Buffer(s) contained in the output of +// a particular HLO instruction. The structure of PointsToSet mirrors the +// structure of the instruction's shape, which may be an arbitrary tree (eg, a +// nested tuple). Each node in this tree corresponds to a single buffer in the +// instruction's output and contains the set of Buffers which might define +// the corresponding buffer. +class PointsToSet { + public: + // Construct our ShapeTree with a pointer rather than a reference to a Shape + // because this is very hot code, and copying (and then destroying) all these + // Shapes is slow. + explicit PointsToSet(const Shape* shape) : tree_(shape) {} + + // Returns true if any points-to sets for any subshape element is not a + // singleton. + bool IsAmbiguous() const; + + // Returns true if no LogicalBuffer appears in more than one points-to set of + // the shape nodes. + bool IsDistinct() const; + + // Returns the total number of different LogicalBuffers contained in this + // object. This is equal to CreateFlattenedSet().size(). + size_t size() const; + + // Creates a set containing the union of all LogicalBuffers contained in the + // PointsToSet. + using BufferSet = tsl::gtl::CompactPointerSet; + BufferSet CreateFlattenedSet() const; + + // Returns true if the given buffer is in the points-to set at the given + // index. + bool ContainsBufferAtIndex(const LogicalBuffer& buffer, + const ShapeIndex& index) const; + + // Returns true if the given buffer is in the points-to set at any index. + bool ContainsBuffer(const LogicalBuffer& buffer) const; + + // Adds the given buffer to the points-to set at the given index. This is a + // nop if the buffer already is in the set at that index. + void AddPointedToBuffer(const LogicalBuffer& buffer, const ShapeIndex& index); + + // For the subshape at the given index (where index is defined as in + // ShapeUtil::GetSubshape) this method returns the set of HLO instructions + // which may produce the tuple subshape at that index. For example, given: + // + // %tuple1 = tuple(...) + // %tuple2 = tuple(...) + // %select = select(%tuple1, %tuple2) + // %nested_tuple = tuple(%select, %tuple1) + // + // These are the values for tuple_sources() for the PointsToSet of + // %nested_tuple: + // + // tuple_sources({}) = {%nested_tuple} + // tuple_sources({0}) = {%tuple1, %tuple2} + // tuple_sources({1}) = {%tuple1} + // + // tuple_sources() at the index of an array shape (not a tuple) returns the + // empty set. The instructions in the set returned by tuple_sources + // necessarily are either Tuple instructions, constants, or parameters. + using SourceSet = tsl::gtl::CompactPointerSet; + const SourceSet& tuple_sources(const ShapeIndex& index) const; + + // Add a tuple source instruction for the given index. + void add_tuple_source(const ShapeIndex& index, HloInstruction* tuple); + + using BufferList = absl::InlinedVector; + + // Return the list of logical buffers for the subshape at index. + const BufferList& element(const ShapeIndex& index) const { + return tree_.element(index).buffers; + } + BufferList* mutable_element(const ShapeIndex& index) { + return &tree_.mutable_element(index)->buffers; + } + + // Call fn(index, buflist) for every subshape index. + template + void ForEachElement(const Fn& fn) const { + tree_.ForEachElement([&fn](const ShapeIndex& index, const Elem& elem) { + fn(index, elem.buffers); + }); + } + template + void ForEachMutableElement(const Fn& fn) { + tree_.ForEachMutableElement([&fn](const ShapeIndex& index, Elem* elem) { + fn(index, &elem->buffers); + }); + } + template + Status ForEachElementWithStatus(const Fn& fn) const { + return tree_.ForEachElementWithStatus( + [&fn](const ShapeIndex& index, const Elem& elem) { + return fn(index, elem.buffers); + }); + } + + private: + struct Elem { + BufferList buffers; + SourceSet tuple_sources; + }; + ShapeTree tree_; + + // PointsToSet contains references (const LogicalBuffer*) to elements within + // TuplePointsToAnalysis, so disable copying. + PointsToSet(const PointsToSet&) = delete; + PointsToSet& operator=(const PointsToSet&) = delete; +}; + +// This class describes a particular subshape in a computation (instruction and +// shape index) and the logical buffer which may be a source of the subshape +// value. +class BufferAlias { + public: + BufferAlias(HloInstruction* instruction, const ShapeIndex& index) + : instruction_(instruction), index_(index) {} + + // Return the instruction/index of the subshape. + HloInstruction* instruction() const { return instruction_; } + const ShapeIndex& index() const { return index_; } + + bool operator==(const BufferAlias& other) const { + return instruction_ == other.instruction_ && index_ == other.index_; + } + bool operator!=(const BufferAlias& other) const { return !(*this == other); } + + std::string ToString() const; + + private: + HloInstruction* instruction_; + ShapeIndex index_; +}; + +std::ostream& operator<<(std::ostream& out, const BufferAlias& buffer_alias); + +// DFS visitor that performs tuple points-to analysis. This analysis determines +// the potential sources of each buffer in each instruction's output. +class TuplePointsToAnalysis : public DfsHloVisitorWithDefault { + public: + // Runs points-to analysis on 'module'. + static StatusOr> Run( + const HloModule* module); + + // Return the points-to set of an instruction. This describes the potential + // sources of each buffer in the instruction's output. + const PointsToSet& GetPointsToSet( + const HloInstruction* hlo_instruction) const; + + // Returns the logical buffer with the given ID. + const LogicalBuffer& GetBuffer(LogicalBuffer::Id id) const; + + // Returns the buffer defined at the given instruction and index. An error is + // returned if no buffer is defined at that point. + StatusOr GetBufferDefinedAt( + const HloInstruction* instruction, const ShapeIndex& index) const; + + // Return a (possibly empty) vector containing all BufferAliases of the given + // logical buffer The buffer alias set is the inverse of the points-to set. + // That is, LogicalBuffer B is in the points-to set of instruction I at index + // N iff instruction I, index N is a BufferAlias of B. + using BufferAliasVector = absl::InlinedVector; + const BufferAliasVector& GetBufferAliases(const LogicalBuffer& buffer) const; + + // Returns the number of logical buffers in the module + LogicalBuffer::Id num_logical_buffers() const { + return logical_buffer_analysis_->num_logical_buffers(); + } + + // Return a the logical buffer with id "id" in the module. Iteration + // over all logical buffers is usually done with something like: + // + // for (LogicalBuffer:Id id = 0; id < points_to.num_logical_buffers(); id++){ + // const auto& buffer = points_to.logical_buffer(id); + // ... do something with buffer ... + // } + LogicalBuffer& logical_buffer(LogicalBuffer::Id id) const { + return logical_buffer_analysis_->GetBuffer(id); + } + + // Returns a vector of buffers that the instruction produces. Most + // instructions produce a single buffer (the top-level buffer), some produce + // no buffers (eg bitcast), and some produce more than one buffer (eg, + // tuple-shaped parameters). + using BufferDefinitionVector = absl::InlinedVector; + const BufferDefinitionVector& GetBuffersDefinedByInstruction( + const HloInstruction* instruction) const; + + // Returns true if the given instruction defines a buffer at the given index. + bool InstructionDefinesBufferAtIndex(const HloInstruction* instruction, + const ShapeIndex& index) const; + + // Returns an OK status if the given buffer is defined by instruction + // 'buffer.instruction()' at index 'buffer.index()' and if the given buffer + // matches the TuplePointsToAnalysis' LogicalBuffer with 'buffer.id'. Returns + // an FailedPrecondition error status otherwise. An example of a LogicalBuffer + // which is not defined is a tuple element in a Tuple instruction. In this + // case, the Tuple instruction does not define the LogicalBuffer, rather that + // index aliases one of its operands. + Status VerifyBuffer(const LogicalBuffer& buffer) const; + + Status DefaultAction(HloInstruction* hlo_instruction) override; + Status HandleTuple(HloInstruction* tuple) override; + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + Status HandleAsyncStart(HloInstruction* async_start) override; + Status HandleAsyncUpdate(HloInstruction* async_update) override; + Status HandleAsyncDone(HloInstruction* async_done) override; + Status HandleBitcast(HloInstruction* bitcast) override; + Status HandleDomain(HloInstruction* domain) override; + Status HandleCopy(HloInstruction* copy) override; + Status HandleCopyStart(HloInstruction* copy_start) override; + Status HandleCopyDone(HloInstruction* copy_done) override; + Status HandleRecvDone(HloInstruction* recv_done) override; + Status HandleSend(HloInstruction* send) override; + Status HandleAddDependency(HloInstruction* add_dependency) override; + Status HandleCustomCall(HloInstruction* custom_call) override; + Status HandleFusion(HloInstruction* fusion) override; + Status HandleOptimizationBarrier(HloInstruction* barrier) override; + + std::string ToString() const; + + // Returns true if 'user' cannot possibly use the buffer at 'index' in + // 'operand'. Returns false otherwise. + // + // REQUIRES: 'operand' is an operand of 'user'. + bool DoesNotUseOperandBuffer(const HloInstruction* operand, + const ShapeIndex& index, + const HloInstruction* user) const; + + private: + explicit TuplePointsToAnalysis( + const HloModule* module, + std::unique_ptr logical_buffer_analysis) + : module_(module), + logical_buffer_analysis_(std::move(logical_buffer_analysis)) {} + + // Perform the analysis. Should be called immediately after constructing the + // object and before calling GetPointsToSet. + Status Analyze(); + + // Populates instruction-defined buffers and aliases for each instruction + // in 'instructions'. + Status PopulateDefinedBuffersAndAliases( + const decltype(std::declval() + .instructions())& instructions); + + // Creates an empty PointsToSet in the points_to_ map for the given + // instruction. + PointsToSet& CreateEmptyPointsToSet(const HloInstruction* instruction); + + // Creates a PointsToSet in the points_to_ map for 'instruction' which is a + // copy of the existing PointsToSet for 'src'. + PointsToSet& CreateCopiedPointsToSet(const HloInstruction* instruction, + const HloInstruction* src); + + // Adds the buffers defined by the given instruction to the given vector. + Status GatherBuffersDefinedByInstruction(const HloInstruction* instruction, + BufferDefinitionVector* buffers); + + // Print points-to set for 'instruction' to 'output'. + void InstructionToString(const HloInstruction* instruction, + std::string* output) const; + + // Information kept per instruction + struct PerInstruction { + std::unique_ptr points_to_set; + // Empirically, ~92% of instructions have 1 + // instruction_defined_buffer, and 99% have 0 or 1 + BufferDefinitionVector instruction_defined_buffers; + }; + + const PerInstruction* PerInst(const HloInstruction* inst) const { + int id = inst->unique_id(); + DCHECK_GE(id, 0); + auto iter = per_instruction_.find(id); + if (iter == per_instruction_.end()) { + LOG(FATAL) << "Expected per-instruction information to already exist"; + } else { + return iter->second.get(); + } + } + PerInstruction* PerInst(const HloInstruction* inst) { + int id = inst->unique_id(); + DCHECK_GE(id, 0); + auto iter = per_instruction_.find(id); + if (iter == per_instruction_.end()) { + return per_instruction_.emplace(id, std::make_unique()) + .first->second.get(); + } else { + return iter->second.get(); + } + } + + std::vector> + GetAllUsesOfInstructionAtIndex(HloInstruction* instruction, + const ShapeIndex& index) const; + bool HasUniqueFusedUseOfOperandAt(HloInstruction* operand, + const ShapeIndex& operand_index, + HloInstruction* fusion, + const int64_t use_operand_index) const; + + // The module this analysis is performed on. + const HloModule* module_; + + // The logical buffers for this module. + const std::unique_ptr logical_buffer_analysis_; + + // A map from instruction->unique_id() to + absl::flat_hash_map> per_instruction_; + + // A map from LogicalBuffer->id() to alias information about that logical + // buffer + std::vector logical_buffer_aliases_; + + TuplePointsToAnalysis(const TuplePointsToAnalysis&) = delete; + TuplePointsToAnalysis& operator=(const TuplePointsToAnalysis&) = delete; + // Whether to alias buffers connected by dataflow relations. This aliasing + // relation should not be recognized if copies can be inserted to break up + // the dataflow relation. + const bool alias_buffer_across_dataflow_ = false; +}; + +} // namespace xla + +#endif // XLA_SERVICE_TUPLE_POINTS_TO_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..b5b029bec95cb1e5b9a98b8fbb748c3bb4a161e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_simplifier.h @@ -0,0 +1,67 @@ +/* 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_SERVICE_TUPLE_SIMPLIFIER_H_ +#define XLA_SERVICE_TUPLE_SIMPLIFIER_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// A pass which simplifies patterns of Tuple and GetTupleElement instructions in +// the module. +class TupleSimplifier : public HloModulePass { + public: + TupleSimplifier() : TupleSimplifier(/*exclude_entry_computation=*/false) {} + explicit TupleSimplifier(bool exclude_entry_computation); + ~TupleSimplifier() override {} + absl::string_view name() const override { return "tuple-simplifier"; } + + // Run tuple simplification on the given computation. Returns whether the + // computation was changed. + using HloPassInterface::Run; + using HloPassInterface::RunOnModuleGroup; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + // When set, this pipeline stage will perform optimization of all computations + // apart from the module's entry computation. This is used by Graphcore's + // backend. + bool exclude_entry_computation_; + + // Collapse the following structure into just 'Tuple-shaped Op': + // + // Tuple-shaped Op + // | + // +-----+-----+ + // | | | + // GTE GTE GTE + // | | | + // +-----+-----+ + // | + // Tuple + // + StatusOr RemoveWholeTuple(HloInstruction* tuple); +}; + +} // namespace xla + +#endif // XLA_SERVICE_TUPLE_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_util.h new file mode 100644 index 0000000000000000000000000000000000000000..59f241f7b86897a4c7a62ba3e53227c455dc8206 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/tuple_util.h @@ -0,0 +1,65 @@ +/* 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_SERVICE_TUPLE_UTIL_H_ +#define XLA_SERVICE_TUPLE_UTIL_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_value.h" + +namespace xla { +class TupleUtil { + public: + // Generates HLO instructions to get a prefix tuple from `input_tuple` (which + // must be of tuple shape) of length `elements`. Returns the root of the + // graph of instructions generated. + // + // The instructions are generated into the computation containing + // `input_tuple`. + static HloInstruction* ExtractPrefix(HloInstruction* input_tuple, + int64_t elements); + + // Generates HLO instructions to create a tuple that consists of the values in + // `trailing_values` appended to `input_tuple` (which must be of tuple shape). + // Returns the root of the graph of instructions generated. + // + // The instructions are generated into the computation containing + // `input_tuple`. + static HloInstruction* AppendSuffix( + HloInstruction* input_tuple, + absl::Span trailing_values); + + // Generates HLO instructions that duplicates the tuple by inserting + // get-tuple-elements and a new tuple instruction. Returns the root of the + // graph of instructions generated. + static HloInstruction* Duplicate(HloInstruction* input_tuple) { + return ExtractPrefix(input_tuple, input_tuple->shape().tuple_shapes_size()); + } + + // Descend to the shape_index element of the tuple and replace that with + // new_instruction. If the replacement instruction has a different shape than + // the old one, we insert a bitcast if insert_bitcast_if_different_shape is + // set to true. + static StatusOr ReplaceTupleWith( + HloInstruction* new_instruction, HloInstruction* tuple, + ShapeIndex shape_index, bool insert_bitcast_if_different_shape = true); + + // Recursively create kGetTupleElement instructions if the defining position + // shape is not an array. Returns the new instruction that has array shape. + static HloInstruction* AddGetTupleElements(const HloPosition& position); +}; +} // namespace xla + +#endif // XLA_SERVICE_TUPLE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/value_range.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/value_range.h new file mode 100644 index 0000000000000000000000000000000000000000..abc471e2f8d485f1270eb00605e0202693d750b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/value_range.h @@ -0,0 +1,76 @@ +/* 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_SERVICE_VALUE_RANGE_H_ +#define XLA_SERVICE_VALUE_RANGE_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/service/constant_value.h" + +namespace xla { + +// Class keeping track of the range of an HLO value. +class Range { + public: + Range() + : min_(ConstantValue::GetZero(/*bitwidth=*/64, /*is_signed=*/false)), + max_(ConstantValue::GetZero(/*bitwidth=*/64, /*is_signed=*/false)), + empty_(true), + is_linear_(false) {} + Range(const ConstantValue& min, const ConstantValue& max, bool is_linear) + : min_(min), max_(max), empty_(false), is_linear_(is_linear) {} + // Minimum value of the range. + const ConstantValue& min() const { return min_; } + // Maximum value of the range. + const ConstantValue& max() const { return max_; } + // Returns if the range is empty (no value in set). + bool IsEmpty() const { return empty_; } + // Only one value in set. This means the range is a constant. + bool IsSingleValue() const { return !IsEmpty() && min_ == max_; } + // This is a way to track in some way recurring values that change in a + // monotonic way. This true means that the variables driving the range change + // in a monotonic way and that the way they are composed together is linear + // causing the final value represented by the range in a monotonic way during + // loop recursion. + bool IsLinear() const { return is_linear_; } + // If this range represents a single value return that signed value. + std::optional GetSingleSignedValue() const; + // If this range represents a single value return that unsigned value. + std::optional GetSingleUnsignedValue() const; + + std::string ToString() const; + + private: + ConstantValue min_; + ConstantValue max_; + bool empty_; + bool is_linear_; +}; + +// Constructs a Range object from a HloInstruction. Gets a "predefined_ranges" +// object as input that returns known ranges for some variables for which we +// already know the range. The final range is composed from operations over +// these predetermined ranges. +// The input HLO needs to be of scalar type and integer. +Range RecursivelyIdentifyRange( + const HloInstruction* instr, + const absl::flat_hash_map& predefined_ranges); + +} // namespace xla + +#endif // XLA_SERVICE_VALUE_RANGE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_all_reduce_code_motion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_all_reduce_code_motion.h new file mode 100644 index 0000000000000000000000000000000000000000..98903c4c5efc9d8679123eeaef106644904eb812 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_all_reduce_code_motion.h @@ -0,0 +1,64 @@ +/* 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_SERVICE_WHILE_LOOP_ALL_REDUCE_CODE_MOTION_H_ +#define XLA_SERVICE_WHILE_LOOP_ALL_REDUCE_CODE_MOTION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass that rewrites while loops to sink all-reduces that are only +// accumulated into a buffer and not otherwise used in the loop body. +// An all-reduce instruction can be sinked if its result is only added +// to a number of accumulation buffers, and the accumulation buffers are not +// used inside the loop. +// +// Pattern before this pass: +// a = ... +// while: +// b = ... +// c = all-reduce(b) +// a += c +// Pattern after this pass: +// a = ... +// d = 0 +// while: +// b = ... +// d += b +// e = all-reduce(d) +// a += e +class WhileLoopAllReduceCodeMotion : public HloModulePass { + public: + explicit WhileLoopAllReduceCodeMotion(bool enable_reduce_scatter = false) + : enable_reduce_scatter_(enable_reduce_scatter) {} + ~WhileLoopAllReduceCodeMotion() override = default; + + absl::string_view name() const override { + return "while-loop-all-reduce-code-motion"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const bool enable_reduce_scatter_; +}; +} // namespace xla + +#endif // XLA_SERVICE_WHILE_LOOP_ALL_REDUCE_CODE_MOTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..a9e1d074f850c2511e39a4f35668a837fd1ec7ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_analysis.h @@ -0,0 +1,62 @@ +/* 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_SERVICE_WHILE_LOOP_ANALYSIS_H_ +#define XLA_SERVICE_WHILE_LOOP_ANALYSIS_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { + +// Returns the precise trip count of the loop if it's statically known, +// nullopt otherwise. +// +// max_brute_force_iters limits the number of steps that are evaluated while +// trying to brute force a loop trip count. trip counts larger than +// max_brute_force_iters may be returned if we can pattern-match the loop +// condition. +std::optional ComputeWhileLoopTripCount( + const HloInstruction *while_op, int64_t max_brute_force_iters = 128); + +// Returns an upper bound on the trip count of the loop if it's statically +// known, nullopt otherwise. +std::optional ComputeWhileLoopTripCountUpperBound( + const HloInstruction *while_op); + +// The below function identifies a subset of all possible auxiliary +// induction variables (AIV). Specifically, candidates are gtes, e.g., +// gte(param0, N) +std::vector GetAuxiliaryLoopInductionVars( + const HloInstruction *while_op); +// Returns the tuple index of the loop induction variable if there is such an +// induction variable detected. Otherwise returns nullopt. +std::optional GetLoopInductionVarTupleIdx( + const HloInstruction *while_op); + +// Checks the following conditions: +// - `i`, the induction varaiable, is initialized to a scalar constant K +// (namely, `indvar_init`), +// - the while condition does `i < N` or `i <= N` (where N is a know constant) +// - the while body does `i++`. +// If so, it's trivial to compute the loop bound as `N - k` or `N - k + 1`, +// respectively. +std::optional MatchTrivialLoopTripCount(const HloInstruction *while_op, + int64_t indvar_tuple_idx, + const Literal &indvar_init); +} // namespace xla + +#endif // XLA_SERVICE_WHILE_LOOP_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_constant_sinking.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_constant_sinking.h new file mode 100644 index 0000000000000000000000000000000000000000..7bdc186768fd58ba61be455de7d3c140e85b027c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_constant_sinking.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_SERVICE_WHILE_LOOP_CONSTANT_SINKING_H_ +#define XLA_SERVICE_WHILE_LOOP_CONSTANT_SINKING_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Sinks while loop invariant values that happen to be constants into the while +// loop body and conditional. This is probably not a win in isolation but may +// unlock further optimizations like constant folding. +// +// state = (..., const, ...) +// while (pred(state)) { +// (..., v, ...) = state +// use(v) +// state = (..., v, ...) +// } +// +// => +// +// state = (..., const, ...) +// while (pred(state)) { +// (..., v, ...) = state +// use(const) +// state = (..., v, ...) +// } +// +// Note that it leaves the `v` in place to keep that component of the state +// tuple trivially loop invariant. WhileLoopSimplifier will later get rid of +// `v`. +// +class WhileLoopConstantSinking : public HloModulePass { + public: + explicit WhileLoopConstantSinking(bool sink_broadcast_of_constants = false) + : sink_broadcast_of_constants_(sink_broadcast_of_constants) {} + + ~WhileLoopConstantSinking() override = default; + + absl::string_view name() const override { + return "while-loop-constant-sinking"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr TrySinkingConstantsIntoWhileLoop(HloInstruction* while_instr); + + const bool sink_broadcast_of_constants_; +}; +} // namespace xla + +#endif // XLA_SERVICE_WHILE_LOOP_CONSTANT_SINKING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_invariant_code_motion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_invariant_code_motion.h new file mode 100644 index 0000000000000000000000000000000000000000..7f96acc6f75d5f9cdbd2414f3c97046e5f35ef28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_invariant_code_motion.h @@ -0,0 +1,87 @@ +/* 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_SERVICE_WHILE_LOOP_INVARIANT_CODE_MOTION_H_ +#define XLA_SERVICE_WHILE_LOOP_INVARIANT_CODE_MOTION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/compile_time_cap.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass that rewrites while loops to hoist loop invariant instructions in +// the while body into the computation that contains the while instruction. + +class WhileLoopInvariantCodeMotion : public HloModulePass { + public: + using ShapeSizeFunction = std::function; + // If `hoist_constants` is true then constants are always hoisted out of while + // loop bodies. Otherwise they are only hoisted out if they enable other + // non-trivial computations to be hoisted out. + // + // Setting `hoist_constants` to false can be help if LICM is run in the mid + // level HLO pipeline because hoisting constants out of while loop bodies can + // break optimizations like constant folding. + // + // Setting `hoist_other` and `hoist_reshapes` to false can be used to hoist + // only constants. If provided, `hoist_size_inflation_ratio` will forbid + // hoisting instructions where the ratio of the size of the output(s) to the + // input(s) is larger than hoist_size_inflation_ratio. This is useful on + // platforms on which it's important to prevent blow-ups in memory size. + // + // If `hoist_reshapes` is true, then reshapes are allowed to be hoisted out of + // while loop body by themselves. Otherwise, they are only hoisted out if they + // enable other non-trivial computations to be hoisted out. + // + // Setting `hoist_reshapes` to false can be useful when LICM is run in the + // mid level HLO pipeline because the reshapes will often get fused with + // consumer instructions, and won't cost anything if not hoisted. However, + // any stand alone reshapes after fusion will benefit from hoisting. + explicit WhileLoopInvariantCodeMotion( + bool hoist_constants = false, bool hoist_reshapes = false, + bool hoist_other = true, + std::optional hoist_size_inflation_ratio = std::nullopt, + ShapeSizeFunction shape_size_function = ShapeUtil::ByteSizeOfElements) + : hoist_constants_(hoist_constants), + hoist_reshapes_(hoist_reshapes), + hoist_other_(hoist_other), + hoist_size_inflation_ratio_(hoist_size_inflation_ratio), + shape_size_function_(shape_size_function) {} + ~WhileLoopInvariantCodeMotion() override = default; + + absl::string_view name() const override { + return "while-loop-invariant-code-motion"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + bool NotWorthHoistingIndividually(const HloInstruction& instruction); + StatusOr TryHoistingInvariantInstructionsFromWhileBody( + HloInstruction* while_instr, BoundNonLinearCompilerAnalysis* allowance); + + bool hoist_constants_; + bool hoist_reshapes_; + bool hoist_other_; + std::optional hoist_size_inflation_ratio_; + ShapeSizeFunction shape_size_function_; +}; +} // namespace xla + +#endif // XLA_SERVICE_WHILE_LOOP_INVARIANT_CODE_MOTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..f39a77c417c37e3eb84c7d45b6815e31e56444d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_simplifier.h @@ -0,0 +1,56 @@ +/* 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_SERVICE_WHILE_LOOP_SIMPLIFIER_H_ +#define XLA_SERVICE_WHILE_LOOP_SIMPLIFIER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// HLO pass that makes the following transformations on while loops: +// +// - A while loop with static trip count of 0 is deleted. +// +// - A while loop with static trip count of 1 is replaced by its body (sans +// loop). +// +// - Elements of a while loop's tuple that the loop doesn't use are removed +// from the tuple. +// +// - If the while loop's parameter is a nested tuple, it's flattened to a +// single-level tuple. This is good because it usually reduces the number of +// kTuple instructions, but also because it unlocks additional optimizations +// (e.g. removing unused loop parameters). +// +// Flattening nested while loop tuples adds a whole mess of likely unnecessary +// kGetTupleElement and kTuple operations to the graph. We expect that tuple +// simplifier will be run afterwards. +// +class WhileLoopSimplifier : public HloModulePass { + public: + ~WhileLoopSimplifier() override {} + absl::string_view name() const override { return "simplify-while-loops"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_WHILE_LOOP_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_trip_count_annotator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_trip_count_annotator.h new file mode 100644 index 0000000000000000000000000000000000000000..1c8374a98712ec38492674741f41140e9c928494 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_loop_trip_count_annotator.h @@ -0,0 +1,51 @@ +/* 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_SERVICE_WHILE_LOOP_TRIP_COUNT_ANNOTATOR_H_ +#define XLA_SERVICE_WHILE_LOOP_TRIP_COUNT_ANNOTATOR_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Pass that annotates `while` loops with known trip counts. +// +// The annotation is stored as a backend-config on the while loop node. +// +// This pass should run after all passes that might semantically modify a while +// loop, e.g. by unrolling it. Otherwise, a loop could end up with a +// backend-config that doesn't match its true trip-count. +// +// This pass does some pattern-matching on loop bodies and conditions, so it +// should run after most HLO simplifications and before fusion and layout +// assignment, which make pattern matching much more difficult by e.g. +// introducing `copy` nodes. +class WhileLoopTripCountAnnotator : public HloModulePass { + public: + ~WhileLoopTripCountAnnotator() override {} + absl::string_view name() const override { + return "while-loop-trip-count-annotator"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_WHILE_LOOP_TRIP_COUNT_ANNOTATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_util.h new file mode 100644 index 0000000000000000000000000000000000000000..97ad67af285483d10023343d87c81cf7185b7cd7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/while_util.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_SERVICE_WHILE_UTIL_H_ +#define XLA_SERVICE_WHILE_UTIL_H_ + +#include "absl/container/flat_hash_map.h" +#include "absl/container/inlined_vector.h" +#include "absl/functional/function_ref.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/call_inliner.h" + +namespace xla { +class WhileUtil { + public: + // Holds a return value from MakeInstructionsLiveIn. + struct MakeInstructionsLiveInResult { + // The new while operation that has the requested values live in. + HloInstruction* new_while_instr; + + // The new tuple instruction that replaced the original while instruction + // with the same shape. + HloInstruction* replacement_instr; + + // The i'th element of `while_body_live_in_values` is an instruction in the + // while body that holds the i'th *newly added* live in value at runtime. + std::vector while_body_live_in_values; + + // `while_body_instruction_map` maps instructions in the original while body + // to the corresponding instructions in the body for the newly created while + // operation. + CallInliner::InlinedInstructionMap while_body_instruction_map; + }; + + // Replaces `while_instr` with a new while instruction that is equivalent to + // `while_instr` except that it has all of the HLO instructions in + // `instructions` as live-in, loop invariant values. These new live in values + // are represented as new elements appended to the parameter of the while + // loop, which must be of tuple shape. GetTupleElement instructions computing + // each new live in value is returned in the `while_body_live_in_values` + // vector. + // + // Deletes `while_instr` after replacing it. + // + // Preconditions: + // + // `while_instr` must have a tuple shaped state. + // + // Every instruction in `instructions` must be contained in the computation + // that contains `while_instr`. + static StatusOr MakeInstructionsLiveIn( + HloInstruction* while_instr, + absl::Span instructions); + + using LoopStateTy = std::vector; + using LoopBodyGeneratorTy = absl::FunctionRef( + HloInstruction* /*induction_var*/, + const LoopStateTy& /*current_values*/)>; + + // Creates a while loop in `computation` that runs for `trip_count` + // iterations. The structure of the while loop is as follows, in pseudocode: + // + // loop_state while_loop() { + // indvar = 0; + // loop_state = init_values + // while (indvar < trip_count) { + // loop_state = loop_body_generator(loop_state) + // indvar++; + // } + // return loop_state; + // } + static StatusOr MakeCountedLoop( + HloComputation* computation, int32_t trip_count, + const LoopStateTy& init_values, LoopBodyGeneratorTy loop_body_generator, + const OpMetadata& metadata); + + struct OwningLoopStateTy { + std::vector> instructions_to_add; + WhileUtil::LoopStateTy while_results; + }; + // As above but does not add the while loop or other instructions created + // around it in any particular computation. The caller can instead add it to a + // computation of their choosing. + static StatusOr MakeCountedLoop( + HloModule* module, int32_t trip_count, + const WhileUtil::LoopStateTy& init_values, + WhileUtil::LoopBodyGeneratorTy loop_body_generator, + const OpMetadata& metadata); + + // Returns the GetTupleElement instructions in `while_body` that access + // elements in the parameter tuple that don't change across iterations. + // Assumes `while_body` is the body computation of the while loop in question. + static std::vector GetInvariantGTEsForWhileBody( + const HloComputation& while_body); + + // Returns a map of index to GetTupleElement instructions in + // `while_conditional` that access elements in the parameter tuple. Assumes + // `while_conditional` is the conditional computation of the while loop in + // question. + static absl::flat_hash_map> + GetGTEsMapForWhileConditional(const HloComputation& while_conditional); +}; +} // namespace xla + +#endif // XLA_SERVICE_WHILE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/xla_debug_info_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/xla_debug_info_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..ff75a1ad1eef710cbed67a49a4ea940f3ec60452 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/xla_debug_info_manager.h @@ -0,0 +1,88 @@ +/* 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_SERVICE_XLA_DEBUG_INFO_MANAGER_H_ +#define XLA_SERVICE_XLA_DEBUG_INFO_MANAGER_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo.pb.h" +#include "tsl/platform/status.h" + +namespace xla { + +using ModuleIdentifier = int; + +// XlaDebugInfoManager tracks all XLA programs (Executables) throughout their +// lifetime. Because the tracing period can start during an Executable's +// execution, we need to track Executables even when tracing is off. +// This class is thread-safe. +class XlaDebugInfoManager { + public: + static XlaDebugInfoManager* Get() { + static XlaDebugInfoManager* singleton = new XlaDebugInfoManager(); + return singleton; + } + + // Registers an active module to XlaDebugInfoManager. + // The module_id of the module is expected to be unique per process. + void RegisterModule( + std::shared_ptr hlo_module, + std::shared_ptr buffer_assignment); + + // Unregisters an active module. + void UnregisterModule(ModuleIdentifier module_id); + + // Start tracing, began to collecting debug information for all the running + // modules during the tracing period. + void StartTracing(); + + // Stops tracing. + // If module_debug_info is not null, returns debug information for all the + // modules that were alive since StartTracing(). + void StopTracing( + std::vector>* module_debug_info = nullptr); + + // Returns whether 'module_id' is tracked by XlaDebugInfoManager. + bool TracksModule(ModuleIdentifier module_id) const; + + friend class XlaDebugInfoManagerTestPeer; + + private: + XlaDebugInfoManager() = default; + + struct XlaModuleEntry { + std::shared_ptr hlo_module; + std::shared_ptr buffer_assignment; + bool active = false; + }; + + mutable absl::Mutex mutex_; + bool tracing_active_ ABSL_GUARDED_BY(mutex_) = false; + // Active modules are those still tracked by us. There could be much more + // active modules than running modules, we will try to reduce the trace size + // by only transfer those modules that were running during tracing period. + absl::flat_hash_map modules_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace xla + +#endif // XLA_SERVICE_XLA_DEBUG_INFO_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/zero_sized_hlo_elimination.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/zero_sized_hlo_elimination.h new file mode 100644 index 0000000000000000000000000000000000000000..4d2ac76299b66003e0297c993b99da0b73eb8680 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/zero_sized_hlo_elimination.h @@ -0,0 +1,35 @@ +/* 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_SERVICE_ZERO_SIZED_HLO_ELIMINATION_H_ +#define XLA_SERVICE_ZERO_SIZED_HLO_ELIMINATION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +// HLO pass that replaces zero sized Hlos with a zero sized constant literal. +namespace xla { +class ZeroSizedHloElimination : public HloModulePass { + public: + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + absl::string_view name() const override { + return "zero_sized_hlo_elimination"; + } +}; +} // namespace xla +#endif // XLA_SERVICE_ZERO_SIZED_HLO_ELIMINATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/allocator_stats.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/allocator_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..d073d08cb92d5b327e77c7d609cae5a7554740ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/allocator_stats.h @@ -0,0 +1,63 @@ +/* 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_STREAM_EXECUTOR_ALLOCATOR_STATS_H_ +#define XLA_STREAM_EXECUTOR_ALLOCATOR_STATS_H_ + +#include + +#include "absl/types/optional.h" +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +// Runtime statistics collected by an allocator. Exactly the same as +// tsl::AllocatorStats, but independently defined to preserve the mutual +// independence of StreamExecutor and TensorFlow. +struct AllocatorStats { + int64_t num_allocs; // Number of allocations. + int64_t bytes_in_use; // Number of bytes in use. + int64_t peak_bytes_in_use; // The peak bytes in use. + int64_t largest_alloc_size; // The largest single allocation seen. + + // The upper limit of bytes of user allocatable device memory, if such a limit + // is known. + std::optional bytes_limit; + + // Stack related memory usage. + int64_t bytes_reserved; // Number of bytes reserved on the stack. + int64_t + peak_bytes_reserved; // The peak number of bytes reserved on the stack. + // The upper limit on the number bytes of reservable memory on the stack, + // if such a limit is known. + std::optional bytes_reservable_limit; + + int64_t largest_free_block_bytes; // Largest free block's size in heap. + + AllocatorStats() + : num_allocs(0), + bytes_in_use(0), + peak_bytes_in_use(0), + largest_alloc_size(0), + bytes_reserved(0), + peak_bytes_reserved(0), + largest_free_block_bytes(0) {} + + std::string DebugString() const; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_ALLOCATOR_STATS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/blas.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/blas.h new file mode 100644 index 0000000000000000000000000000000000000000..a85ea3b460d6ed659dbabc4a533a570df30ad218 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/blas.h @@ -0,0 +1,696 @@ +/* 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. +==============================================================================*/ + +// Exposes the family of BLAS routines as pre-canned high performance calls for +// use in conjunction with the StreamExecutor abstraction. +// +// Note that this interface is optionally supported by platforms. +// +// This abstraction makes it simple to entrain BLAS operations on GPU data into +// a Stream -- users typically will not use this API directly, but will use the +// Stream builder methods to entrain these operations "under the hood". For +// example: +// +// DeviceMemory x = stream_exec->AllocateArray(1024); +// DeviceMemory y = stream_exec->AllocateArray(1024); +// // ... populate x and y ... +// Stream stream{stream_exec}; +// stream +// .Init() +// .ThenBlasAxpy(1024, 5.5, x, 1, &y, 1); +// TF_CHECK_OK(stream.BlockHostUntilDone()); +// +// By using stream operations in this manner the user can easily intermix custom +// kernel launches (via StreamExecutor::ThenLaunch()) with these pre-canned BLAS +// routines. + +#ifndef XLA_STREAM_EXECUTOR_BLAS_H_ +#define XLA_STREAM_EXECUTOR_BLAS_H_ + +#include +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/stream_executor/data_type.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/statusor.h" +#include "tsl/protobuf/dnn.pb.h" + +namespace Eigen { +struct half; +} // namespace Eigen + +namespace stream_executor { + +class Stream; +class ScratchAllocator; + +template +class DeviceMemory; + +template +class HostOrDeviceScalar; + +template +using DeviceMemorySlice = absl::Span *const>; + +namespace blas { + +// Specifies whether the input matrix will be transposed or +// transposed+conjugated before any BLAS operations. +enum class Transpose { kNoTranspose, kTranspose, kConjugateTranspose }; + +// Returns a name for t. +std::string TransposeString(Transpose t); + +// Specifies whether the upper or lower triangular part of a +// symmetric/Hermitian matrix is used. +enum class UpperLower { kUpper, kLower }; + +// Returns a name for ul. +std::string UpperLowerString(UpperLower ul); + +// Specifies whether a matrix is unit triangular. +enum class Diagonal { kUnit, kNonUnit }; + +// Returns a name for d. +std::string DiagonalString(Diagonal d); + +// Specifies whether a Hermitian matrix appears on the left or right in +// operation. +enum class Side { kLeft, kRight }; + +// Returns a name for s. +std::string SideString(Side s); + +// Type with which intermediate computations of a blas routine are performed. +// +// Some blas calls can perform computations with a type that's different than +// the type of their inputs/outputs. This lets you e.g. multiply two matrices +// of int8s using float32s to store the matmul's intermediate values. +enum class ComputationType { + kF16, // 16-bit floating-point + kF32, // 32-bit floating-point + kF64, // 64-bit floating-point + kI32, // 32-bit integer + // The below values use float32 for accumulation, but allow the inputs and + // outputs to be downcast to a lower precision: + kF16AsF32, // Allow downcast to F16 precision. + kBF16AsF32, // Allow downcast to BF16 precision. + kTF32AsF32, // Allow downcast to TF32 precision. +}; + +// Converts a ComputationType to a string. +std::string ComputationTypeString(ComputationType ty); + +std::ostream &operator<<(std::ostream &os, ComputationType ty); + +using dnn::DataType; +using dnn::ToDataType; + +// Converts a ComputationType to a string. +std::string DataTypeString(DataType ty); + +std::ostream &operator<<(std::ostream &os, DataType ty); + +// Opaque identifier for an "algorithm" used by a blas routine. This functions +// as a hint to the blas library. +typedef int64_t AlgorithmType; +constexpr AlgorithmType kDefaultAlgorithm = -1; +constexpr AlgorithmType kDefaultBlasGemm = -2; +constexpr AlgorithmType kDefaultBlasGemv = -3; +constexpr AlgorithmType kNoAlgorithm = -4; +constexpr AlgorithmType kRuntimeAutotuning = -5; + +// blas uses -1 to represent the default algorithm. This happens to match up +// with the CUBLAS_GEMM_DFALT constant, so cuda_blas.cc is using static_cast +// to convert from AlgorithmType to cublasGemmAlgo_t, and uses a static_assert +// to ensure that this assumption does not break. +// If another blas implementation uses a different value for the default +// algorithm, then it needs to convert kDefaultGemmAlgo to that value +// (e.g. via a function called ToWhateverGemmAlgo). +constexpr AlgorithmType kDefaultGemmAlgo = -1; + +// Describes the result of a performance experiment, usually timing the speed of +// a particular AlgorithmType. +// +// If the call we were benchmarking failed (a common occurrence; not all +// algorithms are valid for all calls), is_valid() will be false. +class ProfileResult { + public: + bool is_valid() const { return is_valid_; } + void set_is_valid(bool val) { is_valid_ = val; } + AlgorithmType algorithm() const { return algorithm_; } + void set_algorithm(AlgorithmType val) { algorithm_ = val; } + float elapsed_time_in_ms() const { return elapsed_time_in_ms_; } + void set_elapsed_time_in_ms(float val) { elapsed_time_in_ms_ = val; } + + private: + bool is_valid_ = false; + AlgorithmType algorithm_ = kDefaultAlgorithm; + float elapsed_time_in_ms_ = std::numeric_limits::max(); +}; + +class AlgorithmConfig { + public: + AlgorithmConfig() : algorithm_(kDefaultAlgorithm) {} + explicit AlgorithmConfig(AlgorithmType algorithm) : algorithm_(algorithm) {} + AlgorithmType algorithm() const { return algorithm_; } + void set_algorithm(AlgorithmType val) { algorithm_ = val; } + bool operator==(const AlgorithmConfig &other) const { + return this->algorithm_ == other.algorithm_; + } + bool operator!=(const AlgorithmConfig &other) const { + return !(*this == other); + } + std::string ToString() const; + + private: + AlgorithmType algorithm_; +}; + +// Opaque identifier specifying the precision to use in gemm calls. +typedef int64_t ComputePrecision; +constexpr ComputePrecision kDefaultComputePrecision = 0; + +// BLAS support interface -- this can be derived from a GPU executor when the +// underlying platform has an BLAS library implementation available. See +// StreamExecutor::AsBlas(). +// +// Thread-hostile: CUDA associates a CUDA-context with a particular thread in +// the system. Any operation that a user attempts to perform by enqueueing BLAS +// operations on a thread not-associated with the CUDA-context has unknown +// behavior at the current time; see b/13176597 +class BlasSupport { + public: + virtual ~BlasSupport() {} + + // Performs a BLAS y <- ax+y operation. + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, float alpha, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, double alpha, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, + std::complex alpha, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, + std::complex alpha, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + + // Copies vector to another vector: y <- x. + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + + // Computes the product of a vector by a scalar: x <- a*x. + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, + DeviceMemory *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, + DeviceMemory *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, + DeviceMemory> *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, + DeviceMemory> *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, + std::complex alpha, + DeviceMemory> *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, + std::complex alpha, + DeviceMemory> *x, int incx) = 0; + + // Computes a matrix-vector product using a general matrix. + // + // y <- alpha * a * x + beta * y, + // or + // y <- alpha * a' * x + beta * y, + // or + // y <- alpha * conj(a') * x + beta * y, + // + // alpha and beta are scalars; a is an m-by-n general matrix; x is a vector + // with n(trans==kNoTranspose)/m(otherwise) elements; + // y is a vector with m(trans==kNoTranspose)/n(otherwise) elements. + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, float alpha, const DeviceMemory &a, + int lda, const DeviceMemory &x, int incx, + float beta, DeviceMemory *y, int incy) = 0; + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, double alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, double beta, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy) = 0; + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy) = 0; + + // Computes a matrix-vector product using a symmetric band matrix. + // + // y <- alpha * a * x + beta * y, + // + // alpha and beta are scalars; a is an n-by-n symmetric band matrix, with k + // super-diagonals; x and y are n-element vectors. + virtual bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, + uint64_t k, float alpha, const DeviceMemory &a, + int lda, const DeviceMemory &x, int incx, + float beta, DeviceMemory *y, int incy) = 0; + virtual bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, + uint64_t k, double alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, double beta, + DeviceMemory *y, int incy) = 0; + + // Computes a matrix-matrix product with general matrices: + // + // c <- alpha * op(a) * op(b) + beta * c, + // + // op(X) is one of op(X) = X, or op(X) = X', or op(X) = conj(X'); alpha and + // beta are scalars; a, b, and c are matrices; op(a) is an m-by-k matrix; + // op(b) is a k-by-n matrix; c is an m-by-n matrix. + // + // Note: The half interface uses float precision internally; the version + // that uses half precision internally is not yet supported. There is no + // batched version of the half-precision interface. + // + // Alpha/beta type matches `dtype`, unless `dtype` is `Eigen::half`, in that + // case the expected alpha/beta type is `float`. + virtual tsl::Status DoBlasGemm(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, DataType dtype, const void *alpha, + const DeviceMemoryBase &a, int lda, + const DeviceMemoryBase &b, int ldb, + const void *beta, DeviceMemoryBase *c, int ldc, + const NumericOptions &numeric_options) = 0; + + // Gets a list of supported algorithms for DoBlasGemmWithAlgorithm. + virtual bool GetBlasGemmAlgorithms( + Stream *stream, std::vector *out_algorithms) = 0; + + // Like DoBlasGemm, but accepts an algorithm and an compute type. + // + // The compute type lets you say (e.g.) that the inputs and outputs are + // Eigen::halfs, but you want the internal computations to be done with + // float32 precision. + // + // If output_profile_result is not null, a failure here does not put the + // stream in a failure state. Instead, success/failure is indicated by + // output_profile_result->is_valid(). This lets you use this function for + // choosing the best algorithm among many (some of which may fail) without + // creating a new Stream for each attempt. + virtual tsl::Status DoBlasGemmWithAlgorithm( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, const void *alpha, + const DeviceMemoryBase &a, DataType type_a, int lda, + const DeviceMemoryBase &b, DataType type_b, int ldb, const void *beta, + DeviceMemoryBase *c, DataType type_c, int ldc, + ComputationType computation_type, AlgorithmType algorithm, + const NumericOptions &numeric_options, + ProfileResult *output_profile_result) = 0; + + virtual tsl::Status DoBlasGemmStridedBatchedWithAlgorithm( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, const void *alpha, + const DeviceMemoryBase &a, DataType type_a, int lda, int64_t stride_a, + const DeviceMemoryBase &b, DataType type_b, int ldb, int64_t stride_b, + const void *beta, DeviceMemoryBase *c, DataType type_c, int ldc, + int64_t stride_c, int batch_count, ComputationType computation_type, + AlgorithmType algorithm, const NumericOptions &numeric_options, + ProfileResult *output_profile_result) = 0; + + // Computes a batch of matrix-matrix product with general matrices. + // This is a batched version of DoBlasGemm. + // The batched GEMM computes matrix product for each input/output in a, b, + // and c, which contain batch_count DeviceMemory objects. + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, + DeviceMemorySlice c, int ldc, + int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, double alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + double beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + + // Batched gemm with strides instead of pointer arrays. + virtual tsl::Status DoBlasGemmStridedBatched( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, DataType dtype, const void *alpha, + const DeviceMemoryBase &a, int lda, int64_t stride_a, + const DeviceMemoryBase &b, int ldb, int64_t stride_b, const void *beta, + DeviceMemoryBase *c, int ldc, int64_t stride_c, int batch_count, + const NumericOptions &numeric_options) = 0; + + // Solves a triangular matrix equation. + // + // op(a) * x = alpha * b, + // or + // x * op(a) = alpha * b + // + // alpha is a scalar; x and b are m-by-n matrices; a is a unit, or non-unit, + // upper or lower triangular matrix; op(a) is one of op(a) = a, or op(a) = a', + // or op(a) = conj(a'). + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + float alpha, const DeviceMemory &a, int lda, + DeviceMemory *b, int ldb) = 0; + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + double alpha, const DeviceMemory &a, int lda, + DeviceMemory *b, int ldb) = 0; + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb) = 0; + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb) = 0; + + // Same as DoBlasTrsm, but operates over a list of a's and b's. The lists + // `as` and `bs` must have the same length. + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + float alpha, const DeviceMemory &as, + int lda, DeviceMemory *bs, int ldb, + int batch_count) = 0; + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + double alpha, const DeviceMemory &as, + int lda, DeviceMemory *bs, int ldb, + int batch_count) = 0; + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory *> &as, + int lda, + DeviceMemory *> *bs, + int ldb, int batch_count) = 0; + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory *> &as, + int lda, + DeviceMemory *> *bs, + int ldb, int batch_count) = 0; + + virtual tsl::Status GetVersion(std::string *version) = 0; + + protected: + BlasSupport() {} + + private: + BlasSupport(const BlasSupport &) = delete; + void operator=(const BlasSupport &) = delete; +}; + +// Macro used to quickly declare overrides for abstract virtuals in the +// BlasSupport base class. +#define TENSORFLOW_STREAM_EXECUTOR_GPU_BLAS_SUPPORT_OVERRIDES \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, float alpha, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, double alpha, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, \ + DeviceMemory *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, \ + DeviceMemory *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + float alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, float beta, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + double alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, double beta, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + const DeviceMemory> &x, int incx, \ + std::complex beta, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + const DeviceMemory> &x, int incx, \ + std::complex beta, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, uint64 k, \ + float alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, float beta, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, uint64 k, \ + double alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, double beta, \ + DeviceMemory *y, int incy) override; \ + tsl::Status DoBlasGemm( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, blas::DataType dtype, const void *alpha, \ + const DeviceMemoryBase &a, int lda, const DeviceMemoryBase &b, int ldb, \ + const void *beta, DeviceMemoryBase *c, int ldc, \ + const NumericOptions &numeric_options) override; \ + bool GetBlasGemmAlgorithms(Stream *stream, \ + std::vector *out_algorithms) \ + override; \ + tsl::Status DoBlasGemmWithAlgorithm( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, const void *alpha, \ + const DeviceMemoryBase &a, blas::DataType type_a, int lda, \ + const DeviceMemoryBase &b, blas::DataType type_b, int ldb, \ + const void *beta, DeviceMemoryBase *c, blas::DataType type_c, int ldc, \ + blas::ComputationType computation_type, blas::AlgorithmType algorithm, \ + const NumericOptions &numeric_options, \ + blas::ProfileResult *output_profile_result) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, float alpha, \ + DeviceMemorySlice a, int lda, \ + DeviceMemorySlice b, int ldb, float beta, \ + DeviceMemorySlice c, int ldc, int batch_count, \ + const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, float alpha, \ + DeviceMemorySlice a, int lda, \ + DeviceMemorySlice b, int ldb, float beta, \ + DeviceMemorySlice c, int ldc, int batch_count, \ + const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, float alpha, DeviceMemorySlice a, \ + int lda, DeviceMemorySlice b, int ldb, float beta, \ + DeviceMemorySlice c, int ldc, int batch_count, \ + const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, double alpha, \ + DeviceMemorySlice a, int lda, DeviceMemorySlice b, \ + int ldb, double beta, DeviceMemorySlice c, int ldc, \ + int batch_count, const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, std::complex alpha, \ + DeviceMemorySlice> a, int lda, \ + DeviceMemorySlice> b, int ldb, \ + std::complex beta, DeviceMemorySlice> c, \ + int ldc, int batch_count, const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, std::complex alpha, \ + DeviceMemorySlice> a, int lda, \ + DeviceMemorySlice> b, int ldb, \ + std::complex beta, DeviceMemorySlice> c, \ + int ldc, int batch_count, const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + tsl::Status DoBlasGemmStridedBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, blas::DataType dtype, const void *alpha, \ + const DeviceMemoryBase &a, int lda, int64_t stride_a, \ + const DeviceMemoryBase &b, int ldb, int64_t stride_b, const void *beta, \ + DeviceMemoryBase *c, int ldc, int64_t stride_c, int batch_count, \ + const NumericOptions &numeric_options) override; \ + tsl::Status DoBlasGemmStridedBatchedWithAlgorithm( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, const void *alpha, \ + const DeviceMemoryBase &a, blas::DataType type_a, int lda, \ + int64_t stride_a, const DeviceMemoryBase &b, blas::DataType type_b, \ + int ldb, int64_t stride_b, const void *beta, DeviceMemoryBase *c, \ + blas::DataType type_c, int ldc, int64_t stride_c, int batch_count, \ + blas::ComputationType computation_type, blas::AlgorithmType algorithm, \ + const NumericOptions &numeric_options, \ + blas::ProfileResult *output_profile_result) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, float alpha, const DeviceMemory &a, \ + int lda, DeviceMemory *b, int ldb) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, double alpha, const DeviceMemory &a, \ + int lda, DeviceMemory *b, int ldb) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + DeviceMemory> *b, int ldb) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + DeviceMemory> *b, int ldb) override; \ + bool DoBlasTrsmBatched( \ + Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, uint64 n, \ + float alpha, const DeviceMemory &as, int lda, \ + DeviceMemory *bs, int ldb, int batch_count) override; \ + bool DoBlasTrsmBatched( \ + Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, uint64 n, \ + double alpha, const DeviceMemory &as, int lda, \ + DeviceMemory *bs, int ldb, int batch_count) override; \ + bool DoBlasTrsmBatched(Stream *stream, blas::Side side, \ + blas::UpperLower uplo, blas::Transpose transa, \ + blas::Diagonal diag, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory *> &as, \ + int lda, DeviceMemory *> *bs, \ + int ldb, int batch_count) override; \ + bool DoBlasTrsmBatched(Stream *stream, blas::Side side, \ + blas::UpperLower uplo, blas::Transpose transa, \ + blas::Diagonal diag, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory *> &as, \ + int lda, DeviceMemory *> *bs, \ + int ldb, int batch_count) override; \ + tsl::Status GetVersion(std::string *version) override; + +} // namespace blas +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_BLAS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/command_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/command_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..2587872d27e5438ff733391d47a4f3aec43db17f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/command_buffer.h @@ -0,0 +1,163 @@ +/* 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_STREAM_EXECUTOR_COMMAND_BUFFER_H_ +#define XLA_STREAM_EXECUTOR_COMMAND_BUFFER_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; +class StreamExecutor; + +namespace internal { +class CommandBufferInterface; +} + +//===----------------------------------------------------------------------===// +// CommandBuffer +//===----------------------------------------------------------------------===// + +// Command buffer represent a "bundle of work items" for StreamExecutor device +// that can be submitted with one API call, e.g. command buffer might have +// multiple device kernels and synchronization barriers between them. Command +// buffers allow to amortize the cost of launching "work" on device by building +// it on the host ahead of time without expensive interaction with underlying +// device. +class CommandBuffer { + public: + // Command buffer state: + // + // (1) kCreate: a new command buffer under construction + // (2) kUpdate: updating a previously finalized command buffer + // (3) kFinalized: command buffer ready for execution + // + // Supported state transitions: + // + // (1) Finalize: (kCreate|kUpdate) -> kFinalized + // (2) Update: kFinalized -> kUpdate + // + enum class State { kCreate, kUpdate, kFinalized }; + + // Command buffers have two modes of execution: + // + // (1) kPrimary: command buffer can be submitted for execution via + // StreamExecutor APIs + // (2) kNested: command buffer can be executed only within a primary + // command buffer + // + enum class Mode { kPrimary, kNested }; + + //===--------------------------------------------------------------------===// + // Command buffer constructors + //===--------------------------------------------------------------------===// + + // Creates a new empty command buffer on the given executor. + static tsl::StatusOr Create(StreamExecutor* executor, + Mode mode = Mode::kPrimary); + + // Creates a new command buffer on the given executor by tracing `function` + // invocation. All StreamExecutor operations on a Stream argument will be + // recorded into the command buffer. Returned command buffer is finalized, and + // can't be updated. + // + // Command buffer tracing should be used only when it is impossible to use + // explicit construction APIs, e.g. when calling external libraries. + static tsl::StatusOr Trace( + StreamExecutor* executor, + absl::AnyInvocable function, + Mode mode = Mode::kPrimary); + + //===--------------------------------------------------------------------===// + // Command buffer API + //===--------------------------------------------------------------------===// + + // Adds a kernel launch command to the command buffer. + tsl::Status Launch(const ThreadDim& threads, const BlockDim& blocks, + const KernelBase& kernel, const KernelArgsArrayBase& args); + + // Adds a device-to-device memory copy to the command buffer. + tsl::Status MemcpyDeviceToDevice(DeviceMemoryBase* dst, + const DeviceMemoryBase& src, uint64_t size); + + // Finalizes command buffer and makes it executable. Once command buffer is + // finalized no commands can be added to it. + tsl::Status Finalize(); + + // Begins command buffer update. Command buffer update should be finalized + // before it can be executed. + tsl::Status Update(); + + // Type-safe wrapper for launching typed kernels. Notice that the order of + // arguments is different do disambiguate from the regular launch API. + template + tsl::Status Launch(const TypedKernel& kernel, + const ThreadDim& threads, const BlockDim& blocks, + Args... args); + + // Returns command buffer execution mode. + Mode mode() const; + + internal::CommandBufferInterface* implementation() { + return implementation_.get(); + } + + const internal::CommandBufferInterface* implementation() const { + return implementation_.get(); + } + + CommandBuffer(CommandBuffer&&) = default; + CommandBuffer& operator=(CommandBuffer&&) = default; + + private: + explicit CommandBuffer( + std::unique_ptr implementation); + + std::unique_ptr implementation_; + + CommandBuffer(const CommandBuffer&) = delete; + void operator=(const CommandBuffer&) = delete; +}; + +//===----------------------------------------------------------------------===// +// CommandBuffer templates implementation below +//===----------------------------------------------------------------------===// + +template +inline tsl::Status CommandBuffer::Launch(const TypedKernel& kernel, + const ThreadDim& threads, + const BlockDim& blocks, Args... args) { + KernelInvocationChecker, + std::tuple>::CheckAllStaticAssert(); + + KernelArgsArray kernel_args; + kernel.PackParams(&kernel_args, args...); + TF_RETURN_IF_ERROR(Launch(threads, blocks, kernel, kernel_args)); + return tsl::OkStatus(); +} + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_COMMAND_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_activation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_activation.h new file mode 100644 index 0000000000000000000000000000000000000000..bcdc8f5e178efec265331e3c3d551f09f231b8e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_activation.h @@ -0,0 +1,39 @@ +/* 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. +==============================================================================*/ + +// This file contains APIs that assume a StreamExecutor is backed by CUDA. +// It reaches into the CUDA implementation to activate an underlying CUDA +// context. +// +// Having this file separate from cuda/cuda_executor.h means that dependent +// code does not also have to depend on cuda.h. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_ACTIVATION_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_ACTIVATION_H_ + +#include "xla/stream_executor/gpu/gpu_activation.h" + +namespace stream_executor { + +class StreamExecutor; + +namespace cuda { + +using ScopedActivateExecutorContext = gpu::ScopedActivateExecutorContext; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_ACTIVATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas.h new file mode 100644 index 0000000000000000000000000000000000000000..a23fb616181e4261f4879604d59dfa81b9783118 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas.h @@ -0,0 +1,131 @@ +/* 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. +==============================================================================*/ + +// CUDA-specific support for BLAS functionality -- this wraps the cuBLAS library +// capabilities, and is only included into CUDA implementation code -- it will +// not introduce cuda headers into other code. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_H_ + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "third_party/gpus/cuda/include/cublas_v2.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/plugin_registry.h" + +namespace stream_executor { + +class Stream; + +namespace gpu { +class GpuExecutor; +} // namespace gpu + +namespace cuda { + +// BLAS plugin for CUDA platform via cuBLAS library. +// +// This satisfies the platform-agnostic BlasSupport interface. +// +// Note that the cuBLAS handle that this encapsulates is implicitly tied to the +// context (and, as a result, the device) that the parent GpuExecutor is tied +// to. This simply happens as an artifact of creating the cuBLAS handle when a +// CUDA context is active. +// +// Thread-safe post-initialization. +class CUDABlas : public blas::BlasSupport { + public: + explicit CUDABlas(gpu::GpuExecutor *parent); + + // Allocates a cuBLAS handle. + bool Init(); + + // Releases the cuBLAS handle, if present. + ~CUDABlas() override; + + TENSORFLOW_STREAM_EXECUTOR_GPU_BLAS_SUPPORT_OVERRIDES + + BlasLt &blas_lt() { return blas_lt_; } + + private: + // Tells cuBLAS to enqueue the BLAS operation onto a particular Stream. + // + // cuBLAS is stateful, and only be associated with one stream (in order to + // enqueue dispatch) at a given time. As a result, this generally must be + // invoked before calling into cuBLAS. + bool SetStream(Stream *stream) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + // Returns the underlying CUDA stream. + cudaStream_t CUDAStream(Stream *stream); + + // A helper function that calls the real cuBLAS function together with error + // handling. + // + // cublas_func: cuBLAS function pointer. + // cublas_name: cuBLAS function name. + // stream: Stream to enqueue the BLAS operation onto. + // pointer_mode_host: Indicate if the pointer to a scalar value is from host + // (true) or device (false). + // args: Arguments of cuBLAS function. + template + tsl::Status DoBlasInternalImpl(FuncT cublas_func, Stream *stream, + bool pointer_mode_host, cublasMath_t math_type, + Args... args); + + // Convenience functions that call DoBlasInternalImpl with err_on_failure=true + // and math_type=CUBLAS_DEFAULT_MATH. + template + bool DoBlasInternal(FuncT cublas_func, Stream *stream, bool pointer_mode_host, + Args... args) { + return DoBlasInternalImpl(cublas_func, stream, pointer_mode_host, + CUBLAS_DEFAULT_MATH, args...) + .ok(); + } + + // A helper function to implement DoBlasGemmBatched interfaces for generic + // types. + template + tsl::Status DoBlasGemmBatchedInternal( + FuncT cublas_func, Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64 n, uint64 k, Scalar alpha, + const DeviceMemorySlice &a_array, int lda, + const DeviceMemorySlice &b_array, int ldb, Scalar beta, + const DeviceMemorySlice &c_array, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + + // Guards the cuBLAS handle for this device. + absl::Mutex mu_; + + // GpuExecutor which instantiated this CUDABlas. + // Immutable post-initialization. + gpu::GpuExecutor *parent_; + + // cuBLAS library handle on the device. + cublasHandle_t blas_ ABSL_GUARDED_BY(mu_); + + BlasLt blas_lt_; + + CUDABlas(const CUDABlas &) = delete; + void operator=(const CUDABlas &) = delete; +}; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas_lt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas_lt.h new file mode 100644 index 0000000000000000000000000000000000000000..44e11206925f8baea84ca7ca54e6c3acaf8c58e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas_lt.h @@ -0,0 +1,250 @@ +/* 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_STREAM_EXECUTOR_CUDA_CUDA_BLAS_LT_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_LT_H_ + +#include +#include +#include +#include +#include + +#include "third_party/gpus/cuda/include/cublasLt.h" +#include "third_party/gpus/cuda/include/cublas_v2.h" +#include "third_party/gpus/cuda/include/cuda.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/cuda/cuda_blas_utils.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/host_or_device_scalar.h" +#include "tsl/platform/status.h" + +namespace stream_executor { +namespace gpu { +class GpuExecutor; +} // namespace gpu + +namespace cuda { + +class BlasLt { + template + using Owned = + std::unique_ptr, cublasStatus_t (*)(T)>; + + public: + class MatrixLayout { + public: + enum class Order { kRowMajor, kColumnMajor }; + + // If `leading_dim_stride` is not specified, it defaults to: + // - `num_cols` if `order == kRowMajor`, + // - `num_rows` if `order == kColumnMajor`. + // If `batch_stride` is not specified, it defaults to `num_rows * num_cols` + // if `batch_size > 1`, otherwise `0`. + static tsl::StatusOr Create( + blas::DataType type, size_t num_rows, size_t num_cols, Order order, + size_t batch_size = 1, + std::optional leading_dim_stride = std::nullopt, + std::optional batch_stride = std::nullopt); + + cudaDataType_t type() const; + + cublasLtMatrixLayout_t get() const { return handle_.get(); } + + private: + explicit MatrixLayout(cublasLtMatrixLayout_t handle) + : handle_(handle, cublasLtMatrixLayoutDestroy) {} + + Owned handle_; + }; + + enum class Epilogue { + kDefault = 1, // No special postprocessing + kReLU = 2, // Apply point-wise ReLU function + kBias = 4, // Add broadcasted bias vector + kBiasThenReLU = kBias | kReLU, // Apply bias and then ReLU transform + kGELU = 32, // Apply GELU point-wise transform to the results + kGELUWithAux = 32 | 1024, // Apply GELU with auxiliary output. + kBiasThenGELU = kBias | kGELU, // Apply bias and then approximate GELU. + kBiasThenGELUWithAux = kBiasThenGELU | 1024, + }; + + // Describes the location of pointers for the scaling factors alpha and beta. + enum class PointerMode { + kHost, + kDevice, + }; + + class MatmulDesc { + public: + static tsl::StatusOr Create( + blas::ComputationType compute_type, blas::DataType scale_type, + blas::Transpose trans_a = blas::Transpose::kNoTranspose, + blas::Transpose trans_b = blas::Transpose::kNoTranspose, + Epilogue epilogue = Epilogue::kDefault, + PointerMode pointer_mode = PointerMode::kHost); + + cublasComputeType_t compute_type() const; + cudaDataType_t scale_type() const; + cublasLtPointerMode_t pointer_mode() const; + + cublasLtMatmulDesc_t get() const { return handle_.get(); } + + private: + explicit MatmulDesc(cublasLtMatmulDesc_t handle) + : handle_(handle, cublasLtMatmulDescDestroy) {} + + Owned handle_; + }; + + // TODO(cjfj): Add consistency checks for types, shapes, etc.? + struct MatmulPlan { + MatmulDesc op_desc; + MatrixLayout a_desc; + MatrixLayout b_desc; + MatrixLayout c_desc; + MatrixLayout d_desc; + }; + + class MatmulPreference { + public: + static tsl::StatusOr Create(size_t max_workspace_size); + + cublasLtMatmulPreference_t get() const { return handle_.get(); } + + private: + explicit MatmulPreference(cublasLtMatmulPreference_t handle) + : handle_(handle, cublasLtMatmulPreferenceDestroy) {} + + Owned handle_; + }; + + struct MatmulAlgorithm { + cublasLtMatmulAlgo_t algo; + size_t workspace_size; + }; + + explicit BlasLt(gpu::GpuExecutor* parent) + : parent_(parent), blas_lt_(nullptr, cublasLtDestroy) {} + + tsl::Status Init(); + + // Returns a list of supported algorithms for DoMatmul. The algorithms are + // returned in the order of increasing estimated compute time according to an + // internal heuristic. + tsl::StatusOr> GetMatmulAlgorithms( + const MatmulPlan& plan, const MatmulPreference& preference, + size_t max_algorithm_count = 128); + + template + tsl::Status DoMatmul(Stream* stream, const MatmulPlan& plan, + const HostOrDeviceScalar& alpha, + const DeviceMemory& a, const DeviceMemory& b, + const HostOrDeviceScalar& beta, + const DeviceMemory& c, DeviceMemory& d, + const MatmulAlgorithm& algorithm, + ScratchAllocator& scratch_allocator, + const DeviceMemory& bias = {}, + const DeviceMemoryBase& aux = DeviceMemory{}, + const DeviceMemory& a_scale = {}, + const DeviceMemory& b_scale = {}, + const DeviceMemory& c_scale = {}, + const DeviceMemory& d_scale = {}, + const DeviceMemory& d_amax = {}, + blas::ProfileResult* profile_result = nullptr) { + if (AsCudaDataType(blas::ToDataType::value) != + plan.op_desc.scale_type()) { + return tsl::errors::InvalidArgument("mismatched scale types"); + } + + bool expect_scale_factor_on_device = + (plan.op_desc.pointer_mode() == CUBLASLT_POINTER_MODE_DEVICE); + + if (alpha.on_device() != expect_scale_factor_on_device) { + return tsl::errors::InvalidArgument("wrong location for alpha"); + } + + if (beta.on_device() != expect_scale_factor_on_device) { + return tsl::errors::InvalidArgument("wrong location for beta"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.a_desc.type()) { + return tsl::errors::InvalidArgument("mismatched A matrix types"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.b_desc.type()) { + return tsl::errors::InvalidArgument("mismatched B matrix types"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.c_desc.type()) { + return tsl::errors::InvalidArgument("mismatched C matrix types"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.d_desc.type()) { + return tsl::errors::InvalidArgument("mismatched D matrix types"); + } + + return DoMatmul(stream, plan, alpha.opaque(), a, b, beta.opaque(), c, d, + algorithm, scratch_allocator, bias, aux, a_scale, b_scale, + c_scale, d_scale, d_amax, profile_result); + } + + template + tsl::Status DoMatmul(Stream* stream, const MatmulPlan& plan, + const HostOrDeviceScalar& alpha, + const DeviceMemory& a, const DeviceMemory& b, + const HostOrDeviceScalar& beta, + const DeviceMemory& c, DeviceMemory& d, + const MatmulAlgorithm& algorithm, + ScratchAllocator& scratch_allocator, + const DeviceMemory& bias = {}, + const DeviceMemoryBase& aux = DeviceMemory{}, + blas::ProfileResult* profile_result = nullptr) { + return DoMatmul(stream, plan, alpha, a, b, beta, c, d, algorithm, + scratch_allocator, bias, aux, {}, {}, {}, {}, {}, + profile_result); + } + + private: + tsl::Status DoMatmul(Stream* stream, const MatmulPlan& plan, + const void* alpha, DeviceMemoryBase a, + DeviceMemoryBase b, const void* beta, DeviceMemoryBase c, + DeviceMemoryBase d, const MatmulAlgorithm& algorithm, + ScratchAllocator& scratch_allocator, + DeviceMemoryBase bias, DeviceMemoryBase aux, + DeviceMemoryBase a_scale, DeviceMemoryBase b_scale, + DeviceMemoryBase c_scale, DeviceMemoryBase d_scale, + DeviceMemoryBase d_amax, + blas::ProfileResult* profile_result); + + gpu::GpuExecutor* parent_; + + absl::Mutex mu_; + Owned blas_lt_ ABSL_GUARDED_BY(mu_); +}; + +// Returns `BlasLt` implementation for a stream if available, or `nullptr`. +BlasLt* GetBlasLt(Stream* stream); + +} // namespace cuda + +namespace gpu { +using BlasLt = ::stream_executor::cuda::BlasLt; +inline BlasLt* GetBlasLt(Stream* stream) { return cuda::GetBlasLt(stream); } +} // namespace gpu + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_LT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..2e8789b1f1bcde7d87cf5ace2356a9f08d58e109 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_blas_utils.h @@ -0,0 +1,41 @@ +/* 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_STREAM_EXECUTOR_CUDA_CUDA_BLAS_UTILS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_UTILS_H_ + +#include + +#include "third_party/gpus/cuda/include/cublas_v2.h" +#include "xla/stream_executor/blas.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" + +#define SE_CUBLAS_RETURN_IF_ERROR(expr) \ + TF_RETURN_IF_ERROR(::stream_executor::cuda::ToStatus(expr, #expr)) + +namespace stream_executor { +namespace cuda { + +const char* ToString(cublasStatus_t status); +tsl::Status ToStatus(cublasStatus_t status, const char* prefix = "cublasLt"); +cudaDataType_t AsCudaDataType(blas::DataType type); +cublasComputeType_t AsCublasComputeType(blas::ComputationType type); +cublasOperation_t AsCublasOperation(blas::Transpose trans); + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_diagnostics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_diagnostics.h new file mode 100644 index 0000000000000000000000000000000000000000..46d1a001051c658bdca8efeec990b2b51c177b48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_diagnostics.h @@ -0,0 +1,41 @@ +/* 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 XLA_STREAM_EXECUTOR_CUDA_CUDA_DIAGNOSTICS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_DIAGNOSTICS_H_ + +#include "xla/stream_executor/gpu/gpu_diagnostics.h" + +namespace stream_executor { +namespace cuda { + +// e.g. DriverVersion{346, 3, 4} +using DriverVersion = gpu::DriverVersion; + +// Converts a parsed driver version to string form. +std::string DriverVersionToString(DriverVersion version); + +// Converts a parsed driver version or status value to natural string form. +std::string DriverVersionStatusToString(tsl::StatusOr version); + +// Converts a string of a form like "331.79" to a DriverVersion{331, 79}. +tsl::StatusOr StringToDriverVersion(const std::string& value); + +using Diagnostician = gpu::Diagnostician; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_DIAGNOSTICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_dnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_dnn.h new file mode 100644 index 0000000000000000000000000000000000000000..1157093b53bedcd891ab9301de6ae48228b3fd7a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_dnn.h @@ -0,0 +1,777 @@ +/* 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 CUDA-specific DNN library support, implementing the general DnnSupport +// interface. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_DNN_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_DNN_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/types/span.h" +#include "xla/stream_executor/cuda/cuda_activation.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/plugin_registry.h" +#include "xla/stream_executor/temporary_device_memory.h" +#include "tsl/platform/status.h" + +namespace stream_executor { +namespace gpu { + +class GpuExecutor; +class CudnnRnnDescriptor; +class CudnnRnnSequenceTensorDescriptor; +class CudnnRnnStateTensorDescriptor; +class CudnnCtcLossDescriptor; + +using BatchDescriptorSlice = absl::Span; + +template +using DeviceMemorySlice = absl::Span* const>; + +// cudnn-library based DNN support. For details on overridden interface +// functions, see dnn.h. +class CudnnSupport : public dnn::DnnSupport { + public: + explicit CudnnSupport(GpuExecutor* parent); + + tsl::Status Init() override; + tsl::StatusOr GetVersion() override; + + tsl::StatusOr> createRnnDescriptor( + int num_layers, int hidden_size, int input_size, int cell_size, + int batch_size, dnn::RnnInputMode input_mode, + dnn::RnnDirectionMode direction_mode, dnn::RnnMode rnn_mode, + dnn::DataType data_type, const dnn::AlgorithmConfig& algorithm_config, + const NumericOptions& numeric_options, float dropout, uint64_t seed, + ScratchAllocator* state_allocator, bool use_padded_io) override; + + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + dnn::DataType data_type) override; + + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + const absl::Span& seq_lengths, + bool time_major, + dnn::DataType data_type) override; + + tsl::StatusOr> + createRnnStateTensorDescriptor(int num_layer, int batch_size, int data_size, + dnn::DataType data_type) override; + + bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnBackward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnBackward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnBackward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + tsl::Status GetConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, ScratchAllocator* scratch_allocator, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans) + override; + + tsl::StatusOr> ConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor) override; + + tsl::Status GetGraphConvolveRunners( + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, const NumericOptions& numeric_options, + std::vector>* out_exec_plans, + std::string serialized_graph) override; + + tsl::StatusOr> + GraphConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + std::string serialized_graph) override; + + tsl::Status GetFusedConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_scale, double side_input_scale, + double leakyrelu_alpha, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, dnn::ActivationMode activation_mode, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans) + override; + + tsl::Status GetFusedMatmulRunners( + bool use_cudnn_frontend, dnn::DataType input_type, + dnn::DataType bias_type, dnn::DataType output_type, Stream* stream, + bool trans_a, bool trans_b, uint64_t m, uint64_t n, uint64_t k, + int64_t lda, int64_t ldb, int64_t ldc, + dnn::ActivationMode activation_mode, bool use_fallback, + const NumericOptions& numeric_options, + std::vector>* + out_exec_plans) override; + + tsl::StatusOr> + FusedConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType bias_type, dnn::DataType output_type, double conv_scale, + double side_input_scale, double leakyrelu_alpha, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::ActivationMode activation_mode) override; + + tsl::StatusOr> + FusedMHARunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor& bmm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& intermediate_bmm2_lhs_descriptor, + const dnn::TensorDescriptor& output_descriptor, + std::optional activation_descriptor, + std::optional mask_descriptor, + std::optional bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) override; + + tsl::StatusOr> + FusedMHABackwardRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor& bmm1_grad_gemm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm1_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_grad_gemm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& d_output_descriptor, + const dnn::TensorDescriptor& d_bmm1_lhs_descriptor, + const dnn::TensorDescriptor& d_bmm1_rhs_descriptor, + const dnn::TensorDescriptor& d_bmm2_rhs_descriptor, + const dnn::TensorDescriptor& d_s_descriptor, + std::optional mask_descriptor, + std::optional d_bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) override; + bool GetRnnAlgorithms( + std::vector* out_algorithms) override; + + bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_var_iance, + const DeviceMemory& side_input, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, + const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoConvolve( + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::AlgorithmDesc algorithm_desc, DeviceMemory scratch_memory, + dnn::ProfileResult* output_profile_result) override; + + tsl::Status DoFusedConvolve( + Stream* stream, dnn::DataType input_type, dnn::DataType side_input_type, + dnn::DataType bias_type, dnn::DataType output_type, + const dnn::BatchDescriptor& conv_input_descriptor, + DeviceMemoryBase conv_input_data, double conv_input_scale, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + DeviceMemoryBase side_input_data, double side_input_scale, + const dnn::BatchDescriptor& bias_descriptor, DeviceMemoryBase biases, + dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, ScratchAllocator* scratch_allocator, + const dnn::AlgorithmConfig& algorithm_config, + dnn::ProfileResult* output_profile_result) override; + + tsl::Status CudnnReorderConvolutionFilterAndBias( + Stream* stream, const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_input, + DeviceMemory* filter_output, + std::optional> bias_input, + std::optional> bias_output) override; + + bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) override { + LOG(ERROR) << "DoConvolveQuantized not supported by cuDNN"; + return false; + } + + bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) override { + LOG(ERROR) << "DoConvolveQuantized not supported by cuDNN"; + return false; + } + + bool DoSeparableConvolve( + Stream* stream, const dnn::BatchDescriptor& batch_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, int depth_multiplier, + const DeviceMemory& first_weights, + const DeviceMemory& second_weights, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) override { + LOG(ERROR) << "separable convolution not supported by CUDNN"; + return false; + } + + bool DoMatMul(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& weights, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override; + + bool DoMatMulQuantized(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override { + LOG(ERROR) << "DNN MatMulQuantized not supported by CUDNN"; + return false; + } + + bool DoMatMulQuantized(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override { + LOG(ERROR) << "DNN MatMulQuantized not supported by CUDNN"; + return false; + } + + bool DoBiasAdd(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& biases, + const dnn::BatchDescriptor& dimensions, + DeviceMemory* output_data) override; + + bool DoActivate(Stream* stream, dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + DeviceMemory* output_data, uint64_t options) override; + + tsl::Status DoPoolForward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoPoolForward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoPoolBackward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoPoolBackward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, + ScratchAllocator* workspace_allocator) override; + + bool DoNormalizeWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + DeviceMemory* output_data) override; + + bool DoNormalizeBackwardWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& raw_data, + const DeviceMemory& normalized_data, + const DeviceMemory& normalized_variable_gradient, + DeviceMemory* raw_variable_gradient, + ScratchAllocator* workspace_allocator) override; + + bool DoDepthConcatenate(Stream* stream, BatchDescriptorSlice input_dimensions, + DeviceMemorySlice input_data, + DeviceMemory* output_data) override; + + bool DoElementwiseOperate(Stream* stream, dnn::ElementwiseOperation operation, + BatchDescriptorSlice input_dimensions, + DeviceMemorySlice input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override; + + bool DoXYPad(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, int64_t left_pad, + int64_t right_pad, int64_t top_pad, int64_t bottom_pad, + DeviceMemory* output_data) override; + + bool DoXYSlice(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, int64_t left_trim, + int64_t right_trim, int64_t top_trim, int64_t bottom_trim, + DeviceMemory* output_data) override; + + bool DoMemcpyD2HQuantized(Stream* stream, + const DeviceMemory& device_unquantized_src, + dnn::QuantizedActivationMode mode, void* host_dst, + int64_t size) override; + + bool DoMemcpyH2DQuantized( + Stream* stream, const void* host_src, int64_t size, + dnn::QuantizedActivationMode mode, + DeviceMemory* device_unquantized_dst) override; + + // Derives an output batch descriptor from an input batch and convolution + // descriptors. + bool DeriveOutputBatchDescriptor( + const dnn::BatchDescriptor& batch_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::BatchDescriptor* output_batch_descriptor); + + tsl::Status DoCtcLoss(Stream* stream, dnn::DataType element_type, + const dnn::RnnStateTensorDescriptor& probs_desc, + const DeviceMemoryBase probs_data, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + DeviceMemoryBase costs_data, + const dnn::RnnStateTensorDescriptor& grads_desc, + DeviceMemoryBase grads_data, + DeviceMemory scratch_memory, + int ctc_loss_algo_id) override; + + bool DoTransformTensor(Stream* stream, const dnn::BatchDescriptor& input_desc, + dnn::DataType input_type, + const DeviceMemoryBase& input_data, + const dnn::BatchDescriptor& output_desc, + dnn::DataType output_type, float scale, + DeviceMemoryBase* output_data) override; + + void NotifyStreamDestroyed(Stream* stream) override; + + private: + GpuExecutor* parent_; // Parent executor object. Not owned. + + // Provides access to the cuDNN handle. + std::unique_ptr cudnn_; + + bool GetConvolveAlgorithms(CudaComputeCapability cuda_compute_capability, + dnn::DataType input_type, + const NumericOptions& numeric_options, + std::vector* out_algorithms); + + bool GetConvolveBackwardDataAlgorithms( + CudaComputeCapability cuda_compute_capability, dnn::DataType input_type, + const NumericOptions& numeric_options, + std::vector* out_algorithms); + + bool GetConvolveBackwardFilterAlgorithms( + CudaComputeCapability cuda_compute_capability, dnn::DataType input_type, + const NumericOptions& numeric_options, + std::vector* out_algorithms); + + template + tsl::Status DoBatchNormalizationForwardImpl( + Stream* stream, dnn::DataType input_data_type, + dnn::DataType scale_data_type, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator); + + template + tsl::Status DoBatchNormalizationBackwardImpl( + Stream* stream, int cudnn_input_type, int cudnn_scale_type, + const DeviceMemory& y_backprop, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& mean, const DeviceMemory& inv_var, + const DeviceMemory& y, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator); + + template + tsl::Status DoRnnForwardImpl( + Stream* stream, const CudnnRnnDescriptor& rnn_desc, + const CudnnRnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const CudnnRnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const CudnnRnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, const DeviceMemory& params, + const CudnnRnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const CudnnRnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const CudnnRnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result); + + template + tsl::Status DoRnnBackwardImpl( + Stream* stream, const CudnnRnnDescriptor& rnn_desc, + const CudnnRnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const CudnnRnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const CudnnRnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, const DeviceMemory& params, + const CudnnRnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const CudnnRnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const CudnnRnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result); + + tsl::Status DoCtcLossImpl( + Stream* stream, const CudnnRnnStateTensorDescriptor& probs_desc, + const DeviceMemoryBase probs_data, absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, DeviceMemoryBase costs_data, + const CudnnRnnStateTensorDescriptor& grads_desc, + DeviceMemoryBase grads_data, const CudnnCtcLossDescriptor& ctc_loss_desc, + DeviceMemory scratch_memory, int ctc_loss_algo_id); + + private: + tsl::Status DoPrepareForConvolution( + dnn::ConvolutionKind kind, dnn::DataType element_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::AlgorithmConfig& algorithm_config, + ScratchAllocator* scratch_allocator, dnn::AlgorithmDesc* algorithm_desc, + DeviceMemory* scratch_memory) override; + + tsl::Status DoPrepareForCtcLoss( + Stream* stream, dnn::DataType element_type, + const dnn::RnnStateTensorDescriptor& probs_desc, + const dnn::RnnStateTensorDescriptor& grads_desc, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions& numeric_options, + ScratchAllocator* scratch_allocator, + DeviceMemory* scratch_memory, int* ctc_loss_algo_id) override; + + CudnnSupport(const CudnnSupport&) = delete; + void operator=(const CudnnSupport&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_DNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_driver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_driver.h new file mode 100644 index 0000000000000000000000000000000000000000..7f3314fbff585c8868badeedc7ae478dd5ffadcf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_driver.h @@ -0,0 +1,165 @@ +/* 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. +==============================================================================*/ + +// CUDA userspace driver library wrapper functionality. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ + +#include "absl/container/node_hash_map.h" +#include "absl/memory/memory.h" +#include "absl/strings/str_cat.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/gpu/gpu_driver.h" + +namespace stream_executor { +namespace gpu { +// Formats CUresult to output prettified values into a log stream. +static std::string ToString(CUresult result) { + const char* error_name; + if (cuGetErrorName(result, &error_name)) { + return absl::StrCat("UNKNOWN ERROR (", static_cast(result), ")"); + } + const char* error_string; + if (cuGetErrorString(result, &error_string)) { + return error_name; + } + return absl::StrCat(error_name, ": ", error_string); +} + +// CUDAContext wraps a cuda CUcontext handle, and includes a unique id. The +// unique id is positive, and ids are not repeated within the process. +class GpuContext { + public: + GpuContext(CUcontext context, int64_t id) : context_(context), id_(id) {} + + CUcontext context() const { return context_; } + int64_t id() const { return id_; } + + // Disallow copying and moving. + GpuContext(GpuContext&&) = delete; + GpuContext(const GpuContext&) = delete; + GpuContext& operator=(GpuContext&&) = delete; + GpuContext& operator=(const GpuContext&) = delete; + + private: + CUcontext const context_; + const int64_t id_; +}; + +// Manages the singleton map of contexts that we've created, mapping +// from the CUcontext to the GpuContext* that we pass around internally. +// This also manages assignment of unique ids to GpuContexts, to allow +// for fast comparison of a context against the current context. +// +// CUDA-runtime-created contexts are avoided, if triple angle +// brace launches are required, by using the scoped activations in +// gpu/gpu_activation.h. +class CreatedContexts { + public: + // Returns whether context is a member of the live set. + static bool Has(CUcontext context) { + absl::ReaderMutexLock lock(&mu_); + return Live()->find(context) != Live()->end(); + } + + // Adds context to the live set, or returns it if it's already present. + static GpuContext* Add(CUcontext context, int device_ordinal) { + CHECK(context != nullptr); + absl::MutexLock lock(&mu_); + + auto insert_result = Live()->insert(std::make_pair(context, nullptr)); + auto it = insert_result.first; + if (insert_result.second) { + // context was not present in the map. Add it. + it->second = std::make_unique(context, next_id_++); + (*LiveOrdinal())[device_ordinal].push_back(context); + } + return it->second.get(); + } + + // Removes context from the live set. + static void Remove(CUcontext context) { + CHECK(context != nullptr); + absl::MutexLock lock(&mu_); + auto it = Live()->find(context); + CHECK(it != Live()->end()) << context; + Live()->erase(it); + for (auto p : (*LiveOrdinal())) { + auto it2 = std::find(p.second.begin(), p.second.end(), context); + if (it2 != p.second.end()) { + p.second.erase(it2, it2++); + if (p.second.empty()) { + LiveOrdinal()->erase(p.first); + } + break; + } + } + } + + // Return the context associated to that ptr. + static CUcontext GetAnyContext(void* ptr) { + absl::ReaderMutexLock lock(&mu_); + int device_ordinal; + CUresult result = cuPointerGetAttribute(static_cast(&device_ordinal), + CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, + reinterpret_cast(ptr)); + if (result != CUDA_SUCCESS) { + LOG(FATAL) << "Not able to get the device_ordinal for ptr: " << ptr + << ". Error: " << ToString(result); + } + CHECK_EQ(LiveOrdinal()->count(device_ordinal), 1); + CHECK(!LiveOrdinal()->at(device_ordinal).empty()) + << "Need at least one context."; + return LiveOrdinal()->at(device_ordinal)[0]; + } + + private: + // Returns the live map singleton. + static absl::node_hash_map>* Live() { + static auto singleton = + new absl::node_hash_map>; + return singleton; + } + static absl::node_hash_map>* LiveOrdinal() { + static auto singleton = + new absl::node_hash_map>; + return singleton; + } + + // Lock that guards access-to/mutation-of the live set. + static absl::Mutex mu_; + static int64_t next_id_; +}; +} // namespace gpu + +namespace cuda { + +using MemorySpace = gpu::MemorySpace; + +using CUDADriver = gpu::GpuDriver; + +using ScopedActivateContext = gpu::ScopedActivateContext; + +using CudaContext = gpu::GpuContext; + +// Returns the current context set in CUDA. This is done by calling the cuda +// driver (e.g., this value is not our cached view of the current context). +CUcontext CurrentContextOrDie(); + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_event.h new file mode 100644 index 0000000000000000000000000000000000000000..b4aa70392a46ccf05fa70eb4fae2363794f80283 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_event.h @@ -0,0 +1,29 @@ +/* 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 XLA_STREAM_EXECUTOR_CUDA_CUDA_EVENT_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_EVENT_H_ + +#include "xla/stream_executor/gpu/gpu_event.h" + +namespace stream_executor { +namespace cuda { + +using CUDAEvent = gpu::GpuEvent; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_fft.h new file mode 100644 index 0000000000000000000000000000000000000000..e5ce88163e4bbca8b3018474da4b561020a3a54a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_fft.h @@ -0,0 +1,141 @@ +/* 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. +==============================================================================*/ + +// CUDA-specific support for FFT functionality -- this wraps the cuFFT library +// capabilities, and is only included into CUDA implementation code -- it will +// not introduce cuda headers into other code. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_ + +#include + +#include "third_party/gpus/cuda/include/cufft.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/plugin_registry.h" +#include "xla/stream_executor/scratch_allocator.h" + +namespace stream_executor { + +class Stream; + +namespace gpu { + +class GpuExecutor; + +// CUDAFftPlan uses deferred initialization. Only a single call of +// Initialize() is allowed to properly create cufft plan and set member +// variable is_initialized_ to true. Newly added interface that uses member +// variables should first check is_initialized_ to make sure that the values of +// member variables are valid. +class CUDAFftPlan : public fft::Plan { + public: + CUDAFftPlan() + : parent_(nullptr), + plan_(-1), + fft_type_(fft::Type::kInvalid), + scratch_(nullptr), + scratch_size_bytes_(0), + is_initialized_(false), + scratch_allocator_(nullptr) {} + ~CUDAFftPlan() override; + + // Get FFT direction in cuFFT based on FFT type. + int GetFftDirection() const; + cufftHandle GetPlan() const { + if (IsInitialized()) { + return plan_; + } else { + LOG(FATAL) << "Try to get cufftHandle value before initialization."; + } + } + + // Initialize function for batched plan + tsl::Status Initialize(GpuExecutor* parent, Stream* stream, int rank, + uint64_t* elem_count, uint64_t* input_embed, + uint64_t input_stride, uint64 input_distance, + uint64_t* output_embed, uint64_t output_stride, + uint64_t output_distance, fft::Type type, + int batch_count, ScratchAllocator* scratch_allocator); + + // Initialize function for 1d,2d, and 3d plan + tsl::Status Initialize(GpuExecutor* parent, Stream* stream, int rank, + uint64_t* elem_count, fft::Type type, + ScratchAllocator* scratch_allocator); + + tsl::Status UpdateScratchAllocator(Stream* stream, + ScratchAllocator* scratch_allocator); + + ScratchAllocator* GetScratchAllocator() const { return scratch_allocator_; } + + protected: + bool IsInitialized() const { return is_initialized_; } + + private: + GpuExecutor* parent_; + cufftHandle plan_; + fft::Type fft_type_; + DeviceMemory scratch_; + size_t scratch_size_bytes_; + bool is_initialized_; + ScratchAllocator* scratch_allocator_; +}; + +// FFT support for CUDA platform via cuFFT library. +// +// This satisfies the platform-agnostic FftSupport interface. +// +// Note that the cuFFT handle that this encapsulates is implicitly tied to the +// context (and, as a result, the device) that the parent GpuExecutor is tied +// to. This simply happens as an artifact of creating the cuFFT handle when a +// CUDA context is active. +// +// Thread-safe. The CUDA context associated with all operations is the CUDA +// context of parent_, so all context is explicit. +class CUDAFft : public fft::FftSupport { + public: + explicit CUDAFft(GpuExecutor* parent) : parent_(parent) {} + ~CUDAFft() override {} + + TENSORFLOW_STREAM_EXECUTOR_GPU_FFT_SUPPORT_OVERRIDES + + private: + GpuExecutor* parent_; + + // Two helper functions that execute dynload::cufftExec?2?. + + // This is for complex to complex FFT, when the direction is required. + template + bool DoFftWithDirectionInternal(Stream *stream, fft::Plan *plan, + FuncT cufft_exec, + const DeviceMemory &input, + DeviceMemory *output); + + // This is for complex to real or real to complex FFT, when the direction + // is implied. + template + bool DoFftInternal(Stream *stream, fft::Plan *plan, FuncT cufft_exec, + const DeviceMemory &input, + DeviceMemory *output); + + CUDAFft(const CUDAFft&) = delete; + void operator=(const CUDAFft&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_helpers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..5ff0ed0d2af5db9c360bd69f12d7b8e07ef8b679 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_helpers.h @@ -0,0 +1,25 @@ +/* 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. +==============================================================================*/ + +// Common helper functions used for dealing with CUDA API datatypes. +// +// These are typically placed here for use by multiple source components (for +// example, BLAS and executor components). +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_HELPERS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_HELPERS_H_ + +#include "xla/stream_executor/gpu/gpu_helpers.h" + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_HELPERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7077ee952ec9e2f270816070a29895cc93f2236b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_kernel.h @@ -0,0 +1,35 @@ +/* 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 CUDA implementation of the StreamExecutorInterface functionality. +// CUDA inclusions are ideally confined to this implementation file. +// +// The notions from the StreamExecutor basically correspond to the CUDA streams +// programming model provided by the libcuda.so driver APIs, so we don't have +// to do much more than wrap the calls to the libraries appropriately. +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_KERNEL_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_KERNEL_H_ + +#include "xla/stream_executor/gpu/gpu_kernel.h" + +namespace stream_executor { +namespace cuda { + +using CUDAKernel = gpu::GpuKernel; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_platform_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_platform_id.h new file mode 100644 index 0000000000000000000000000000000000000000..83af581d6f209492a5ec45ac7e646e0496481d33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_platform_id.h @@ -0,0 +1,34 @@ +/* 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 XLA_STREAM_EXECUTOR_CUDA_CUDA_PLATFORM_ID_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_PLATFORM_ID_H_ + +#include "xla/stream_executor/platform.h" + +namespace stream_executor { +namespace cuda { + +// Opaque and unique identifier for the cuda platform. +// This is needed so that plugins can refer to/identify this platform without +// instantiating a CudaPlatform object. +// This is broken out here to avoid a circular dependency between CudaPlatform +// and CudaExecutor. +extern const Platform::Id kCudaPlatformId; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_PLATFORM_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..a99fe6d5eecb85dea24c4e594216aead4af5ffa6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/cuda/cuda_stream.h @@ -0,0 +1,36 @@ +/* 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. +==============================================================================*/ + +// Defines the GpuStream type - the CUDA-specific implementation of the generic +// StreamExecutor Stream interface. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_STREAM_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_STREAM_H_ + +#include "xla/stream_executor/gpu/gpu_stream.h" + +namespace stream_executor { +namespace cuda { + +using CUDAStream = gpu::GpuStream; + +inline CUDAStream* AsCUDAStream(Stream* stream) { + return gpu::AsGpuStream(stream); +} + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/data_type.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..c0f900d4794e4d2c89741c97dd3e80c2b0fc2330 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/data_type.h @@ -0,0 +1,95 @@ +/* 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_STREAM_EXECUTOR_DATA_TYPE_H_ +#define XLA_STREAM_EXECUTOR_DATA_TYPE_H_ + +#include +#include + +#include "tsl/platform/float8.h" +#include "tsl/protobuf/dnn.pb.h" + +namespace Eigen { +struct bfloat16; +struct half; +} // namespace Eigen + +namespace stream_executor { +namespace dnn { + +// A helper class to convert C/C++ types to the proper enums. +template +struct ToDataType; + +// Note: If you add a new specialization below, make sure to add the +// corresponding definition in stream_executor/dnn.cc. +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E4M3FN; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E5M2; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E4M3FNUZ; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E5M2FNUZ; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kFloat; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kDouble; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kHalf; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kBF16; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kInt8; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kInt32; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kInt64; +}; +template <> +struct ToDataType> { + static constexpr DataType value = DataType::kComplexFloat; +}; +template <> +struct ToDataType> { + static constexpr DataType value = DataType::kComplexDouble; +}; + +} // namespace dnn +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DATA_TYPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_description.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_description.h new file mode 100644 index 0000000000000000000000000000000000000000..84653c070ec56f1599213d778e43f227b48207a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_description.h @@ -0,0 +1,549 @@ +/* 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. +==============================================================================*/ + +// Describes the underlying platform for a StreamExecutor; e.g. OpenCL or CUDA +// device and platform properties. Also contains convenience functions for +// checking/calculating launch dimensionality based on device properties. + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_DESCRIPTION_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_DESCRIPTION_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_join.h" +#include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { +namespace internal { +class DeviceDescriptionBuilder; +} // namespace internal + +// CUDA compute capability, as reported by the device description. +struct CudaComputeCapability { + int major = 0; + int minor = 0; + + // MSVC does not like "PASCAL" symbol. + enum CudaComputeCapabilities { + PASCAL_ = 6, + VOLTA = 7, + AMPERE = 8, + HOPPER = 9 + }; + + CudaComputeCapability() = default; + CudaComputeCapability(int major, int minor) { + this->major = major; + this->minor = minor; + } + + explicit CudaComputeCapability(const CudaComputeCapabilityProto &proto) { + this->major = proto.major(); + this->minor = proto.minor(); + } + + bool IsAtLeast(int other_major, int other_minor = 0) const { + return !(*this < CudaComputeCapability{other_major, other_minor}); + } + + bool operator<(const CudaComputeCapability &other) const { + return ToPair() < other.ToPair(); + } + + bool operator==(const CudaComputeCapability &other) const { + return ToPair() == other.ToPair(); + } + + bool operator!=(const CudaComputeCapability &other) const { + return !(*this == other); + } + + // Maximum resident blocks per multiprocessor, values taken from + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capabilities. + int GetMaxResidentBlocksPerSM() const { + if (IsAtLeast(8, 6)) { + return 16; + } else if (IsAtLeast(8)) { + return 32; + } else if (IsAtLeast(7, 5)) { + return 16; + } + return 32; + } + + // Maximum resident warps per multiprocessor, values taken from + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capabilities. + int GetMaxResidentWarpsPerSM() const { + if (IsAtLeast(8, 6)) { + return 48; + } else if (IsAtLeast(8)) { + return 64; + } else if (IsAtLeast(7, 5)) { + return 32; + } + return 64; + } + + std::string ToString() const { return absl::StrCat(major, ".", minor); } + + std::pair ToPair() const { return std::make_pair(major, minor); } + + CudaComputeCapabilityProto ToProto() const { + CudaComputeCapabilityProto proto; + proto.set_major(major); + proto.set_minor(minor); + return proto; + } +}; + +// ROCm compute capability, as reported by the device description. +class RocmComputeCapability { + public: + // gcn_arch_name example -- gfx90a:sramecc+:xnack- + // gfx_version is the "gfx90a" part of the gcn_arch_name + explicit RocmComputeCapability(const std::string &gcn_arch_name) + : gcn_arch_name_(gcn_arch_name) {} + + explicit RocmComputeCapability(const RocmComputeCapabilityProto &proto) + : gcn_arch_name_(proto.gcn_arch_name()) {} + + RocmComputeCapability() = default; + ~RocmComputeCapability() = default; + + std::string gcn_arch_name() const { return gcn_arch_name_; } + + std::string gfx_version() const { + std::vector tokens = absl::StrSplit(gcn_arch_name_, ':'); + return tokens[0]; + } + + bool is_supported_gfx_version() const { + return absl::c_count(kSupportedGfxVersions, gfx_version()) != 0; + } + + std::string supported_gfx_versions_str() const { + return absl::StrJoin(kSupportedGfxVersions, ", "); + } + + bool has_nhwc_layout_support() const { + static constexpr absl::string_view kList[] = {"gfx908", "gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_bf16_dtype_support() const { + static constexpr absl::string_view kList[] = {"gfx908", "gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_fast_fp16_support() const { + static constexpr absl::string_view kList[] = {"gfx906", "gfx908", "gfx90a", + "gfx1030"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_mfma_instr_support() const { + static constexpr absl::string_view kList[] = {"gfx908", "gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_fp16_atomics_support() const { + // TODO(rocm): Check. This should be the same as has_fast_fp16_support(). + static constexpr absl::string_view kList[] = {"gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + RocmComputeCapabilityProto ToProto() const { + RocmComputeCapabilityProto proto; + proto.set_gcn_arch_name(gcn_arch_name_); + return proto; + } + + bool operator==(const RocmComputeCapability &other) const { + return gcn_arch_name_ == other.gcn_arch_name_; + } + + private: + std::string gcn_arch_name_ = "gfx000"; // default to invalid arch. + + static constexpr absl::string_view kSupportedGfxVersions[]{ + "gfx900", // MI25 + "gfx906", // MI50 / MI60 + "gfx908", // MI100 + "gfx90a", // MI200 + "gfx1030" // Navi21 + }; +}; + +using GpuComputeCapability = + std::variant; + +// Data that describes the execution target of the StreamExecutor, in terms of +// important logical parameters. These include dimensionality limits and +// physical parameters of interest, such as number of cores present on the +// device. +// +// Thread-safe: immutable post-initialization. +class DeviceDescription { + public: + // Returns the platform being run on; this value is primarily intended for + // printing, and comes out something like "OpenCL 1.2" or "Compute Capability + // 3.5". + const std::string &platform_version() const { return platform_version_; } + + // Returns the driver version interfacing with the underlying platform. Vendor + // dependent format. + const std::string &driver_version() const { return driver_version_; } + + // Return the runtime version, if one is provided by the underlying platform. + // Vendor dependent format / usefulness. + const std::string &runtime_version() const { return runtime_version_; } + + // Returns the name that the device reports. Vendor dependent. + const std::string &name() const { return name_; } + + // Gets a human-readable description of the device, e.g. "nvidia GPU + // supporting sm75 with 32GB RAM, 80 SMs, ...". This is intended to be the + // same if and only if two devices are "the same" (e.g. the same make/model of + // GPU), though it may not completely succeed at this for all platforms. + // + // This string is not guaranteed to be stable between versions. Please DO NOT + // rely on it never changing. (Within one version of the code, it won't + // change, don't worry.) + const std::string &model_str() const { return model_str_; } + + // Returns the PCI bus identifier for this device, of the form + // [domain]:[bus]:[device].[function] + const std::string &pci_bus_id() const { return pci_bus_id_; } + + // Returns the NUMA node associated with this device, for use in + // determining socket locality. If the NUMA node could not be determined, -1 + // is returned. + int numa_node() const { return numa_node_; } + + // Number of cores (traditional notion of core; i.e. an SM on an NVIDIA device + // or an AMD Compute Unit. + int core_count() const { return core_count_; } + + // Number of floating point operations one core (SM, compute unit) can execute + // in parallel. Corresponds to the number of "CUDA cores" for NVIDIA devices. + int fpus_per_core() const { return fpus_per_core_; } + + // Returns the limit on the thread dimensionality values in each of the + // respective dimensions. These limits affect what constitutes a legitimate + // kernel launch request. + const ThreadDim &thread_dim_limit() const { return thread_dim_limit_; } + + // Returns the limit on the block dimensionality values in each of the + // respective dimensions. These limits may affect what constitutes a + // legitimate kernel launch request. + const BlockDim &block_dim_limit() const { return block_dim_limit_; } + + // Returns the limit on the total number of threads that can be launched in a + // single block; i.e. the limit on x * y * z dimensions of a ThreadDim. + // This limit affects what constitutes a legitimate kernel launch request. + const int64_t &threads_per_block_limit() const { + return threads_per_block_limit_; + } + + // Returns the limit on the total number of threads that can be simultaneously + // launched on a given multiprocessor. + const int64_t &threads_per_core_limit() const { + return threads_per_core_limit_; + } + + // Returns the number of threads per warp/wavefront. + const int64_t &threads_per_warp() const { return threads_per_warp_; } + + // Returns the limit on the total number of registers per core. + const int64_t ®isters_per_core_limit() const { + return registers_per_core_limit_; + } + + // Returns the limit on the total number of registers that can be + // simultaneously used by a block. + const int64_t ®isters_per_block_limit() const { + return registers_per_block_limit_; + } + + // Returns the number of address bits available to kernel code running on the + // platform. This affects things like the maximum allocation size and perhaps + // types used in kernel code such as size_t. + const int64_t &device_address_bits() const { return device_address_bits_; } + + // Returns the device memory size in bytes. + int64_t device_memory_size() const { return device_memory_size_; } + + // Returns the L2 cache size in bytes. + int64_t l2_cache_size() const { return l2_cache_size_; } + + // Returns the device's memory bandwidth in bytes/sec. (This is for + // reads/writes to/from the device's own memory, not for transfers between the + // host and device.) + int64_t memory_bandwidth() const { return memory_bandwidth_; } + + // Returns the device's core clock rate in GHz. + float clock_rate_ghz() const { return clock_rate_ghz_; } + + // Returns whether ECC is enabled. + bool ecc_enabled() const { return ecc_enabled_; } + + // Returns the device vendor string, e.g., "NVIDIA Corporation", "Advanced + // Micro Devices, Inc.", or "GenuineIntel". + const std::string &device_vendor() const { return device_vendor_; } + + // Returns the CUDA compute capability if we're running on the CUDA platform. + // If a CUDA compute capability is not available, the major version will be + // zero. + CudaComputeCapability cuda_compute_capability() const; + + // Returns the ROCm compute capability if we're running on the ROCm platform. + // If a ROCm compute capability is not available, the default gfx_arch will + // be "gfx000" (which is an invalid gfx arch). + RocmComputeCapability rocm_compute_capability() const; + + const GpuComputeCapability &gpu_compute_capability() const; + + // Returns the maximum amount of shared memory present on a single core + // (i.e. Streaming Multiprocessor on NVIDIA GPUs; Compute Unit for OpenCL + // devices). Note that some devices, such as NVIDIA's have a configurable + // partitioning between shared memory and L1 cache. + int64_t shared_memory_per_core() const { return shared_memory_per_core_; } + + // Returns the maximum amount of static shared memory + // available for a single block. + int64_t shared_memory_per_block() const { return shared_memory_per_block_; } + + // Returns the maximum amount of shared memory available for a single block + // including the dynamically allocated one. + int64_t shared_memory_per_block_optin() const { + return shared_memory_per_block_optin_; + } + + GpuDeviceInfoProto ToGpuProto() const; + explicit DeviceDescription(const GpuDeviceInfoProto &proto); + + // For string values that are not available via the underlying platform, this + // value will be provided. + static const char *kUndefinedString; + + private: + friend class internal::DeviceDescriptionBuilder; + + DeviceDescription(); + + // For description of the following members, see the corresponding accessor + // above. + // + // N.B. If another field is added, update ToMap() above. + std::string device_vendor_; + std::string platform_version_; + std::string driver_version_; + std::string runtime_version_; + std::string pci_bus_id_; + std::string name_; + std::string model_str_; + + ThreadDim thread_dim_limit_; + BlockDim block_dim_limit_; + + int64_t threads_per_core_limit_; + int64_t threads_per_block_limit_; + int64_t threads_per_warp_; + + int64_t registers_per_core_limit_; + int64_t registers_per_block_limit_; + + int64_t device_address_bits_; + int64_t device_memory_size_; + int64_t l2_cache_size_; + int64_t memory_bandwidth_; + + // Shared memory limits on a given device. + int64_t shared_memory_per_core_; + int64_t shared_memory_per_block_; + int64_t shared_memory_per_block_optin_; + + float clock_rate_ghz_; + + GpuComputeCapability gpu_compute_capability_; + + int numa_node_; + int core_count_; + int fpus_per_core_; + bool ecc_enabled_; +}; + +namespace internal { + +// Helper class the builds a device description, given that it has a large +// number of fields that would be easily confused in constructor form. +class DeviceDescriptionBuilder { + public: + DeviceDescriptionBuilder() = default; + + // For descriptions of the following fields, see comments on the corresponding + // DeviceDescription::* accessors above. + + void set_gpu_compute_capability(GpuComputeCapability c) { + device_description_.gpu_compute_capability_ = c; + } + + void set_block_dim_limit_x(int64_t limit) { + device_description_.block_dim_limit_.x = limit; + } + + void set_block_dim_limit_y(int64_t limit) { + device_description_.block_dim_limit_.y = limit; + } + + void set_block_dim_limit_z(int64_t limit) { + device_description_.block_dim_limit_.z = limit; + } + + void set_device_vendor(const std::string &value) { + device_description_.device_vendor_ = value; + } + void set_platform_version(const std::string &value) { + device_description_.platform_version_ = value; + } + void set_driver_version(const std::string &value) { + device_description_.driver_version_ = value; + } + void set_runtime_version(const std::string &value) { + device_description_.runtime_version_ = value; + } + void set_pci_bus_id(const std::string &value) { + device_description_.pci_bus_id_ = value; + } + void set_name(const std::string &value) { device_description_.name_ = value; } + void set_model_str(const std::string &value) { + device_description_.model_str_ = value; + } + + void set_thread_dim_limit(const ThreadDim &value) { + device_description_.thread_dim_limit_ = value; + } + void set_block_dim_limit(const BlockDim &value) { + device_description_.block_dim_limit_ = value; + } + + void set_threads_per_core_limit(int64_t value) { + device_description_.threads_per_core_limit_ = value; + } + void set_threads_per_block_limit(int64_t value) { + device_description_.threads_per_block_limit_ = value; + } + void set_threads_per_warp(int64_t value) { + device_description_.threads_per_warp_ = value; + } + + void set_registers_per_core_limit(int64_t value) { + device_description_.registers_per_core_limit_ = value; + } + void set_registers_per_block_limit(int64_t value) { + device_description_.registers_per_block_limit_ = value; + } + + void set_device_address_bits(int64_t value) { + device_description_.device_address_bits_ = value; + } + void set_device_memory_size(int64_t value) { + device_description_.device_memory_size_ = value; + } + void set_l2_cache_size(int64_t value) { + device_description_.l2_cache_size_ = value; + } + void set_memory_bandwidth(int64_t value) { + device_description_.memory_bandwidth_ = value; + } + + void set_shared_memory_per_core(int64_t value) { + device_description_.shared_memory_per_core_ = value; + } + void set_shared_memory_per_block(int64_t value) { + device_description_.shared_memory_per_block_ = value; + } + void set_shared_memory_per_block_optin(int64_t value) { + device_description_.shared_memory_per_block_optin_ = value; + } + + void set_clock_rate_ghz(float value) { + device_description_.clock_rate_ghz_ = value; + } + + void set_cuda_compute_capability(int major, int minor) { + device_description_.gpu_compute_capability_ = + CudaComputeCapability{major, minor}; + } + + void set_rocm_compute_capability(std::string gcn_arch_name) { + device_description_.gpu_compute_capability_ = + RocmComputeCapability(gcn_arch_name); + } + + void set_numa_node(int value) { device_description_.numa_node_ = value; } + void set_core_count(int value) { device_description_.core_count_ = value; } + void set_fpus_per_core(int value) { + device_description_.fpus_per_core_ = value; + } + void set_ecc_enabled(bool value) { device_description_.ecc_enabled_ = value; } + + // Returns a built DeviceDescription with ownership transferred to the + // caller. There are currently no restrictions on which fields must be set in + // order to build the descriptor. + // + // Once the description is built, this builder object should be discarded. + std::unique_ptr Build() { + return std::make_unique(device_description_); + } + + DeviceDescription BuildObject() { return device_description_; } + + private: + DeviceDescription device_description_; + + DeviceDescriptionBuilder(const DeviceDescriptionBuilder &) = delete; + void operator=(const DeviceDescriptionBuilder &) = delete; +}; + +} // namespace internal + +// Returns whether the given thread_dim is acceptable given the limits described +// in device_description. For detailed reasons for failing the predicate, enable +// VLOG(2) for this module. +bool ThreadDimOk(const DeviceDescription &device_description, + const ThreadDim &thread_dim); + +// Calculate the number of threads/blocks required to process element_count +// elements. Note that you can still end up with more threads than +// element_count due to rounding, so kernels often start with an "is this +// thread id in the element_count range?" test. +void CalculateDimensionality(const DeviceDescription &device_description, + int64_t element_count, int64_t *threads_per_block, + int64_t *block_count); + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_DESCRIPTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_description.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_description.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..c47979277859a746c7d10c130c8dba9de6ac07e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_description.pb.h @@ -0,0 +1,2164 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/stream_executor/device_description.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fstream_5fexecutor_2fdevice_5fdescription_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/autotune_results.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +namespace stream_executor { +class CudaComputeCapabilityProto; +struct CudaComputeCapabilityProtoDefaultTypeInternal; +extern CudaComputeCapabilityProtoDefaultTypeInternal _CudaComputeCapabilityProto_default_instance_; +class DnnVersionInfoProto; +struct DnnVersionInfoProtoDefaultTypeInternal; +extern DnnVersionInfoProtoDefaultTypeInternal _DnnVersionInfoProto_default_instance_; +class GpuDeviceInfoProto; +struct GpuDeviceInfoProtoDefaultTypeInternal; +extern GpuDeviceInfoProtoDefaultTypeInternal _GpuDeviceInfoProto_default_instance_; +class GpuTargetConfigProto; +struct GpuTargetConfigProtoDefaultTypeInternal; +extern GpuTargetConfigProtoDefaultTypeInternal _GpuTargetConfigProto_default_instance_; +class RocmComputeCapabilityProto; +struct RocmComputeCapabilityProtoDefaultTypeInternal; +extern RocmComputeCapabilityProtoDefaultTypeInternal _RocmComputeCapabilityProto_default_instance_; +} // namespace stream_executor +PROTOBUF_NAMESPACE_OPEN +template<> ::stream_executor::CudaComputeCapabilityProto* Arena::CreateMaybeMessage<::stream_executor::CudaComputeCapabilityProto>(Arena*); +template<> ::stream_executor::DnnVersionInfoProto* Arena::CreateMaybeMessage<::stream_executor::DnnVersionInfoProto>(Arena*); +template<> ::stream_executor::GpuDeviceInfoProto* Arena::CreateMaybeMessage<::stream_executor::GpuDeviceInfoProto>(Arena*); +template<> ::stream_executor::GpuTargetConfigProto* Arena::CreateMaybeMessage<::stream_executor::GpuTargetConfigProto>(Arena*); +template<> ::stream_executor::RocmComputeCapabilityProto* Arena::CreateMaybeMessage<::stream_executor::RocmComputeCapabilityProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace stream_executor { + +// =================================================================== + +class CudaComputeCapabilityProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.CudaComputeCapabilityProto) */ { + public: + inline CudaComputeCapabilityProto() : CudaComputeCapabilityProto(nullptr) {} + ~CudaComputeCapabilityProto() override; + explicit PROTOBUF_CONSTEXPR CudaComputeCapabilityProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CudaComputeCapabilityProto(const CudaComputeCapabilityProto& from); + CudaComputeCapabilityProto(CudaComputeCapabilityProto&& from) noexcept + : CudaComputeCapabilityProto() { + *this = ::std::move(from); + } + + inline CudaComputeCapabilityProto& operator=(const CudaComputeCapabilityProto& from) { + CopyFrom(from); + return *this; + } + inline CudaComputeCapabilityProto& operator=(CudaComputeCapabilityProto&& 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 CudaComputeCapabilityProto& default_instance() { + return *internal_default_instance(); + } + static inline const CudaComputeCapabilityProto* internal_default_instance() { + return reinterpret_cast( + &_CudaComputeCapabilityProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CudaComputeCapabilityProto& a, CudaComputeCapabilityProto& b) { + a.Swap(&b); + } + inline void Swap(CudaComputeCapabilityProto* 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(CudaComputeCapabilityProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CudaComputeCapabilityProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CudaComputeCapabilityProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CudaComputeCapabilityProto& from) { + CudaComputeCapabilityProto::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(CudaComputeCapabilityProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.CudaComputeCapabilityProto"; + } + protected: + explicit CudaComputeCapabilityProto(::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:stream_executor.CudaComputeCapabilityProto) + 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_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class RocmComputeCapabilityProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.RocmComputeCapabilityProto) */ { + public: + inline RocmComputeCapabilityProto() : RocmComputeCapabilityProto(nullptr) {} + ~RocmComputeCapabilityProto() override; + explicit PROTOBUF_CONSTEXPR RocmComputeCapabilityProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + RocmComputeCapabilityProto(const RocmComputeCapabilityProto& from); + RocmComputeCapabilityProto(RocmComputeCapabilityProto&& from) noexcept + : RocmComputeCapabilityProto() { + *this = ::std::move(from); + } + + inline RocmComputeCapabilityProto& operator=(const RocmComputeCapabilityProto& from) { + CopyFrom(from); + return *this; + } + inline RocmComputeCapabilityProto& operator=(RocmComputeCapabilityProto&& 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 RocmComputeCapabilityProto& default_instance() { + return *internal_default_instance(); + } + static inline const RocmComputeCapabilityProto* internal_default_instance() { + return reinterpret_cast( + &_RocmComputeCapabilityProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(RocmComputeCapabilityProto& a, RocmComputeCapabilityProto& b) { + a.Swap(&b); + } + inline void Swap(RocmComputeCapabilityProto* 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(RocmComputeCapabilityProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + RocmComputeCapabilityProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const RocmComputeCapabilityProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const RocmComputeCapabilityProto& from) { + RocmComputeCapabilityProto::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(RocmComputeCapabilityProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.RocmComputeCapabilityProto"; + } + protected: + explicit RocmComputeCapabilityProto(::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 { + kGcnArchNameFieldNumber = 1, + }; + // string gcn_arch_name = 1; + void clear_gcn_arch_name(); + const std::string& gcn_arch_name() const; + template + void set_gcn_arch_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_gcn_arch_name(); + PROTOBUF_NODISCARD std::string* release_gcn_arch_name(); + void set_allocated_gcn_arch_name(std::string* gcn_arch_name); + private: + const std::string& _internal_gcn_arch_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_gcn_arch_name(const std::string& value); + std::string* _internal_mutable_gcn_arch_name(); + public: + + // @@protoc_insertion_point(class_scope:stream_executor.RocmComputeCapabilityProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr gcn_arch_name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class GpuDeviceInfoProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.GpuDeviceInfoProto) */ { + public: + inline GpuDeviceInfoProto() : GpuDeviceInfoProto(nullptr) {} + ~GpuDeviceInfoProto() override; + explicit PROTOBUF_CONSTEXPR GpuDeviceInfoProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + GpuDeviceInfoProto(const GpuDeviceInfoProto& from); + GpuDeviceInfoProto(GpuDeviceInfoProto&& from) noexcept + : GpuDeviceInfoProto() { + *this = ::std::move(from); + } + + inline GpuDeviceInfoProto& operator=(const GpuDeviceInfoProto& from) { + CopyFrom(from); + return *this; + } + inline GpuDeviceInfoProto& operator=(GpuDeviceInfoProto&& 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 GpuDeviceInfoProto& default_instance() { + return *internal_default_instance(); + } + enum ComputeCapabilityCase { + kCudaComputeCapability = 16, + kRocmComputeCapability = 17, + COMPUTE_CAPABILITY_NOT_SET = 0, + }; + + static inline const GpuDeviceInfoProto* internal_default_instance() { + return reinterpret_cast( + &_GpuDeviceInfoProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(GpuDeviceInfoProto& a, GpuDeviceInfoProto& b) { + a.Swap(&b); + } + inline void Swap(GpuDeviceInfoProto* 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(GpuDeviceInfoProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + GpuDeviceInfoProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const GpuDeviceInfoProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const GpuDeviceInfoProto& from) { + GpuDeviceInfoProto::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(GpuDeviceInfoProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.GpuDeviceInfoProto"; + } + protected: + explicit GpuDeviceInfoProto(::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 { + kThreadsPerBlockLimitFieldNumber = 1, + kThreadsPerWarpFieldNumber = 2, + kSharedMemoryPerBlockFieldNumber = 3, + kSharedMemoryPerCoreFieldNumber = 4, + kThreadsPerCoreLimitFieldNumber = 5, + kCoreCountFieldNumber = 6, + kFpusPerCoreFieldNumber = 7, + kBlockDimLimitXFieldNumber = 8, + kBlockDimLimitYFieldNumber = 9, + kMemoryBandwidthFieldNumber = 11, + kBlockDimLimitZFieldNumber = 10, + kClockRateGhzFieldNumber = 13, + kL2CacheSizeFieldNumber = 12, + kDeviceMemorySizeFieldNumber = 14, + kSharedMemoryPerBlockOptinFieldNumber = 15, + kCudaComputeCapabilityFieldNumber = 16, + kRocmComputeCapabilityFieldNumber = 17, + }; + // int32 threads_per_block_limit = 1; + void clear_threads_per_block_limit(); + int32_t threads_per_block_limit() const; + void set_threads_per_block_limit(int32_t value); + private: + int32_t _internal_threads_per_block_limit() const; + void _internal_set_threads_per_block_limit(int32_t value); + public: + + // int32 threads_per_warp = 2; + void clear_threads_per_warp(); + int32_t threads_per_warp() const; + void set_threads_per_warp(int32_t value); + private: + int32_t _internal_threads_per_warp() const; + void _internal_set_threads_per_warp(int32_t value); + public: + + // int32 shared_memory_per_block = 3; + void clear_shared_memory_per_block(); + int32_t shared_memory_per_block() const; + void set_shared_memory_per_block(int32_t value); + private: + int32_t _internal_shared_memory_per_block() const; + void _internal_set_shared_memory_per_block(int32_t value); + public: + + // int32 shared_memory_per_core = 4; + void clear_shared_memory_per_core(); + int32_t shared_memory_per_core() const; + void set_shared_memory_per_core(int32_t value); + private: + int32_t _internal_shared_memory_per_core() const; + void _internal_set_shared_memory_per_core(int32_t value); + public: + + // int32 threads_per_core_limit = 5; + void clear_threads_per_core_limit(); + int32_t threads_per_core_limit() const; + void set_threads_per_core_limit(int32_t value); + private: + int32_t _internal_threads_per_core_limit() const; + void _internal_set_threads_per_core_limit(int32_t value); + public: + + // int32 core_count = 6; + void clear_core_count(); + int32_t core_count() const; + void set_core_count(int32_t value); + private: + int32_t _internal_core_count() const; + void _internal_set_core_count(int32_t value); + public: + + // int64 fpus_per_core = 7; + void clear_fpus_per_core(); + int64_t fpus_per_core() const; + void set_fpus_per_core(int64_t value); + private: + int64_t _internal_fpus_per_core() const; + void _internal_set_fpus_per_core(int64_t value); + public: + + // int32 block_dim_limit_x = 8; + void clear_block_dim_limit_x(); + int32_t block_dim_limit_x() const; + void set_block_dim_limit_x(int32_t value); + private: + int32_t _internal_block_dim_limit_x() const; + void _internal_set_block_dim_limit_x(int32_t value); + public: + + // int32 block_dim_limit_y = 9; + void clear_block_dim_limit_y(); + int32_t block_dim_limit_y() const; + void set_block_dim_limit_y(int32_t value); + private: + int32_t _internal_block_dim_limit_y() const; + void _internal_set_block_dim_limit_y(int32_t value); + public: + + // int64 memory_bandwidth = 11; + void clear_memory_bandwidth(); + int64_t memory_bandwidth() const; + void set_memory_bandwidth(int64_t value); + private: + int64_t _internal_memory_bandwidth() const; + void _internal_set_memory_bandwidth(int64_t value); + public: + + // int32 block_dim_limit_z = 10; + void clear_block_dim_limit_z(); + int32_t block_dim_limit_z() const; + void set_block_dim_limit_z(int32_t value); + private: + int32_t _internal_block_dim_limit_z() const; + void _internal_set_block_dim_limit_z(int32_t value); + public: + + // float clock_rate_ghz = 13; + void clear_clock_rate_ghz(); + float clock_rate_ghz() const; + void set_clock_rate_ghz(float value); + private: + float _internal_clock_rate_ghz() const; + void _internal_set_clock_rate_ghz(float value); + public: + + // int64 l2_cache_size = 12; + void clear_l2_cache_size(); + int64_t l2_cache_size() const; + void set_l2_cache_size(int64_t value); + private: + int64_t _internal_l2_cache_size() const; + void _internal_set_l2_cache_size(int64_t value); + public: + + // int64 device_memory_size = 14; + void clear_device_memory_size(); + int64_t device_memory_size() const; + void set_device_memory_size(int64_t value); + private: + int64_t _internal_device_memory_size() const; + void _internal_set_device_memory_size(int64_t value); + public: + + // int32 shared_memory_per_block_optin = 15; + void clear_shared_memory_per_block_optin(); + int32_t shared_memory_per_block_optin() const; + void set_shared_memory_per_block_optin(int32_t value); + private: + int32_t _internal_shared_memory_per_block_optin() const; + void _internal_set_shared_memory_per_block_optin(int32_t value); + public: + + // .stream_executor.CudaComputeCapabilityProto cuda_compute_capability = 16; + bool has_cuda_compute_capability() const; + private: + bool _internal_has_cuda_compute_capability() const; + public: + void clear_cuda_compute_capability(); + const ::stream_executor::CudaComputeCapabilityProto& cuda_compute_capability() const; + PROTOBUF_NODISCARD ::stream_executor::CudaComputeCapabilityProto* release_cuda_compute_capability(); + ::stream_executor::CudaComputeCapabilityProto* mutable_cuda_compute_capability(); + void set_allocated_cuda_compute_capability(::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability); + private: + const ::stream_executor::CudaComputeCapabilityProto& _internal_cuda_compute_capability() const; + ::stream_executor::CudaComputeCapabilityProto* _internal_mutable_cuda_compute_capability(); + public: + void unsafe_arena_set_allocated_cuda_compute_capability( + ::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability); + ::stream_executor::CudaComputeCapabilityProto* unsafe_arena_release_cuda_compute_capability(); + + // .stream_executor.RocmComputeCapabilityProto rocm_compute_capability = 17; + bool has_rocm_compute_capability() const; + private: + bool _internal_has_rocm_compute_capability() const; + public: + void clear_rocm_compute_capability(); + const ::stream_executor::RocmComputeCapabilityProto& rocm_compute_capability() const; + PROTOBUF_NODISCARD ::stream_executor::RocmComputeCapabilityProto* release_rocm_compute_capability(); + ::stream_executor::RocmComputeCapabilityProto* mutable_rocm_compute_capability(); + void set_allocated_rocm_compute_capability(::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability); + private: + const ::stream_executor::RocmComputeCapabilityProto& _internal_rocm_compute_capability() const; + ::stream_executor::RocmComputeCapabilityProto* _internal_mutable_rocm_compute_capability(); + public: + void unsafe_arena_set_allocated_rocm_compute_capability( + ::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability); + ::stream_executor::RocmComputeCapabilityProto* unsafe_arena_release_rocm_compute_capability(); + + void clear_compute_capability(); + ComputeCapabilityCase compute_capability_case() const; + // @@protoc_insertion_point(class_scope:stream_executor.GpuDeviceInfoProto) + private: + class _Internal; + void set_has_cuda_compute_capability(); + void set_has_rocm_compute_capability(); + + inline bool has_compute_capability() const; + inline void clear_has_compute_capability(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t threads_per_block_limit_; + int32_t threads_per_warp_; + int32_t shared_memory_per_block_; + int32_t shared_memory_per_core_; + int32_t threads_per_core_limit_; + int32_t core_count_; + int64_t fpus_per_core_; + int32_t block_dim_limit_x_; + int32_t block_dim_limit_y_; + int64_t memory_bandwidth_; + int32_t block_dim_limit_z_; + float clock_rate_ghz_; + int64_t l2_cache_size_; + int64_t device_memory_size_; + int32_t shared_memory_per_block_optin_; + union ComputeCapabilityUnion { + constexpr ComputeCapabilityUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability_; + ::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability_; + } compute_capability_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class DnnVersionInfoProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.DnnVersionInfoProto) */ { + public: + inline DnnVersionInfoProto() : DnnVersionInfoProto(nullptr) {} + ~DnnVersionInfoProto() override; + explicit PROTOBUF_CONSTEXPR DnnVersionInfoProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DnnVersionInfoProto(const DnnVersionInfoProto& from); + DnnVersionInfoProto(DnnVersionInfoProto&& from) noexcept + : DnnVersionInfoProto() { + *this = ::std::move(from); + } + + inline DnnVersionInfoProto& operator=(const DnnVersionInfoProto& from) { + CopyFrom(from); + return *this; + } + inline DnnVersionInfoProto& operator=(DnnVersionInfoProto&& 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 DnnVersionInfoProto& default_instance() { + return *internal_default_instance(); + } + static inline const DnnVersionInfoProto* internal_default_instance() { + return reinterpret_cast( + &_DnnVersionInfoProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(DnnVersionInfoProto& a, DnnVersionInfoProto& b) { + a.Swap(&b); + } + inline void Swap(DnnVersionInfoProto* 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(DnnVersionInfoProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DnnVersionInfoProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DnnVersionInfoProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DnnVersionInfoProto& from) { + DnnVersionInfoProto::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(DnnVersionInfoProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.DnnVersionInfoProto"; + } + protected: + explicit DnnVersionInfoProto(::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:stream_executor.DnnVersionInfoProto) + 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_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class GpuTargetConfigProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.GpuTargetConfigProto) */ { + public: + inline GpuTargetConfigProto() : GpuTargetConfigProto(nullptr) {} + ~GpuTargetConfigProto() override; + explicit PROTOBUF_CONSTEXPR GpuTargetConfigProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + GpuTargetConfigProto(const GpuTargetConfigProto& from); + GpuTargetConfigProto(GpuTargetConfigProto&& from) noexcept + : GpuTargetConfigProto() { + *this = ::std::move(from); + } + + inline GpuTargetConfigProto& operator=(const GpuTargetConfigProto& from) { + CopyFrom(from); + return *this; + } + inline GpuTargetConfigProto& operator=(GpuTargetConfigProto&& 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 GpuTargetConfigProto& default_instance() { + return *internal_default_instance(); + } + static inline const GpuTargetConfigProto* internal_default_instance() { + return reinterpret_cast( + &_GpuTargetConfigProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(GpuTargetConfigProto& a, GpuTargetConfigProto& b) { + a.Swap(&b); + } + inline void Swap(GpuTargetConfigProto* 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(GpuTargetConfigProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + GpuTargetConfigProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const GpuTargetConfigProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const GpuTargetConfigProto& from) { + GpuTargetConfigProto::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(GpuTargetConfigProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.GpuTargetConfigProto"; + } + protected: + explicit GpuTargetConfigProto(::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 { + kPlatformNameFieldNumber = 4, + kDeviceDescriptionStrFieldNumber = 7, + kGpuDeviceInfoFieldNumber = 1, + kDnnVersionInfoFieldNumber = 5, + kAutotuneResultsFieldNumber = 6, + }; + // string platform_name = 4; + void clear_platform_name(); + const std::string& platform_name() const; + template + void set_platform_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_platform_name(); + PROTOBUF_NODISCARD std::string* release_platform_name(); + void set_allocated_platform_name(std::string* platform_name); + private: + const std::string& _internal_platform_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_platform_name(const std::string& value); + std::string* _internal_mutable_platform_name(); + public: + + // string device_description_str = 7; + void clear_device_description_str(); + const std::string& device_description_str() const; + template + void set_device_description_str(ArgT0&& arg0, ArgT... args); + std::string* mutable_device_description_str(); + PROTOBUF_NODISCARD std::string* release_device_description_str(); + void set_allocated_device_description_str(std::string* device_description_str); + private: + const std::string& _internal_device_description_str() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device_description_str(const std::string& value); + std::string* _internal_mutable_device_description_str(); + public: + + // .stream_executor.GpuDeviceInfoProto gpu_device_info = 1; + bool has_gpu_device_info() const; + private: + bool _internal_has_gpu_device_info() const; + public: + void clear_gpu_device_info(); + const ::stream_executor::GpuDeviceInfoProto& gpu_device_info() const; + PROTOBUF_NODISCARD ::stream_executor::GpuDeviceInfoProto* release_gpu_device_info(); + ::stream_executor::GpuDeviceInfoProto* mutable_gpu_device_info(); + void set_allocated_gpu_device_info(::stream_executor::GpuDeviceInfoProto* gpu_device_info); + private: + const ::stream_executor::GpuDeviceInfoProto& _internal_gpu_device_info() const; + ::stream_executor::GpuDeviceInfoProto* _internal_mutable_gpu_device_info(); + public: + void unsafe_arena_set_allocated_gpu_device_info( + ::stream_executor::GpuDeviceInfoProto* gpu_device_info); + ::stream_executor::GpuDeviceInfoProto* unsafe_arena_release_gpu_device_info(); + + // .stream_executor.DnnVersionInfoProto dnn_version_info = 5; + bool has_dnn_version_info() const; + private: + bool _internal_has_dnn_version_info() const; + public: + void clear_dnn_version_info(); + const ::stream_executor::DnnVersionInfoProto& dnn_version_info() const; + PROTOBUF_NODISCARD ::stream_executor::DnnVersionInfoProto* release_dnn_version_info(); + ::stream_executor::DnnVersionInfoProto* mutable_dnn_version_info(); + void set_allocated_dnn_version_info(::stream_executor::DnnVersionInfoProto* dnn_version_info); + private: + const ::stream_executor::DnnVersionInfoProto& _internal_dnn_version_info() const; + ::stream_executor::DnnVersionInfoProto* _internal_mutable_dnn_version_info(); + public: + void unsafe_arena_set_allocated_dnn_version_info( + ::stream_executor::DnnVersionInfoProto* dnn_version_info); + ::stream_executor::DnnVersionInfoProto* unsafe_arena_release_dnn_version_info(); + + // .xla.AutotuneResults autotune_results = 6; + bool has_autotune_results() const; + private: + bool _internal_has_autotune_results() const; + public: + void clear_autotune_results(); + const ::xla::AutotuneResults& autotune_results() const; + PROTOBUF_NODISCARD ::xla::AutotuneResults* release_autotune_results(); + ::xla::AutotuneResults* mutable_autotune_results(); + void set_allocated_autotune_results(::xla::AutotuneResults* autotune_results); + private: + const ::xla::AutotuneResults& _internal_autotune_results() const; + ::xla::AutotuneResults* _internal_mutable_autotune_results(); + public: + void unsafe_arena_set_allocated_autotune_results( + ::xla::AutotuneResults* autotune_results); + ::xla::AutotuneResults* unsafe_arena_release_autotune_results(); + + // @@protoc_insertion_point(class_scope:stream_executor.GpuTargetConfigProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr platform_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_description_str_; + ::stream_executor::GpuDeviceInfoProto* gpu_device_info_; + ::stream_executor::DnnVersionInfoProto* dnn_version_info_; + ::xla::AutotuneResults* autotune_results_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CudaComputeCapabilityProto + +// int32 major = 1; +inline void CudaComputeCapabilityProto::clear_major() { + _impl_.major_ = 0; +} +inline int32_t CudaComputeCapabilityProto::_internal_major() const { + return _impl_.major_; +} +inline int32_t CudaComputeCapabilityProto::major() const { + // @@protoc_insertion_point(field_get:stream_executor.CudaComputeCapabilityProto.major) + return _internal_major(); +} +inline void CudaComputeCapabilityProto::_internal_set_major(int32_t value) { + + _impl_.major_ = value; +} +inline void CudaComputeCapabilityProto::set_major(int32_t value) { + _internal_set_major(value); + // @@protoc_insertion_point(field_set:stream_executor.CudaComputeCapabilityProto.major) +} + +// int32 minor = 2; +inline void CudaComputeCapabilityProto::clear_minor() { + _impl_.minor_ = 0; +} +inline int32_t CudaComputeCapabilityProto::_internal_minor() const { + return _impl_.minor_; +} +inline int32_t CudaComputeCapabilityProto::minor() const { + // @@protoc_insertion_point(field_get:stream_executor.CudaComputeCapabilityProto.minor) + return _internal_minor(); +} +inline void CudaComputeCapabilityProto::_internal_set_minor(int32_t value) { + + _impl_.minor_ = value; +} +inline void CudaComputeCapabilityProto::set_minor(int32_t value) { + _internal_set_minor(value); + // @@protoc_insertion_point(field_set:stream_executor.CudaComputeCapabilityProto.minor) +} + +// ------------------------------------------------------------------- + +// RocmComputeCapabilityProto + +// string gcn_arch_name = 1; +inline void RocmComputeCapabilityProto::clear_gcn_arch_name() { + _impl_.gcn_arch_name_.ClearToEmpty(); +} +inline const std::string& RocmComputeCapabilityProto::gcn_arch_name() const { + // @@protoc_insertion_point(field_get:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) + return _internal_gcn_arch_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void RocmComputeCapabilityProto::set_gcn_arch_name(ArgT0&& arg0, ArgT... args) { + + _impl_.gcn_arch_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) +} +inline std::string* RocmComputeCapabilityProto::mutable_gcn_arch_name() { + std::string* _s = _internal_mutable_gcn_arch_name(); + // @@protoc_insertion_point(field_mutable:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) + return _s; +} +inline const std::string& RocmComputeCapabilityProto::_internal_gcn_arch_name() const { + return _impl_.gcn_arch_name_.Get(); +} +inline void RocmComputeCapabilityProto::_internal_set_gcn_arch_name(const std::string& value) { + + _impl_.gcn_arch_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* RocmComputeCapabilityProto::_internal_mutable_gcn_arch_name() { + + return _impl_.gcn_arch_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* RocmComputeCapabilityProto::release_gcn_arch_name() { + // @@protoc_insertion_point(field_release:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) + return _impl_.gcn_arch_name_.Release(); +} +inline void RocmComputeCapabilityProto::set_allocated_gcn_arch_name(std::string* gcn_arch_name) { + if (gcn_arch_name != nullptr) { + + } else { + + } + _impl_.gcn_arch_name_.SetAllocated(gcn_arch_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.gcn_arch_name_.IsDefault()) { + _impl_.gcn_arch_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) +} + +// ------------------------------------------------------------------- + +// GpuDeviceInfoProto + +// int32 threads_per_block_limit = 1; +inline void GpuDeviceInfoProto::clear_threads_per_block_limit() { + _impl_.threads_per_block_limit_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_threads_per_block_limit() const { + return _impl_.threads_per_block_limit_; +} +inline int32_t GpuDeviceInfoProto::threads_per_block_limit() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.threads_per_block_limit) + return _internal_threads_per_block_limit(); +} +inline void GpuDeviceInfoProto::_internal_set_threads_per_block_limit(int32_t value) { + + _impl_.threads_per_block_limit_ = value; +} +inline void GpuDeviceInfoProto::set_threads_per_block_limit(int32_t value) { + _internal_set_threads_per_block_limit(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.threads_per_block_limit) +} + +// int32 threads_per_warp = 2; +inline void GpuDeviceInfoProto::clear_threads_per_warp() { + _impl_.threads_per_warp_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_threads_per_warp() const { + return _impl_.threads_per_warp_; +} +inline int32_t GpuDeviceInfoProto::threads_per_warp() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.threads_per_warp) + return _internal_threads_per_warp(); +} +inline void GpuDeviceInfoProto::_internal_set_threads_per_warp(int32_t value) { + + _impl_.threads_per_warp_ = value; +} +inline void GpuDeviceInfoProto::set_threads_per_warp(int32_t value) { + _internal_set_threads_per_warp(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.threads_per_warp) +} + +// int32 shared_memory_per_block = 3; +inline void GpuDeviceInfoProto::clear_shared_memory_per_block() { + _impl_.shared_memory_per_block_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_shared_memory_per_block() const { + return _impl_.shared_memory_per_block_; +} +inline int32_t GpuDeviceInfoProto::shared_memory_per_block() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.shared_memory_per_block) + return _internal_shared_memory_per_block(); +} +inline void GpuDeviceInfoProto::_internal_set_shared_memory_per_block(int32_t value) { + + _impl_.shared_memory_per_block_ = value; +} +inline void GpuDeviceInfoProto::set_shared_memory_per_block(int32_t value) { + _internal_set_shared_memory_per_block(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.shared_memory_per_block) +} + +// int32 shared_memory_per_core = 4; +inline void GpuDeviceInfoProto::clear_shared_memory_per_core() { + _impl_.shared_memory_per_core_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_shared_memory_per_core() const { + return _impl_.shared_memory_per_core_; +} +inline int32_t GpuDeviceInfoProto::shared_memory_per_core() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.shared_memory_per_core) + return _internal_shared_memory_per_core(); +} +inline void GpuDeviceInfoProto::_internal_set_shared_memory_per_core(int32_t value) { + + _impl_.shared_memory_per_core_ = value; +} +inline void GpuDeviceInfoProto::set_shared_memory_per_core(int32_t value) { + _internal_set_shared_memory_per_core(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.shared_memory_per_core) +} + +// int32 threads_per_core_limit = 5; +inline void GpuDeviceInfoProto::clear_threads_per_core_limit() { + _impl_.threads_per_core_limit_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_threads_per_core_limit() const { + return _impl_.threads_per_core_limit_; +} +inline int32_t GpuDeviceInfoProto::threads_per_core_limit() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.threads_per_core_limit) + return _internal_threads_per_core_limit(); +} +inline void GpuDeviceInfoProto::_internal_set_threads_per_core_limit(int32_t value) { + + _impl_.threads_per_core_limit_ = value; +} +inline void GpuDeviceInfoProto::set_threads_per_core_limit(int32_t value) { + _internal_set_threads_per_core_limit(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.threads_per_core_limit) +} + +// int32 core_count = 6; +inline void GpuDeviceInfoProto::clear_core_count() { + _impl_.core_count_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_core_count() const { + return _impl_.core_count_; +} +inline int32_t GpuDeviceInfoProto::core_count() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.core_count) + return _internal_core_count(); +} +inline void GpuDeviceInfoProto::_internal_set_core_count(int32_t value) { + + _impl_.core_count_ = value; +} +inline void GpuDeviceInfoProto::set_core_count(int32_t value) { + _internal_set_core_count(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.core_count) +} + +// int64 fpus_per_core = 7; +inline void GpuDeviceInfoProto::clear_fpus_per_core() { + _impl_.fpus_per_core_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_fpus_per_core() const { + return _impl_.fpus_per_core_; +} +inline int64_t GpuDeviceInfoProto::fpus_per_core() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.fpus_per_core) + return _internal_fpus_per_core(); +} +inline void GpuDeviceInfoProto::_internal_set_fpus_per_core(int64_t value) { + + _impl_.fpus_per_core_ = value; +} +inline void GpuDeviceInfoProto::set_fpus_per_core(int64_t value) { + _internal_set_fpus_per_core(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.fpus_per_core) +} + +// int32 block_dim_limit_x = 8; +inline void GpuDeviceInfoProto::clear_block_dim_limit_x() { + _impl_.block_dim_limit_x_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_block_dim_limit_x() const { + return _impl_.block_dim_limit_x_; +} +inline int32_t GpuDeviceInfoProto::block_dim_limit_x() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.block_dim_limit_x) + return _internal_block_dim_limit_x(); +} +inline void GpuDeviceInfoProto::_internal_set_block_dim_limit_x(int32_t value) { + + _impl_.block_dim_limit_x_ = value; +} +inline void GpuDeviceInfoProto::set_block_dim_limit_x(int32_t value) { + _internal_set_block_dim_limit_x(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.block_dim_limit_x) +} + +// int32 block_dim_limit_y = 9; +inline void GpuDeviceInfoProto::clear_block_dim_limit_y() { + _impl_.block_dim_limit_y_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_block_dim_limit_y() const { + return _impl_.block_dim_limit_y_; +} +inline int32_t GpuDeviceInfoProto::block_dim_limit_y() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.block_dim_limit_y) + return _internal_block_dim_limit_y(); +} +inline void GpuDeviceInfoProto::_internal_set_block_dim_limit_y(int32_t value) { + + _impl_.block_dim_limit_y_ = value; +} +inline void GpuDeviceInfoProto::set_block_dim_limit_y(int32_t value) { + _internal_set_block_dim_limit_y(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.block_dim_limit_y) +} + +// int32 block_dim_limit_z = 10; +inline void GpuDeviceInfoProto::clear_block_dim_limit_z() { + _impl_.block_dim_limit_z_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_block_dim_limit_z() const { + return _impl_.block_dim_limit_z_; +} +inline int32_t GpuDeviceInfoProto::block_dim_limit_z() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.block_dim_limit_z) + return _internal_block_dim_limit_z(); +} +inline void GpuDeviceInfoProto::_internal_set_block_dim_limit_z(int32_t value) { + + _impl_.block_dim_limit_z_ = value; +} +inline void GpuDeviceInfoProto::set_block_dim_limit_z(int32_t value) { + _internal_set_block_dim_limit_z(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.block_dim_limit_z) +} + +// int64 memory_bandwidth = 11; +inline void GpuDeviceInfoProto::clear_memory_bandwidth() { + _impl_.memory_bandwidth_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_memory_bandwidth() const { + return _impl_.memory_bandwidth_; +} +inline int64_t GpuDeviceInfoProto::memory_bandwidth() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.memory_bandwidth) + return _internal_memory_bandwidth(); +} +inline void GpuDeviceInfoProto::_internal_set_memory_bandwidth(int64_t value) { + + _impl_.memory_bandwidth_ = value; +} +inline void GpuDeviceInfoProto::set_memory_bandwidth(int64_t value) { + _internal_set_memory_bandwidth(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.memory_bandwidth) +} + +// int64 l2_cache_size = 12; +inline void GpuDeviceInfoProto::clear_l2_cache_size() { + _impl_.l2_cache_size_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_l2_cache_size() const { + return _impl_.l2_cache_size_; +} +inline int64_t GpuDeviceInfoProto::l2_cache_size() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.l2_cache_size) + return _internal_l2_cache_size(); +} +inline void GpuDeviceInfoProto::_internal_set_l2_cache_size(int64_t value) { + + _impl_.l2_cache_size_ = value; +} +inline void GpuDeviceInfoProto::set_l2_cache_size(int64_t value) { + _internal_set_l2_cache_size(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.l2_cache_size) +} + +// float clock_rate_ghz = 13; +inline void GpuDeviceInfoProto::clear_clock_rate_ghz() { + _impl_.clock_rate_ghz_ = 0; +} +inline float GpuDeviceInfoProto::_internal_clock_rate_ghz() const { + return _impl_.clock_rate_ghz_; +} +inline float GpuDeviceInfoProto::clock_rate_ghz() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.clock_rate_ghz) + return _internal_clock_rate_ghz(); +} +inline void GpuDeviceInfoProto::_internal_set_clock_rate_ghz(float value) { + + _impl_.clock_rate_ghz_ = value; +} +inline void GpuDeviceInfoProto::set_clock_rate_ghz(float value) { + _internal_set_clock_rate_ghz(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.clock_rate_ghz) +} + +// int64 device_memory_size = 14; +inline void GpuDeviceInfoProto::clear_device_memory_size() { + _impl_.device_memory_size_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_device_memory_size() const { + return _impl_.device_memory_size_; +} +inline int64_t GpuDeviceInfoProto::device_memory_size() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.device_memory_size) + return _internal_device_memory_size(); +} +inline void GpuDeviceInfoProto::_internal_set_device_memory_size(int64_t value) { + + _impl_.device_memory_size_ = value; +} +inline void GpuDeviceInfoProto::set_device_memory_size(int64_t value) { + _internal_set_device_memory_size(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.device_memory_size) +} + +// int32 shared_memory_per_block_optin = 15; +inline void GpuDeviceInfoProto::clear_shared_memory_per_block_optin() { + _impl_.shared_memory_per_block_optin_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_shared_memory_per_block_optin() const { + return _impl_.shared_memory_per_block_optin_; +} +inline int32_t GpuDeviceInfoProto::shared_memory_per_block_optin() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.shared_memory_per_block_optin) + return _internal_shared_memory_per_block_optin(); +} +inline void GpuDeviceInfoProto::_internal_set_shared_memory_per_block_optin(int32_t value) { + + _impl_.shared_memory_per_block_optin_ = value; +} +inline void GpuDeviceInfoProto::set_shared_memory_per_block_optin(int32_t value) { + _internal_set_shared_memory_per_block_optin(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.shared_memory_per_block_optin) +} + +// .stream_executor.CudaComputeCapabilityProto cuda_compute_capability = 16; +inline bool GpuDeviceInfoProto::_internal_has_cuda_compute_capability() const { + return compute_capability_case() == kCudaComputeCapability; +} +inline bool GpuDeviceInfoProto::has_cuda_compute_capability() const { + return _internal_has_cuda_compute_capability(); +} +inline void GpuDeviceInfoProto::set_has_cuda_compute_capability() { + _impl_._oneof_case_[0] = kCudaComputeCapability; +} +inline void GpuDeviceInfoProto::clear_cuda_compute_capability() { + if (_internal_has_cuda_compute_capability()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.compute_capability_.cuda_compute_capability_; + } + clear_has_compute_capability(); + } +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::release_cuda_compute_capability() { + // @@protoc_insertion_point(field_release:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + if (_internal_has_cuda_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::CudaComputeCapabilityProto* temp = _impl_.compute_capability_.cuda_compute_capability_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.compute_capability_.cuda_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::stream_executor::CudaComputeCapabilityProto& GpuDeviceInfoProto::_internal_cuda_compute_capability() const { + return _internal_has_cuda_compute_capability() + ? *_impl_.compute_capability_.cuda_compute_capability_ + : reinterpret_cast< ::stream_executor::CudaComputeCapabilityProto&>(::stream_executor::_CudaComputeCapabilityProto_default_instance_); +} +inline const ::stream_executor::CudaComputeCapabilityProto& GpuDeviceInfoProto::cuda_compute_capability() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + return _internal_cuda_compute_capability(); +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::unsafe_arena_release_cuda_compute_capability() { + // @@protoc_insertion_point(field_unsafe_arena_release:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + if (_internal_has_cuda_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::CudaComputeCapabilityProto* temp = _impl_.compute_capability_.cuda_compute_capability_; + _impl_.compute_capability_.cuda_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void GpuDeviceInfoProto::unsafe_arena_set_allocated_cuda_compute_capability(::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability) { + clear_compute_capability(); + if (cuda_compute_capability) { + set_has_cuda_compute_capability(); + _impl_.compute_capability_.cuda_compute_capability_ = cuda_compute_capability; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::_internal_mutable_cuda_compute_capability() { + if (!_internal_has_cuda_compute_capability()) { + clear_compute_capability(); + set_has_cuda_compute_capability(); + _impl_.compute_capability_.cuda_compute_capability_ = CreateMaybeMessage< ::stream_executor::CudaComputeCapabilityProto >(GetArenaForAllocation()); + } + return _impl_.compute_capability_.cuda_compute_capability_; +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::mutable_cuda_compute_capability() { + ::stream_executor::CudaComputeCapabilityProto* _msg = _internal_mutable_cuda_compute_capability(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + return _msg; +} + +// .stream_executor.RocmComputeCapabilityProto rocm_compute_capability = 17; +inline bool GpuDeviceInfoProto::_internal_has_rocm_compute_capability() const { + return compute_capability_case() == kRocmComputeCapability; +} +inline bool GpuDeviceInfoProto::has_rocm_compute_capability() const { + return _internal_has_rocm_compute_capability(); +} +inline void GpuDeviceInfoProto::set_has_rocm_compute_capability() { + _impl_._oneof_case_[0] = kRocmComputeCapability; +} +inline void GpuDeviceInfoProto::clear_rocm_compute_capability() { + if (_internal_has_rocm_compute_capability()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.compute_capability_.rocm_compute_capability_; + } + clear_has_compute_capability(); + } +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::release_rocm_compute_capability() { + // @@protoc_insertion_point(field_release:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + if (_internal_has_rocm_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::RocmComputeCapabilityProto* temp = _impl_.compute_capability_.rocm_compute_capability_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.compute_capability_.rocm_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::stream_executor::RocmComputeCapabilityProto& GpuDeviceInfoProto::_internal_rocm_compute_capability() const { + return _internal_has_rocm_compute_capability() + ? *_impl_.compute_capability_.rocm_compute_capability_ + : reinterpret_cast< ::stream_executor::RocmComputeCapabilityProto&>(::stream_executor::_RocmComputeCapabilityProto_default_instance_); +} +inline const ::stream_executor::RocmComputeCapabilityProto& GpuDeviceInfoProto::rocm_compute_capability() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + return _internal_rocm_compute_capability(); +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::unsafe_arena_release_rocm_compute_capability() { + // @@protoc_insertion_point(field_unsafe_arena_release:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + if (_internal_has_rocm_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::RocmComputeCapabilityProto* temp = _impl_.compute_capability_.rocm_compute_capability_; + _impl_.compute_capability_.rocm_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void GpuDeviceInfoProto::unsafe_arena_set_allocated_rocm_compute_capability(::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability) { + clear_compute_capability(); + if (rocm_compute_capability) { + set_has_rocm_compute_capability(); + _impl_.compute_capability_.rocm_compute_capability_ = rocm_compute_capability; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::_internal_mutable_rocm_compute_capability() { + if (!_internal_has_rocm_compute_capability()) { + clear_compute_capability(); + set_has_rocm_compute_capability(); + _impl_.compute_capability_.rocm_compute_capability_ = CreateMaybeMessage< ::stream_executor::RocmComputeCapabilityProto >(GetArenaForAllocation()); + } + return _impl_.compute_capability_.rocm_compute_capability_; +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::mutable_rocm_compute_capability() { + ::stream_executor::RocmComputeCapabilityProto* _msg = _internal_mutable_rocm_compute_capability(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + return _msg; +} + +inline bool GpuDeviceInfoProto::has_compute_capability() const { + return compute_capability_case() != COMPUTE_CAPABILITY_NOT_SET; +} +inline void GpuDeviceInfoProto::clear_has_compute_capability() { + _impl_._oneof_case_[0] = COMPUTE_CAPABILITY_NOT_SET; +} +inline GpuDeviceInfoProto::ComputeCapabilityCase GpuDeviceInfoProto::compute_capability_case() const { + return GpuDeviceInfoProto::ComputeCapabilityCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// DnnVersionInfoProto + +// int32 major = 1; +inline void DnnVersionInfoProto::clear_major() { + _impl_.major_ = 0; +} +inline int32_t DnnVersionInfoProto::_internal_major() const { + return _impl_.major_; +} +inline int32_t DnnVersionInfoProto::major() const { + // @@protoc_insertion_point(field_get:stream_executor.DnnVersionInfoProto.major) + return _internal_major(); +} +inline void DnnVersionInfoProto::_internal_set_major(int32_t value) { + + _impl_.major_ = value; +} +inline void DnnVersionInfoProto::set_major(int32_t value) { + _internal_set_major(value); + // @@protoc_insertion_point(field_set:stream_executor.DnnVersionInfoProto.major) +} + +// int32 minor = 2; +inline void DnnVersionInfoProto::clear_minor() { + _impl_.minor_ = 0; +} +inline int32_t DnnVersionInfoProto::_internal_minor() const { + return _impl_.minor_; +} +inline int32_t DnnVersionInfoProto::minor() const { + // @@protoc_insertion_point(field_get:stream_executor.DnnVersionInfoProto.minor) + return _internal_minor(); +} +inline void DnnVersionInfoProto::_internal_set_minor(int32_t value) { + + _impl_.minor_ = value; +} +inline void DnnVersionInfoProto::set_minor(int32_t value) { + _internal_set_minor(value); + // @@protoc_insertion_point(field_set:stream_executor.DnnVersionInfoProto.minor) +} + +// int32 patch = 3; +inline void DnnVersionInfoProto::clear_patch() { + _impl_.patch_ = 0; +} +inline int32_t DnnVersionInfoProto::_internal_patch() const { + return _impl_.patch_; +} +inline int32_t DnnVersionInfoProto::patch() const { + // @@protoc_insertion_point(field_get:stream_executor.DnnVersionInfoProto.patch) + return _internal_patch(); +} +inline void DnnVersionInfoProto::_internal_set_patch(int32_t value) { + + _impl_.patch_ = value; +} +inline void DnnVersionInfoProto::set_patch(int32_t value) { + _internal_set_patch(value); + // @@protoc_insertion_point(field_set:stream_executor.DnnVersionInfoProto.patch) +} + +// ------------------------------------------------------------------- + +// GpuTargetConfigProto + +// .stream_executor.GpuDeviceInfoProto gpu_device_info = 1; +inline bool GpuTargetConfigProto::_internal_has_gpu_device_info() const { + return this != internal_default_instance() && _impl_.gpu_device_info_ != nullptr; +} +inline bool GpuTargetConfigProto::has_gpu_device_info() const { + return _internal_has_gpu_device_info(); +} +inline void GpuTargetConfigProto::clear_gpu_device_info() { + if (GetArenaForAllocation() == nullptr && _impl_.gpu_device_info_ != nullptr) { + delete _impl_.gpu_device_info_; + } + _impl_.gpu_device_info_ = nullptr; +} +inline const ::stream_executor::GpuDeviceInfoProto& GpuTargetConfigProto::_internal_gpu_device_info() const { + const ::stream_executor::GpuDeviceInfoProto* p = _impl_.gpu_device_info_; + return p != nullptr ? *p : reinterpret_cast( + ::stream_executor::_GpuDeviceInfoProto_default_instance_); +} +inline const ::stream_executor::GpuDeviceInfoProto& GpuTargetConfigProto::gpu_device_info() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.gpu_device_info) + return _internal_gpu_device_info(); +} +inline void GpuTargetConfigProto::unsafe_arena_set_allocated_gpu_device_info( + ::stream_executor::GpuDeviceInfoProto* gpu_device_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.gpu_device_info_); + } + _impl_.gpu_device_info_ = gpu_device_info; + if (gpu_device_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuTargetConfigProto.gpu_device_info) +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::release_gpu_device_info() { + + ::stream_executor::GpuDeviceInfoProto* temp = _impl_.gpu_device_info_; + _impl_.gpu_device_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 ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::unsafe_arena_release_gpu_device_info() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.gpu_device_info) + + ::stream_executor::GpuDeviceInfoProto* temp = _impl_.gpu_device_info_; + _impl_.gpu_device_info_ = nullptr; + return temp; +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::_internal_mutable_gpu_device_info() { + + if (_impl_.gpu_device_info_ == nullptr) { + auto* p = CreateMaybeMessage<::stream_executor::GpuDeviceInfoProto>(GetArenaForAllocation()); + _impl_.gpu_device_info_ = p; + } + return _impl_.gpu_device_info_; +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::mutable_gpu_device_info() { + ::stream_executor::GpuDeviceInfoProto* _msg = _internal_mutable_gpu_device_info(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.gpu_device_info) + return _msg; +} +inline void GpuTargetConfigProto::set_allocated_gpu_device_info(::stream_executor::GpuDeviceInfoProto* gpu_device_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.gpu_device_info_; + } + if (gpu_device_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(gpu_device_info); + if (message_arena != submessage_arena) { + gpu_device_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, gpu_device_info, submessage_arena); + } + + } else { + + } + _impl_.gpu_device_info_ = gpu_device_info; + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.gpu_device_info) +} + +// string platform_name = 4; +inline void GpuTargetConfigProto::clear_platform_name() { + _impl_.platform_name_.ClearToEmpty(); +} +inline const std::string& GpuTargetConfigProto::platform_name() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.platform_name) + return _internal_platform_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GpuTargetConfigProto::set_platform_name(ArgT0&& arg0, ArgT... args) { + + _impl_.platform_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:stream_executor.GpuTargetConfigProto.platform_name) +} +inline std::string* GpuTargetConfigProto::mutable_platform_name() { + std::string* _s = _internal_mutable_platform_name(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.platform_name) + return _s; +} +inline const std::string& GpuTargetConfigProto::_internal_platform_name() const { + return _impl_.platform_name_.Get(); +} +inline void GpuTargetConfigProto::_internal_set_platform_name(const std::string& value) { + + _impl_.platform_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::_internal_mutable_platform_name() { + + return _impl_.platform_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::release_platform_name() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.platform_name) + return _impl_.platform_name_.Release(); +} +inline void GpuTargetConfigProto::set_allocated_platform_name(std::string* platform_name) { + if (platform_name != nullptr) { + + } else { + + } + _impl_.platform_name_.SetAllocated(platform_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.platform_name_.IsDefault()) { + _impl_.platform_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.platform_name) +} + +// .stream_executor.DnnVersionInfoProto dnn_version_info = 5; +inline bool GpuTargetConfigProto::_internal_has_dnn_version_info() const { + return this != internal_default_instance() && _impl_.dnn_version_info_ != nullptr; +} +inline bool GpuTargetConfigProto::has_dnn_version_info() const { + return _internal_has_dnn_version_info(); +} +inline void GpuTargetConfigProto::clear_dnn_version_info() { + if (GetArenaForAllocation() == nullptr && _impl_.dnn_version_info_ != nullptr) { + delete _impl_.dnn_version_info_; + } + _impl_.dnn_version_info_ = nullptr; +} +inline const ::stream_executor::DnnVersionInfoProto& GpuTargetConfigProto::_internal_dnn_version_info() const { + const ::stream_executor::DnnVersionInfoProto* p = _impl_.dnn_version_info_; + return p != nullptr ? *p : reinterpret_cast( + ::stream_executor::_DnnVersionInfoProto_default_instance_); +} +inline const ::stream_executor::DnnVersionInfoProto& GpuTargetConfigProto::dnn_version_info() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.dnn_version_info) + return _internal_dnn_version_info(); +} +inline void GpuTargetConfigProto::unsafe_arena_set_allocated_dnn_version_info( + ::stream_executor::DnnVersionInfoProto* dnn_version_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dnn_version_info_); + } + _impl_.dnn_version_info_ = dnn_version_info; + if (dnn_version_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuTargetConfigProto.dnn_version_info) +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::release_dnn_version_info() { + + ::stream_executor::DnnVersionInfoProto* temp = _impl_.dnn_version_info_; + _impl_.dnn_version_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 ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::unsafe_arena_release_dnn_version_info() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.dnn_version_info) + + ::stream_executor::DnnVersionInfoProto* temp = _impl_.dnn_version_info_; + _impl_.dnn_version_info_ = nullptr; + return temp; +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::_internal_mutable_dnn_version_info() { + + if (_impl_.dnn_version_info_ == nullptr) { + auto* p = CreateMaybeMessage<::stream_executor::DnnVersionInfoProto>(GetArenaForAllocation()); + _impl_.dnn_version_info_ = p; + } + return _impl_.dnn_version_info_; +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::mutable_dnn_version_info() { + ::stream_executor::DnnVersionInfoProto* _msg = _internal_mutable_dnn_version_info(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.dnn_version_info) + return _msg; +} +inline void GpuTargetConfigProto::set_allocated_dnn_version_info(::stream_executor::DnnVersionInfoProto* dnn_version_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.dnn_version_info_; + } + if (dnn_version_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(dnn_version_info); + if (message_arena != submessage_arena) { + dnn_version_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, dnn_version_info, submessage_arena); + } + + } else { + + } + _impl_.dnn_version_info_ = dnn_version_info; + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.dnn_version_info) +} + +// .xla.AutotuneResults autotune_results = 6; +inline bool GpuTargetConfigProto::_internal_has_autotune_results() const { + return this != internal_default_instance() && _impl_.autotune_results_ != nullptr; +} +inline bool GpuTargetConfigProto::has_autotune_results() const { + return _internal_has_autotune_results(); +} +inline const ::xla::AutotuneResults& GpuTargetConfigProto::_internal_autotune_results() const { + const ::xla::AutotuneResults* p = _impl_.autotune_results_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_AutotuneResults_default_instance_); +} +inline const ::xla::AutotuneResults& GpuTargetConfigProto::autotune_results() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.autotune_results) + return _internal_autotune_results(); +} +inline void GpuTargetConfigProto::unsafe_arena_set_allocated_autotune_results( + ::xla::AutotuneResults* autotune_results) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.autotune_results_); + } + _impl_.autotune_results_ = autotune_results; + if (autotune_results) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuTargetConfigProto.autotune_results) +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::release_autotune_results() { + + ::xla::AutotuneResults* temp = _impl_.autotune_results_; + _impl_.autotune_results_ = 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::AutotuneResults* GpuTargetConfigProto::unsafe_arena_release_autotune_results() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.autotune_results) + + ::xla::AutotuneResults* temp = _impl_.autotune_results_; + _impl_.autotune_results_ = nullptr; + return temp; +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::_internal_mutable_autotune_results() { + + if (_impl_.autotune_results_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::AutotuneResults>(GetArenaForAllocation()); + _impl_.autotune_results_ = p; + } + return _impl_.autotune_results_; +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::mutable_autotune_results() { + ::xla::AutotuneResults* _msg = _internal_mutable_autotune_results(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.autotune_results) + return _msg; +} +inline void GpuTargetConfigProto::set_allocated_autotune_results(::xla::AutotuneResults* autotune_results) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.autotune_results_); + } + if (autotune_results) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(autotune_results)); + if (message_arena != submessage_arena) { + autotune_results = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, autotune_results, submessage_arena); + } + + } else { + + } + _impl_.autotune_results_ = autotune_results; + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.autotune_results) +} + +// string device_description_str = 7; +inline void GpuTargetConfigProto::clear_device_description_str() { + _impl_.device_description_str_.ClearToEmpty(); +} +inline const std::string& GpuTargetConfigProto::device_description_str() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.device_description_str) + return _internal_device_description_str(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GpuTargetConfigProto::set_device_description_str(ArgT0&& arg0, ArgT... args) { + + _impl_.device_description_str_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:stream_executor.GpuTargetConfigProto.device_description_str) +} +inline std::string* GpuTargetConfigProto::mutable_device_description_str() { + std::string* _s = _internal_mutable_device_description_str(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.device_description_str) + return _s; +} +inline const std::string& GpuTargetConfigProto::_internal_device_description_str() const { + return _impl_.device_description_str_.Get(); +} +inline void GpuTargetConfigProto::_internal_set_device_description_str(const std::string& value) { + + _impl_.device_description_str_.Set(value, GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::_internal_mutable_device_description_str() { + + return _impl_.device_description_str_.Mutable(GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::release_device_description_str() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.device_description_str) + return _impl_.device_description_str_.Release(); +} +inline void GpuTargetConfigProto::set_allocated_device_description_str(std::string* device_description_str) { + if (device_description_str != nullptr) { + + } else { + + } + _impl_.device_description_str_.SetAllocated(device_description_str, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_description_str_.IsDefault()) { + _impl_.device_description_str_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.device_description_str) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace stream_executor + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_host_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_host_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..b724f2e1d2292dc716a2b14502cde3a1f1c2a306 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_host_allocator.h @@ -0,0 +1,86 @@ +/* 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_STREAM_EXECUTOR_DEVICE_HOST_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_HOST_ALLOCATOR_H_ + +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/platform/macros.h" +#include "tsl/profiler/lib/traceme.h" + +namespace stream_executor { +// Allocator for pinned CPU RAM that is made known to a StreamExecutor-based +// device for the purpose of efficient DMA with the device. +class DeviceHostAllocator : public tsl::SubAllocator { + public: + // Note: stream_exec cannot be null. + explicit DeviceHostAllocator(StreamExecutor* stream_exec, int numa_node, + const std::vector& alloc_visitors, + const std::vector& free_visitors) + : SubAllocator(alloc_visitors, free_visitors), + stream_exec_(stream_exec), + numa_node_(numa_node) { + CHECK(stream_exec_ != nullptr); + } + + ~DeviceHostAllocator() override = default; + + void* Alloc(size_t alignment, size_t num_bytes, + size_t* bytes_received) override { + tsl::profiler::TraceMe traceme("DeviceHostAllocator::Alloc"); + + void* ptr = nullptr; + *bytes_received = num_bytes; + if (num_bytes > 0) { + ptr = stream_exec_->HostMemoryAllocate(num_bytes); + if (ptr == nullptr) { + LOG(WARNING) << "could not allocate pinned host memory of size: " + << num_bytes; + return ptr; + } + VisitAlloc(ptr, numa_node_, num_bytes); + } + return ptr; + } + + void Free(void* ptr, size_t num_bytes) override { + tsl::profiler::TraceMe traceme("DeviceHostAllocator::Free"); + + if (ptr != nullptr) { + VisitFree(ptr, numa_node_, num_bytes); + stream_exec_->HostMemoryDeallocate(ptr); + } + } + + bool SupportsCoalescing() const override { return false; } + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kHostPinned; + } + + private: + StreamExecutor* stream_exec_; // not owned, non-null + const int numa_node_; + + DeviceHostAllocator(const DeviceHostAllocator&) = delete; + void operator=(const DeviceHostAllocator&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_HOST_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_id_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_id_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..76aada1dcfec0af1ad8cd0c1cd976fe611c69abd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_id_utils.h @@ -0,0 +1,47 @@ + +/* 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 XLA_STREAM_EXECUTOR_DEVICE_ID_UTILS_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_ID_UTILS_H_ + +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/device_id.h" +#include "tsl/framework/device_id_manager.h" + +namespace stream_executor { + +// Utility methods for getting the associated executor given a TfDeviceId +// or PlatformDeviceId. +class DeviceIdUtil { + public: + static tsl::StatusOr ExecutorForPlatformDeviceId( + Platform* device_manager, tsl::PlatformDeviceId platform_device_id) { + return device_manager->ExecutorForDevice(platform_device_id.value()); + } + static tsl::StatusOr ExecutorForTfDeviceId( + const tsl::DeviceType& type, Platform* device_manager, + tsl::TfDeviceId tf_device_id) { + tsl::PlatformDeviceId platform_device_id; + TF_RETURN_IF_ERROR(tsl::DeviceIdManager::TfToPlatformDeviceId( + type, tf_device_id, &platform_device_id)); + return ExecutorForPlatformDeviceId(device_manager, platform_device_id); + } +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_ID_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_mem_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_mem_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..fe02b44f5fd5bdc931afa282fc5f413f09e55400 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_mem_allocator.h @@ -0,0 +1,96 @@ +/* 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_STREAM_EXECUTOR_DEVICE_MEM_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_MEM_ALLOCATOR_H_ + +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" +#include "tsl/profiler/lib/traceme.h" + +namespace stream_executor { + +// Suballocator for StreamExecutor-based device memory. +class DeviceMemAllocator : public tsl::SubAllocator { + public: + // 'platform_device_id' refers to the ID of the device within + // the process and must reference a valid ID in the process. + // Note: stream_exec cannot be null. + explicit DeviceMemAllocator(StreamExecutor* stream_exec, + tsl::PlatformDeviceId device_id, + bool use_unified_memory, + const std::vector& alloc_visitors, + const std::vector& free_visitors) + : SubAllocator(alloc_visitors, free_visitors), + stream_exec_(stream_exec), + device_id_(device_id), + use_unified_memory_(use_unified_memory) { + CHECK(stream_exec_ != nullptr); + } + + ~DeviceMemAllocator() override = default; + + void* Alloc(size_t alignment, size_t num_bytes, + size_t* bytes_received) override { + tsl::profiler::TraceMe traceme("DeviceMemAllocator::Alloc"); + + void* ptr = nullptr; + *bytes_received = num_bytes; + if (num_bytes > 0) { + if (use_unified_memory_) { + ptr = stream_exec_->UnifiedMemoryAllocate(num_bytes); + } else { + ptr = stream_exec_->AllocateArray(num_bytes).opaque(); + } + VisitAlloc(ptr, device_id_.value(), num_bytes); + } + return ptr; + } + + void Free(void* ptr, size_t num_bytes) override { + tsl::profiler::TraceMe traceme("DeviceMemAllocator::Free"); + + if (ptr != nullptr) { + VisitFree(ptr, device_id_.value(), num_bytes); + if (use_unified_memory_) { + stream_exec_->UnifiedMemoryDeallocate(ptr); + } else { + DeviceMemoryBase device_ptr(ptr); + stream_exec_->Deallocate(&device_ptr); + } + } + } + + bool SupportsCoalescing() const override { return false; } + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kDevice; + } + + private: + StreamExecutor* stream_exec_; // not owned, non-null + const tsl::PlatformDeviceId device_id_; + const bool use_unified_memory_ = false; + + DeviceMemAllocator(const DeviceMemAllocator&) = delete; + void operator=(const DeviceMemAllocator&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_MEM_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_memory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..f69fe8148c67a014da76b6c7a3daeb87ec63065e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_memory.h @@ -0,0 +1,202 @@ +/* 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. +==============================================================================*/ + +// Suite of types that represent device memory allocations. These are +// allocated by the StreamExecutor interface, which produces values appropriate +// for the underlying platform (whether it be CUDA or OpenCL). +// +// The untyped base class (like a device void*) is DeviceMemoryBase, which can +// be specialized for a given allocation type (like a device T*) using +// DeviceMemory. + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_MEMORY_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_MEMORY_H_ + +#include + +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class DeviceMemoryAllocator; +class StreamExecutor; + +// void*-analogous device memory allocation. For the typed variation, see +// DeviceMemory. +// +// This is effectively a two-tuple of a pointer and size; however, note that the +// pointer may not be to the virtual address itself -- in OpenCL the pointer is +// to a cl_mem handle that describes the device allocation. Therefore, +// DeviceMemoryBase::opaque does not necessarily produce a pointer that can be +// referenced directly, so use it with caution. +// +// Thread-compatible. +class DeviceMemoryBase { + public: + // Default constructor instantiates a null-pointed, zero-sized device memory + // region. An opaque pointer may be provided -- see header for details on the + // opacity of that pointer. + explicit DeviceMemoryBase(void *opaque = nullptr, uint64_t size = 0) + : opaque_(opaque), size_(size) {} + + // Returns whether the backing memory is the null pointer. + // A `== nullptr` convenience method is also provided. + bool is_null() const { return opaque_ == nullptr; } + bool operator==(std::nullptr_t other) const { return is_null(); } + bool operator!=(std::nullptr_t other) const { return !is_null(); } + + // Provides a partial order between device memory values. + // + // This operator is provided so that this object can be used as a key in an + // ordered map. + bool operator<(const DeviceMemoryBase &other) const { + return opaque() < other.opaque(); + } + + // Returns the size, in bytes, for the backing memory. + uint64_t size() const { return size_; } + + // Warning: note that the pointer returned is not necessarily directly to + // device virtual address space, but is platform-dependent. + void *opaque() { return opaque_; } + const void *opaque() const { return opaque_; } + + // Returns the payload of this memory region. + uint64_t payload() const { return payload_; } + + // Sets payload to given value. + void SetPayload(uint64_t payload) { payload_ = payload; } + + // Returns whether the two DeviceMemoryBase segments are identical (both in + // their opaque pointer and size). + bool IsSameAs(const DeviceMemoryBase &other) const { + return opaque() == other.opaque() && size() == other.size(); + } + + protected: + friend class StreamExecutor; + + // Resets the internal values of the opaque pointer and number of bytes in the + // memory region, just as in the constructor. + void Reset(void *opaque, uint64_t bytes) { + opaque_ = opaque; + size_ = bytes; + } + + private: + void *opaque_; // Platform-dependent value representing allocated memory. + uint64_t size_; // Size in bytes of this allocation. + uint64_t payload_ = 0; // Payload data associated with this allocation. +}; + +// Typed wrapper around "void *"-like DeviceMemoryBase. +// +// For example, DeviceMemory is a simple wrapper around DeviceMemoryBase +// that represents one or more integers in Device memory. +// +// Thread-compatible. +template +class DeviceMemory final : public DeviceMemoryBase { + public: + // Default constructor instantiates a null-pointed, zero-sized memory region. + DeviceMemory() : DeviceMemoryBase(nullptr, 0) {} + explicit DeviceMemory(std::nullptr_t) : DeviceMemory() {} + + // Typed device memory regions may be constructed from untyped device memory + // regions, this effectively amounts to a cast from a void*. + explicit DeviceMemory(const DeviceMemoryBase &other) + : DeviceMemoryBase(const_cast(other).opaque(), + other.size()) { + SetPayload(other.payload()); + } + + // Returns the number of elements of type ElemT that constitute this + // allocation. + uint64_t ElementCount() const { return size() / sizeof(ElemT); } + + // Returns whether this is a single-element allocation. + bool IsScalar() const { return ElementCount() == 1; } + + // Create a typed area of DeviceMemory with a given opaque pointer and the + // quantity of bytes in the allocation. This function is broken out to + // distinguish bytes from an element count. + static DeviceMemory MakeFromByteSize(void *opaque, uint64_t bytes) { + return DeviceMemory(opaque, bytes); + } + + // Resets the DeviceMemory data, in MakeFromByteSize fashion. + // This simply clobbers the prior values. + void ResetFromByteSize(void *opaque, uint64_t bytes) { + // TODO(leary) when NVCC is eliminated we can add this check (and the + // logging include it requires). + // CHECK_EQ(0, bytes % sizeof(ElemT)); + DeviceMemoryBase::Reset(opaque, bytes); + } + + // ------------------------------------------------------------ + + protected: + // This constructor is solely used from derived classes; it is made protected + // because it accepts a byte-size instead of an element count, which could + // potentially be misused given the ElementCount() nature of this interface. + // + // In order to specify the desire to use byte size instead of element count + // explicitly, use MakeFromByteSize. + DeviceMemory(void *opaque, uint64_t size) : DeviceMemoryBase(opaque, size) {} +}; + +// A class to encapsulate the type and size of a dynamic shared memory +// buffer. Because the buffer exists solely on the device and is not copyable +// to the host, memory objects of this type do not maintain buffer pointers +// on the host. +template +class SharedDeviceMemory final : public DeviceMemoryBase { + public: + explicit SharedDeviceMemory(uint64_t elem_count) + : DeviceMemoryBase(nullptr, elem_count * kElemSize) {} + + static constexpr size_t kElemSize = sizeof(ElemT); + + // Returns the number of elements of type ElemT that constitute this + // allocation. + uint64_t ElementCount() const { return size() / kElemSize; } + + // Returns whether this is a single-element allocation. + bool IsScalar() const { return ElementCount() == 1; } +}; + +// Host-side representation of packed-and-aligned vector datatypes on the device +// side. Since these can appear in device kernel signatures, we support +// launching them with these datatypes in launch signatures. + +struct Float2 { + float x, y; +}; + +struct Float4 { + Float2 xz, yw; +}; + +struct Double2 { + double x, y; +}; + +static_assert(sizeof(Float2) == 2 * sizeof(float), "Float2 must be packed"); +static_assert(sizeof(Float4) == 4 * sizeof(float), "Float4 must be packed"); +static_assert(sizeof(Double2) == 2 * sizeof(double), "Double2 must be packed"); + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_MEMORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_memory_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_memory_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..500428b0ed24b5f70b5679535a088ca11820d063 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_memory_allocator.h @@ -0,0 +1,289 @@ +/* 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_STREAM_EXECUTOR_DEVICE_MEMORY_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_MEMORY_ALLOCATOR_H_ + +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/platform.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; +class DeviceMemoryAllocator; + +// Owning pointer for memory on a device. +// +// ScopedDeviceMemory is an owning pointer like std::unique_ptr, but it can +// point to memory that resides on a "device" (e.g. a GPU). When a +// ScopedDeviceMemory goes out of scope, it frees the memory it owns. +// +// We say that an instance of ScopedDeviceMemory is "active" if it currently +// owns a (possibly empty) slice of memory on the device. Moving, +// Release()'ing, Free()'ing, and other actions can deactivate an active object. +template +class ScopedDeviceMemory { + public: + // Default construction initializes the internal state to nullptr. This + // mirrors the std::unique_ptr<> functionality, where default construction + // produces a nullptr unique_ptr, which can be assigned later. + ScopedDeviceMemory() : device_ordinal_(-1), allocator_(nullptr) {} + + // Construct a ScopedDeviceMemory from a custom allocator. + // + // Parameters: + // mem: Already-allocated device memory value for this scoped mechanism to + // deallocate. This memory must have been allocated by parent. + // device_ordinal: Device on which the memory was allocated. + // allocator: Allocator used to deallocate memory when this instance goes + // out of scope. + ScopedDeviceMemory(DeviceMemoryBase mem, int device_ordinal, + DeviceMemoryAllocator *allocator) + : wrapped_(mem), device_ordinal_(device_ordinal), allocator_(allocator) { + DCHECK_GE(device_ordinal_, 0); + } + + // A helper constructor to generate a scoped device memory given an already + // allocated memory and a stream executor. + // + // Precondition: memory was allocated by the stream executor `parent`. + ScopedDeviceMemory(StreamExecutor *parent, DeviceMemoryBase value); + + // Constructor overload that places a literal array into device memory. + // + // Relies on the allocation function exposed by the stream executor `parent`, + // which will be also used for deallocating the memory + ScopedDeviceMemory(StreamExecutor *parent, + std::initializer_list values); + + // Moves ownership of the memory from other to the constructed + // object. + // + // Postcondition: other == nullptr. + ScopedDeviceMemory(ScopedDeviceMemory &&other) + : wrapped_(other.Release()), + device_ordinal_(other.device_ordinal_), + allocator_(other.allocator_) {} + + // Releases the memory that was provided in the constructor, through the + // "parent" StreamExecutor. + ~ScopedDeviceMemory() { TF_CHECK_OK(Free()); } + + // Moves ownership of the memory from other to this object. + // + // Postcondition: other == nullptr. + ScopedDeviceMemory &operator=(ScopedDeviceMemory &&other) { + TF_CHECK_OK(Free()); + wrapped_ = other.Release(); + allocator_ = other.allocator_; + device_ordinal_ = other.device_ordinal_; + return *this; + } + + // Returns the memory that backs this scoped allocation converted to + // DeviceMemory apparent type. This is useful for cases where the + // DeviceMemory must be passed by const-ref, as the ScopedDeviceMemory doesn't + // allow copying, for scoped-object-lifetime reasons. + const DeviceMemory &cref() const { return wrapped_; } + + // Returns a pointer to the DeviceMemory apparent type for use in mutable + // operations. The value returned should not be used outside the scope of this + // ScopedDeviceMemory object's lifetime. + DeviceMemory *ptr() { return &wrapped_; } + const DeviceMemory *ptr() const { return &wrapped_; } + + // Smart-pointer-like operators for the wrapped DeviceMemory. + // This reference must not be used outside the lifetime of this + // ScopedDeviceMemory. + const DeviceMemory &operator*() const { return cref(); } + DeviceMemory *operator->() { return ptr(); } + const DeviceMemory *operator->() const { return ptr(); } + + bool is_null() const { return wrapped_.is_null(); } + bool operator==(std::nullptr_t other) const { return is_null(); } + bool operator!=(std::nullptr_t other) const { return !is_null(); } + + // Analogous to std::unique_ptr::release, releases ownership of the held + // memory and transfers it to the caller. + // + // Postcondition: *this == nullptr + DeviceMemory Release() { + DeviceMemory tmp = wrapped_; + wrapped_ = DeviceMemory{}; + return tmp; + } + + // The returned allocator is nonnull iff this object is active. + DeviceMemoryAllocator *allocator() const { return allocator_; } + + int device_ordinal() const { return device_ordinal_; } + + // Frees the existing memory, resets the wrapped memory to null. + tsl::Status Free(); + + private: + DeviceMemory wrapped_; // Value we wrap with scoped-release. + int device_ordinal_; // Negative one for inactive object. + DeviceMemoryAllocator *allocator_; // Null if this object is inactive. + + ScopedDeviceMemory(const ScopedDeviceMemory &) = delete; + void operator=(const ScopedDeviceMemory &) = delete; +}; + +// Type alias for compatibility with the previous managed memory implementation. +using OwningDeviceMemory = ScopedDeviceMemory; + +// Memory allocator interface for the device. +// +// Intended usage is through Allocate() functions which return an owning smart +// pointer. +class DeviceMemoryAllocator { + public: + // Parameter platform indicates which platform the allocator allocates memory + // on. Must be non-null. + explicit DeviceMemoryAllocator(const Platform *platform) + : platform_(platform) {} + virtual ~DeviceMemoryAllocator() {} + + // Allocates memory on the device. + // + // If size > 0 and the returned StatusOr is OK, the wrapped OwningDeviceMemory + // must not be null. If size == 0, must return a null OwningDeviceMemory. + // + // 'retry_on_failure': If false, and the first attempt to allocate the memory + // fails, the allocation should return immediately without retrying. An + // example use case is optional scratch spaces where a failure has only + // performance impact. + virtual tsl::StatusOr Allocate(int device_ordinal, + uint64_t size, + bool retry_on_failure, + int64_t memory_space) = 0; + + // Two-arg version of Allocate(), which sets retry-on-failure to true and + // memory_space to default (0). + // + // (We don't simply use a default argument on the virtual Allocate function + // because default args on virtual functions are disallowed by the Google + // style guide.) + tsl::StatusOr Allocate(int device_ordinal, + uint64_t size) { + return Allocate(device_ordinal, size, /*retry_on_failure=*/true, + /*memory_space=*/0); + } + + // Three-arg version of Allocate(), which sets memory_space to default (0). + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure) { + return Allocate(device_ordinal, size, retry_on_failure, + /*memory_space=*/0); + } + + // Typed version of the allocation, returning typed memory. + template + tsl::StatusOr> Allocate( + int device_ordinal, uint64_t size, bool retry_on_failure = true, + int64_t memory_space = 0) { + return Allocate(device_ordinal, size, retry_on_failure, memory_space); + } + + // Must be a nop for null pointers. Should not be used. + // + // TODO(cheshire): Add deprecation notice. + virtual tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) = 0; + + // Return the platform that the allocator allocates memory on. + const Platform *platform() const { return platform_; } + + // Can we call Deallocate() as soon as a computation has been scheduled on + // a stream, or do we have to wait for the computation to complete first? + virtual bool AllowsAsynchronousDeallocation() const { return false; } + + // Returns a stream pointer on which it is always safe to access memory + // allocated by this allocator. It is not necessary to use the returned stream + // though, as clients may have additional information letting them safely use + // a different stream. + virtual tsl::StatusOr GetStream(int device_ordinal) = 0; + + protected: + const Platform *platform_; +}; + +// Default memory allocator for a platform which uses +// StreamExecutor::Allocate/Deallocate. +class StreamExecutorMemoryAllocator : public DeviceMemoryAllocator { + public: + // Create an allocator supporting a single device, corresponding to the passed + // executor. + explicit StreamExecutorMemoryAllocator(StreamExecutor *executor); + + // Create an allocator supporting multiple stream executors. + // + // Precondition: all stream_executors have different device ordinals. + StreamExecutorMemoryAllocator( + const Platform *platform, + absl::Span stream_executors); + + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure, + int64_t memory_space) override; + + // Pull in two-arg overload that sets retry_on_failure to true. + using DeviceMemoryAllocator::Allocate; + + tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) override; + + bool AllowsAsynchronousDeallocation() const override; + + // Gets-or-creates a stream for a given `device_ordinal` from an appropriate + // stream executor. + tsl::StatusOr GetStream(int device_ordinal) override; + + // Gets the stream executor for given device ordinal. + tsl::StatusOr GetStreamExecutor(int device_ordinal) const; + + private: + // Available stream executors. Each stream executor has a different device + // ordinal. + std::vector stream_executors_; + + absl::Mutex mutex_; + + // Cache of streams for GetStream. + std::map streams_ ABSL_GUARDED_BY(mutex_); +}; + +template +tsl::Status ScopedDeviceMemory::Free() { + if (!wrapped_.is_null()) { + CHECK(allocator_ != nullptr) << "Owning pointer in inconsistent state"; + TF_RETURN_IF_ERROR(allocator_->Deallocate(device_ordinal_, wrapped_)); + } + wrapped_ = DeviceMemory{}; + return ::tsl::OkStatus(); +} + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_MEMORY_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_options.h new file mode 100644 index 0000000000000000000000000000000000000000..776fa4220813c4cf159b3b0482885edce0836677 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/device_options.h @@ -0,0 +1,104 @@ +/* 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. +==============================================================================*/ + +// Contains device-level options that can be specified at a platform level. +// Example usage: +// auto device_options = DeviceOptions::Default(); + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_OPTIONS_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_OPTIONS_H_ + +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/str_join.h" + +namespace stream_executor { + +// Indicates a set of options for a device's usage, which generally must be +// provided at StreamExecutor device-initialization time. +// +// These are intended to be useful-but-not-mandatorily-supported options for +// using devices on the underlying platform. Presently, if the option requested +// is not available on the target platform, a warning will be emitted. +struct DeviceOptions { + public: + // When it is observed that more memory has to be allocated for thread stacks, + // this flag prevents it from ever being deallocated. Potentially saves + // thrashing the thread stack memory allocation, but at the potential cost of + // some memory space. + static constexpr unsigned kDoNotReclaimStackAllocation = 0x1; + + // The following options refer to synchronization options when + // using SynchronizeStream or SynchronizeContext. + + // Synchronize with spinlocks. + static constexpr unsigned kScheduleSpin = 0x02; + // Synchronize with spinlocks that also call CPU yield instructions. + static constexpr unsigned kScheduleYield = 0x04; + // Synchronize with a "synchronization primitive" (e.g. mutex). + static constexpr unsigned kScheduleBlockingSync = 0x08; + + static constexpr unsigned kMask = 0xf; // Mask of all available flags. + + // Constructs an or-d together set of device options. + explicit DeviceOptions(unsigned flags) : flags_(flags) { + CHECK((flags & kMask) == flags); + } + + // Factory for the default set of device options. + static DeviceOptions Default() { return DeviceOptions(0); } + + unsigned flags() const { return flags_; } + + bool operator==(const DeviceOptions& other) const { + return flags_ == other.flags_ && + non_portable_tags == other.non_portable_tags; + } + + bool operator!=(const DeviceOptions& other) const { + return !(*this == other); + } + + std::string ToString() const { + std::vector flags_on; + if (flags_ & kDoNotReclaimStackAllocation) { + flags_on.push_back("kDoNotReclaimStackAllocation"); + } + if (flags_ & kScheduleSpin) { + flags_on.push_back("kScheduleSpin"); + } + if (flags_ & kScheduleYield) { + flags_on.push_back("kScheduleYield"); + } + if (flags_ & kScheduleBlockingSync) { + flags_on.push_back("kScheduleBlockingSync"); + } + return flags_on.empty() ? "none" : absl::StrJoin(flags_on, "|"); + } + + // Platform-specific device options. Expressed as key-value pairs to avoid + // DeviceOptions subclass proliferation. + std::map non_portable_tags; + + private: + unsigned flags_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/dnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/dnn.h new file mode 100644 index 0000000000000000000000000000000000000000..3561a1ffd4f13b21a74a6beabe80f8acf5cf0500 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/dnn.h @@ -0,0 +1,2603 @@ +/* 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. +==============================================================================*/ + +// Neural Net operation support for StreamExecutor instances. +// +// This is an abstract interface for a platform to optionally support common +// neural net operations; it accommodates implementations such as the cudnn +// library operations. + +#ifndef XLA_STREAM_EXECUTOR_DNN_H_ +#define XLA_STREAM_EXECUTOR_DNN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "google/protobuf/wrappers.pb.h" +#include "absl/types/optional.h" +#include "absl/types/span.h" +#include "xla/stream_executor/data_type.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/logging.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" +#include "tsl/protobuf/dnn.pb.h" + +namespace Eigen { +struct half; +} // namespace Eigen + +namespace stream_executor { + +class HostBuffer; +class Stream; +class ScratchAllocator; + +namespace dnn { + +// Specifies an index to use when accessing specific spatial dimensions. +enum class DimIndex : int { + X = 0, + Y = 1, + Z = 2, +}; + +// Return a reordered dims. +std::vector ReorderDims(const std::vector& input, + const DataLayout& from, const DataLayout& to); + +// Helper functions to make methods more readable. +inline int64_t GetDim(absl::Span data, DimIndex dim) { + return data.rbegin()[static_cast(dim)]; +} + +inline void SetDim(absl::Span data, DimIndex dim, int64_t value) { + data.rbegin()[static_cast(dim)] = value; +} + +inline void SetDim(std::vector* data, DimIndex dim, int64_t value) { + return SetDim(absl::MakeSpan(*data), dim, value); +} + +// int64_t is not the same type as tensorflow::protobuf_int64 in open-source. +// This wrapper function gives an int64_t array slice view of a repeated int64 +// protobuf field. +// +// T should be a protobuf RepeatedField. +template +inline absl::Span AsInt64Slice(const T& repeated_field) { + using data_ty = + typename std::remove_reference::type; + static_assert(std::is_integral::value && + std::is_signed::value && sizeof(data_ty) == 8, + "repeated_field.data() must return a pointer to a signed " + "64-bit integer type."); + return absl::Span( + reinterpret_cast(repeated_field.data()), + repeated_field.size()); +} +template +inline absl::Span AsInt64Slice(T* repeated_field) { + using data_ty = + typename std::remove_referencedata())>::type; + static_assert(std::is_integral::value && + std::is_signed::value && sizeof(data_ty) == 8, + "repeated_field->data() must return a pointer to a signed " + "64-bit integer type."); + return absl::Span( + reinterpret_cast(repeated_field->mutable_data()), + repeated_field->size()); +} + +// Returns a string representation of the given data layout. +std::string DataLayoutString(DataLayout layout); + +// Specifies a quantization for activations in a given BatchDescriptor. +enum class QuantizedActivationMode { + k8Bit = 1, + k16Bit = 2, + k32Bit = 4, +}; + +// Specifies the types of a RNN model. +enum class RnnMode { + kRnnRelu = 0, + kRnnTanh = 1, + kRnnLstm = 2, + kRnnGru = 3, +}; + +// Specifies the input model and whether there is a linear transformation +// between the input state and the first layer hidden state. +enum class RnnInputMode { + kRnnLinearSkip = 0, + kRnnSkipInput = 1, +}; + +// Specifies the number of directions used in a RNN model. When bidirection +// is used, the input states and output sequence contain data for both +// directions. +enum class RnnDirectionMode { + kRnnUnidirectional = 0, + kRnnBidirectional = 1, +}; + +// Relevant to DepthToSpace and SpaceToDepth. This is the write layout when +// performing depth to space and the read layout when performing space to depth. +// It's specified with most-major dimension first and most-minor dimension last. +// In DepthToSpace, the D*M^2 values are read in and then, for DepthHeightWidth, +// written out to the output patch, by varying first width, then height, then +// depth. In C array format, it looks like [depth][height][width]. See +// DepthToSpace comment for more information. +enum class DepthToSpaceLayout { DepthHeightWidth }; + +class TensorDescriptor { + public: + TensorDescriptor() = default; + tsl::StatusOr> GetPhysicalDimensionsMajorToMinor() const; + std::vector GetPhysicalStridesMajorToMinor() const; + std::vector GetLogicalStrides() const; + + static TensorDescriptor For(DataType type, + absl::Span dimensions, + absl::Span minor_to_major); + int ndims() const; + std::vector dimensions() const { return dimensions_; } + std::vector minor_to_major() const { return minor_to_major_; } + DataType type() const { return d_type_; } + std::string ToString() const; + + protected: + TensorDescriptor(DataType type, std::vector dimensions, + std::vector minor_to_major) + : d_type_(type), + dimensions_(dimensions), + minor_to_major_(minor_to_major) {} + + private: + DataType d_type_; + std::vector dimensions_; + std::vector minor_to_major_; +}; + +class MatmulTensorDescriptor { + public: + MatmulTensorDescriptor() = default; + tsl::StatusOr> GetNonContractingDims() const; + std::vector GetCudnnCompatibleDimensions( + bool is_lhs + /*if not lhs, then rhs*/) const; + std::vector GetCudnnCompatibleStrides( + bool is_lhs + /*if not lhs, then rhs*/) const; + tsl::StatusOr> MakeCudnnCompatible( + const std::vector&, bool is_lhs) const; + + static MatmulTensorDescriptor For(DataType type, + absl::Span dimensions, + absl::Span minor_to_major, + absl::Span batch_dims, + absl::Span contracting_dims); + std::vector dimensions() const { return tensor_.dimensions(); } + std::vector minor_to_major() const { + return tensor_.minor_to_major(); + } + DataType type() const { return tensor_.type(); } + + std::string ToString() const; + + protected: + MatmulTensorDescriptor(TensorDescriptor tensor, + std::vector batch_dims, + std::vector contracting_dims) + : tensor_(tensor), + batch_dimension_numbers_(batch_dims), + contracting_dim_(contracting_dims) {} + + private: + TensorDescriptor tensor_; + std::vector batch_dimension_numbers_; + std::vector contracting_dim_; +}; + +// Specifies the descriptor for a RNN model. +// +// An example use case: +// * The user first creates a model through createRnnDescriptor. +// * The user queries the size of the underlying opaque parameter buffer. +// * The user creates and initializes a parameter buffer of the proper size. +// * The user runs forward and backward operations using this RNN descriptor. +// * Once a while, user queries maintainable weights and bias regions from +// the underlying parameter buffer. They are more likely to be forward +// compatible and should used in saving and restoring a model. +// * The user releases the RNN descriptor when the model is no longer in use. +class RnnDescriptor { + public: + struct ParamsRegion { + int64_t offset; + int64_t size; + }; + typedef std::vector ParamsRegions; + virtual ~RnnDescriptor() = default; + virtual int64_t ParamsSizeInBytes() const { return -1; } + virtual ParamsRegions ParamsWeightRegions() const { return ParamsRegions(); } + virtual ParamsRegions ParamsBiasRegions() const { return ParamsRegions(); } +}; + +// Specifies the sequence in a RNN model. +// +// The user is responsible for releasing this descriptor when it is no longer +// in use. The destructor releases the underlying descriptors. +class RnnSequenceTensorDescriptor { + public: + virtual ~RnnSequenceTensorDescriptor() = default; +}; + +// Specifies either the input and hidden state in a RNN model. +// +// The user is responsible for releasing this descriptor when it is no longer +// in use. The destructor releases the underlying descriptors. +class RnnStateTensorDescriptor { + public: + virtual ~RnnStateTensorDescriptor() = default; +}; + +// Returns a string representation of the given quantization mode. +std::string QuantizedActivationModeString(QuantizedActivationMode mode); + +// Describes the dimensions that a layer consumes/produces. +// +// This is a matrix (height, width), its "depth" (feature_map_count), +// how many of these matrices are present (count), +// and the maximum and minimum values expected in the matrix (value_max, +// value_min). +// If input is quantized, all values greater +// than value_max will be clipped to value_max and all values less than +// value_min will be clipped to value_min. +// When quantized output is dequantized no value will be greater than +// value_max or less than value_min. +// +// Uses the named argument construction form: +// +// auto input_batch_dimensions = +// BatchDescriptor().set_count(42).set_feature_map_count(7)... +// +// Details: +// +// For a convolutional layer, a single inference takes a 3-dimensional matrix +// of input and produces a 3-dimensional matrix of output. We call the three +// dimensions height, width and feature_map_count, where for an image, the +// height and width correspond to the Y and X pixel indices, respectively, and +// the feature_map_count corresponds to the RGB dimension of the input data. +// Then the count indicates how many 3D matrices are being presented to be +// processed at once; this corresponds to the neural network concept of +// minibatch size. +// +// For a fully connected layer, it's better to put the nodes of the layer in +// the feature_map_count, and leave the height and weight as degenerate (== 1). +// Count indicates how many input vectors (degenerate 3D matrices) are to be +// processed. +// +// If unspecified, value_max and value_min default to 0.0. +// If value_max == value_min the Stream will attempt to derive valid values - +// for example the output of Relu6 activation will always be in the range +// [0.0, 6.0]. +// +// If unspecified, layout defaults to kYXDepthBatch. +class BatchDescriptor { + public: + // Creates a "blank" batch descriptor, which should be initialized via the + // named argument helpers. + BatchDescriptor(); + explicit BatchDescriptor(int ndims); + + // Clones values from 'other' for initialization. + void CloneFrom(const BatchDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + + // Pre-condition: + // value_max_ == 0 + // value_min_ == 0 + // quantized_activation_mode_ == QuantizedActivationMode::k8Bit + TensorDescriptorProto ToProto(DataType data_type) const; + + // Accessors. + int64_t count() const { return tensor_.dimensions(0); } + int64_t feature_map_count() const { return tensor_.dimensions(1); } + int64_t height() const { return GetDim(spatial_size(), DimIndex::Y); } + int64_t width() const { return GetDim(spatial_size(), DimIndex::X); } + int64_t spatial_dim(DimIndex dim) const { + return GetDim(spatial_size(), dim); + } + int ndims() const { return spatial_size().size(); } + float value_max() const { return value_max_; } + float value_min() const { return value_min_; } + DataLayout layout() const { return tensor_.data_layout(); } + QuantizedActivationMode quantized_activation_mode() const { + return quantized_activation_mode_; + } + // Full dimensions of the underlying data, ordered according to a specific + // layout. + std::vector full_dims(const DataLayout& layout) const; + + // Full strides of the underlying data, ordered according to a specific + // layout. + std::vector full_strides(const DataLayout& layout) const; + + // Vectorized dimensions where users can specify the dimension that the number + // of dimensions is reported rather than the full number of elements. + std::vector vectorized_dims(const DataLayout& layout, + int vector_size, int vector_dim) const; + + // Vectorized strides correspond to the vectorized_dims. + std::vector vectorized_strides(const DataLayout& layout, + int vector_size, + int vector_dim) const; + + // Named-argument helpers for avoiding user error during construction. + BatchDescriptor& set_count(int64_t value) { + tensor_.set_dimensions(0, value); + return *this; + } + BatchDescriptor& set_feature_map_count(int64_t value) { + tensor_.set_dimensions(1, value); + return *this; + } + BatchDescriptor& set_height(int64_t value) { + SetDim(spatial_size(), DimIndex::Y, value); + return *this; + } + BatchDescriptor& set_width(int64_t value) { + SetDim(spatial_size(), DimIndex::X, value); + return *this; + } + BatchDescriptor& set_spatial_dim(DimIndex dim, int64_t value) { + SetDim(spatial_size(), dim, value); + return *this; + } + BatchDescriptor& set_value_max(float value) { + value_max_ = value; + return *this; + } + BatchDescriptor& set_value_min(float value) { + value_min_ = value; + return *this; + } + BatchDescriptor& set_layout(DataLayout layout) { + tensor_.set_data_layout(layout); + return *this; + } + BatchDescriptor& set_quantized_activation_mode( + QuantizedActivationMode quantized_activation_mode) { + quantized_activation_mode_ = quantized_activation_mode; + return *this; + } + + // Return the number of nodes in a single feature map. + int64_t NodesPerFeatureMap() const; + + // Return the number of nodes across all feature maps. Note that this is not + // affected by the batch count. + int64_t NodesAcrossFeatureMaps() const; + + // Returns the number of elements (e.g. RGB pixel values) required to hold a + // given batch descriptor, given a no-padding assumption. Note that this is + // affected by the batch count. + int64_t ElementCount() const; + + // Return the number of weights required to fully connect a layer with + // dimensions given by the 'input' descriptor with a layer with dimensions + // given by the 'output' descriptor. + static int64_t FullyConnectedWeightCount(const BatchDescriptor& input, + const BatchDescriptor& output); + + // Return the number of biases required to fully connect to an output layer + // with dimensions given the 'output' descriptor. + static int64_t FullyConnectedBiasCount(const BatchDescriptor& output); + + // Return a BatchDescriptor for the output of a depth concatenation + // with the given input descriptors. The inputs should have the same + // dimensions, except possibly for feature_map_count(), though this + // function does not verify that. + static BatchDescriptor DepthConcatenateOutputDescriptor( + absl::Span inputs); + + private: + absl::Span spatial_size() const { + return AsInt64Slice(tensor_.dimensions()).subspan(2); + } + + absl::Span spatial_size() { + return AsInt64Slice(tensor_.mutable_dimensions()).subspan(2); + } + + TensorDescriptorProto tensor_; + float value_max_; + float value_min_; + QuantizedActivationMode quantized_activation_mode_; +}; + +// Returns a string representation of the given filter layout. +std::string FilterLayoutString(FilterLayout layout); + +// Describes a filter for the convolution. This is the "window" from +// height-by-width patches of each of the feature maps in the input layer to the +// cells within the output feature map. +// +// Uses the named argument construction form: +// +// FilterDescriptor filter_dimensions; +// filter_dimensions +// .set_output_feature_map_count(42) +// .set_input_feature_map_count(7) +// ... +// +// Arguments: +// - output_feature_map_count: number of feature maps in the output layer. +// - input_feature_map_count: number of feature maps in the input layer (from +// which the filter patch is taken). +// - input_filter_height: "height" number of neurons used in the sliding window +// over the input layer. +// - input_filter_width: "width" number of neurons used in the sliding window +// over the input layer. +// +// Sometimes names like "filter input height" are referred to by synonymous +// terminology, such as "kernel y size". +// +// If unspecified, layout defaults to kOutputInputYX. +class FilterDescriptor { + public: + // By default construction, all dimensions are set to zero, so they should all + // be populated by the user via the named-argument helpers below. (See class + // comment for details.) + FilterDescriptor(); + explicit FilterDescriptor(int ndims); + ~FilterDescriptor(); + + // Named-argument helpers for avoiding user error during construction. + FilterDescriptor& set_output_feature_map_count(int64_t value) { + tensor_.set_dimensions(0, value); + return *this; + } + FilterDescriptor& set_input_feature_map_count(int64_t value) { + tensor_.set_dimensions(1, value); + return *this; + } + FilterDescriptor& set_input_filter_height(int64_t value) { + SetDim(input_filter_dims(), DimIndex::Y, value); + return *this; + } + FilterDescriptor& set_input_filter_width(int64_t value) { + SetDim(input_filter_dims(), DimIndex::X, value); + return *this; + } + FilterDescriptor& set_layout(FilterLayout layout) { + tensor_.set_filter_layout(layout); + return *this; + } + FilterDescriptor& set_spatial_dim(DimIndex dim, int64_t value) { + SetDim(input_filter_dims(), dim, value); + return *this; + } + int ndims() const { return input_filter_dims().size(); } + + void CloneFrom(const FilterDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + TensorDescriptorProto ToProto(DataType data_type) const; + + // Returns the number of weights required as parameters for a convolution + // using this filter descriptor. + int64_t ComputeWeightCount() const; + + // Returns the number of biases required as parameters for a convolution + // using this filter descriptor. + int64_t bias_count() const { return output_feature_map_count(); } + + int64_t output_feature_map_count() const { return tensor_.dimensions(0); } + int64_t input_feature_map_count() const { return tensor_.dimensions(1); } + int64_t input_filter_height() const { + return GetDim(input_filter_dims(), DimIndex::Y); + } + int64_t input_filter_width() const { + return GetDim(input_filter_dims(), DimIndex::X); + } + int64_t input_filter_dim(DimIndex dim) const { + return GetDim(input_filter_dims(), dim); + } + + FilterLayout layout() const { return tensor_.filter_layout(); } + + absl::Span input_filter_dims() const { + return AsInt64Slice(tensor_.dimensions()).subspan(2); + } + + // Full dimensions of the underlying filter, + // ordered according to a specific layout. + std::vector full_dims(const FilterLayout& layout) const; + + // Full strides of the underlying filter, + // ordered according to a specific layout. + std::vector full_strides(const FilterLayout& layout) const; + + // Vectorized dimensions where users can specify the dimension that the number + // of dimensions is reported rather than the full number of elements. + std::vector vectorized_dims(const FilterLayout& layout, + int vector_size, int vector_dim) const; + + // Vectorized strides correspond to the vectorized_dims. + std::vector vectorized_strides(const FilterLayout& layout, + int vector_size, + int vector_dim) const; + + private: + absl::Span input_filter_dims() { + return AsInt64Slice(tensor_.mutable_dimensions()).subspan(2); + } + + TensorDescriptorProto tensor_; +}; + +// Describes how padding should be aligned when the total number of pad +// elements is odd. +enum class PadAlignment : int64_t { + kDefault = 0, // default padding for the device. + kCudnnPadding, // cuDNN padding - prefer to pad at the start. + kTensorFlowPadding, // TensorFlow padding - prefer to pad at the end. +}; + +// Returns a string representation of the given padding alignment. +std::string PadAlignmentString(PadAlignment alignment); + +// Print alignment to str. Needed to use CHECK_EQ between two PadAlignments. +std::ostream& operator<<(std::ostream& str, dnn::PadAlignment alignment); + +// Describes a convolution. +// +// Uses the named argument construction form: +// +// ConvolutionDescriptor convolution_dimensions; +// convolution_dimensions +// .set_vertical_filter_stride(2) +// .set_horizontal_filter_stride(2) +// ... +// +// Arguments: +// - zero_padding_height: padding of the "y dimension" of the input data. Note +// that this is different from the height of the filter. +// - zero_padding_width: analogous to the height above, but in the "x +// dimension". +// - vertical_filter_stride: the convolution slides a 2-dimensional window of +// filter-height-by-filter-width over the input layer -- the center of that +// window is moved in the "y dimension" according to this stride value. +// - horizontal_filter_stride: analogous to the vertical stride above, but in +// the "x dimension". +// - vertical_dilation_rate: there will be (vertical_dilation_rate - 1) skipped +// cells between each filter element in the "y dimension". +// - horizontal_dilation_rate: there will be (horizontal_dilation_rate - 1) +// skipped cells between each filter element in the "x dimension". +// - convolution_not_crosscor: By default (convolution_not_crosscor == false), +// we perform cross correlation rather than convolution. With the flag set, +// we perform convolution. Convolution and cross correlation are related by +// rotating the filter by 180 degrees (or equivalently flipping all spatial +// dimensions). +class ConvolutionDescriptor { + public: + // By default construction, there is no zero-padding and the filter stride is + // 1x1 (centering the filter on every cell in the input layer's + // width-by-height area). + ConvolutionDescriptor(); + explicit ConvolutionDescriptor(int ndims); + ~ConvolutionDescriptor(); + + std::string ToString() const; + std::string ToShortString() const; + ConvolutionDescriptorProto ToProto() const { return proto_; } + + ConvolutionDescriptor& set_zero_padding_height(int64_t value) { + SetDim(padding(), DimIndex::Y, value); + return *this; + } + ConvolutionDescriptor& set_zero_padding_width(int64_t value) { + SetDim(padding(), DimIndex::X, value); + return *this; + } + ConvolutionDescriptor& set_zero_padding(DimIndex dim, int64_t value) { + SetDim(padding(), dim, value); + return *this; + } + ConvolutionDescriptor& set_vertical_filter_stride(int64_t value) { + SetDim(strides(), DimIndex::Y, value); + return *this; + } + ConvolutionDescriptor& set_horizontal_filter_stride(int64_t value) { + SetDim(strides(), DimIndex::X, value); + return *this; + } + ConvolutionDescriptor& set_filter_stride(DimIndex dim, int64_t value) { + SetDim(strides(), dim, value); + return *this; + } + ConvolutionDescriptor& set_vertical_dilation_rate(int64_t value) { + SetDim(dilations(), DimIndex::Y, value); + return *this; + } + ConvolutionDescriptor& set_horizontal_dilation_rate(int64_t value) { + SetDim(dilations(), DimIndex::X, value); + return *this; + } + ConvolutionDescriptor& set_dilation_rate(DimIndex dim, int64_t value) { + SetDim(dilations(), dim, value); + return *this; + } + ConvolutionDescriptor& set_group_count(int group_count) { + proto_.set_group_count(group_count); + return *this; + } + ConvolutionDescriptor& set_convolution_not_crosscorr(bool conv) { + proto_.set_convolution_mode(conv ? ConvolutionMode::CONVOLUTION + : ConvolutionMode::CROSS_CORRELATION); + return *this; + } + ConvolutionDescriptor& set_name(const std::string& name) { + proto_.set_name(name); + return *this; + } + int64_t zero_padding_height() const { return GetDim(padding(), DimIndex::Y); } + int64_t zero_padding_width() const { return GetDim(padding(), DimIndex::X); } + int64_t vertical_filter_stride() const { + return GetDim(strides(), DimIndex::Y); + } + int64_t horizontal_filter_stride() const { + return GetDim(strides(), DimIndex::X); + } + int64_t vertical_dilation_rate() const { + return GetDim(dilations(), DimIndex::Y); + } + int64_t horizontal_dilation_rate() const { + return GetDim(dilations(), DimIndex::X); + } + + int zero_padding(DimIndex dim) const { return GetDim(padding(), dim); } + int filter_stride(DimIndex dim) const { return GetDim(strides(), dim); } + int dilation_rate(DimIndex dim) const { return GetDim(dilations(), dim); } + // TODO(timshen): remove this function. No users of this class is setting a + // non-default pad alignment. + PadAlignment pad_alignment() const { return PadAlignment::kDefault; } + int group_count() const { return proto_.group_count(); } + int ndims() const { return padding().size(); } + bool convolution_not_crosscorr() const { + return proto_.convolution_mode() == ConvolutionMode::CONVOLUTION; + } + + absl::Span strides() const { + return AsInt64Slice(proto_.strides()); + } + + absl::Span dilations() const { + return AsInt64Slice(proto_.dilations()); + } + + absl::Span padding() const { + return AsInt64Slice(proto_.paddings()); + } + + std::string name() const { return proto_.name(); } + + private: + absl::Span strides() { + return AsInt64Slice(proto_.mutable_strides()); + } + + absl::Span dilations() { + return AsInt64Slice(proto_.mutable_dilations()); + } + + absl::Span padding() { + return AsInt64Slice(proto_.mutable_paddings()); + } + + ConvolutionDescriptorProto proto_; + + // TODO(leary) cudnn provides these fields, but need to characterize what + // their effect is -- they may be boolean rather than integral. + // int64_t upscale_input_x; + // int64_t upscale_input_y; +}; + +// A patch of values in the input can be pooled via either a max or an average +// operation. +// Specify int64_t so there's no padding in PoolingDescriptor. +enum class PoolingMode : int64_t { + kMaximum, + kAverage, +}; + +// Specify the dimension in which to concatenate inputs in space. +// Specify int64_t so there's no padding in SpaceConcatenateMode. +enum class SpaceConcatenateMode : int64_t { + XDirection, + YDirection, +}; + +// Returns a short name for the pooling mode, e.g. "Avg". +std::string ShortPoolingModeString(PoolingMode mode); + +// Describes a pooling operation to be enqueued onto a stream via a platform's +// DnnSupport. +// +// TODO(broune): describe how padding works and what happens if the +// window height/width is not divisible by the vertical/horizontal +// stride. +// +// Arguments: +// pooling_mode: pooling operator to use on the input patch +// window_height: height of input window +// window_width: width of input window +// vertical_stride: vertical delta for center of the input patch +// horizontal_stride: horizontal delta for center of the input patch +class PoolingDescriptor { + public: + PoolingDescriptor(); + explicit PoolingDescriptor(int ndims); + + PoolingDescriptor& set_pooling_mode(PoolingMode value) { + mode_ = value; + return *this; + } + PoolingDescriptor& set_window_height(int64_t value) { + SetDim(&window_, DimIndex::Y, value); + return *this; + } + PoolingDescriptor& set_window_width(int64_t value) { + SetDim(&window_, DimIndex::X, value); + return *this; + } + PoolingDescriptor& set_window(DimIndex dim, int64_t value) { + SetDim(&window_, dim, value); + return *this; + } + PoolingDescriptor& set_vertical_padding(int64_t value) { + SetDim(&padding_, DimIndex::Y, value); + return *this; + } + PoolingDescriptor& set_horizontal_padding(int64_t value) { + SetDim(&padding_, DimIndex::X, value); + return *this; + } + PoolingDescriptor& set_padding(DimIndex dim, int64_t value) { + SetDim(&padding_, dim, value); + return *this; + } + PoolingDescriptor& set_vertical_stride(int64_t value) { + SetDim(&strides_, DimIndex::Y, value); + return *this; + } + PoolingDescriptor& set_horizontal_stride(int64_t value) { + SetDim(&strides_, DimIndex::X, value); + return *this; + } + PoolingDescriptor& set_stride(DimIndex dim, int64_t value) { + SetDim(&strides_, dim, value); + return *this; + } + PoolingDescriptor& set_propagate_nans(bool value) { + propagate_nans_ = value; + return *this; + } + PoolingDescriptor& set_name(const std::string& name) { + name_ = name; + return *this; + } + + int ndims() const { return ndims_; } + void CloneFrom(const PoolingDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + + PoolingMode mode() const { return mode_; } + int64_t window_height() const { return GetDim(window_, DimIndex::Y); } + int64_t window_width() const { return GetDim(window_, DimIndex::X); } + int64_t window(DimIndex dim) const { return GetDim(window_, dim); } + int64_t vertical_padding() const { return GetDim(padding_, DimIndex::Y); } + int64_t horizontal_padding() const { return GetDim(padding_, DimIndex::X); } + int64_t padding(DimIndex dim) const { return GetDim(padding_, dim); } + int64_t vertical_stride() const { return GetDim(strides_, DimIndex::Y); } + int64_t horizontal_stride() const { return GetDim(strides_, DimIndex::X); } + int64_t stride(DimIndex dim) const { return GetDim(strides_, dim); } + absl::Span window() const { return window_; } + absl::Span padding() const { return padding_; } + absl::Span strides() const { return strides_; } + bool propagate_nans() const { return propagate_nans_; } + std::string name() const { return name_; } + + private: + PoolingMode mode_; + int ndims_; + bool propagate_nans_; + std::string name_; // Name as in Tensorflow NodeDef, for debugging purposes. + + // Stored as: ..., y, x. + std::vector window_; + std::vector padding_; + std::vector strides_; +}; + +// Collects parameters for DNN algorithms +class AlgorithmDesc { + public: + typedef int64_t Index; + AlgorithmDesc() : AlgorithmDesc(0, false, std::nullopt) {} + explicit AlgorithmDesc(AlgorithmProto proto) : proto_(std::move(proto)) {} + AlgorithmDesc(Index algo_id, bool use_tensor_ops) + : AlgorithmDesc(algo_id, use_tensor_ops, std::nullopt) {} + AlgorithmDesc(Index algo_id, bool use_tensor_ops, + std::optional workspace_size) { + proto_.set_is_cudnn_frontend(false); + proto_.set_algo_id(algo_id); + proto_.set_math_type(use_tensor_ops ? AlgorithmProto::TENSOR_OP_MATH + : AlgorithmProto::DEFAULT_MATH); + if (workspace_size) { + proto_.mutable_workspace_size()->set_value(*workspace_size); + } + } + AlgorithmDesc(int64_t engine_id, + const std::vector>& tuning_knobs, + std::optional workspace_size); + bool is_cudnn_frontend() const { return proto_.is_cudnn_frontend(); } + + bool tensor_ops_enabled() const { + return proto_.math_type() == AlgorithmProto::TENSOR_OP_MATH; + } + std::optional workspace_size() const { + if (proto_.has_workspace_size()) { + return proto_.workspace_size().value(); + } + return std::nullopt; + } + Index algo_id() const { return proto_.algo_id(); } + + std::vector> TuningKnobs() const; + + bool operator==(const AlgorithmDesc& other) const; + + uint64_t hash() const; + + AlgorithmProto ToProto() const { return proto_; } + + std::string ToString() const; + + private: + AlgorithmProto proto_; +}; + +// Describes the result from a perf experiment. +// +// Arguments: +// algorithm: returns the exact algorithm that was used. +// elapsed_time_in_ms: returns the measured elapsed time in milliseconds. +class ProfileResult { + public: + bool is_valid() const { + return algorithm_.has_value() && + elapsed_time_in_ms() != std::numeric_limits::max(); + } + + AlgorithmDesc algorithm() const { return *algorithm_; } + void set_algorithm(AlgorithmDesc val) { algorithm_ = val; } + + float elapsed_time_in_ms() const { return elapsed_time_in_ms_; } + void set_elapsed_time_in_ms(float val) { elapsed_time_in_ms_ = val; } + + size_t scratch_size() const { return scratch_size_; } + void set_scratch_size(size_t val) { scratch_size_ = val; } + + private: + std::optional algorithm_; + float elapsed_time_in_ms_ = std::numeric_limits::max(); + // The scratch size algorithm_ requires. Currently it's only populated by + // convolutions. + size_t scratch_size_ = 0; +}; + +// Backend-specific data shared between repeated launches of the same +// convolution. +template +class OpRunner; + +// An abstract class owning cached state for a particular op/configuration. +// +// The primary motivation for this is cuDNN backend ExecutionPlans, which are +// costly to recreate. +// +// All OpRunners must be outlived by their parent Stream. +template +class OpRunner { + public: + virtual ~OpRunner() = default; + + // Get a description of the runner, for uniqueness of autotune entries. + // + // Since this is used to determine whether runners are equivalent for the + // purpose of scoring autotune entries, it shall be unique among runners of + // the same op and parameters. + virtual std::string ToString() const = 0; + + // Get the number of bytes of scratch space needed for `operator()`. + // + // If determining the workspace size can fail, runners should precompute and + // cache it at construction time. + virtual size_t GetWorkspaceSize() const = 0; + + // Convert to an AlgorithmDesc for AoT compilation or autotuning. + virtual tsl::StatusOr ToAlgorithmDesc() const = 0; + + // Launch the operation, with the signature determined by `Sig`. + virtual tsl::Status operator()(Stream*, ProfileResult*, + DeviceMemoryBase scratch_memory, + Args... args) const = 0; +}; + +using ConvSignature = void(DeviceMemoryBase /* input_data */, + DeviceMemoryBase /* filter_data */, + DeviceMemoryBase /* output_data */); +using ConvRunner = OpRunner; + +using GraphConvSignature = void(std::vector); +using GraphConvRunner = OpRunner; + +using FusedConvSignature = void(DeviceMemoryBase /* input_data */, + DeviceMemoryBase /* filter_data */, + DeviceMemoryBase /* side_input_data */, + DeviceMemoryBase /* bias_data */, + DeviceMemoryBase /* output_data */); +using FusedConvRunner = OpRunner; + +using FusedMatmulSignature = void(DeviceMemoryBase /* a_data */, + DeviceMemoryBase /* b_data */, + DeviceMemoryBase /* bias_data */, + DeviceMemoryBase /* c_data */); +using FusedMatmulRunner = OpRunner; + +using FusedMHASignature = void(DeviceMemoryBase /*BMM1_inputA_data*/, + DeviceMemoryBase /* BMM1_inputB_data */, + DeviceMemoryBase /* BMM2_inputA_data */, + DeviceMemoryBase /* output_data */, + DeviceMemoryBase /* mask_data */, + DeviceMemoryBase /* bias_data */, + DeviceMemoryBase /* activation_data */); +using FusedMHARunner = OpRunner; + +using FusedMHABackwardSignature = void( + DeviceMemoryBase /* BMM1_GRAD_GEMM1_inputA_data */, + DeviceMemoryBase /* BMM1_GRAD_GEMM2_inputB_data */, + DeviceMemoryBase /* BMM2_GRAD_GEMM1_inputA_data */, + DeviceMemoryBase /* BMM2_GRAD_GEMM2_inputB_data */, + DeviceMemoryBase /* d_output_data */, + DeviceMemoryBase /* d_BMM1_inputA_data */, + DeviceMemoryBase /* d_BMM1_inputB_data */, + DeviceMemoryBase /* d_BMM2_inputB_data */, DeviceMemoryBase /* d_s_data */, + DeviceMemoryBase /* mask_data */, DeviceMemoryBase /* d_bias_data */); +using FusedMHABackwardRunner = OpRunner; + +// Describes the configuration for the algorithms that will used. +// +// Arguments: +// algorithm: the primary algorithm that should be used. +// algorithm_no_scratch: a secondary algorithm that should be used, if the +// the allocation for the scratch memory fails. +// scrach_size: specify the size of scratch memory in bytes needed for the +// algorithm used. +// +// On CUDA platform with CUDNN library, algorithm and algorithm_no_scratch +// would be used. On ROCm platform with MIOpen library, algorithm and +// scratch_size would be used. The major difference between the two platforms +// are whether it's possible to get an algorithm without scratch memory. On +// CUDA + CUDNN it's possible, and algorithm_no_scratch can be used to track +// such information, whereas on ROCm + MIOpen there is no guarantee to getting +// one without scratch memory, and scratch_size field is used to track it. +class AlgorithmConfig { + public: + AlgorithmConfig() = default; + explicit AlgorithmConfig(AlgorithmDesc algorithm) : algorithm_(algorithm) {} + AlgorithmConfig(AlgorithmDesc algorithm, size_t scratch_size) + : algorithm_(algorithm), scratch_size_(scratch_size) {} + AlgorithmConfig(AlgorithmDesc algorithm, AlgorithmDesc algorithm_no_scratch) + : algorithm_(algorithm), algorithm_no_scratch_(algorithm_no_scratch) {} + AlgorithmConfig(AlgorithmDesc algorithm, size_t scratch_size, + AlgorithmDesc algorithm_no_scratch) + : algorithm_(algorithm), + algorithm_no_scratch_(algorithm_no_scratch), + scratch_size_(scratch_size) {} + + // TODO(ruochengw): After cl/380702564, add support for algorithm configs with + // cuDNN Frontend APIs. + explicit AlgorithmConfig(const AlgorithmConfigProto& algorithm_config_proto) { + const AlgorithmProto& algorithm_proto = algorithm_config_proto.algorithm(); + algorithm_ = AlgorithmDesc(algorithm_proto); + if (algorithm_config_proto.optional_scratch_size_case() != + /*ONEOF_NAME_NOT_SET=*/0) { + scratch_size_ = algorithm_config_proto.scratch_size(); + } + if (algorithm_config_proto.optional_algorithm_no_scratch_case() != + /*ONEOF_NAME_NOT_SET=*/0) { + const AlgorithmProto& algorithm_no_scratch_proto = + algorithm_config_proto.algorithm_no_scratch(); + algorithm_no_scratch_ = AlgorithmDesc(algorithm_no_scratch_proto); + } + } + + std::optional algorithm() const { return algorithm_; } + void set_algorithm(AlgorithmDesc val) { algorithm_ = val; } + std::optional algorithm_no_scratch() const { + return algorithm_no_scratch_; + } + void set_algorithm_no_scratch(AlgorithmDesc val) { + algorithm_no_scratch_ = val; + } + std::optional scratch_size() const { return scratch_size_; } + void set_scratch_size(size_t val) { scratch_size_ = val; } + bool operator==(const AlgorithmConfig& other) const { + return this->algorithm_ == other.algorithm_ && + this->algorithm_no_scratch_ == other.algorithm_no_scratch_ && + this->scratch_size_ == other.scratch_size_; + } + bool operator!=(const AlgorithmConfig& other) const { + return !(*this == other); + } + std::string ToString() const; + + // TODO(ruochengw): After cl/380702564, add support for algorithm configs with + // cuDNN Frontend APIs. + AlgorithmConfigProto ToProto() const { + AlgorithmConfigProto algorithm_config_proto; + if (algorithm_.has_value()) { + *algorithm_config_proto.mutable_algorithm() = + algorithm_.value().ToProto(); + } + if (algorithm_no_scratch_.has_value()) { + *algorithm_config_proto.mutable_algorithm_no_scratch() = + algorithm_no_scratch_.value().ToProto(); + } + if (scratch_size_.has_value()) { + algorithm_config_proto.set_scratch_size(scratch_size_.value()); + } + return algorithm_config_proto; + } + + private: + std::optional algorithm_; + std::optional algorithm_no_scratch_; + std::optional scratch_size_; +}; + +// Describes a local response normalization (LRN). LRN is used e.g. in +// dist_belief. +// +// Let V be the vector of feature maps at some (batch, y, x) +// coordinate. LRN applies independently to each vector V in the +// input, across all coordinates (batch, y, x), by mapping each V to +// another vector U of the same size using the formula +// +// U_i = V_i / ((bias + alpha * (sum_j V_j^2)) ^ beta) +// +// where the sum is taken over j in the closed range [i - range, i + range]. +// +// When calculating U_i the j in the sum can extend beyond the bounds +// of V. If wrap_around is true, then V_j = V_{j mod F} where F is the +// size of V, which is the number of feature maps. If wrap_around is +// false, then V_j = 0 for j outside [0, F-1]. +// +// If segment_size <= F, where F is the number of feature_maps, then +// segment_size has no effect. Otherwise, each consecutive segment of +// segment_size entries in V are normalized separately. +// +// Not all StreamExecutors allow wrap_around == true or segment_size +// != 64. Some do not implement normalization at all. +class NormalizeDescriptor { + public: + NormalizeDescriptor(); + + NormalizeDescriptor& set_bias(float bias) { + bias_ = bias; + return *this; + } + + NormalizeDescriptor& set_range(int32_t range) { + range_ = range; + return *this; + } + + NormalizeDescriptor& set_alpha(float alpha) { + alpha_ = alpha; + return *this; + } + + NormalizeDescriptor& set_beta(float beta) { + beta_ = beta; + return *this; + } + + NormalizeDescriptor& set_wrap_around(bool wrap_around) { + wrap_around_ = wrap_around; + return *this; + } + + NormalizeDescriptor& set_segment_size(int32_t segment_size) { + segment_size_ = segment_size; + return *this; + } + + void CloneFrom(const NormalizeDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + + float bias() const { return bias_; } + int32_t range() const { return range_; } + float alpha() const { return alpha_; } + float beta() const { return beta_; } + bool wrap_around() const { return wrap_around_; } + int32_t segment_size() const { return segment_size_; } + + private: + float bias_; + int32_t range_; + float alpha_; + float beta_; + bool wrap_around_; + int32_t segment_size_; +}; + +// Returns a string representation of the given activation mode. +std::string ActivationModeString(ActivationMode mode); + +// Describes the operation that DoElementwiseOperation should perform on its +// inputs. +enum class ElementwiseOperation { kAdd, kMultiply }; + +std::string ElementwiseOperationString(ElementwiseOperation op); + +// A simple class representing the version of the backing library, to +// workaround the "too perfect forwarding" issue in gcc6+ compilers. +// See PR#16309 and issue #18402 for links discussing the issue. +class VersionInfo { + public: + explicit VersionInfo(int major = 0, int minor = 0, int patch = 0) + : major_(major), minor_(minor), patch_(patch) {} + explicit VersionInfo(DnnVersionInfoProto proto) + : major_(proto.major()), minor_(proto.minor()), patch_(proto.patch()) {} + + DnnVersionInfoProto ToProto() const { + DnnVersionInfoProto proto; + proto.set_major(major_); + proto.set_minor(minor_); + proto.set_patch(patch_); + return proto; + } + + int major_version() const { return major_; } + int minor_version() const { return minor_; } + int patch() const { return patch_; } + + std::tuple as_tuple() const { + return std::make_tuple(major_, minor_, patch_); + } + + friend bool operator<(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() < b.as_tuple(); + } + friend bool operator>(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() > b.as_tuple(); + } + friend bool operator<=(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() <= b.as_tuple(); + } + friend bool operator>=(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() >= b.as_tuple(); + } + friend bool operator==(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() == b.as_tuple(); + } + friend bool operator!=(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() != b.as_tuple(); + } + + std::string ToString() const { + return absl::StrCat(major_, ".", minor_, ".", patch_); + } + + private: + int major_; + int minor_; + int patch_; +}; + +// Suite of operations typically used for implementing Deep/Convolutional Neural +// Nets. Note: A false return value of an operation indicates the +// implementation is not available. +// +// TODO(b/118763918): this class (or rather dispatch table) has several +// problems: +// * Some overloads are missing. Ideally we want to have template virtual +// functions while the template arguments is a closed set. However, we don't +// get that from the language. +// * The API is a union of cuDNN and another private backend. Only 10% of the +// functions are actually implemented by both backends, the rest are +// actually backend-specific. The massive interface creates extra mental +// burden. +// * Poor error handling: the API should return tsl::Status objects. +// +// PrepareForConvolution is an example for how new APIs should be written. +class DnnSupport { + public: + DnnSupport() = default; + virtual ~DnnSupport() = default; + + virtual tsl::Status Init() = 0; + + // Gets the version of the backing library, as a VersionInfo object. + virtual tsl::StatusOr GetVersion() { + return tsl::errors::Unimplemented( + "DnnSupport::GetVersion not implemented on this platform."); + } + + // Performs a single-precision forward batch normalization operation onto + // the stream. + // + // Arguments: + // stream: borrowed pointer to the stream that the batch normalization + // operation should be enqueued onto. + // x: input data. + // scale: scaling parameters. + // offset: offset parameters. + // estimated_mean: population mean estimated during training. + // Used for inference only; empty for training. + // estimated_variance: population variance estimated during training, + // used for inference only; empty for training. + // side_input: optional input that is element-wise added to the output of + // batch normalization. + // x_desc: dimensions of the input data, which is the same as the dimensions + // of the output and side input. + // scale_offset_desc: dimensions of scale and offset. + // epsilon: a small floating point number added to the variance of x. + // activation_mode: activation applied to the result of batch normalization + // (or after adding optional side input) + // y: output data. + // batch_mean: batch mean, to be used to compute the running mean. + // batch_variance: batch variance, to be used to compute + // the running variance. + // reserve_space_1: saved mean, to be reused in the backward gradient + // computation. + // reserve_space_2: saved inv_var (1/sqrt(epsilon + variance), to be reused + // in the backward gradient computation. + // is_training: Set to true for training, false for inference. + virtual bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* reserve_space_1, + DeviceMemory* reserve_space_2, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a half-precision forwards batch normalization operation onto the + // stream. See DoBatchNormalizationForward above for argument details. + virtual bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* reserve_space_1, + DeviceMemory* reserve_space_2, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a bfloat16 forward batch normalization operation onto the + // stream. See DoBatchNormalizationForward above for argument details. + virtual bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* reserve_space_1, + DeviceMemory* reserve_space_2, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a single-precision backward batch normalization gradient + // computation operation onto the stream. + // + // Arguments: + // stream: borrowed pointer to the stream that the batch normalization + // gradient computation operation should be enqueued onto. + // y_backprop: gradient with regard to output y. + // x: input data. + // scale: scaling parameters. + // inv_var: 1/sqrt(epsilon + variance) of x. + // x_desc: dimensions of the input data, which is the same as the dimensions + // of the output. + // scale_offset_desc: dimensions of scale and offset. + // epsilon: a small floating point number added to the variance of x. + // x_backprop: gradient with respect to input x. + // scale_backprop: gradient with respect to scale. + // offset_backprop: gradient with respect to offset. + virtual bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a half-precision backward batch normalization gradient computation + // operation onto the stream. See DoBatchNormalizationBackward above for + // argument details. + virtual bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a bfloat16 backward batch normalization gradient computation + // operation onto the stream. See DoBatchNormalizationBackward above for + // argument details. + virtual bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, + const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Enqueues a fused convolution operation onto the stream. + // We provide several variants with different types for inputs, biases and + // scaling parameters. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'convolve' operation + // should be enqueued onto. + // conv_input_descriptor: dimensions of the convolution input layer. + // conv_input_data: un-owned device memory region which contains the + // convolution input. + // conv_input_scale: a floating point scale to multiply with each element + // of conv_input_data. + // filter_descriptor: dimensions of the convolution filter. + // filter_data: un-owned device memory region which contains the + // convolution filter weights. + // convolution_descriptor: stride of the convolution filter. + // biases: un-owned device memory region containing biases to add to the + // input. + // activation_mode: Type of activation to perform. + // side_input_data: un-owned device memory region which contains optional + // side input data. If 'side_input_scale' is non-zero, then this must + // point to data in the tensor shape specified by output_shape. + // It will be scaled by 'side_input_scale' and added to the convolution + // result and bias prior to applying the activation function. + // side_input_scale: a floating point scale to multiply with each element + // of side_input_data. + // output_descriptor: dimensions of the output layer. + // output_data: un-owned device memory region in which to place the + // convolution result. + // scratch_allocator: un-owned, may-be-null object that may allocate scratch + // space in order to speed up the convolution operation. + // algorithm_config: specifies which algorithm should be used for the + // operation. + // output_profile_result: the output profile result for this call. The + // profiling is only enabled when this is not nullptr. + // + // conv_input_descriptor, filter_descriptor, convolution_descriptor and + // output_descriptor together specify exactly how the convolution is aligned + // with the input data: + // + // * (input dimensions - filter size + 1) / filter stride == output dimensions + // corresponds to dist_belief padding = VALID, i.e. the input is not padded. + // * input dimensions / filter stride == output dimensions + // corresponds to dist_belief padding = SAME, i.e. input and output are the + // same size - this requires padding the input. + // * (input dimensions + filter size - 1) / filter stride == output dimensions + // corresponds to dist_belief padding = FULL, i.e. the output is sized so + // that if the inverse of the filter is applied to the output in VALID mode + // the result is the same size as the input - this requires even more + // padding of the input. + virtual tsl::Status DoFusedConvolve( + Stream* stream, DataType input_type, DataType side_input_type, + DataType bias_type, DataType output_type, + const dnn::BatchDescriptor& conv_input_descriptor, + DeviceMemoryBase conv_input_data, double conv_input_scale, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + DeviceMemoryBase side_input_data, double side_input_scale, + const dnn::BatchDescriptor& bias_descriptor, DeviceMemoryBase biases, + dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, ScratchAllocator* scratch_allocator, + const dnn::AlgorithmConfig& algorithm_config, + dnn::ProfileResult* output_profile_result) { + return tsl::errors::Unimplemented( + "DnnSupport::DoFusedConvolve not implemented on this platform."); + } + + template + tsl::Status PrepareForConvolution( + ConvolutionKind kind, Stream* stream, + const BatchDescriptor& batch_descriptor, + DeviceMemory input_data, + const FilterDescriptor& filter_descriptor, + DeviceMemory filter_data, + const BatchDescriptor& output_descriptor, + DeviceMemory output_data, + const ConvolutionDescriptor& convolution_descriptor, + const AlgorithmConfig& algorithm_config, + ScratchAllocator* scratch_allocator, AlgorithmDesc* algorithm_desc, + DeviceMemory* scratch_memory) { + return DoPrepareForConvolution( + kind, ToDataType::value, stream, batch_descriptor, + input_data, filter_descriptor, filter_data, output_descriptor, + output_data, convolution_descriptor, algorithm_config, + scratch_allocator, algorithm_desc, scratch_memory); + } + + // cuDNN-specific input transformation that allows running int8x32 + // convolutions faster using Tensor Core IMMA instruction. + virtual tsl::Status CudnnReorderConvolutionFilterAndBias( + Stream* stream, const FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_input, + DeviceMemory* filter_output, + std::optional> bias_input, + std::optional> bias_output) { + return tsl::errors::Unimplemented( + "DnnSupport::CudnnReorderConvolutionFilterAndBias is specific to CUDA " + "convolution implementation."); + } + + // Enqueues a single-precision convolution operation onto the stream. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'convolve' operation + // should be enqueued onto. + // input_descriptor: dimensions of the input layer. + // input_data: un-owned device memory region which contains the + // convolution input. + // filter_descriptor: dimensions of the convolution filter. + // convolution_descriptor: stride of the convolution filter. + // output_descriptor: dimensions of the output layer. + // output_data: un-owned device memory region in which to place the + // convolution result. + // algorithm_desc: specifies which algorithm should be used for the + // operation. + // scratch: un-owned device memory for scratch space in order to speed up + // the convolution operation. + // output_profile_result: the output profile result for this call. The + // profiling is only enabled when this is not nullptr. + // + // input_descriptor, filter_descriptor, convolution_descriptor and + // output_descriptor together specify exactly how the convolution is aligned + // with the input data: + // + // * (input dimensions - filter size + 1) / filter stride == output dimensions + // corresponds to dist_belief padding = VALID, i.e. the input is not padded. + // * input dimensions / filter stride == output dimensions + // corresponds to dist_belief padding = SAME, i.e. input and output are the + // same size - this requires padding the input. + // * (input dimensions + filter size - 1) / filter stride == output dimensions + // corresponds to dist_belief padding = FULL, i.e. the output is sized so + // that if the inverse of the filter is applied to the output in VALID mode + // the result is the same size as the input - this requires even more + // padding of the input. + virtual tsl::Status DoConvolve( + ConvolutionKind kind, DataType element_type, DataType output_type, + Stream* stream, const BatchDescriptor& input_descriptor, + DeviceMemoryBase input_data, const FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, const BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const ConvolutionDescriptor& convolution_descriptor, + AlgorithmDesc algorithm_desc, DeviceMemory scratch_memory, + ProfileResult* output_profile_result) = 0; + + virtual tsl::Status GetConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, ScratchAllocator* scratch_allocator, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + virtual tsl::StatusOr> + ConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor); + + virtual tsl::Status GetGraphConvolveRunners( + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, const NumericOptions& numeric_options, + std::vector>* out_exec_plans, + std::string serialized_graph); + + virtual tsl::StatusOr> + GraphConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + std::string serialized_graph); + + virtual tsl::Status GetFusedConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_input_scale, + double side_input_scale, double leakyrelu_alpha, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, dnn::ActivationMode activation_mode, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + virtual tsl::Status GetFusedMatmulRunners( + bool use_cudnn_frontend, dnn::DataType element_type, + dnn::DataType bias_type, dnn::DataType output_type, Stream* stream, + bool trans_a, bool trans_b, uint64_t m, uint64_t n, uint64_t k, + int64_t lda, int64_t ldb, int64_t ldc, + dnn::ActivationMode activation_mode, bool use_fallback, + const NumericOptions& numeric_options, + std::vector>* + out_exec_plans); + + virtual tsl::StatusOr> + FusedConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType bias_type, dnn::DataType output_type, double conv_scale, + double side_input_scale, double leakyrelu_alpha, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::ActivationMode activation_mode); + + virtual tsl::StatusOr> + FusedMHARunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor& bmm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& intermediate_bmm2_lhs_descriptor, + const dnn::TensorDescriptor& output_descriptor, + std::optional activation_descriptor, + std::optional mask_descriptor, + std::optional bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed); + + virtual tsl::StatusOr> + FusedMHABackwardRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const MatmulTensorDescriptor& bmm1_grad_gemm1_rhs_descriptor, + const MatmulTensorDescriptor& bmm1_grad_gemm2_rhs_descriptor, + const MatmulTensorDescriptor& bmm2_grad_gemm1_lhs_descriptor, + const MatmulTensorDescriptor& bmm2_grad_gemm2_rhs_descriptor, + const MatmulTensorDescriptor& d_output_descriptor, + const TensorDescriptor& d_bmm1_lhs_descriptor, + const TensorDescriptor& d_bmm1_rhs_descriptor, + const TensorDescriptor& d_bmm2_rhs_descriptor, + const TensorDescriptor& d_s_descriptor, + std::optional mask_descriptor, + std::optional d_bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed); + + virtual bool GetMIOpenConvolveAlgorithms( + dnn::ConvolutionKind kind, dnn::DataType element_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + ScratchAllocator* scratch_allocator, + std::vector* out_algorithms); + + // Returns a list of supported rnn algorithms. + virtual bool GetRnnAlgorithms(std::vector* out_algorithms); + + // Version of DoConvolve that uses pre-quantized 8 bit coefficients. + // coefficient_scales specifies the scaling of each column of coefficients: + // original float coefficient[row * num_columns + column] = + // quantized coefficient[row * num_columns + column] * + // coefficient_scales[column]. + virtual bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) = 0; + + // Same as DoConvolveQuantized above, but int8 filter coefficients. + virtual bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) = 0; + + // Variation of the above with the weight matrix split into two matrices. + // first_weights: Coefficients of the first matrix. + // second_weights: Coefficients of the second matrix. + // depth_multiplier: specifies the columns of the first matrix and rows + // of the second one - first_weights columns = depth_multiplier, + // second_weights rows = depth_multiplier * + // filter_descriptor.input_feature_map_count(). + // see go/separable for documentation on separable convolutions. + virtual bool DoSeparableConvolve( + Stream* stream, const BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const FilterDescriptor& filter_descriptor, int depth_multiplier, + const DeviceMemory& first_weights, + const DeviceMemory& second_weights, + const ConvolutionDescriptor& convolution_descriptor, + const BatchDescriptor& output_descriptor, + DeviceMemory* output_data) = 0; + + // Fully connects the "nodes" (float values) in input_data with + // shape input_dimensions to output_data with output_dimensions + // using provided weights. This is equivalent to computing a matrix + // product, hence the name MatMul. + // + // A BatchDescriptor has four dimensions: batch, y, x, depth. Matrix products + // happen in two dimensions. To get down to two dimensions, we consider the + // input y, x and depth dimension as one combined dimension T. For now, + // assume that the output height and width are 1 and let OD be the output + // depth. + // + // There are three device memory buffers passed in to this + // function. We can now view all three as matrices: + // + // input_data: A batch x T matrix + // weights: A T x OD matrix + // output_data: A batch x OD matrix + // + // This function then computes the matrix product of input_data and + // weights and writes the result into output_data. + // + // Here the weights buffer is in row major order, i.e. the first OD + // entries in weights are the first row, the second OD entries in + // weights are the second row and so on. + // + // The case for output width*height > 1 is more complicated. Let K = + // OY * OX where OY is the output height and OX is the output + // width. Then weights is divided into K sub-arrays W_i, for + // i=0,...,k-1, that each represent a T x OD matrix. This function + // then computes the K matrix multiplications of input_data with + // each W_i. This creates K matrices with dimensions batch x + // OD. These K matrices are concatenated horizontally to form one + // larger matrix with dimensions batch x (K*OD); note that this is + // not the same as concatenating the bytes of the matrices. The + // combined matrix can then be interpreted as a tensor with + // dimensions (batch, OY, OX, OD). If the output tensor format is + // not kBatchYXDepth, this function would then need to arrange for + // the output to be in the requested layout, if that is + // supported. Note that the case K=1 is equivalent to the + // description above. It is recommended to prefer the case K=1. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'fully connect' operation + // should be enqueued onto. + // output_data: un-owned device memory region in which to place the + // fully connected result. + virtual bool DoMatMul(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& weights, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Version of DoMatMul that uses pre-quantized 8 bit weights. + // weight_scales specifies the scaling of each column of weights: + // original float weight[row * num_columns + column] = + // quantized_weight[row * nnum_columns + column] * weight_scales[column]. + virtual bool DoMatMulQuantized(Stream* stream, + const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Version of DoMatMul that uses pre-quantized 16 bit weights. + // weight_scales specifies the scaling of each column of weights: + // original float weight[row * num_columns + column] = + // quantized_weight[row * nnum_columns + column] * weight_scales[column]. + virtual bool DoMatMulQuantized(Stream* stream, + const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Adds biases to the feature maps in input_data producing + // output_data. input_data can equal output_data, but must not + // partially overlap it. + // + // Let K = count() * height() * width() and N = feature_map_count() + // on dimensions. Then input_value contains K*N values and biases + // contains N values. We can thus logically consider input_value to + // contain K vectors of N elements each. This function adds biases + // to each of those N vectors. + // + // TODO(broune): This works differently when width() * height() > 1 + // and the call to ThenBiasAdd() follows a call to ThenMatMul(). In + // that case there should be width() * height() * + // feature_map_count() biases, but this is not implemented on all + // StreamExecutors. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'bias add' operation + // should be enqueued onto. + // input_data: un-owned device memory region containing the input. + // biases: un-owned device memory region containing biases to add to the + // input. + // dimensions: dimensions of input_data and output_data. + // output_data: un-owned device memory region in which to place the result. + virtual bool DoBiasAdd(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& biases, + const dnn::BatchDescriptor& dimensions, + DeviceMemory* output_data) = 0; + + // Performs a forward pooling operation on input_data, writing to + // output_data. See PoolingDescriptor for how to configure the + // pooling operation. + // + // Pooling happens as a window that moves across the Y and X + // dimensions of input_data, where each position of the window + // yields one output value. E.g. for max pooling, the computed value + // is the maximum element in the window. The operation is applied + // independently to each batch and at each feature map (depth), so + // that the output depth and feature_map_count are the same as for + // the input. The output width and height can be different. + // + // See PoolingDescriptor for how to configure the pooling operation. + virtual tsl::Status DoPoolForward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, ScratchAllocator* workspace_allocator) = 0; + + virtual tsl::Status DoPoolForward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, ScratchAllocator* workspace_allocator); + + // Performs differentiation of the pooling operation. + virtual tsl::Status DoPoolBackward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, + ScratchAllocator* workspace_allocator) = 0; + + virtual tsl::Status DoPoolBackward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, ScratchAllocator* workspace_allocator); + + // Applies local response normalization to the values from input_data and + // writes the result to output_data. + // + // See comments on NormalizeDescriptor for a description of local response + // normalization. + virtual bool DoNormalizeWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, DeviceMemory* output_data) { + return false; + } + + // Performs backpropagation for the normalization operation + // + // Given raw data, its corresponding normalized output, and a gradient of some + // unspecified function with respect to the normalized variables, computes the + // gradient of that unspecified function with respect to the raw variables. + // + // The normalized data input array is expected to match the output that would + // be obtained by running the raw data input array through the DoNormalize + // method above. + // + // See comments on NormalizeDescriptor for a description of local response + // normalization. + virtual bool DoNormalizeBackwardWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& raw_data, + const DeviceMemory& normalized_data, + const DeviceMemory& normalized_variable_gradient, + DeviceMemory* raw_variable_gradient, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Applies an activation function (see ActivationMode) to all of the values + // held on the device in 'input_data', whose dimensions are described by + // 'dimensions'. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'activate' operation + // should be enqueued onto. + // activation_mode: Type of activation to perform. + // input_data: un-owned device memory region which contains the + // activate input. + // output_data: un-owned device memory region in which to place the + // activate result. + virtual bool DoActivate(Stream* stream, ActivationMode activation_mode, + const BatchDescriptor& dimensions, + const DeviceMemory& input_data, + DeviceMemory* output_data, uint64_t options) { + return false; + } + + // Concatenates several layers into one, by concatenating the depth of each + // layer at matching x and y coordinates. + // The inputs must all have the same width and height, the output will have + // the same width and height as the inputs and its depth will be the sum of + // the input depths. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'depth concatenate' + // operation should be enqueued onto. + // input_dimensions: The dimensions of each input. + // input_data: un-owned device memory region which contains the + // input data for each input layer. + // output_data: un-owned device memory region in which to place the + // depth concatenate result. + virtual bool DoDepthConcatenate( + Stream* stream, absl::Span input_dimensions, + absl::Span* const> input_data, + DeviceMemory* output_data) = 0; + + // Depth to space takes an X by Y image with depth D*M^2 and changes it to an + // MX x MY image with depth D. Each input location (x,y) with depth D*M^2 in + // the input image is changed to an MxM contiguous area in the output image, + // with the values being laid out in the raster order by DepthToSpaceLayout, + // and will have a new depth of D. + // + // Example. + // M=2, Din =8, Xin=2, Yin=2. Xout=4, Yout=4, Dout=2 + // DepthHeightWidth layout + // Values within a 'cell' are at different depths and same x & y. + // Input: + // abcdefgh ijklmnop + // qrstuvwx yz012345 + // Output: + // ae bf im jn + // cg dh ko lp + // qu rv y2 z3 + // sw tx 04 15 + // + // sqrt_depth_reduction: 'M' in the comment above + virtual bool DoDepthToSpace(Stream* stream, + const dnn::BatchDescriptor& input_dimensions, + const DeviceMemory& input_data, + const DepthToSpaceLayout& depth_to_space_layout, + const int& sqrt_depth_reduction, + DeviceMemory* output_data) { + return false; + } + + // Computes the specified operation (e.g. addition or multiplication) + // between corresponding elements in the inputs and stores the result in the + // output element. + // The inputs and output must all have the same dimensions, but may have + // different quantization parameters (min_value and max_value). + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // operation: The operation to perform. + // input_dimensions: The dimensions of each input. + // input_data: un-owned device memory region which contains the + // input data for each input layer. + // output_dimensions: The dimensions of the output. + // output_data: un-owned device memory region in which to place the + // operation result. + virtual bool DoElementwiseOperate( + Stream* stream, ElementwiseOperation operation, + absl::Span input_dimensions, + absl::Span* const> input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Computes the specified operation (e.g. addition or multiplication) + // between corresponding elements in the inputs and stores the result in the + // output element. Each input is multiplied by a scalar constant and the + // result is divided by a scalar constant. + // e.g. To perform Z = 0.9*X + 1.1*Y, set the input multiplicands to 9 and 11 + // and the output divisor to 10. + // The inputs and output must all have the same dimensions, but may have + // different quantization parameters (min_value and max_value). + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // operation: The operation to perform. + // input_multiplicands: Amount to scale each input. + // output_divisor: Amount to divide the output. + // input_dimensions: The dimensions of each input. + // input_data: un-owned device memory region which contains the + // input data for each input layer. + // output_dimensions: The dimensions of the output. + // output_data: un-owned device memory region in which to place the + // operation result. + virtual bool DoElementwiseOperateScaledQuantized( + Stream* stream, ElementwiseOperation operation, + absl::Span input_multiplicands, int output_divisor, + absl::Span input_dimensions, + absl::Span* const> input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) { + return false; + } + + // Pads the input with zeros in the X and Y dimensions. The feature_map + // dimension is unchanged. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // dimensions: The dimensions of the input. + // input_data: un-owned device memory region which contains the + // input data for the input layer. + // left_pad: Amount to pad the input on the left. + // right_pad: Amount to pad the input on the right. + // top_pad: Amount to pad the input at the top (low Y). + // bottom_pad: Amount to pad the input at the bottom (high Y). + // output_data: un-owned device memory region in which to place the + // padded result. + virtual bool DoXYPad(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, int64_t left_pad, + int64_t right_pad, int64_t top_pad, int64_t bottom_pad, + DeviceMemory* output_data) = 0; + + // Extracts a slice of the input in the X and Y dimensions. The feature_map + // dimension is unchanged. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // dimensions: The dimensions of the input. + // input_data: un-owned device memory region which contains the + // input data for the input layer. + // left_trim: Amount to cut off the input on the left. + // right_trim: Amount to cut off the input on the right. + // top_trim: Amount to cut off the input at the top (low y). + // bottom_trim: Amount to cut off the input at the bottom (high Y). + // output_data: un-owned device memory region in which to place the + // padded result. + virtual bool DoXYSlice(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + int64_t left_trim, int64_t right_trim, + int64_t top_trim, int64_t bottom_trim, + DeviceMemory* output_data) = 0; + + // Grows the input tensor by replicating the X and Y dimensions. The batch and + // depth/feature_map dimensions are unchanged. Currently, the input tensor is + // limited to X=1 and Y=1. + // + // For example, the input has dimensions x=2, y=3, and replicate_x=3, + // replicate_y=2. The diagonal elements of the output would be: [x0y0, x1y1, + // x0y2, x1y0, x0y1, x1y2]. + // Here is the example as a picture. input: + // AB + // CD + // EF + // broadcast result: + // ABABAB + // CDCDCD + // EFEFEF + // ABABAB + // CDCDCD + // EFEFEF + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // dimensions: The dimensions of the input. + // input_data: un-owned device memory region which contains the + // input data for the input layer. + // replicate_x: Amount to replicate the input's X dimension. + // replicate_y: Amount to replicate the input's Y dimension. + // output_data: un-owned device memory region in which to place the + // padded result. + virtual bool DoXYBroadcast(Stream* stream, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + int64_t replicate_x, int64_t replicate_y, + DeviceMemory* output_data) { + return false; + } + + // Enqueues an asynchronous memcpy of the *quantized* output of a layer (that + // is, bytes instead of scaled floats) into 'host_dst' if they are available + // for the underlying DNN implementation. If this quantized output is not + // available, false is returned, which will place 'stream' into an error + // state. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'quantized memcpy' + // operation should be enqueued onto. + // gpu_unquantized_src: the device memory that contains the unquantized data + // -- this data should also have a corresponding quantized representation + // on the device for this operation to succeed. + // mode: Type of quantization of the data to write into host_dst. + // host_dst: un-owned host memory region that is mutated in place, + // it is clobbered by the values in 'gpu_unquantized_src' when the enqueued + // (asynchronous) memcpy operation is performed. + // size: size in bytes of the host_dst host memory region. + virtual bool DoMemcpyD2HQuantized( + Stream* stream, const DeviceMemory& gpu_unquantized_src, + QuantizedActivationMode mode, void* host_dst, int64_t size) = 0; + + // Enqueues an asynchronous memcpy of 'host_dst' into the *quantized* input + // of a layer (that is, bytes instead of scaled floats) if they are supported + // by the underlying DNN implementation. If this quantized input is not + // supported, false is returned, which will place 'stream' into an error + // state. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'quantized memcpy' + // operation should be enqueued onto. + // host_src: un-owned host memory region that contains the quantized data. + // size: size in bytes of the host_src host memory region. + // mode: Type of quantization of the data to read from host_src. + // gpu_unquantized_dst: the device memory that is clobbered by the values in + // 'host_src' when the enqueued (asynchronous) memcpy operation is + // performed. -- this data should also have a corresponding quantized + // representation on the device for this operation to + // succeed. + virtual bool DoMemcpyH2DQuantized( + Stream* stream, const void* host_src, int64_t size, + QuantizedActivationMode mode, + DeviceMemory* gpu_unquantized_dst) = 0; + + // Create an RNN descriptor based on model shapes and configurations. + // The caller retains the ownership of the descriptor. + // + // Arguments: + // num_layers: the number of layers for a RNN model. + // hidden_size: the size of the hidden state. + // input_size: the size of the input state. + // cell_size: the size of the cell state + // input_mode: an enum to specify whether a linear transformation is added + // after the input state. If input_size is different from hidden_size, this + // is required. + // direction_mode: an enum to specify whether this model is unidirectional or + // bidirectional. + // rnn_mode: an enum to specify the type of model to build. + // data_type: an enum to specify the data types used in this model. + // dropout: the dropout threshold between layers. When it is 0., no dropout + // is added. + // seed: a seed for initializing the dropout layers. + // state_allocator: an memory allocator that will be used to store the state + // for dropout layer. The user has to maintain the memory until the model + // is no longer in use. + // use_padded_io: a bool to specify whether the input is using padded IO. + virtual tsl::StatusOr> + createRnnDescriptor(int num_layers, int hidden_size, int input_size, + int cell_size, int batch_size, + dnn::RnnInputMode input_mode, + dnn::RnnDirectionMode direction_mode, + dnn::RnnMode rnn_mode, dnn::DataType data_type, + const dnn::AlgorithmConfig& algorithm_config, + const NumericOptions& numeric_options, float dropout, + uint64_t seed, ScratchAllocator* state_allocator, + bool use_padded_io) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnDescriptor is unimplemented"); + } + + // Create a RNN sequence descriptor that specifies either the input or output + // sequence. The caller retains the ownership of the returned descriptor. + // + // Arguments: + // max_seq_length: the max length of the sequences. + // batch_size: the size of a minibatch. + // data_size: the size of the state. + // seq_lengths: the lengths of sequences in a batch. + // data_type: an enum to specify the type for the underlying data. + virtual tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, dnn::DataType data_type) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnSequenceTensorDescriptor is unimplemented"); + } + + virtual tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + const absl::Span& seq_lengths, + bool time_major, dnn::DataType data_type) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnSequenceTensorDescriptor is unimplemented"); + } + + // Create an RNN state descriptor that specifies the input or hidden state. + // The caller retains the ownership of the returned descriptor. + virtual tsl::StatusOr> + createRnnStateTensorDescriptor(int num_layer, int batch_size, int data_size, + dnn::DataType data_type) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnStateTensorDescriptor is unimplemented"); + } + + // Enqueue a forward operation of the RNN model onto the stream. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // rnn_desc: a RNN descriptor created by createRnnDescriptor. + // input_desc: descriptor for the input sequence. + // input_data: the device memory region that contains the input data. + // input_h_desc: descriptor for the input "h" state. + // input_h_data: the device memory region that contains the input "h" data. + // input_c_desc: descriptor for the input "c" state. + // input_c_data: the device memory region that contains the input "c" data. + // This must be specified for LSTM models. + // params: the device memory region that contains the parameters used in this + // model. + // output_desc: descriptor for the output sequence. + // output_data: the memory region that stores the output sequence data. + // output_h_desc: descriptor for the output "h" state. + // output_h_data: the memory region that stores the output "h" data. + // output_c_desc: descriptor for the output "c" state. + // output_c_data: the memory region that stores the output "c" data. This + // must be specified for LSTM models. + // is_training: whether this is used in training or inference. That decides + // whether respace_space data need to be produced. + // reserve_space_allocator: if "is_training" is true, an memory allocator + // to create memory that holds the produced reserve_space. The caller is + // retains the data and feed it to the backward pass. + // workspace_allocator: an allocator to create temporary workspace used in + // this kernel. The caller is responsible for retaining the memory long + // enough for the lifespan of this operation, and recycles afterwards. + virtual bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, + bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, + bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, + bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + // Enqueue a backward operation of the RNN model onto the stream. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // rnn_desc: a RNN descriptor created by createRnnDescriptor. + // input_desc: descriptor for the input sequence. + // input_data: the device memory region that contains the input data. + // input_h_desc: descriptor for the input "h" state. + // input_h_data: the device memory region that contains the input "h" data. + // input_c_desc: descriptor for the input "c" state. + // input_c_data: the device memory region that contains the input "c" data. + // This must be specified for LSTM models. + // params: the device memory region that contains the parameters used in this + // model. + // output_desc: descriptor for the output sequence. + // output_data: the memory region that stores the output sequence data. + // output_h_desc: descriptor for the output "h" state. + // output_h_data: the memory region that stores the output "h" data. + // output_c_desc: descriptor for the output "c" state. + // output_c_data: the memory region that stores the output "c" data. This + // must be specified for LSTM models. + // output_backprop_data: the device memory region that contains the backprop + // to the output sequence. + // output_h_backprop_data: the device memory region that contains the + // backprop to the output "h" state. + // output_c_backprop_data: the device memory region that contains the + // backprop to the output "c" state. + // input_backprop_data: the device memory region that stores the backprop + // to the input sequence. + // input_h_backprop_data: the device memory region that stores the backprop + // to the input "h" state. + // input_c_backprop_data: the device memory region that stores the backprop + // to the input "c" state. + // params_backprop_data: the device memory region that stores the backprop + // to the parameters. + // reserve_space_data: the reserve_space data that is produced by the forward + // operation. This memory region could be modified by this operation. + // workspace_allocator: a memory allocator that creates the temporary + // workspace memory used by this operation. The caller is responsible for + // keeping the memory alive long enough for this operation, and recylces + // afterwards. + virtual bool DoRnnBackward( + Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnBackward( + Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnBackward( + Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + template + tsl::Status PrepareForCtcLoss(Stream* stream, + const RnnStateTensorDescriptor& probs_desc, + DeviceMemory probs_data, + const RnnStateTensorDescriptor& grads_desc, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions& numeric_options, + ScratchAllocator* workspace_allocator, + DeviceMemory* scratch_memory, + int* ctc_loss_algo_id) { + return DoPrepareForCtcLoss( + stream, ToDataType::value, probs_desc, grads_desc, + labels_data, labels_lengths_data, input_lengths_data, numeric_options, + workspace_allocator, scratch_memory, ctc_loss_algo_id); + } + + // Enqueue a CTC Loss operation onto the stream. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // element_type: date type of the input tensors + // probs_desc: specifies the shape and the data layout of the input tensor. + // probs_data: the device memory region that contains the input tensor. + // labels_data: the device memory region that contains the labels_value + // tensor. + // labels_lengths_data: the device memory region that contains the + // labels_lengths tensor + // input_lengths_data: the device memory region that contains the seq_lengths + // tensor + // costs_data: the device memory region that contains the costs tensor. + // grads_desc: specifies the shape and the data layout of the grads tensor. + // grads_data: the device memory region that contains the grads tensor. + // ctc_loss_desc: a CTCLoss descriptor. + // workspace_allocator: a memory allocator that creates the temporary + // workspace memory used by this operation. The caller is responsible for + // keeping the memory alive long enough for this operation, and recylces + // afterwards. + virtual tsl::Status DoCtcLoss( + Stream* stream, dnn::DataType element_type, + const RnnStateTensorDescriptor& probs_desc, + const DeviceMemoryBase probs_data, absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, DeviceMemoryBase costs_data, + const RnnStateTensorDescriptor& grads_desc, DeviceMemoryBase grads_data, + DeviceMemory scratch_memory, int ctc_loss_algo_id); + + template + bool DoCtcLoss(Stream* stream, + const dnn::RnnStateTensorDescriptor& probs_desc, + const DeviceMemory& probs_data, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + DeviceMemory* costs_data, + const dnn::RnnStateTensorDescriptor& grads_desc, + DeviceMemory* grads_data, + DeviceMemory* scratch_memory, int ctc_loss_algo_id) { + return IsStatusOk( + DoCtcLoss(stream, ToDataType::value, probs_desc, + probs_data, labels_data, labels_lengths_data, + input_lengths_data, *costs_data, grads_desc, *grads_data, + *scratch_memory, ctc_loss_algo_id), + false); + } + + // Transforms a tensor into another tensor with a different layout and/or data + // type. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // input_desc: specifies the shape and the data layout of the input tensor. + // input_type: the data type of the input tensor. + // input_data: the device memory region that contains the input tensor. + // output_desc: specifies the shape and the data layout of the output tensor. + // output_type: the data type of the output tensor. + // scale: an element-wise scaling factor to apply. + // output_data: the device memory region that contains the output tensor. + virtual bool DoTransformTensor(Stream* stream, + const dnn::BatchDescriptor& input_desc, + dnn::DataType input_type, + const DeviceMemoryBase& input_data, + const dnn::BatchDescriptor& output_desc, + dnn::DataType output_type, float scale, + DeviceMemoryBase* output_data) { + return false; + } + + // Notifies that a stream is being destroyed and should be invalidated from + // any internal caching. This exists to allow the CUDA implementation to + // avoid redundant cudnnSetStream calls without risking problems when a stream + // is destroyed and a new stream later created in the same memory. + virtual void NotifyStreamDestroyed(Stream* stream) {} + + protected: + // Returns whether status is 'ok', and potentially logs the error. + static bool IsStatusOk(const tsl::Status& status, bool report_error); + + private: + virtual tsl::Status DoPrepareForConvolution( + ConvolutionKind kind, DataType element_type, Stream* stream, + const BatchDescriptor& batch_descriptor, DeviceMemoryBase input_data, + const FilterDescriptor& filter_descriptor, DeviceMemoryBase filter_data, + const BatchDescriptor& output_descriptor, DeviceMemoryBase output_data, + const ConvolutionDescriptor& convolution_descriptor, + const AlgorithmConfig& algorithm_config, + ScratchAllocator* scratch_allocator, AlgorithmDesc* algorithm_desc, + DeviceMemory* scratch_memory) { + *algorithm_desc = {}; + *scratch_memory = {}; + return ::tsl::OkStatus(); + } + + virtual tsl::Status DoPrepareForCtcLoss( + Stream* stream, DataType element_type, + const RnnStateTensorDescriptor& probs_desc, + const RnnStateTensorDescriptor& grads_desc, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions& numeric_options, + ScratchAllocator* scratch_allocator, + DeviceMemory* scratch_memory, int* ctc_loss_algo_id) { + *scratch_memory = {}; + return ::tsl::OkStatus(); + } + + DnnSupport(const DnnSupport&) = delete; + void operator=(const DnnSupport&) = delete; +}; + +} // namespace dnn +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/event.h new file mode 100644 index 0000000000000000000000000000000000000000..8721c9d53d559b512726b88e59efffa156ace847 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/event.h @@ -0,0 +1,89 @@ +/* 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 XLA_STREAM_EXECUTOR_EVENT_H_ +#define XLA_STREAM_EXECUTOR_EVENT_H_ + +#include + +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/status.h" + +namespace stream_executor { + +namespace internal { +class EventInterface; +} + +class Stream; +class StreamExecutor; + +// The Event class, when supported by a platform, enables low-overhead status +// reporting for a Stream. An Event is inserted at a location in a stream via +// the Stream::ThenRecordEvent() API. From then on, the Event's status can be +// monitored via the nonblocking Event::PollForStatus() call. +class Event { + public: + // Potential states for an Event. If PollForStatus() returns anything aside + // from kPending or kComplete, an error has occurred; kUnknown is a bad state. + // Not all implementations are able to return all enumeration values. Refer to + // the platform-specific implementation for details. + enum class Status { + kUnknown, + kError, + kPending, + kComplete, + }; + + explicit Event(StreamExecutor* stream_exec); // NOLINT + + // Releases any resources held by the Event object. + ~Event(); + + // Performs any platform-specific or potentially error-generating + // initialization. + bool Init(); + + // Returns the current Status for the event. + Status PollForStatus(); + + // Blocks `stream` on this event. `stream` is a raw platform-specific + // stream (e.g. GpuStreamHandle). + tsl::Status WaitForEventOnExternalStream(std::intptr_t stream); + + // Returns a pointer to the underlying platform-specific implementation. + internal::EventInterface* implementation() { return implementation_.get(); } + + Event(Event&&); + Event& operator=(Event&&); + + private: + friend class Stream; + + // Pointer to the StreamExecutor interface used to create this object. + // Not owned. + StreamExecutor* stream_exec_; + + // Pointer to the platform-specific EventInterface implementation underlying + // the object. Owned. + std::unique_ptr implementation_; + + Event(const Event&) = delete; + void operator=(const Event&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/executor_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/executor_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..6e9668afdbf39da6f2c04cb19123c4e30dabb3d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/executor_cache.h @@ -0,0 +1,90 @@ +/* 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 XLA_STREAM_EXECUTOR_EXECUTOR_CACHE_H_ +#define XLA_STREAM_EXECUTOR_EXECUTOR_CACHE_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +// Forward declare. +class StreamExecutor; + +// Utility class to allow Platform objects to manage cached StreamExecutors. +// Thread-safe. +class ExecutorCache { + public: + using ExecutorFactory = + std::function>()>; + + ExecutorCache(); + ~ExecutorCache(); + + // Looks up 'config' in the cache. Returns a pointer to the existing executor, + // if already present, or creates it using 'factory', if it does not. + // Factories may be executed concurrently for different device ordinals. + tsl::StatusOr GetOrCreate(const StreamExecutorConfig& config, + const ExecutorFactory& factory); + + // Returns a pointer to the described executor (if one with a matching config + // has been created), or a NOT_FOUND status. + tsl::StatusOr Get(const StreamExecutorConfig& config); + + // Destroys all Executors and clears the cache. + // Performs no synchronization with the executors - undefined behavior may + // occur if any executors are active! + void DestroyAllExecutors(); + + private: + // Each Entry contains zero or more cached executors for a device ordinal. + struct Entry { + ~Entry(); + + // Mutex that guards the contents of each entry. The 'mutex_' of the + // ExecutorCache class protects both the 'cache_' and the existence of each + // Entry, but not the Entry's contents. 'configurations_mutex' protects the + // contents of the entry after 'mutex_' has been dropped. + absl::Mutex configurations_mutex; + + // Vector of cached {config, executor} pairs. + std::vector< + std::pair>> + configurations ABSL_GUARDED_BY(configurations_mutex); + }; + + // Maps ordinal number to a list of cached executors for that ordinal. + // We key off of ordinal (instead of just looking up all fields in the + // StreamExecutorConfig) for a slight improvement in lookup time. + absl::Mutex mutex_; + absl::node_hash_map cache_ ABSL_GUARDED_BY(mutex_); + + ExecutorCache(const ExecutorCache&) = delete; + void operator=(const ExecutorCache&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_EXECUTOR_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/fft.h new file mode 100644 index 0000000000000000000000000000000000000000..88a383b84cb1e74e762260fe54fbc803546ef4a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/fft.h @@ -0,0 +1,270 @@ +/* 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. +==============================================================================*/ + +// Exposes the family of FFT routines as pre-canned high performance calls for +// use in conjunction with the StreamExecutor abstraction. +// +// Note that this interface is optionally supported by platforms.. +// +// This abstraction makes it simple to entrain FFT operations on GPU data into +// a Stream -- users typically will not use this API directly, but will use the +// Stream builder methods to entrain these operations "under the hood". For +// example: +// +// DeviceMemory> x = +// stream_exec->AllocateArray>(1024); +// DeviceMemory> y = +// stream_exec->AllocateArray>(1024); +// // ... populate x and y ... +// Stream stream{stream_exec}; +// std::unique_ptr plan = +// stream_exec.AsFft()->Create1dPlan(&stream, 1024, Type::kC2CForward); +// stream +// .Init() +// .ThenFft(plan.get(), x, &y); +// TF_CHECK_OK(stream.BlockHostUntilDone()); +// +// By using stream operations in this manner the user can easily intermix custom +// kernel launches (via StreamExecutor::ThenLaunch()) with these pre-canned FFT +// routines. + +#ifndef XLA_STREAM_EXECUTOR_FFT_H_ +#define XLA_STREAM_EXECUTOR_FFT_H_ + +#include +#include + +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class Stream; +template +class DeviceMemory; +class ScratchAllocator; + +namespace fft { + +// Specifies FFT input and output types, and the direction. +// R, D, C, and Z stand for SP real, DP real, SP complex, and DP complex. +enum class Type { + kInvalid, + kC2CForward, + kC2CInverse, + kC2R, + kR2C, + kZ2ZForward, + kZ2ZInverse, + kZ2D, + kD2Z +}; + +// FFT plan class. Each FFT implementation should define a plan class that is +// derived from this class. It does not provide any interface but serves +// as a common type that is used to execute the plan. +class Plan { + public: + virtual ~Plan() {} +}; + +// FFT support interface -- this can be derived from a GPU executor when the +// underlying platform has an FFT library implementation available. See +// StreamExecutor::AsFft(). +// +// This support interface is not generally thread-safe; it is only thread-safe +// for the CUDA platform (cuFFT) usage; host side FFT support is known +// thread-compatible, but not thread-safe. +class FftSupport { + public: + virtual ~FftSupport() {} + + // Creates a 1d FFT plan. + virtual std::unique_ptr Create1dPlan(Stream *stream, uint64_t num_x, + Type type, bool in_place_fft) = 0; + + // Creates a 2d FFT plan. + virtual std::unique_ptr Create2dPlan(Stream *stream, uint64_t num_x, + uint64_t num_y, Type type, + bool in_place_fft) = 0; + + // Creates a 3d FFT plan. + virtual std::unique_ptr Create3dPlan(Stream *stream, uint64_t num_x, + uint64_t num_y, uint64 num_z, + Type type, bool in_place_fft) = 0; + + // Creates a 1d FFT plan with scratch allocator. + virtual std::unique_ptr Create1dPlanWithScratchAllocator( + Stream *stream, uint64_t num_x, Type type, bool in_place_fft, + ScratchAllocator *scratch_allocator) = 0; + + // Creates a 2d FFT plan with scratch allocator. + virtual std::unique_ptr Create2dPlanWithScratchAllocator( + Stream *stream, uint64_t num_x, uint64 num_y, Type type, + bool in_place_fft, ScratchAllocator *scratch_allocator) = 0; + + // Creates a 3d FFT plan with scratch allocator. + virtual std::unique_ptr Create3dPlanWithScratchAllocator( + Stream *stream, uint64_t num_x, uint64 num_y, uint64 num_z, Type type, + bool in_place_fft, ScratchAllocator *scratch_allocator) = 0; + + // Creates a batched FFT plan. + // + // stream: The GPU stream in which the FFT runs. + // rank: Dimensionality of the transform (1, 2, or 3). + // elem_count: Array of size rank, describing the size of each dimension. + // input_embed, output_embed: + // Pointer of size rank that indicates the storage dimensions + // of the input/output data in memory. If set to null_ptr all + // other advanced data layout parameters are ignored. + // input_stride: Indicates the distance (number of elements; same below) + // between two successive input elements. + // input_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the input data. + // output_stride: Indicates the distance between two successive output + // elements. + // output_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the output data. + virtual std::unique_ptr CreateBatchedPlan( + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, + uint64_t output_stride, uint64 output_distance, Type type, + bool in_place_fft, int batch_count) = 0; + + // Creates a batched FFT plan with scratch allocator. + // + // stream: The GPU stream in which the FFT runs. + // rank: Dimensionality of the transform (1, 2, or 3). + // elem_count: Array of size rank, describing the size of each dimension. + // input_embed, output_embed: + // Pointer of size rank that indicates the storage dimensions + // of the input/output data in memory. If set to null_ptr all + // other advanced data layout parameters are ignored. + // input_stride: Indicates the distance (number of elements; same below) + // between two successive input elements. + // input_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the input data. + // output_stride: Indicates the distance between two successive output + // elements. + // output_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the output data. + virtual std::unique_ptr CreateBatchedPlanWithScratchAllocator( + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, + uint64_t output_stride, uint64 output_distance, Type type, + bool in_place_fft, int batch_count, + ScratchAllocator *scratch_allocator) = 0; + + // Updates the plan's work area with space allocated by a new scratch + // allocator. This facilitates plan reuse with scratch allocators. + // + // This requires that the plan was originally created using a scratch + // allocator, as otherwise scratch space will have been allocated internally + // by cuFFT. + virtual void UpdatePlanWithScratchAllocator( + Stream *stream, Plan *plan, ScratchAllocator *scratch_allocator) = 0; + + // Computes complex-to-complex FFT in the transform direction as specified + // by direction parameter. + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output) = 0; + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output) = 0; + + // Computes real-to-complex FFT in forward direction. + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory &input, + DeviceMemory> *output) = 0; + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory &input, + DeviceMemory> *output) = 0; + + // Computes complex-to-real FFT in inverse direction. + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output) = 0; + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output) = 0; + + protected: + FftSupport() {} + + private: + FftSupport(const FftSupport &) = delete; + void operator=(const FftSupport &) = delete; +}; + +// Macro used to quickly declare overrides for abstract virtuals in the +// fft::FftSupport base class. Assumes that it's emitted somewhere inside the +// ::stream_executor namespace. +#define TENSORFLOW_STREAM_EXECUTOR_GPU_FFT_SUPPORT_OVERRIDES \ + std::unique_ptr Create1dPlan(Stream *stream, uint64_t num_x, \ + fft::Type type, bool in_place_fft) \ + override; \ + std::unique_ptr Create2dPlan(Stream *stream, uint64_t num_x, \ + uint64_t num_y, fft::Type type, \ + bool in_place_fft) override; \ + std::unique_ptr Create3dPlan( \ + Stream *stream, uint64_t num_x, uint64 num_y, uint64 num_z, \ + fft::Type type, bool in_place_fft) override; \ + std::unique_ptr Create1dPlanWithScratchAllocator( \ + Stream *stream, uint64_t num_x, fft::Type type, bool in_place_fft, \ + ScratchAllocator *scratch_allocator) override; \ + std::unique_ptr Create2dPlanWithScratchAllocator( \ + Stream *stream, uint64_t num_x, uint64 num_y, fft::Type type, \ + bool in_place_fft, ScratchAllocator *scratch_allocator) override; \ + std::unique_ptr Create3dPlanWithScratchAllocator( \ + Stream *stream, uint64_t num_x, uint64 num_y, uint64 num_z, \ + fft::Type type, bool in_place_fft, ScratchAllocator *scratch_allocator) \ + override; \ + std::unique_ptr CreateBatchedPlan( \ + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, \ + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, \ + uint64_t output_stride, uint64 output_distance, fft::Type type, \ + bool in_place_fft, int batch_count) override; \ + std::unique_ptr CreateBatchedPlanWithScratchAllocator( \ + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, \ + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, \ + uint64_t output_stride, uint64 output_distance, fft::Type type, \ + bool in_place_fft, int batch_count, ScratchAllocator *scratch_allocator) \ + override; \ + void UpdatePlanWithScratchAllocator(Stream *stream, fft::Plan *plan, \ + ScratchAllocator *scratch_allocator) \ + override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory *output) override; + +} // namespace fft +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/asm_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/asm_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..0e15e326ca23e5ca7eb086065c42ee12c0c9def2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/asm_compiler.h @@ -0,0 +1,143 @@ +/* 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_STREAM_EXECUTOR_GPU_ASM_COMPILER_H_ +#define XLA_STREAM_EXECUTOR_GPU_ASM_COMPILER_H_ + +#include +#include +#include +#include + +#include "absl/base/const_init.h" +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/statusor.h" +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_driver.h" +#endif // GOOGLE_CUDA + +namespace stream_executor { +namespace gpu { +class GpuContext; +} + +// Compiles the given PTX string using ptxas and returns the resulting machine +// code (i.e. a cubin) as a byte array. The generated cubin matches the compute +// capabilities of the device associated with 'device_ordinal'. +// +// 'options' is used to query for the CUDA location in case it is +// customized in a passed flag, and for controlling ptxas optimizations. +tsl::StatusOr> CompileGpuAsm(int device_ordinal, + const char* ptx_contents, + GpuAsmOpts options); + +// Compiles the given PTX string using ptxas and returns the resulting machine +// code (i.e. a cubin) as a byte array. The generated cubin matches the compute +// capabilities provided by 'cc_major' and 'cc_minor'. +// +// 'options' is used to query for the CUDA location in case it is +// customized in a passed flag, and for controlling ptxas optimizations. +tsl::StatusOr> CompileGpuAsm( + int cc_major, int cc_minor, const char* ptx_contents, GpuAsmOpts options, + bool cancel_if_reg_spill = false); + +// Same as CompileGpuAsm, but caches the result, and returns unowned view of +// the compiled binary. +// +// A copy of the string provided in ptx will be made. +tsl::StatusOr> CompileGpuAsmOrGetCached( + int device_ordinal, const char* ptx, GpuAsmOpts compilation_options); + +struct CubinOrPTXImage { + std::string profile; + std::vector bytes; +}; + +// Bundles the GPU machine code (cubins) and PTX if requested and returns the +// resulting binary (i.e. a fatbin) as a byte array. +tsl::StatusOr> BundleGpuAsm( + std::vector images, GpuAsmOpts options); + +struct HsacoImage { + std::string gfx_arch; + std::vector bytes; +}; + +// Bundles the GPU machine code (HSA Code Object) and returns the resulting +// binary (i.e. a fatbin) as a byte array. +tsl::StatusOr> BundleGpuAsm( + std::vector images, const std::string rocm_root_dir); + +// Links multiple relocatable GPU images (e.g. results of ptxas -c) into a +// single image. +tsl::StatusOr> LinkGpuAsm( + gpu::GpuContext* context, std::vector images); + +tsl::StatusOr> LinkUsingNvlink( + absl::string_view preferred_cuda_dir, gpu::GpuContext* context, + std::vector images); + +std::string FindCudaExecutable(const std::string& binary_name, + const std::string& preferred_cuda_dir); + +// Runs tool --version and parses its version string. +tsl::StatusOr> GetToolVersion( + absl::string_view tool_path); + +// On NVIDIA GPUs, returns the CUDA toolkit version supported by the driver, +tsl::StatusOr> GetAsmCompilerVersion( + const std::string& preferred_cuda_dir); + +#if GOOGLE_CUDA +// Maintains a cache of pointers to loaded kernels +template +tsl::StatusOr>> LoadKernelOrGetPtr( + StreamExecutor* executor, absl::string_view kernel_name, + absl::string_view ptx, absl::Span cubin_data) { + using KernelPtrCacheKey = + std::tuple; + + static absl::Mutex kernel_ptr_cache_mutex(absl::kConstInit); + static auto& kernel_ptr_cache ABSL_GUARDED_BY(kernel_ptr_cache_mutex) = + *new absl::flat_hash_map>>(); + CUcontext current_context = cuda::CurrentContextOrDie(); + KernelPtrCacheKey kernel_ptr_cache_key{current_context, kernel_name, ptx}; + absl::MutexLock lock(&kernel_ptr_cache_mutex); + + auto it = kernel_ptr_cache.find(kernel_ptr_cache_key); + if (it == kernel_ptr_cache.end()) { + TF_ASSIGN_OR_RETURN( + std::shared_ptr> loaded, + executor->CreateTypedKernel(kernel_name, ptx, cubin_data)); + it = + kernel_ptr_cache.emplace(kernel_ptr_cache_key, std::move(loaded)).first; + } + + CHECK(it != kernel_ptr_cache.end()); + return it->second; +} +#endif // GOOGLE_CUDA + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_ASM_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_activation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_activation.h new file mode 100644 index 0000000000000000000000000000000000000000..385644d7ac197529765e8058dcce2660f3af169c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_activation.h @@ -0,0 +1,60 @@ +/* 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 contains APIs that assume a StreamExecutor is backed by CUDA. +// It reaches into the CUDA implementation to activate an underlying CUDA +// context. +// +// Having this file separate from gpu/gpu_executor.h means that dependent +// code does not also have to depend on cuda.h. + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_ACTIVATION_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_ACTIVATION_H_ + +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class StreamExecutor; + +namespace gpu { + +class GpuExecutor; +class ScopedActivateContext; + +// Activates a CUDA context within an enclosing scope. +class ScopedActivateExecutorContext { + public: + // Form that takes a CUDA executor implementation. + explicit ScopedActivateExecutorContext(GpuExecutor* gpu_exec); + + // Form that takes a pImpl executor and extracts a CUDA implementation -- + // fatal failure if it is not CUDA inside. + explicit ScopedActivateExecutorContext(StreamExecutor* stream_exec); + + ~ScopedActivateExecutorContext(); + + private: + // The cuda.h-using datatype that we wrap. + ScopedActivateContext* driver_scoped_activate_context_; + + ScopedActivateExecutorContext(const ScopedActivateExecutorContext&) = delete; + void operator=(const ScopedActivateExecutorContext&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_ACTIVATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_asm_opts.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_asm_opts.h new file mode 100644 index 0000000000000000000000000000000000000000..6a10c2653e906c8340fa205996e3e24ea4d216ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_asm_opts.h @@ -0,0 +1,54 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_ASM_OPTS_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_ASM_OPTS_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" + +namespace stream_executor { +// Compilation options for compiling ptxas. +struct GpuAsmOpts { + // Disable Cuda ptxas optimizations. + bool disable_gpuasm_optimizations; + + // Cuda directory which would be searched first. + std::string preferred_cuda_dir; + + std::vector extra_flags; + + explicit GpuAsmOpts(bool disable_gpuasm_optimizations = false, + absl::string_view preferred_cuda_dir = "", + absl::Span extra_flags = {}) + : disable_gpuasm_optimizations(disable_gpuasm_optimizations), + preferred_cuda_dir(preferred_cuda_dir), + extra_flags(extra_flags.begin(), extra_flags.end()) {} + + using PtxOptionsTuple = + std::tuple>; + + PtxOptionsTuple ToTuple() { + return std::make_tuple(disable_gpuasm_optimizations, preferred_cuda_dir, + extra_flags); + } +}; +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_ASM_OPTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_command_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_command_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..9b620e7bca1801f0920d627ff26727e193bd5c48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_command_buffer.h @@ -0,0 +1,112 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_COMMAND_BUFFER_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_COMMAND_BUFFER_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/gpu/gpu_executor.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/status.h" + +namespace stream_executor::gpu { + +// GpuCommandBuffer provides platform-specific CommandBufferInterface +// implementation (it's backed by CUDA or HIP graphs on NVIDIA and AMD devices). +class GpuCommandBuffer : public internal::CommandBufferInterface { + public: + GpuCommandBuffer(CommandBuffer::Mode mode, GpuExecutor* parent, + GpuGraphHandle graph); + ~GpuCommandBuffer() override; + + tsl::Status Trace(Stream* stream, + absl::AnyInvocable function) override; + + tsl::Status Launch(const ThreadDim& threads, const BlockDim& blocks, + const KernelBase& kernel, + const KernelArgsArrayBase& args) override; + + tsl::Status MemcpyDeviceToDevice(DeviceMemoryBase* dst, + const DeviceMemoryBase& src, + uint64_t size) override; + + tsl::Status Finalize() override; + tsl::Status Update() override; + + GpuGraphExecHandle executable() const { return exec_; } + + CommandBuffer::Mode mode() const override { return mode_; } + CommandBuffer::State state() const override { return state_; } + + // We track the total number of allocated and alive executable graphs in the + // process to track the command buffers resource usage. Executable graph + // allocates resources on a GPU devices (rule of thumb is ~8kb per node), so + // we have to be careful not to keep too many of them alive for too long, or + // we have a higher risk of OOM errors. + // + // TODO(ezhulenev): We need to have a policy for how to evict unused + // executable graph instances from a device, currently lifetime of an + // executable graph is tied to a parent command buffer, and we can have + // thousands of command buffers alive at the same time. + static int64_t AllocatedExecs(); + static int64_t AliveExecs(); + + static const GpuCommandBuffer* Cast(const CommandBuffer* command_buffer) { + return static_cast( + command_buffer->implementation()); + } + + private: + // Returns OK status if command buffer is not finalized and it is still + // possible to add new commands to it, otherwise returns internal error. + tsl::Status CheckNotFinalized(); + + static_assert(std::is_pointer_v, + "GpuGraphHandle must be a pointer"); + static_assert(std::is_pointer_v, + "GpuGraphExecHandle must be a pointer"); + static_assert(std::is_pointer_v, + "GpuGraphNodeHandle must be a pointer"); + + CommandBuffer::Mode mode_; + CommandBuffer::State state_ = CommandBuffer::State::kCreate; + + GpuExecutor* parent_; // not owned, must outlive *this + GpuGraphHandle graph_ = nullptr; // owned handle + GpuGraphExecHandle exec_ = nullptr; // owned handle + + // Handles to graph nodes corresponding to command buffer commands. Owned by + // the `graph_` instance. + std::vector nodes_; + + // When command buffer is in update state this index will point to the graph + // node inside `nodes_` that will be updated next. + int64_t node_update_idx_ = 0; + + // Track the number of command buffer updates for debugging. + int64_t num_updates_ = 0; +}; + +} // namespace stream_executor::gpu + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_COMMAND_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..c428132d74aa9367deb6c158b3c9d62a6a1501ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h @@ -0,0 +1,142 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_CUDAMALLOCASYNC_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_CUDAMALLOCASYNC_ALLOCATOR_H_ + +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" +#include "tsl/platform/macros.h" +#include "tsl/platform/mutex.h" + +#if GOOGLE_CUDA +#include "third_party/gpus/cuda/include/cuda.h" + +#define TF_CUDA_MALLOC_ASYNC_SUPPORTED CUDA_VERSION >= 11020 +#endif // GOOGLE_CUDA + + +namespace stream_executor { + +// An allocator that wraps cudaMallocAsync. It has fewer fragmentation +// issues then the BFC memory allocator. The compute-sanitizer tool +// helps to detect OOB memory errors when using cudaMallocAsync. Use +// the environment variable `TF_GPU_ALLOCATOR=cuda_malloc_async` to +// enable it. +// +// It needs CUDA 11.2+. When using a container, this only needs the +// container driver to be 11.2. It has a WAR again a driver bug in +// multi-GPU setup with CUDA 11.2. The WAR creates an extra context on +// GPU 0. +// +// We configure cudaMallocAsync to grow when more memory is needed +// instead of preallocating everything up front and to keep a local +// pool up to pool_size bytes that is never released to other processes. +// So no other process will "steal" the GPU memory already used by the +// current process. This is to speed up execution and prevent crashes +// of long-running jobs. Use `reserve_memory=true` if you want to +// preallocate the full pool_size. You can also use the environment +// variable `TF_CUDA_MALLOC_ASYNC_SUPPORTED_PREALLOC=nb_bytes` to preallocate +// that amount of memory. `TF_CUDA_MALLOC_ASYNC_SUPPORTED_PREALLOC=-1` is a +// special value that preallocate all what the BFC memory allocator +// would have allocated. This is useful when benchmarking as it doesn't +// change when driver allocations are done. +// +// Here, the pool_size isn't the absolute max as for [Gpu]BFCAllocator. +// The pool can grow above that up to the total GPU memory. But the +// driver can return the excess memory to other processes. +class GpuCudaMallocAsyncAllocator : public tsl::Allocator { + public: + explicit GpuCudaMallocAsyncAllocator(tsl::PlatformDeviceId platform_device_id, + size_t pool_size, + bool reserve_memory = false, + bool compute_stats = true); + ~GpuCudaMallocAsyncAllocator() override; + std::string Name() override { return name_; } + void* AllocateRaw(size_t alignment, + size_t num_bytes) override ABSL_NO_THREAD_SAFETY_ANALYSIS; + void DeallocateRaw(void* ptr) override ABSL_NO_THREAD_SAFETY_ANALYSIS; + + bool TracksAllocationSizes() const override; + + size_t RequestedSize(const void* ptr) const override; + + size_t AllocatedSize(const void* ptr) const override; + + std::optional GetStats() override; + + bool ClearStats() override; + + void SetStreamAndPreallocateMemory(void* stream) override; + + // With the right VLOG set, it prints: + // - the number of ptr currently allocated per size (histogram). + // - each ptr value and its size. + // - If CUDA_VERSION >= 11030, print cudaMallocAsync statistics. + void PrintAllocatorStatistics(); + + static int GetInstantiatedCountTestOnly() { return number_instantiated_; } + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kDevice; + } + + private: + void PrintAllocatorStatisticsNoLock() ABSL_EXCLUSIVE_LOCKS_REQUIRED(lock_); + +#if TF_CUDA_MALLOC_ASYNC_SUPPORTED + StreamExecutor* stream_exec_; // Not owned. + + // cudaMallocAsync is stream aware. But TF StreamExecutor use only 1 + // compute stream and already synchronize with the h2d, d2h and d2d + // stream. So we do not need to ask cudaMallocAsync to add extra + // synchronization. + // Not owned. + CUstream cuda_stream_; + + // Not owned. The default pool of the associated GPU. + // If null, then the instanciation failed and the first allocation + // will return an error. + CUmemoryPool pool_; +#endif // TF_CUDA_MALLOC_ASYNC_SUPPORTED + + // Just a counter for the number of time this class is instantiated. + // Only useful for tests. + static std::atomic number_instantiated_; + + std::string name_; + + bool reserve_memory_; + + GpuCudaMallocAsyncAllocator(const GpuCudaMallocAsyncAllocator&) = delete; + void operator=(const GpuCudaMallocAsyncAllocator&) = delete; + + // Stats. + // Structures mutable after construction + mutable tsl::mutex lock_; + std::unique_ptr stats_ ABSL_PT_GUARDED_BY(lock_); + absl::flat_hash_map size_map_ ABSL_GUARDED_BY(lock_); +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_CUDAMALLOCASYNC_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_diagnostics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_diagnostics.h new file mode 100644 index 0000000000000000000000000000000000000000..7892a3bcf4f50830b53b94bd69614b9c0afb28dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_diagnostics.h @@ -0,0 +1,99 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_ + +#include + +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace gpu { + +// e.g. DriverVersion{346, 3, 4} +using DriverVersion = std::tuple; + +// FIXME: These functions are in stream_executor::cuda namespaces for now +// Will move to stream_executor::gpu namespace in the near future +// +//// Converts a parsed driver version to string form. +// string DriverVersionToString(DriverVersion version); +// +//// Converts a parsed driver version or status value to natural string form. +// string DriverVersionStatusToString(tsl::StatusOr version); +// +//// Converts a string of a form like "331.79" to a DriverVersion{331, 79}. +// tsl::StatusOr StringToDriverVersion(const string& value); + +class Diagnostician { + public: + // Logs diagnostic information when CUDA appears to be misconfigured (e.g. is + // not initializing). + // + // Note: if we're running on a machine that has no GPUs, we don't want to + // produce very much log spew beyond saying, "looks like there's no CUDA + // kernel + // module running". + // + // Note: we use non-Google-File:: API here because we may be called before + // InitGoogle has completed. + static void LogDiagnosticInformation(); + + // Given the driver version file contents, finds the kernel module version and + // returns it as a string. + // + // This is solely used for more informative log messages when the user is + // running on a machine that happens to have a libcuda/kernel driver mismatch. + static tsl::StatusOr FindKernelModuleVersion( + const std::string& driver_version_file_contents); + + // Extracts the kernel driver version from the current host. + static tsl::StatusOr FindKernelDriverVersion(); + + // Iterates through loaded DSOs with DlIteratePhdrCallback to find the + // driver-interfacing DSO version number. Returns it as a string. + static tsl::StatusOr FindDsoVersion(); + + // Logs information about the kernel driver version and userspace driver + // library version. + static void LogDriverVersionInformation(); + + private: + // Given the DSO version number and the driver version file contents, extracts + // the driver version and compares, warning the user in the case of + // incompatibility. + // + // This is solely used for more informative log messages when the user is + // running on a machine that happens to have a libcuda/kernel driver mismatch. + static void WarnOnDsoKernelMismatch( + tsl::StatusOr dso_version, + tsl::StatusOr kernel_version); + + // Logs information about the dev nodes present on this machine: their + // existence, permissions, accessibility from this uid/gid. + static void LogDevNodeDiagnosticInformation(); + + static std::string GetDevNodePath(int dev_node_ordinal); + + Diagnostician(const Diagnostician&) = delete; + void operator=(const Diagnostician&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_driver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_driver.h new file mode 100644 index 0000000000000000000000000000000000000000..3895e7b0bf008c9132b85d5ce95089349cc90d39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_driver.h @@ -0,0 +1,793 @@ +/* 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. +==============================================================================*/ + +// CUDA/ROCm userspace driver library wrapper functionality. + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_DRIVER_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_DRIVER_H_ + +#include + +#include + +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/platform.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace gpu { + +// Identifies the memory space where an allocation resides. See +// GpuDriver::GetPointerMemorySpace(). +enum class MemorySpace { kHost, kDevice }; + +// Returns a casual string, such as "host" for the provided memory space. +std::string MemorySpaceString(MemorySpace memory_space); + +class GpuContext; + +// GpuDriver contains wrappers for calls to the userspace library driver. It's +// useful to isolate these calls and put basic wrappers around them to separate +// userspace library driver behaviors from the rest of the program. +// +// At the moment it's simply used as a namespace. +// +// The calls log any specific errors internally and return whether the operation +// was successful to the caller. +// +// The order of parameters is generally kept symmetric with the underlying +// CUDA/ROCm driver API. +// +// Links on functions are to specific documentation under +// http://docs.nvidia.com/cuda/cuda-driver-api/ +// https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html +// +// Thread safety: these functions should not be used from signal handlers. +class GpuDriver { + public: + // Wraps a call to cuInit/hipInit with logging to help indicate what has gone + // wrong in the case of failure. Safe to call multiple times; will be fast on + // all calls after the first. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__INITIALIZE.html#group__CUDA__INITIALIZE_1g0a2f1517e1bd8502c7194c3a8c134bc3 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#initialization + static tsl::Status Init(); + + // Returns the device associated with the given context. + // device is an outparam owned by the caller, must not be null. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g4e84b109eba36cdaaade167f34ae881e + static tsl::StatusOr DeviceFromContext(GpuContext* context); + + // Creates a new CUDA/HIP stream associated with the given context via + // cuStreamCreate/hipStreamCreateWithFlags. + // stream is an outparam owned by the caller, must not be null. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1ga581f0c5833e21ded8b5a56594e243f4 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#stream-management + static bool CreateStream(GpuContext* context, GpuStreamHandle* stream, + int priority = 0); + + // Destroys a CUDA/HIP stream associated with the given context. + // stream is owned by the caller, must not be null, and *stream is set to null + // if the stream is successfully destroyed. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g244c8833de4596bcd31a06cdf21ee758 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#stream-management + static void DestroyStream(GpuContext* context, GpuStreamHandle* stream); + + // CUDA/HIP events can explicitly disable event TSC retrieval for some + // presumed performance improvement if timing is unnecessary. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g450687e75f3ff992fe01662a43d9d3db + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + enum class EventFlags { kDefault, kDisableTiming }; + + // Creates a new event associated with the given context. + // result is an outparam owned by the caller and must not be null. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g450687e75f3ff992fe01662a43d9d3db + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + static tsl::Status InitEvent(GpuContext* context, GpuEventHandle* result, + EventFlags flags); + + // Destroys *event and turns it into a nullptr. event may not be null, but + // *event may be, via cuEventDestroy/hipEventDestroy + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g593ec73a8ec5a5fc031311d3e4dca1ef + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#event-management + static tsl::Status DestroyEvent(GpuContext* context, GpuEventHandle* event); + + // Allocates a GPU memory space of size bytes associated with the given + // context via cuMemAlloc/hipMalloc. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gb82d2a09844a58dd9e744dc31e8aa467 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void* DeviceAllocate(GpuContext* context, uint64_t bytes); + + // Deallocates a GPU memory space of size bytes associated with the given + // context via cuMemFree/hipFree. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g89b3f154e17cc89b6eea277dbdf5c93a + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void DeviceDeallocate(GpuContext* context, void* location); + + // Allocates a unified memory space of size bytes associated with the given + // context via cuMemAllocManaged. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gb347ded34dc326af404aa02af5388a32 + // (supported on CUDA only) + static void* UnifiedMemoryAllocate(GpuContext* context, uint64_t bytes); + + // Deallocates a unified memory space of size bytes associated with the given + // context via cuMemFree. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g89b3f154e17cc89b6eea277dbdf5c93a + // (supported on CUDA only) + static void UnifiedMemoryDeallocate(GpuContext* context, void* location); + + // Allocates page-locked and CUDA-registered memory on the host via + // cuMemAllocHost/hipHostMalloc. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gdd8311286d2c2691605362c689bc64e0 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void* HostAllocate(GpuContext* context, uint64_t bytes); + + // Deallocates a location created by HostAllocate, via + // cuMemFreeHost/hipHostFree. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g62e0fdbe181dab6b1c90fa1a51c7b92c + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void HostDeallocate(GpuContext* context, void* location); + + // Registers a memory region at location of size bytes via + // cuMemHostRegister/hipHostRegister. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gf0a9fe11544326dabd743b7aa6b54223 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static bool HostRegister(GpuContext* context, void* location, uint64_t bytes); + + // Unregisters a memory region that was previously registered at location via + // cuMemHostUnregister/hipHostUnregister. + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g63f450c8125359be87b7623b1c0b2a14 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + // + // TODO(leary) verify an error will be returned if the location wasn't + // previously registered. + static bool HostUnregister(GpuContext* context, void* location); + + // Queries the priority range and returns the corresponding integer value via + // cuCtxGetStreamPriorityRange/hipDeviceGetStreamPriorityRange + // + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g137920ab61a71be6ce67605b9f294091 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#context-management + static int GetGpuStreamPriority( + GpuContext* context, stream_executor::StreamPriority stream_priority); + + // Virtual memory support was added to CUDA in 10.2 +#if CUDA_VERSION >= 10020 + + // Reserves a range of virtual device memory addresses via + // cuMemAddressReserve. bytes must be a multiple of the host page size. + // Returns nullptr base address in VmemSpan if the reservation fails. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1ge489256c107df2a07ddf96d80c86cd9b + struct VmemSpan { + GpuDevicePtr base; + // Size in bytes. + uint64_t size_bytes; + }; + static tsl::StatusOr ReserveVirtualMemory(GpuContext* context, + uint64_t bytes); + + // Frees a range of virtual addresses that were previously reserved through + // ReserveVirtualMemory via cuMemAddressFree. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g6993ecea2ea03e1b802b8255edc2da5b + static void FreeVirtualMemory(GpuContext* context, VmemSpan reservation); + + // Calculates the minimum alignment for memory allocations done through + // cuMemCreate via cuMemGetAllocationGranularity. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g30ee906c2cf66a0347b3dfec3d7eb31a + static tsl::StatusOr GetMinAllocationGranularity( + GpuDeviceHandle device); + + // Allocates physical memory and returns a handle that can be mapped to + // virtual addresses via cuMemCreate. bytes must be a multiple of the + // granularity returned by GetMinAllocationGranularity. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g899d69a862bba36449789c64b430dc7c + struct GenericMemoryHandle { + uint64_t handle; + uint64_t bytes; + }; + static tsl::StatusOr CreateMemoryHandle( + GpuContext* context, uint64_t bytes); + + // Frees memory represented by the provided MemoryHandle via cuMemRelease. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g3014f0759f43a8d82db951b8e4b91d68 + static void ReleaseMemoryHandle(GpuContext* context, + GenericMemoryHandle handle); + + // Maps a memory allocation handle to a reserved virtual address range via + // cuMemMap and sets the appropriate access settings via cuMemSetAccess. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1gff1d395423af5c5c75375516959dae56 + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g1b6b12b10e8324bf462ecab4e7ef30e1 + static tsl::Status MapMemory( + GpuContext* context, GpuDevicePtr va, const GenericMemoryHandle& handle, + const std::vector& device_handles); + + // Unmaps the backing memory from the given virtual address range. This range + // must fully unmap a memory handle that was mapped using MapMemory; partial + // unmapping is not supported. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1gfb50aac00c848fd7087e858f59bf7e2a + static void UnmapMemory(GpuContext* context, GpuDevicePtr va, uint64_t bytes); + +#endif // CUDA_VERSION >= 10200 + + // Given a device ordinal, returns a device handle into the device outparam, + // which must not be null. + // + // N.B. these device handles do not have a corresponding destroy function in + // the CUDA/HIP driver API. + static tsl::Status GetDevice(int device_ordinal, GpuDeviceHandle* device); + + // Given a device handle, returns the name reported by the driver for the + // device. + static tsl::Status GetDeviceName(GpuDeviceHandle device, + std::string* device_name); + + // Given a device to create a context for, returns a context handle into the + // context outparam, which must not be null. + // + // N.B. CUDA contexts are weird. They are implicitly associated with the + // calling thread. Current documentation on contexts and their influence on + // userspace processes is given here: + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g65dc0012348bc84810e2103a40d8e2cf + static tsl::Status CreateContext(int device_ordinal, GpuDeviceHandle device, + const DeviceOptions& device_options, + GpuContext** context); + + // Destroys the provided context via cuCtxDestroy. + // Don't do this while clients could still be using the context, per the docs + // bad things will happen. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g27a365aebb0eb548166309f58a1e8b8e + static void DestroyContext(GpuContext* context); + + // Returns the context handle (CUcontext for CUDA and hipCtx_t for ROCm) of a + // GpuContext. + static GpuContextHandle GetContextHandle(GpuContext* context); + + // Queries the runtime for the specified attribute of the specified function. + // cuFuncGetAttribute (the underlying CUDA driver API routine) only operates + // in terms of integer-sized values, so there's no potential for overrun (as + // of CUDA 5.5). + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1g5e92a1b0d8d1b82cb00dcfb2de15961b + static tsl::Status FuncGetAttribute(GpuFunctionAttribute attribute, + GpuFunctionHandle function, + int* attribute_value); + + // Sets the preferred cache configuration for the specified function. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1g40f8c11e81def95dc0072a375f965681 + static tsl::Status FuncSetCacheConfig(GpuFunctionHandle function, + GpuFuncCachePreference cache_config); + + // Gets the preferred shared memory bank configuration for the specified + // CONTEXT (not function!), either default or four- or eight-byte bank size. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g17153a1b8b8c756f7ab8505686a4ad74 + // https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___execution.html + static tsl::StatusOr ContextGetSharedMemConfig( + GpuContext* context); + + // Sets the preferred shared memory bank configuration for the specified + // CONTEXT (not function!), either default or four- or eight-byte bank size. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g2574235fa643f8f251bf7bc28fac3692 + // https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___execution.html + static tsl::Status ContextSetSharedMemConfig( + GpuContext* context, GpuSharedMemConfig shared_mem_config); + + // Launches a CUDA/ROCm kernel via cuLaunchKernel/hipModuleLaunchKernel. + // TODO(leary) describe the structure of kernel_params and extra in a readable + // way. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#execution-control + static tsl::Status LaunchKernel( + GpuContext* context, absl::string_view kernel_name, + GpuFunctionHandle function, unsigned int grid_dim_x, + unsigned int grid_dim_y, unsigned int grid_dim_z, + unsigned int block_dim_x, unsigned int block_dim_y, + unsigned int block_dim_z, unsigned int shared_mem_bytes, + GpuStreamHandle stream, void** kernel_params, void** extra); + + // Creates a new GPU graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gd885f719186010727b75c3315f865fdf + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status CreateGraph(GpuGraphHandle* graph); + + // Destroys GPU graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g718cfd9681f078693d4be2426fd689c8 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status DestroyGraph(GpuGraphHandle graph); + + // Begins graph capture on a stream. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g767167da0bbf07157dc20b6c258a2143 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + enum class StreamCaptureMode { kGlobal, kThreadLocal, kRelaxed }; + static tsl::Status StreamBeginCapture(GpuStreamHandle stream, + StreamCaptureMode mode); + + // Ends capture on a stream, returning the captured graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g03dab8b2ba76b00718955177a929970c + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status StreamEndCapture(GpuStreamHandle stream, + GpuGraphHandle* graph); + + // Graph instantiation flags. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1g070bf5517d3a7915667c256eefce4956 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + struct GraphInstantiateFlags { + // Automatically free memory allocated in a graph before relaunching. + bool auto_free_on_launch = false; + // Automatically upload the graph after instantiation. + bool upload = false; + // Instantiate the graph to be launchable from the device. + bool device_launch = false; + // Run the graph using the per-node priority attributes rather than the + // priority of the stream it is launched into. + bool use_node_prirotiy = false; + }; + + // Creates an executable graph from a graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gb53b435e178cccfa37ac87285d2c3fa1 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphInstantiate(GpuGraphExecHandle* exec, + GpuGraphHandle graph, + const GraphInstantiateFlags& flags); + + // Launches an executable graph in a stream. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g6b2dceb3901e71a390d2bd8b0491e471 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphLaunch(GpuGraphExecHandle exec, + GpuStreamHandle stream); + + // Graph update result. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1g8edc8969ff6ae00b7cd5d7292f812c3c + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + enum class GraphExecUpdateResult { + kSuccess, + kError, + kTopologyChanged, + kNodeTypeChanged, + kFunctionChanged, + kParametersChanged, + kNotSupported, + kUnsupportedFunctionChange, + kAttributesChanged + }; + + // Graph update result info. + // https://docs.nvidia.com/cuda/cuda-driver-api/structCUgraphExecUpdateResultInfo__v1.html#structCUgraphExecUpdateResultInfo__v1 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + struct GraphExecUpdateResultInfo { + GpuGraphNodeHandle error_from_node; + GpuGraphNodeHandle error_node; + GraphExecUpdateResult result; + }; + + // Check whether an executable graph can be updated with a graph and perform + // the update if possible. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g96efefc56df46927da7297f122adfb9f + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphExecUpdate(GpuGraphExecHandle exec, + GpuGraphHandle graph, + GraphExecUpdateResultInfo* result); + + // Graph node type. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1g0731a28f826922120d783d8444e154dc + // https://docs.amd.com/projects/HIP/en/docs-5.0.0/doxygen/html/group___graph.html#ga4727d20b89566832c74b762f987b9728 + enum class GraphNodeType { + kKernel, + kMemcpy, + kMemset, + kHost, + kGraph, + kEmpty, + kWaitEvent, + kEventRecord, + kExtSemasSignal, + kExtSemasWait, + kMemAlloc, + kMemFree, + kBatchMemOp, + }; + + // Return the node type of the graph node. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gdb1776d97aa1c9d5144774b29e4b8c3e + // https://docs.amd.com/projects/HIP/en/docs-5.0.0/doxygen/html/group___graph.html#ga87c68ae9408a6438d4a1101560ceea11 + static tsl::StatusOr GraphNodeGetType(GpuGraphNodeHandle node); + + // Destroys an executable graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1ga32ad4944cc5d408158207c978bc43a7 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status DestroyGraphExec(GpuGraphExecHandle exec); + + // Write a DOT file describing graph structure. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g0fb0c4d319477a0a98da005fcb0dacc4 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphDebugDotPrint(GpuGraphHandle graph, const char* path); + + // Returns a stream's capture status. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g37823c49206e3704ae23c7ad78560bca + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#stream-management + static tsl::StatusOr StreamIsCapturing(GpuStreamHandle stream); + + // Creates a kernel execution node and adds it to a graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g50d871e3bd06c1b835e52f2966ef366b + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphAddKernelNode( + GpuGraphNodeHandle* node, GpuGraphHandle graph, + absl::Span deps, absl::string_view kernel_name, + GpuFunctionHandle function, unsigned int grid_dim_x, + unsigned int grid_dim_y, unsigned int grid_dim_z, + unsigned int block_dim_x, unsigned int block_dim_y, + unsigned int block_dim_z, unsigned int shared_mem_bytes, + void** kernel_params, void** extra); + + // Sets the parameters for a kernel node in the given graph exec. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gd84243569e4c3d6356b9f2eea20ed48c + static tsl::Status GraphExecKernelNodeSetParams( + GpuGraphExecHandle exec, GpuGraphNodeHandle node, + absl::string_view kernel_name, GpuFunctionHandle function, + unsigned int grid_dim_x, unsigned int grid_dim_y, unsigned int grid_dim_z, + unsigned int block_dim_x, unsigned int block_dim_y, + unsigned int block_dim_z, unsigned int shared_mem_bytes, + void** kernel_params, void** extra); + + // Creates a memcpy node and adds it to a graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g674da6ab54a677f13e0e0e8206ff5073 + static tsl::Status GraphAddMemcpyD2DNode(GpuContext* context, + GpuGraphNodeHandle* node, + GpuGraphHandle graph, + absl::Span deps, + GpuDevicePtr gpu_dst, + GpuDevicePtr gpu_src, uint64_t size); + + // Loads ptx_contents with the CUDA driver's PTX JIT and stores the resulting + // handle in "module". Any error logs that are produced are logged internally. + // (supported on CUDA only) + static tsl::Status LoadPtx(GpuContext* context, const char* ptx_contents, + GpuModuleHandle* module); + + // Loads cubin_bytes with the CUDA driver's blob loading interface and stores + // the resulting handle in "module". + // (supported on CUDA only) + static tsl::Status LoadCubin(GpuContext* context, const char* cubin_bytes, + GpuModuleHandle* module); + + // Loads HSACO with the ROCM runtime and stores the resulting handle in + // "module". Any error logs that are produced are logged internally. + // (supported on ROCm only) + static tsl::Status LoadHsaco(GpuContext* context, const char* hsaco_contents, + GpuModuleHandle* module); + + // Retrieves a named kernel from a loaded module, and places the resulting + // handle into function (outparam) on success. Neither kernel_name nor + // function may be null. No ownership is taken of kernel_name. + static tsl::Status GetModuleFunction(GpuContext* context, + GpuModuleHandle module, + const char* kernel_name, + GpuFunctionHandle* function); + + // Retrieves a named global/constant symbol from a loaded module, and returns + // a device pointer and size of the symbol on success. symbol_name may not be + // null. At least one of dptr or bytes should not be null. No ownership is + // taken of symbol_name. + static bool GetModuleSymbol(GpuContext* context, GpuModuleHandle module, + const char* symbol_name, GpuDevicePtr* dptr, + size_t* bytes); + + // Unloads module from the current context via cuModuleUnload. + // TODO(leary) the documentation doesn't say what kind of disasters happen + // if you try to unload a module while its GpuFunctionHandles are in use. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MODULE.html#group__CUDA__MODULE_1g8ea3d716524369de3763104ced4ea57b + static void UnloadModule(GpuContext* context, GpuModuleHandle module); + + // Performs a synchronous memset of the device memory segment via cuMemsetD8. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g6e582bf866e9e2fb014297bfaf354d7b + static tsl::Status SynchronousMemsetUint8(GpuContext* context, + GpuDevicePtr location, + uint8_t value, size_t size); + + // Performs a synchronous memset of the device memory segment via cuMemsetD32. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g983e8d8759acd1b64326317481fbf132 + static tsl::Status SynchronousMemsetUint32(GpuContext* context, + GpuDevicePtr location, + uint32_t value, + size_t uint32_count); + + // Performs an asynchronous memset of the device memory segment via + // cuMemsetD8Async. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gaef08a7ccd61112f94e82f2b30d43627 + static tsl::Status AsynchronousMemsetUint8(GpuContext* context, + GpuDevicePtr location, + uint8_t value, size_t uint32_count, + GpuStreamHandle stream); + + // Performs an asynchronous memset of the device memory segment via + // cuMemsetD32Async. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g58229da5d30f1c0cdf667b320ec2c0f5 + static tsl::Status AsynchronousMemsetUint32(GpuContext* context, + GpuDevicePtr location, + uint32_t value, + size_t uint32_count, + GpuStreamHandle stream); + + // -- Synchronous memcopies. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g4d32266788c440b0220b1a9ba5795169 + + static tsl::Status SynchronousMemcpyD2H(GpuContext* context, void* host_dst, + GpuDevicePtr gpu_src, uint64_t size); + static tsl::Status SynchronousMemcpyH2D(GpuContext* context, + GpuDevicePtr gpu_dst, + const void* host_src, uint64_t size); + static tsl::Status SynchronousMemcpyD2D(GpuContext* context, + GpuDevicePtr gpu_dst, + GpuDevicePtr gpu_src, uint64_t size); + + // -- Asynchronous memcopies. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g56f30236c7c5247f8e061b59d3268362 + + static bool AsynchronousMemcpyD2H(GpuContext* context, void* host_dst, + GpuDevicePtr gpu_src, uint64_t size, + GpuStreamHandle stream); + static bool AsynchronousMemcpyH2D(GpuContext* context, GpuDevicePtr gpu_dst, + const void* host_src, uint64_t size, + GpuStreamHandle stream); + static bool AsynchronousMemcpyD2D(GpuContext* context, GpuDevicePtr gpu_dst, + GpuDevicePtr gpu_src, uint64_t size, + GpuStreamHandle stream); + + // The CUDA stream callback type signature. + // The data passed to AddStreamCallback is subsequently passed to this + // callback when it fires. + // + // Some notable things: + // * Callbacks must not make any CUDA API calls. + // * Callbacks from independent streams execute in an undefined order and may + // be serialized. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gab95a78143bae7f21eebb978f91e7f3f + typedef void (*StreamCallback)(void* data); + + // Enqueues a callback operation into stream. + // See StreamCallback above and the NVIDIA documentation for additional + // details. + static bool AddStreamCallback(GpuContext* context, GpuStreamHandle stream, + StreamCallback callback, void* data); + + // Causes stream to wait for event to trigger before proceeding via + // cuStreamWaitEvent. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#axzz334nAXAhM + static bool WaitStreamOnEvent(GpuContext* context, GpuStreamHandle stream, + GpuEventHandle event); + + // Blocks the calling thread until the operations enqueued onto stream have + // been completed, via cuStreamSynchronize. + // + // TODO(leary) if a pathological thread enqueues operations onto the stream + // while another thread blocks like this, can you wind up waiting an unbounded + // amount of time? + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g15e49dd91ec15991eb7c0a741beb7dad + static tsl::Status SynchronizeStream(GpuContext* context, + GpuStreamHandle stream); + + // Blocks the calling thread until the operations associated with the context + // have been completed, via cuCtxSynchronize. + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g7a54725f28d34b8c6299f0c6ca579616 + static bool SynchronizeContext(GpuContext* context); + + // Returns true if all stream tasks have completed at time of the call. Note + // the potential for races around this call (if another thread adds work to + // the stream immediately after this returns). + static bool IsStreamIdle(GpuContext* context, GpuStreamHandle stream); + + // Returns whether code in the from context can access memory in the to + // context via cuDeviceCanAccessPeer. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS_1g496bdaae1f632ebfb695b99d2c40f19e + static bool CanEnablePeerAccess(GpuContext* from, GpuContext* to); + + // Returns whether the from device can access memory in the to + // device via cuDeviceCanAccessPeer. Because of differences between ROCM and + // CUDA, this API is not supported in ROCM builds and will result in a link + // error if used. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS_1g496bdaae1f632ebfb695b99d2c40f19e + static bool CanEnablePeerAccess(GpuDeviceHandle from, GpuDeviceHandle to); + + // Enables peer access per CanEnablePeerAccess, via cuCtxEnablePeerAccess. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS_1g0889ec6728e61c05ed359551d67b3f5a + static tsl::Status EnablePeerAccess(GpuContext* from, GpuContext* to); + + // Returns the elapsed milliseconds between start and stop via + // cuEventElapsedTime. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1gdfb1178807353bbcaa9e245da497cf97 + static bool GetEventElapsedTime(GpuContext* context, + float* elapsed_milliseconds, + GpuEventHandle start, GpuEventHandle stop); + + // Records that an event occurred when execution reaches the current point in + // thestream via cuEventRecord. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g95424d3be52c4eb95d83861b70fb89d1 + static tsl::Status RecordEvent(GpuContext* context, GpuEventHandle event, + GpuStreamHandle stream); + + // Polls (without blocking) to determine the status of an event - pending or + // complete (or an error status). + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g6f0704d755066b0ee705749ae911deef + static tsl::StatusOr QueryEvent(GpuContext* context, + GpuEventHandle event); + + // -- Pointer-specific calls. + + // Returns the context in which pointer was allocated or registered. + static tsl::StatusOr GetPointerContext(GpuDevicePtr pointer); + + // Returns the device associated with the context from GetPointerContext(). + static tsl::StatusOr GetPointerDevice(GpuDevicePtr pointer); + + // Returns the memory space addressed by pointer. + static tsl::StatusOr GetPointerMemorySpace(GpuDevicePtr pointer); + + // Returns the base address and size of the device pointer dptr. + static tsl::Status GetPointerAddressRange(GpuDevicePtr dptr, + GpuDevicePtr* base, size_t* size); + + // -- Device-specific calls. + + // Returns the compute capability for the device; i.e (3, 5). + // This is currently done via the deprecated device API. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE__DEPRECATED.html#group__CUDA__DEVICE__DEPRECATED_1ge2091bbac7e1fb18c2821612115607ea + // (supported on CUDA only) + static tsl::Status GetComputeCapability(int* cc_major, int* cc_minor, + GpuDeviceHandle device); + + // Returns Gpu ISA version for the device; i.e 803, 900. + // (supported on ROCm only) + static tsl::Status GetGpuISAVersion(int* version, GpuDeviceHandle device); + + // Return the full GCN Architecture Name for the device + // for eg: amdgcn-amd-amdhsa--gfx908:sramecc+:xnack- + // (supported on ROCm only) + static tsl::Status GetGpuGCNArchName(GpuDeviceHandle device, + std::string* gcnArchName); + +#if TENSORFLOW_USE_ROCM + // tests the current device for MFMA insn support (ROCm only) + static tsl::StatusOr GetMFMASupport(); +#endif + + // Returns the number of multiprocessors on the device (note that the device + // may be multi-GPU-per-board). + static tsl::StatusOr GetMultiprocessorCount(GpuDeviceHandle device); + + // Returns the limit on number of threads that can be resident in a single + // multiprocessor. + static tsl::StatusOr GetMaxThreadsPerMultiprocessor( + GpuDeviceHandle device); + + // Returns the limit on number of threads which may be resident for a single + // block (cooperative thread array). + static tsl::StatusOr GetMaxThreadsPerBlock(GpuDeviceHandle device); + + // Returns the amount of shared memory available on a single GPU core (i.e. + // SM on NVIDIA devices). + static tsl::StatusOr GetMaxSharedMemoryPerCore( + GpuDeviceHandle device); + + // Returns the amount of static shared memory available for a single block + // (cooperative thread array). + static tsl::StatusOr GetMaxSharedMemoryPerBlock( + GpuDeviceHandle device); + + // Returns the total amount of shared memory available for a single block + // (cooperative thread array). + static tsl::StatusOr GetMaxSharedMemoryPerBlockOptin( + GpuDeviceHandle device); + + // Returns the maximum supported number of registers per block. + static tsl::StatusOr GetMaxRegistersPerBlock(GpuDeviceHandle device); + + // Returns the number of threads per warp. + static tsl::StatusOr GetThreadsPerWarp(GpuDeviceHandle device); + + // Queries the grid limits for device with cuDeviceGetAttribute calls. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g9c3e1414f0ad901d3278a4d6645fc266 + static tsl::Status GetGridLimits(int* x, int* y, int* z, + GpuDeviceHandle device); + + // Returns a grab-bag of device properties in a caller-owned device_properties + // structure for device_ordinal via cuDeviceGetProperties. + // + // This call is deprecated in the NVIDIA driver API; its replacement is + // GetDeviceAttribute + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE__DEPRECATED.html#group__CUDA__DEVICE__DEPRECATED_1g65a5b4e25186bd257df80b98c98cffe6 + static bool GetDeviceProperties(GpuDeviceProperty* device_properties, + int device_ordinal); + + // Gets a specific integer-valued property about the given device. + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g9c3e1414f0ad901d3278a4d6645fc266 + static tsl::StatusOr GetDeviceAttribute(GpuDeviceAttribute attribute, + GpuDeviceHandle device); + + // Returns whether ECC is enabled for the given GpuDeviceHandle via + // cuDeviceGetattribute with CU_DEVICE_ATTRIBUTE_ECC_ENABLED. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g9c3e1414f0ad901d3278a4d6645fc266 + static bool IsEccEnabled(GpuDeviceHandle device, bool* result); + + // Returns the total amount of memory available for allocation by the CUDA + // context, in bytes, via cuDeviceTotalMem. + static bool GetDeviceTotalMemory(GpuDeviceHandle device, uint64_t* result); + + // Returns the free amount of memory and total amount of memory, as reported + // by cuMemGetInfo. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g808f555540d0143a331cc42aa98835c0 + static bool GetDeviceMemoryInfo(GpuContext* context, int64_t* free, + int64_t* total); + + // Returns a PCI bus id string for the device. + // [domain]:[bus]:[device].[function] + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g85295e7d9745ab8f0aa80dd1e172acfc + static std::string GetPCIBusID(GpuDeviceHandle device); + + // -- Context- and device-independent calls. + + // Returns the number of visible CUDA device via cuDeviceGetCount. + // This should correspond to the set of device ordinals available. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g52b5ce05cb8c5fb6831b2c0ff2887c74 + static int GetDeviceCount(); + + // Returns the driver version number via cuDriverGetVersion. + // This is, surprisingly, NOT the actual driver version (e.g. 331.79) but, + // instead, the CUDA toolkit release number that this driver is compatible + // with; e.g. 6000 (for a CUDA 6.0 compatible driver) or 6050 (for a CUDA 6.5 + // compatible driver). + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VERSION.html#group__CUDA__VERSION_1g8b7a10395392e049006e61bcdc8ebe71 + static bool GetDriverVersion(int* driver_version); + + // -- Other calls + + // Returns the maximum number of blocks (per multiprocessor) occupied by the + // specified kernel/GpuFunctionHandle when launched with the specified + // parameters. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__OCCUPANCY.html#group__CUDA__OCCUPANCY_1gcc6e1094d05cba2cee17fe33ddd04a98 + static tsl::StatusOr GetMaxOccupiedBlocksPerCore( + GpuContext* context, GpuFunctionHandle kernel, int threads_per_block, + size_t dynamic_shared_memory_bytes); + + // Seam for injecting an error at CUDA initialization time for testing + // purposes. + static bool driver_inject_init_error_; +}; + +// Ensures a context is activated within a scope. +class ScopedActivateContext { + public: + // Activates the context via cuCtxSetCurrent, if it is not the currently + // active context (a la cuCtxGetCurrent). Note the alternative push/pop + // mechanism is said by NVIDIA to be relatively slow and deprecated. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1gbe562ee6258b4fcc272ca6478ca2a2f7 + explicit ScopedActivateContext(GpuContext* context); + + // Checks that the context has remained activated for the duration of the + // scope. + ~ScopedActivateContext(); + + private: + GpuContext* to_restore_ = nullptr; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_DRIVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_event.h new file mode 100644 index 0000000000000000000000000000000000000000..5653e309c675f2af5a02b85fc9d5c442e5fafa90 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_event.h @@ -0,0 +1,62 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_EVENT_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_EVENT_H_ + +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/gpu/gpu_stream.h" +#include "tsl/platform/status.h" + +namespace stream_executor { +namespace gpu { + +// GpuEvent wraps a GpuEventHandle in the platform-independent EventInterface +// interface. +class GpuEvent : public internal::EventInterface { + public: + explicit GpuEvent(GpuExecutor* parent); + + ~GpuEvent() override; + + // Populates the CUDA-platform-specific elements of this object. + tsl::Status Init(); + + // Deallocates any platform-specific elements of this object. This is broken + // out (not part of the destructor) to allow for error reporting. + tsl::Status Destroy(); + + // Inserts the event at the current position into the specified stream. + tsl::Status Record(GpuStream* stream); + + // Polls the CUDA platform for the event's current status. + Event::Status PollForStatus(); + + // The underlying CUDA event element. + GpuEventHandle gpu_event(); + + private: + // The Executor used to which this object and GpuEventHandle are bound. + GpuExecutor* parent_; + + // The underlying CUDA event element. + GpuEventHandle gpu_event_; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..c93073ffd9dafabfaf3712b1a224f1197c1ff865 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_executor.h @@ -0,0 +1,401 @@ +/* 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. +==============================================================================*/ + +// The CUDA implementation of the StreamExecutorInterface functionality. +// CUDA inclusions are ideally confined to this implementation file. +// +// The notions from the StreamExecutor basically correspond to the CUDA streams +// programming model provided by the libcuda.so driver APIs, so we don't have +// to do much more than wrap the calls to the libraries appropriately. +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_EXECUTOR_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_EXECUTOR_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/gpu/gpu_kernel.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/fingerprint.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class StreamExecutor; + +namespace gpu { + +// CUDA-platform implementation of the platform-agnostic +// StreamExecutorInterface. +class GpuExecutor : public internal::StreamExecutorInterface { + // Helper classes to attach a type erased state to the GpuExecutor. Currently, + // we just need to support some XLA specific state. + class Object { + struct Concept { + virtual ~Concept() {} + }; + template + struct Model : Concept { + explicit Model(StreamExecutor* se) : object(se) {} + T object; + }; + + public: + template + T* getOrCreate(StreamExecutor* se) { + absl::MutexLock l(&mu_); + if (!object_) { + object_ = std::make_unique>(se); + } + return &(dynamic_cast*>(object_.get())->object); + } + + private: + absl::Mutex mu_; + std::unique_ptr object_ ABSL_GUARDED_BY(mu_); + }; + + public: + // sub_platform indicates the subplatform used in this executor; it must + // be a CUDA type. + GpuExecutor() + : device_(0), + context_(nullptr), + device_ordinal_(0), + cc_major_(0), + cc_minor_(0), + version_(0) {} + + // See the corresponding StreamExecutor methods for method comments on the + // following overrides. + + ~GpuExecutor() override; + + tsl::Status Init(int device_ordinal, DeviceOptions device_options) override; + + tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, + KernelBase* kernel) override; + + // (supported on CUDA only) + void UnloadKernel(const KernelBase* kernel) override; + tsl::Status LoadModule(const MultiModuleLoaderSpec& spec, + ModuleHandle* module_handle) override; + bool UnloadModule(ModuleHandle module_handle) override; + + // Allocates and initializes a new constant on the device with the given + // content. Or, if a device with identical content is already on-device, + // returns a pointer to that buffer with shared ownership. + tsl::StatusOr> CreateOrShareConstant( + Stream* stream, const std::vector& content) override; + + tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& k, + const KernelArgsArrayBase& args) override; + + tsl::Status Submit(Stream* stream, + const CommandBuffer& command_buffer) override; + + // (supported on CUDA only) + int CalculateOccupancy(const DeviceDescription& device_description, + uint64_t registers_per_thread, + uint64_t shared_memory_per_block, + const ThreadDim& thread_dims, GpuFunctionHandle func); + + // (supported on CUDA only) + int CompareOccupancy(int* initial_blocks, + const DeviceDescription& device_description, + uint64_t registers_per_thread, + uint64_t shared_memory_per_block, + const ThreadDim& thread_dims, GpuFunctionHandle func); + + DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space) override; + + void* GetSubBuffer(DeviceMemoryBase* mem, uint64_t offset_bytes, + uint64_t size_bytes) override; + + void Deallocate(DeviceMemoryBase* mem) override; + + void* UnifiedMemoryAllocate(uint64_t size) override { + return GpuDriver::UnifiedMemoryAllocate(context_, size); + } + + void UnifiedMemoryDeallocate(void* location) override { + return GpuDriver::UnifiedMemoryDeallocate(context_, location); + } + + // CUDA allocation/registration functions are necessary because the driver + // internally sets up buffers for DMA operations (and page locks them). + // There's no external interface for us to otherwise control these DMA + // settings. + void* HostMemoryAllocate(uint64_t size) override { + return GpuDriver::HostAllocate(context_, size); + } + + void HostMemoryDeallocate(void* location) override { + return GpuDriver::HostDeallocate(context_, location); + } + + bool HostMemoryRegister(void* location, uint64_t size) override; + + bool HostMemoryUnregister(void* location) override; + + bool SynchronizeAllActivity() override; + + tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) override; + + tsl::Status SynchronousMemSet(DeviceMemoryBase* location, int value, + uint64_t size) override; + + tsl::Status SynchronousMemcpy(DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + + tsl::Status SynchronousMemcpy(void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + tsl::Status SynchronousMemcpyDeviceToDevice(DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) override; + tsl::Status Memset(Stream* stream, DeviceMemoryBase* location, + uint8_t pattern, uint64_t size) override; + tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size) override; + + bool Memcpy(Stream* stream, void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + bool Memcpy(Stream* stream, DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + + bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + bool HostCallback(Stream* stream, + absl::AnyInvocable callback) override; + + bool AllocateStream(Stream* stream) override; + + void DeallocateStream(Stream* stream) override; + + bool CreateStreamDependency(Stream* dependent, Stream* other) override; + + tsl::Status AllocateEvent(Event* event) override; + + tsl::Status DeallocateEvent(Event* event) override; + + tsl::Status RecordEvent(Stream* stream, Event* event) override; + + tsl::Status WaitForEvent(Stream* stream, Event* event) override; + + tsl::Status WaitForEventOnExternalStream(std::intptr_t stream, + Event* event) override; + + Event::Status PollForEventStatus(Event* event) override; + + tsl::Status BlockHostUntilDone(Stream* stream) override; + + tsl::Status EnablePeerAccessTo(StreamExecutorInterface* other) override; + + bool CanEnablePeerAccessTo(StreamExecutorInterface* other) override; + + bool DeviceMemoryUsage(int64_t* free, int64_t* total) const override; + + // Search for the symbol in the given module and returns a device pointer and + // size. Returns false if symbol does not exist. 'module_handle' must not + // be null. + bool GetSymbol(const std::string& symbol_name, ModuleHandle module_handle, + void** mem, size_t* bytes) override; + + tsl::StatusOr> CreateDeviceDescription() + const override { + return CreateDeviceDescription(device_ordinal_); + } + + static tsl::StatusOr> + CreateDeviceDescription(int device_ordinal); + + blas::BlasSupport* CreateBlas() override; + + fft::FftSupport* CreateFft() override; + + dnn::DnnSupport* CreateDnn() override; + + std::unique_ptr CreateEventImplementation() + override; + + std::unique_ptr CreateKernelImplementation() + override; + + std::unique_ptr GetStreamImplementation() override; + + tsl::StatusOr> + GetCommandBufferImplementation(CommandBuffer::Mode mode) override; + + void* GpuContextHack() override; + + GpuContext* gpu_context(); + + // Provide a type-erased way of attaching arbitrary XLA specific state to the + // GpuExecutor. XLA based execution will use this method to attach per-stream + // executor XLA specific objects (like the Infeed and Outfeed managers) to the + // stream executor, so that their lifetimes can be tied to the lifetime of the + // stream executor for which that object is allocated for. This simplifies + // memory management as compared to having these objects reside on the side + // and then either leaking or having to implement callbacks that the SE + // destructors call to deallocate any side state that is associated with that + // SE object. + template + T* getOrCreateXLAState(StreamExecutor* se) { + return xla_state_.getOrCreate(se); + } + + Stream* FindAllocatedStream(void* gpu_stream) override { + absl::MutexLock lock(&alive_gpu_streams_mu_); + auto it = alive_gpu_streams_.find(gpu_stream); + if (it == alive_gpu_streams_.end()) { + return nullptr; + } + return it->second; + } + + private: + // Host callback landing routine invoked by CUDA. + // data: User-provided callback provided to HostCallback() above, captured + // as a std::function. Allocated/initialized inside + // HostCallback() and owned and deleted by this call. + static void InternalHostCallback(void* data); + + // Collects metadata for the specified kernel. + tsl::Status GetKernelMetadata(GpuKernel* cuda_kernel, + KernelMetadata* kernel_metadata); + + // Prints to VLOG(2) information about the kernel's occupancy and how it might + // be improved. + void VlogOccupancyInfo(const KernelBase& kernel, const ThreadDim& thread_dims, + const BlockDim& block_dims); + + // (supported on CUDA only) + tsl::Status LoadModuleFromCuBin(const char* cubin, GpuModuleHandle* module) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + // Loads the PTX text `ptx` as a CUDA module. `ptx` must be null terminated. + // (supported on CUDA only) + tsl::Status LoadModuleFromPtx(const char* ptx, GpuModuleHandle* module) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + // (supported on ROCm only) + tsl::Status LoadModuleFromHsaco(const char* hsaco, GpuModuleHandle* module) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + bool UnloadGpuBinary(const void* gpu_binary) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + // Guards the on-disk-module mapping. + absl::Mutex disk_modules_mu_; + + // Mapping from filename to GPUModuleHandle, if it was already retrieved. + // Multiple GPUFunctionHandle are usually obtained from a single + // GPUModuleHandle so we attempt to hit in this mapping first, before + // retrieving it. + std::map disk_modules_ + ABSL_GUARDED_BY(disk_modules_mu_); + + // Guards the in-memory-module mapping. + absl::Mutex in_memory_modules_mu_; + + std::map in_memory_modules_ + ABSL_GUARDED_BY(in_memory_modules_mu_); + + absl::Mutex shared_constants_mu_; + // On-device constants that can be shared between multiple executables. A + // pointer for a given constant will expire when no executables require use + // of that constant anymore. + std::map> + shared_constants_ ABSL_GUARDED_BY(shared_constants_mu_); + + // Kernel -> loaded GPU binary. Many kernels may load the same binary. + std::unordered_map kernel_to_gpu_binary_ + ABSL_GUARDED_BY(in_memory_modules_mu_); + // GPU binary (PTX or CUBIN or HSACO) -> {CUDA module, reference count}. + std::unordered_map> + gpu_binary_to_module_ ABSL_GUARDED_BY(in_memory_modules_mu_); + + // Guards the launched kernel set. + absl::Mutex launched_kernels_mu_; + + // Keeps track of the set of launched kernels. Currently used to suppress the + // occupancy check on subsequent launches. + std::set launched_kernels_ + ABSL_GUARDED_BY(launched_kernels_mu_); + + // Handle for the CUDA device being operated on. Immutable + // post-initialization. + GpuDeviceHandle device_; + + // Handle for session with the library/driver. Immutable post-initialization. + GpuContext* context_; + + // The device ordinal value that this executor was initialized with; recorded + // for use in getting device metadata. Immutable post-initialization. + int device_ordinal_; + + // The major version of the compute capability for device_. + int cc_major_; + + // The minor version of the compute capability for device_. + int cc_minor_; + + // GPU ISA version for device_. + int version_; + + // Type erased XLA specific state attached to GpuExecutor. + Object xla_state_; + + absl::Mutex alive_gpu_streams_mu_; + + // Lookup map for alive streams, from raw stream pointers. + absl::flat_hash_map alive_gpu_streams_ + ABSL_GUARDED_BY(alive_gpu_streams_mu_); + + GpuExecutor(const GpuExecutor&) = delete; + void operator=(const GpuExecutor&) = delete; +}; + +inline GpuExecutor* ExtractGpuExecutor(StreamExecutor* stream_exec) { + return static_cast(stream_exec->implementation()); +} + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_graph.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..af58a4102c29f3d6eef9073443b9a48fbef4aab4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_graph.h @@ -0,0 +1,140 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_GRAPH_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_GRAPH_H_ + +#include +#include +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/types/span.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/stream.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace gpu { + +// Forward declare. +class GpuContext; + +class GpuGraphSupport { + public: + // Deleters for gpu graph and graph exec instance that check the returned + // status and terminate on error. + struct DestroyGraph { + void operator()(GpuGraphHandle); + }; + struct DestroyGraphExec { + void operator()(GpuGraphExecHandle); + }; + + static size_t NotifyGraphExecCreated(); + static size_t NotifyGraphExecDestroyed(); + + static size_t allocated_gpu_graph_execs(); + static size_t alive_gpu_graph_execs(); + + private: + // Global counters for the total number of allocated and alive gpu graph + // execs to track the resource usage at run time. + static std::atomic allocated_gpu_graph_execs_; + static std::atomic alive_gpu_graph_execs_; +}; + +//===----------------------------------------------------------------------===// +// RAII helpers for gpu graph types. +//===----------------------------------------------------------------------===// + +class OwnedGpuGraph + : public std::unique_ptr, + GpuGraphSupport::DestroyGraph> { + // Bring std::unique_ptr constructors in scope. + using std::unique_ptr, + GpuGraphSupport::DestroyGraph>::unique_ptr; +}; + +class OwnedGpuGraphExec + : public std::unique_ptr, + GpuGraphSupport::DestroyGraphExec> { + using Base = std::unique_ptr, + GpuGraphSupport::DestroyGraphExec>; + + public: + OwnedGpuGraphExec(uint64_t id, GpuGraphExecHandle exec) + : Base(exec), id_(id) {} + ~OwnedGpuGraphExec(); + + OwnedGpuGraphExec(OwnedGpuGraphExec&&) = default; + OwnedGpuGraphExec& operator=(OwnedGpuGraphExec&&) = default; + + enum class UpdateResult { kSuccess, kFallback }; + + // Updates executable graph instance with a newly captured graph. Returns an + // error if the new graph is not compatible (see `cudaGraphExecUpdate`). + tsl::StatusOr Update(OwnedGpuGraph graph); + + // Launches captured graph on a given stream. + tsl::Status Launch(stream_executor::Stream* stream); + + uint64_t id() const { return id_; } + + private: + uint64_t id_; + uint64_t num_updates_ = 0; + uint64_t num_launches_ = 0; +}; + +//===----------------------------------------------------------------------===// +// Gpu Graph Helpers. +//===----------------------------------------------------------------------===// + +// Creates new empty Gpu graph. +tsl::StatusOr CreateGpuGraph(); + +// Adds a kernel node to the graph. +tsl::StatusOr AddKernelNode( + GpuGraphHandle graph, absl::Span deps, + ThreadDim threads, BlockDim blocks, const KernelBase& kernel, + const KernelArgsArrayBase& args); + +// Adds a memory copy node to the graph. +tsl::StatusOr AddMemcpyD2DNode( + GpuContext* context, GpuGraphHandle graph, + absl::Span deps, const DeviceMemoryBase& dst, + const DeviceMemoryBase& src); + +// Captures all operations added to a `stream` by the `capture` function into +// the gpu graph instance. +tsl::StatusOr CaptureGpuGraph( + stream_executor::Stream* stream, absl::AnyInvocable capture); + +// Instantiates a captured gpu graph instance into a gpu graph executable. +tsl::StatusOr InstantiateGpuGraph(OwnedGpuGraph graph); + +// Returns true if the stream is in graph capture mode +tsl::StatusOr IsStreamCapturing(stream_executor ::Stream* stream); + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_GRAPH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_helpers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..cefd0a6af15dfd70d06c94677230a20d66d219f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_helpers.h @@ -0,0 +1,114 @@ +/* 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. +==============================================================================*/ + +// Common helper functions used for dealing with CUDA API datatypes. +// +// These are typically placed here for use by multiple source components (for +// example, BLAS and executor components). + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_HELPERS_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_HELPERS_H_ + +#include + +#include + +#include "xla/stream_executor/gpu/gpu_types.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { + +template +class DeviceMemory; + +namespace gpu { + +// Converts a const DeviceMemory reference to its underlying typed pointer in +// CUDA device memory. +template +const T* GpuMemory(const DeviceMemory& mem) { + return static_cast(mem.opaque()); +} + +// Converts a (non-const) DeviceMemory pointer reference to its underlying typed +// pointer in CUDA device memory. +template +T* GpuMemoryMutable(DeviceMemory* mem) { + return static_cast(mem->opaque()); +} + +static_assert( + sizeof(std::complex) == sizeof(GpuComplexType), + "std::complex and GpuComplexType should have the same size"); +static_assert(offsetof(GpuComplexType, x) == 0, + "The real part of GpuComplexType should appear first."); +static_assert( + sizeof(std::complex) == sizeof(GpuDoubleComplexType), + "std::complex and GpuDoubleComplexType should have the same " + "size"); +static_assert(offsetof(GpuDoubleComplexType, x) == 0, + "The real part of GpuDoubleComplexType should appear first."); + +// Type traits to get CUDA complex types from std::complex<>. + +template +struct GpuComplexT { + typedef T type; +}; + +template <> +struct GpuComplexT> { + typedef GpuComplexType type; +}; + +template <> +struct GpuComplexT> { + typedef GpuDoubleComplexType type; +}; + +// Converts pointers of std::complex<> to pointers of +// GpuComplexType/GpuDoubleComplexType. No type conversion for non-complex +// types. + +template +inline const typename GpuComplexT::type* GpuComplex(const T* p) { + auto* result = reinterpret_cast::type*>(p); + CHECK_EQ(reinterpret_cast(p) % alignof(decltype(*result)), 0) + << "Source pointer is not aligned by " << alignof(decltype(*result)); + return result; +} + +template +inline typename GpuComplexT::type* GpuComplex(T* p) { + auto* result = reinterpret_cast::type*>(p); + CHECK_EQ(reinterpret_cast(p) % alignof(decltype(*result)), 0) + << "Source pointer is not aligned by " << alignof(decltype(*result)); + return result; +} + +// Converts values of std::complex to values of +// GpuComplexType/GpuDoubleComplexType. +inline GpuComplexType GpuComplexValue(std::complex val) { + return {val.real(), val.imag()}; +} + +inline GpuDoubleComplexType GpuComplexValue(std::complex val) { + return {val.real(), val.imag()}; +} + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_HELPERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_init.h new file mode 100644 index 0000000000000000000000000000000000000000..bcdce71f9ffce79f59d14f7d3e6e84db13d6ac29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_init.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. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_INIT_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_INIT_H_ + +#include + +#include "tsl/platform/status.h" + +namespace stream_executor { +class Platform; + +// Initializes the GPU platform and returns OK if the GPU +// platform could be initialized. +tsl::Status ValidateGPUMachineManager(); + +// Returns the GPU machine manager singleton, creating it and +// initializing the GPUs on the machine if needed the first time it is +// called. Must only be called when there is a valid GPU environment +// in the process (e.g., ValidateGPUMachineManager() returns OK). +Platform* GPUMachineManager(); + +// Returns the string describing the name of the GPU platform in use. +// This value is "CUDA" by default, and +// "ROCM" when TF is built with `--config==rocm` +std::string GpuPlatformName(); + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_INIT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b7fa33c87e5acefbf1932be3b18ba825bab65bbb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_kernel.h @@ -0,0 +1,105 @@ +/* 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. +==============================================================================*/ + +// The CUDA implementation of the StreamExecutorInterface functionality. +// CUDA inclusions are ideally confined to this implementation file. +// +// The notions from the StreamExecutor basically correspond to the CUDA streams +// programming model provided by the libcuda.so driver APIs, so we don't have +// to do much more than wrap the calls to the libraries appropriately. +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_KERNEL_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_KERNEL_H_ + +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/kernel_cache_config.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { +namespace gpu { + +// Wraps a GpuFunctionHandle to implement the platform-independent +// KernelInterface. +class GpuKernel : public internal::KernelInterface { + public: + GpuKernel() + : gpu_function_(nullptr), + arity_(0), + preferred_cache_config_(KernelCacheConfig::kNoPreference) {} + + // Note that the function is unloaded when the module is unloaded, and the + // module that the function is contained in is owned by the GpuExecutor. + ~GpuKernel() override {} + + // As arity cannot be reflected upon using the CUDA API, the arity is + // explicitly set during the GpuExecutor::GetKernel initialization process. + void set_arity(unsigned arity) { arity_ = arity; } + unsigned Arity() const override { return arity_; } + + // Returns the GpuFunctionHandle value for passing to the CUDA API. + GpuFunctionHandle AsGpuFunctionHandle() const { + DCHECK(gpu_function_ != nullptr); + return const_cast(gpu_function_); + } + + // Returns the slot that the GpuFunctionHandle is stored within for this + // object, for the CUDA API which wants to load into a GpuFunctionHandle*. + GpuFunctionHandle* gpu_function_ptr() { return &gpu_function_; } + + // CUDA supports setting the preferred cache configuration of a + // GpuFunctionHandle (more-or-less equivalent to a GpuKernel). We support this + // via the below functions; users can set a preference, and that is applied + // when the kernel is [lazy-]loaded (in GpuExecutor::Launch). The alternative + // would be to load the kernel & set the preference when the user calls the + // setter below; either approach is valid. Sets the current kernel cache + // configuration preference. + void SetPreferredCacheConfig(KernelCacheConfig config) override { + preferred_cache_config_ = config; + } + + // Returns the current kernel cache configuration preference. + KernelCacheConfig GetPreferredCacheConfig() const override { + return preferred_cache_config_; + } + + // Returns the current kernel cache configuration preference as a + // CUfunc_cache. + GpuFuncCachePreference GetGpuCacheConfig() const; + + private: + GpuFunctionHandle gpu_function_; // Wrapped CUDA kernel handle. + unsigned arity_; // Number of formal parameters the kernel takes. + + // Preferred (but not required) cache configuration for this kernel. + KernelCacheConfig preferred_cache_config_; +}; + +// Given a platform-independent kernel datatype, returns the (const) internal +// CUDA platform implementation pointer. +inline const GpuKernel* AsGpuKernel(const KernelBase* kernel) { + return static_cast(kernel->implementation()); +} + +// Given a platform-independent kernel datatype, returns the (non-const) +// internal CUDA platform implementation pointer. +inline GpuKernel* AsGpuKernel(KernelBase* kernel) { + return static_cast(kernel->implementation()); +} + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..66a6df44ee1012f2999fd08a326d4f34a423a955 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_stream.h @@ -0,0 +1,107 @@ +/* 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. +==============================================================================*/ + +// Defines the GpuStream type - the CUDA-specific implementation of the generic +// StreamExecutor Stream interface. + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_STREAM_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_STREAM_H_ + +#include + +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/stream_executor_internal.h" + +namespace stream_executor { +namespace gpu { + +class GpuExecutor; + +// Wraps a GpuStreamHandle in order to satisfy the platform-independent +// StreamInterface. +// +// Thread-safe post-initialization. +class GpuStream : public internal::StreamInterface { + public: + explicit GpuStream(GpuExecutor* parent) + : parent_(parent), gpu_stream_(nullptr), completed_event_(nullptr) {} + + // Note: teardown is handled by a parent's call to DeallocateStream. + ~GpuStream() override = default; + + void* GpuStreamHack() override { return gpu_stream_; } + void** GpuStreamMemberHack() override { + return reinterpret_cast(&gpu_stream_); + } + + // Explicitly initialize the CUDA resources associated with this stream, used + // by StreamExecutor::AllocateStream(). + bool Init(); + + void SetPriority(StreamPriority priority) override { + stream_priority_ = priority; + } + + void SetPriority(int priority) override { stream_priority_ = priority; } + + std::variant priority() const override { + return stream_priority_; + } + + // Explicitly destroy the CUDA resources associated with this stream, used by + // StreamExecutor::DeallocateStream(). + void Destroy(); + + // Returns true if no work is pending or executing on the stream. + bool IsIdle() const; + + // Retrieves an event which indicates that all work enqueued into the stream + // has completed. Ownership of the event is not transferred to the caller, the + // event is owned by this stream. + GpuEventHandle* completed_event() { return &completed_event_; } + + // Returns the GpuStreamHandle value for passing to the CUDA API. + // + // Precond: this GpuStream has been allocated (otherwise passing a nullptr + // into the NVIDIA library causes difficult-to-understand faults). + GpuStreamHandle gpu_stream() const { + DCHECK(gpu_stream_ != nullptr); + return const_cast(gpu_stream_); + } + + // TODO(timshen): Migrate away and remove this function. + GpuStreamHandle cuda_stream() const { return gpu_stream(); } + + GpuExecutor* parent() const { return parent_; } + + private: + GpuExecutor* parent_; // Executor that spawned this stream. + GpuStreamHandle gpu_stream_; // Wrapped CUDA stream handle. + std::variant stream_priority_; + + // Event that indicates this stream has completed. + GpuEventHandle completed_event_ = nullptr; +}; + +// Helper functions to simplify extremely common flows. +// Converts a Stream to the underlying GpuStream implementation. +GpuStream* AsGpuStream(Stream* stream); + +// Extracts a GpuStreamHandle from a GpuStream-backed Stream object. +GpuStreamHandle AsGpuStreamValue(Stream* stream); +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_timer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..23663cb1d978f1dc6a42d81db033330a87c86cf5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_timer.h @@ -0,0 +1,76 @@ +/* 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_STREAM_EXECUTOR_GPU_GPU_TIMER_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_TIMER_H_ + +#include +#include + +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/gpu/gpu_executor.h" +#include "xla/stream_executor/stream_executor_internal.h" + +namespace stream_executor { +namespace gpu { + +class GpuExecutor; +class GpuStream; + +// Timer is started once it's created, and is stopped once read. +class GpuTimer { + public: + static tsl::StatusOr Create(GpuStream* stream); + + // An ugly but a very convenient helper: creates a timer only when we need + // one, but always returns an object. If `is_needed` is false, returns an + // empty optional, acts like `Create` otherwise. + static tsl::StatusOr> CreateIfNeeded( + GpuStream* stream, bool is_needed); + + explicit GpuTimer(GpuExecutor* parent, GpuEventHandle start_event, + GpuEventHandle stop_event, GpuStream* stream) + : parent_(parent), + start_event_(start_event), + stop_event_(stop_event), + stream_(stream) {} + + GpuTimer(GpuTimer&& other) + : parent_(other.parent_), + start_event_(std::exchange(other.start_event_, nullptr)), + stop_event_(std::exchange(other.stop_event_, nullptr)), + stream_(other.stream_) {} + + ~GpuTimer(); + + // Stops the timer on the first call and returns the elapsed duration. + // Subsequent calls error out. + tsl::StatusOr GetElapsedDuration(); + + private: + GpuExecutor* parent_; + GpuEventHandle start_event_ = nullptr; + GpuEventHandle stop_event_ = nullptr; + GpuStream* stream_; + bool is_stopped_ = false; + + GpuTimer(const GpuTimer&) = delete; + void operator=(const GpuTimer&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_TIMER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_types.h new file mode 100644 index 0000000000000000000000000000000000000000..dea81d66a1d59dbf6d95b7118845de39652cb37f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/gpu_types.h @@ -0,0 +1,87 @@ +/* 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. +==============================================================================*/ + +// GPU (ROCm / CUDA) specific type handle resolution + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_TYPES_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_TYPES_H_ + +#if TENSORFLOW_USE_ROCM + +#define __HIP_DISABLE_CPP_FUNCTIONS__ + +#include "rocm/include/hip/hip_complex.h" +#include "rocm/include/hip/hip_runtime.h" +#include "rocm/include/hiprand/hiprand.h" + +#else // CUDA + +#include "third_party/gpus/cuda/include/cuComplex.h" +#include "third_party/gpus/cuda/include/cuda.h" + +#endif + +namespace stream_executor { +namespace gpu { + +#if TENSORFLOW_USE_ROCM + +using GpuContextHandle = hipCtx_t; +using GpuStreamHandle = hipStream_t; +using GpuEventHandle = hipEvent_t; +using GpuFunctionHandle = hipFunction_t; +using GpuFunctionAttribute = hipFunction_attribute; +using GpuDeviceHandle = hipDevice_t; +using GpuDevicePtr = hipDeviceptr_t; +using GpuDeviceAttribute = hipDeviceAttribute_t; +using GpuDeviceProperty = hipDeviceProp_t; +using GpuModuleHandle = hipModule_t; +using GpuStatus = hipError_t; +using GpuFuncCachePreference = hipFuncCache_t; +using GpuSharedMemConfig = hipSharedMemConfig; +using GpuComplexType = hipComplex; +using GpuDoubleComplexType = hipDoubleComplex; +using GpuRngHandle = hiprandGenerator_t; +using GpuGraphHandle = hipGraph_t; +using GpuGraphExecHandle = hipGraphExec_t; +using GpuGraphNodeHandle = hipGraphNode_t; + +#else // CUDA + +using GpuContextHandle = CUcontext; +using GpuStreamHandle = CUstream; +using GpuEventHandle = CUevent; +using GpuFunctionHandle = CUfunction; +using GpuFunctionAttribute = CUfunction_attribute; +using GpuDeviceHandle = CUdevice; +using GpuDevicePtr = CUdeviceptr; +using GpuDeviceAttribute = CUdevice_attribute; +using GpuDeviceProperty = CUdevprop; +using GpuModuleHandle = CUmodule; +using GpuStatus = CUresult; +using GpuFuncCachePreference = CUfunc_cache; +using GpuSharedMemConfig = CUsharedconfig; +using GpuComplexType = cuComplex; +using GpuDoubleComplexType = cuDoubleComplex; +using GpuGraphHandle = CUgraph; +using GpuGraphExecHandle = CUgraphExec; +using GpuGraphNodeHandle = CUgraphNode; + +#endif + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_TYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/redzone_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/redzone_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..43694d3295c3864980e379438f09d7abc880c4de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/gpu/redzone_allocator.h @@ -0,0 +1,135 @@ +/* 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_STREAM_EXECUTOR_GPU_REDZONE_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_GPU_REDZONE_ALLOCATOR_H_ + +#include +#include + +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/gpu/asm_compiler.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/scratch_allocator.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/lib/math/math_util.h" + +namespace stream_executor { + +// An allocator that allocates a bit of extra memory around the beginning/end of +// every allocation and can check that this memory is unmodified. +// +// This can be used to check for out-of-bounds writes, and, if the redzone is +// filled with a sufficiently "ugly" pattern, may also be able to check for +// out-of-bounds reads. The default fill pattern of -1 is an unusual NaN +// pattern when interpreted as a floating-point number, so hopefully works for +// out-of-bounds reads and writes in those cases. +// +// This class implements ScratchAllocator, so can be used to allocate temp +// memory for cudnn convolutions. +class RedzoneAllocator : public ScratchAllocator { + public: + static constexpr int64_t kDefaultRedzoneSize = + 1LL << 23; // 8MiB per side, 16MiB total. + static constexpr uint8_t kDefaultRedzonePattern = -1; // NOLINT + RedzoneAllocator(Stream* stream, DeviceMemoryAllocator* memory_allocator, + GpuAsmOpts gpu_compilation_opts_, + int64_t memory_limit = (1LL << 32), // 4GB + int64_t redzone_size = kDefaultRedzoneSize, + uint8_t redzone_pattern = kDefaultRedzonePattern); + + // Redzones don't count towards the memory limit. + int64_t GetMemoryLimitInBytes() override { return memory_limit_; } + + int64_t TotalAllocatedBytesExcludingRedzones() const { + return allocated_bytes_excluding_redzones_; + } + + tsl::StatusOr> AllocateBytes(int64_t byte_size) override; + + // Non-empty redzone check status implies that there was a write into a + // redzone, with a string communicating the location of the write. + struct RedzoneCheckStatus { + RedzoneCheckStatus() = default; + + RedzoneCheckStatus(absl::string_view buffer_name, void* user_buffer_address, + int64_t offset, uint64_t expected_value, + uint64_t actual_value) + : buffer_name(buffer_name), + user_buffer_address(user_buffer_address), + offset(offset), + expected_value(expected_value), + actual_value(actual_value) {} + + static RedzoneCheckStatus OK() { return {}; } + + bool ok() { return user_buffer_address == nullptr; } + + std::string RedzoneFailureMsg() const; + + std::string buffer_name = {}; + void* user_buffer_address = nullptr; + int64_t offset = 0; + uint64_t expected_value = 0; + uint64_t actual_value = 0; + }; + + // Determines whether redzones around all allocated buffers are unmodified. + // + // Reinitializes redzones to the expected value, so that the same buffer + // can be reused for multiple checks. + // + // Returns: + // + // - RedzoneCheckStatus::OK() if everything went well. + // - RedzoneCheckStatus with a non-empty error message iff a write into a + // redzone has been detected. + // - A stream error, if loading or launching the kernel has failed. + tsl::StatusOr CheckRedzones() const; + + Stream* stream() const { return stream_; } + + private: + const int device_ordinal_; + Stream* stream_; + + // Memory limit of the allocator in bytes. + const int64_t memory_limit_; + + // Redzone size on *one side* of allocation in bytes. + // + // Must be a multiple of kXlaAllocatedBufferAlignBytes, otherwise the buffers + // returned to users will be misaligned. + const int64_t redzone_size_; + + const uint8_t redzone_pattern_; + DeviceMemoryAllocator* memory_allocator_; + GpuAsmOpts gpu_compilation_opts_; + + // The second element of the pair is the size of the user allocation. This + // isn't necessarily just first.size() - 2 * redzone_size_ because when the + // user allocation size is not a multiple of 4 bytes, we round up the size of + // the RHS redzone. + // + // ScratchAllocators need to free all allocated memory on destruction so we + // use `OwningDeviceMemory` here. + std::vector> allocated_buffers_; + + int64_t allocated_bytes_excluding_redzones_ = 0; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_REDZONE_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_gpu_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_gpu_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..2a92fd17c35ac4966c9d5680b0ebff1261de7724 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_gpu_executor.h @@ -0,0 +1,164 @@ +/* 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. +==============================================================================*/ + +// Declares the HostExecutor class, which is a CPU-only implementation of +// the StreamExecutor interface. For now, this is used for testing and to +// examine the performance of host-based StreamExecutor code. +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_GPU_EXECUTOR_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_GPU_EXECUTOR_H_ + +#include + +#include "absl/functional/any_invocable.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/host/host_stream.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/errors.h" + +namespace stream_executor { +namespace host { + +// An implementation of StreamExecutor that does no communication or interaction +// with a device, but DOES perform memory operations backed by the host. +// Plugin routines (BLAS) are also supported and functional. +// Kernel invocations will fail, but host callbacks may be enqueued on this +// executor and its associated stream, and should follow standard ordering +// semantics. +// +// This is useful for evaluating the performance of host-based or fallback +// routines executed under the context of a GPU executor. +// See stream_executor.h for description of the below operations. +class HostExecutor : public internal::StreamExecutorInterface { + public: + HostExecutor() = default; + + // The stack size used for host streams can be set via + // device_options.non_portable_tags["host_stack_size"]. + tsl::Status Init(int device_ordinal, DeviceOptions device_options) override; + + tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, + KernelBase* kernel) override { + return tsl::errors::Unimplemented("Not Implemented"); + } + tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& kernel, + const KernelArgsArrayBase& args) override { + return tsl::errors::Unimplemented("Not Implemented"); + } + + DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space) override; + void* GetSubBuffer(DeviceMemoryBase* parent, uint64_t offset_bytes, + uint64_t size_bytes) override; + void Deallocate(DeviceMemoryBase* mem) override; + + void* HostMemoryAllocate(uint64_t size) override { return new char[size]; } + void HostMemoryDeallocate(void* mem) override { + delete[] static_cast(mem); + } + bool HostMemoryRegister(void* mem, uint64_t size) override { return true; } + bool HostMemoryUnregister(void* mem) override { return true; } + + bool Memcpy(Stream* stream, void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + bool Memcpy(Stream* stream, DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) override; + tsl::Status Memset(Stream* stream, DeviceMemoryBase* location, + uint8_t pattern, uint64_t size) override; + tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size) override; + + // No "synchronize all activity" implemented for this platform at the moment. + bool SynchronizeAllActivity() override { return true; } + tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) override; + + tsl::Status SynchronousMemSet(DeviceMemoryBase* location, int value, + uint64_t size) override; + + tsl::Status SynchronousMemcpy(DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + tsl::Status SynchronousMemcpy(void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + tsl::Status SynchronousMemcpyDeviceToDevice(DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + bool HostCallback(Stream* stream, + absl::AnyInvocable callback) override; + + tsl::Status AllocateEvent(Event* event) override; + tsl::Status DeallocateEvent(Event* event) override; + tsl::Status RecordEvent(Stream* stream, Event* event) override; + tsl::Status WaitForEvent(Stream* stream, Event* event) override; + Event::Status PollForEventStatus(Event* event) override; + + bool AllocateStream(Stream* stream) override; + void DeallocateStream(Stream* stream) override; + bool CreateStreamDependency(Stream* dependent, Stream* other) override; + + tsl::Status BlockHostUntilDone(Stream* stream) override; + + bool DeviceMemoryUsage(int64_t* free, int64_t* total) const override; + + tsl::StatusOr> CreateDeviceDescription() + const override { + return CreateDeviceDescription(0); + } + + static tsl::StatusOr> + CreateDeviceDescription(int device_ordinal); + + tsl::Status EnablePeerAccessTo(StreamExecutorInterface* other) override { + return ::tsl::OkStatus(); + } + + bool CanEnablePeerAccessTo(StreamExecutorInterface* other) override { + return true; + } + + blas::BlasSupport* CreateBlas() override; + + dnn::DnnSupport* CreateDnn() override { return nullptr; } + + fft::FftSupport* CreateFft() override; + + std::unique_ptr CreateEventImplementation() + override; + + std::unique_ptr CreateKernelImplementation() + override { + return nullptr; + } + + std::unique_ptr GetStreamImplementation() override; + + void* GpuContextHack() override { return nullptr; } + + private: + // Size of thread stacks for streams in bytes. '0' means "the default size". + size_t thread_stack_size_in_bytes_ = 0; +}; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_GPU_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_platform.h new file mode 100644 index 0000000000000000000000000000000000000000..4461669b95bbd5a6a9d901680a983f830937c569 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_platform.h @@ -0,0 +1,77 @@ +/* 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. +==============================================================================*/ + +// Declares the "host" platform, which is a CPU-only implementation of the +// StreamExecutor. The host platform only supports memory operations and plugin +// routines, and is primarily used for testing. +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_H_ + +#include +#include +#include + +#include "xla/stream_executor/executor_cache.h" +#include "xla/stream_executor/multi_platform_manager.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/stream_executor/trace_listener.h" + +namespace stream_executor { +namespace host { + +// Host (CPU) platform plugin, registered as a singleton value via module +// initializer. +class HostPlatform : public Platform { + public: + HostPlatform(); + ~HostPlatform() override; + + Platform::Id id() const override; + + // Device count is less clear-cut for CPUs than accelerators. This call + // currently returns the number of thread units in the host, as reported by + // base::NumCPUs(). + int VisibleDeviceCount() const override; + + const std::string& Name() const override; + + tsl::StatusOr> DescriptionForDevice( + int ordinal) const override; + + tsl::StatusOr ExecutorForDevice(int ordinal) override; + + tsl::StatusOr GetExecutor( + const StreamExecutorConfig& config) override; + + tsl::StatusOr> GetUncachedExecutor( + const StreamExecutorConfig& config) override; + + private: + // This platform's name. + std::string name_; + + // Cache of created StreamExecutors. + ExecutorCache executor_cache_; + + HostPlatform(const HostPlatform&) = delete; + void operator=(const HostPlatform&) = delete; +}; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_platform_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_platform_id.h new file mode 100644 index 0000000000000000000000000000000000000000..e29fb5a5188b53d86bee610c176340dec19416d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_platform_id.h @@ -0,0 +1,34 @@ +/* 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_STREAM_EXECUTOR_HOST_HOST_PLATFORM_ID_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_ID_H_ + +#include "xla/stream_executor/platform.h" + +namespace stream_executor { +namespace host { + +// Opaque and unique identifier for the host platform. +// This is needed so that plugins can refer to/identify this platform without +// instantiating a HostPlatform object. +// This is broken out here to avoid a circular dependency between HostPlatform +// and HostStreamExecutor. +extern const Platform::Id kHostPlatformId; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..ed5bc0b056fc18b47363d69da5ffc9f0b0b0d3fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host/host_stream.h @@ -0,0 +1,66 @@ +/* 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. +==============================================================================*/ + +// Class declaration for Stream type that enqueues tasks onto a host/CPU-based +// execution context (as opposed to a GPU device), HostExecutor. +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_STREAM_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_STREAM_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/env.h" + +namespace stream_executor { +namespace host { + +class HostStream : public internal::StreamInterface { + public: + // stack_size_in_bytes may be '0', meaning "use the default thread stack + // size". + explicit HostStream(size_t stack_size_in_bytes); + ~HostStream() override; + + // Enqueue a task that reports a status when finished. Tasks that fail do not + // stop the stream or block any other tasks from executing; rather, the stream + // will remember the first error encountered and return it from + // 'BlockUntilDone'. + bool EnqueueTaskWithStatus(absl::AnyInvocable task); + // Enqueue a task that doesn't report any status. + bool EnqueueTask(absl::AnyInvocable task); + + // Blocks until all tasks are done, returns the first error reported by a task + // (if any) and clears the error status. + tsl::Status BlockUntilDone(); + + private: + bool WorkAvailable() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + void WorkLoop(); + + absl::Mutex mu_; + std::queue> work_queue_ + ABSL_GUARDED_BY(mu_); + std::unique_ptr thread_; + tsl::Status status_; +}; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host_or_device_scalar.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host_or_device_scalar.h new file mode 100644 index 0000000000000000000000000000000000000000..a7d428d05e5657459bd9f5c5aa8e83c07bf8eddc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/host_or_device_scalar.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_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ +#define XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ + +#include +#include + +#include "xla/stream_executor/device_memory.h" + +namespace stream_executor { + +// Allows to represent a value that is either a host scalar or a scalar stored +// on the device. +template +class HostOrDeviceScalar { + public: + explicit HostOrDeviceScalar(T host_value) : value_(std::move(host_value)) {} + explicit HostOrDeviceScalar(DeviceMemory device_ptr) + : value_(std::move(device_ptr)) { + CHECK_EQ(1, device_ptr.ElementCount()); + } + + bool on_device() const { + return std::holds_alternative>(value_); + } + + const void* opaque() const { + return on_device() ? std::get>(value_).opaque() + : &std::get(value_); + } + + private: + std::variant> value_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4a9f7fbbc95c66261d1447190c4249958de8d223 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel.h @@ -0,0 +1,743 @@ +/* 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. +==============================================================================*/ + +// Suite of datatypes to represent data-parallel kernel objects (code entities). +// Kernel is the untyped variant, whereas TypedKernel takes a type signature +// to do some template-based helper generation and give compile-time type +// checking for kernel launch parameters. +// +// Users typically don't see KernelBase, they see typed kernels, analogous to a +// typed function pointer. TypedKernels express their argument types via +// template parameters like so: +// +// TypedKernel*, int> +// +// Which expresses a data parallel kernel signature for: +// +// void(int*, int); +// +// And for a const memory region: +// +// TypedKernel&, int> +// +// Corresponds to a data parallel kernel signature for: +// +// void(const int*, int) +// +// Note that kernels always have a void return type, so results typically must +// be memcpy'ied from device memory to the host. +// +// Also note that a scalar integer residing in device memory and an array of +// integers residing in device memory have the same signature: DeviceMemory. +// However, in the future, checks may be added for additional safety that arrays +// of minimum sizes are passed when those minimum sizes are contractually +// expected by the kernel. +// +// For user-defined types whose definitions are appropriately shared between the +// host code doing the launching and the kernel code being launched, the user +// defined types are similarly permitted to be expressed as residing in device +// memory: +// +// TypedKernel> +// +// And, when the alignment and padding are agreed upon, POD types will also be +// able to be passed by value; for example, it is a common idiom to specify a +// bunch of options simultaneously with a structure: +// +// TypedKernel> +// +// Which corresponds to a data parallel kernel signature like: +// +// void(MyOptionsStructurePassedByValue value, float *result); +// +// Users typically won't need to type out the TypedKernel signature in full, it +// will be typedef'd by automatically generated code; for example, see +// stream_executor::executor_sample::VecReduceAddKernel. + +#ifndef XLA_STREAM_EXECUTOR_KERNEL_H_ +#define XLA_STREAM_EXECUTOR_KERNEL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/kernel_cache_config.h" +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class DeviceMemoryBase; +template +class DeviceMemory; +class StreamExecutor; + +namespace internal { +class KernelInterface; +} // namespace internal + +// KernelMetadata holds runtime-queryable attributes of a loaded kernel, such as +// registers allocated, shared memory used, etc. +// Not all platforms support reporting of all information, so each accessor +// returns false if the associated field is not populated in the underlying +// platform. +class KernelMetadata { + public: + KernelMetadata() + : has_registers_per_thread_(false), has_shared_memory_bytes_(false) {} + + // Returns the number of registers used per thread executing this kernel. + bool registers_per_thread(int *registers_per_thread) const; + + // Sets the number of registers used per thread executing this kernel. + void set_registers_per_thread(int registers_per_thread); + + // Returns the amount of [static] shared memory used per block executing this + // kernel. Note that dynamic shared memory allocations are not (and can not) + // be reported here (since they're not specified until kernel launch time). + bool shared_memory_bytes(int *shared_memory_bytes) const; + + // Sets the amount of [static] shared memory used per block executing this + // kernel. + void set_shared_memory_bytes(int shared_memory_bytes); + + private: + // Holds the value returned by registers_per_thread above. + bool has_registers_per_thread_; + int registers_per_thread_; + + // Holds the value returned by shared_memory_bytes above. + bool has_shared_memory_bytes_; + int64_t shared_memory_bytes_; +}; + +// A data-parallel kernel (code entity) for launching via the StreamExecutor, +// analogous to a void* device function pointer. See TypedKernel for the typed +// variant. +// +// Thread-compatible. +class KernelBase { + public: + KernelBase(KernelBase &&from); + + // Constructs an "empty" (not-yet-loaded) kernel instance. + // + // parent is the StreamExecutor that will be responsible for loading the + // implementation of this kernel. It must not be null. + explicit KernelBase(StreamExecutor *parent); + + // Test-only constructor that can take a mock KernelInterface implementation. + KernelBase(StreamExecutor *parent, internal::KernelInterface *implementation); + + // Releases resources associated with the kernel instance (i.e. + // platform-specific implementation). + ~KernelBase(); + + // Returns the number of parameters that this kernel accepts. (Arity refers to + // nullary, unary, ...). + unsigned Arity() const; + + // Returns the StreamExecutor that represents the platform this kernel + // executes upon. + StreamExecutor *parent() const { return parent_; } + + // Returns a const pointer to the (opaque) platform-dependent implementation. + const internal::KernelInterface *implementation() const { + return implementation_.get(); + } + + // Returns a non-const pointer to the (opaque) platform-dependent + // implementation. + internal::KernelInterface *implementation() { return implementation_.get(); } + + void set_metadata(const KernelMetadata &metadata) { metadata_ = metadata; } + + const KernelMetadata &metadata() const { return metadata_; } + + // Sets the preferred cache configuration for a kernel. This is just a + // suggestion to the runtime, and may not be honored during execution. + void SetPreferredCacheConfig(KernelCacheConfig config); + + // Gets the preferred cache configuration for a kernel. + KernelCacheConfig GetPreferredCacheConfig() const; + + void set_name(absl::string_view name); + const std::string &name() const { return name_; } + const std::string &demangled_name() const { return demangled_name_; } + + private: + // The StreamExecutor that loads this kernel object. + StreamExecutor *parent_; + + // Implementation delegated to for platform-specific functionality. + std::unique_ptr implementation_; + + std::string name_; + std::string demangled_name_; + + KernelMetadata metadata_; + + KernelBase(const KernelBase &) = delete; + void operator=(const KernelBase &) = delete; +}; + +// Whether T is a DeviceMemory-family pointer. +template +struct IsDeviceMemoryPointer { + static constexpr bool value = false; +}; + +template +struct IsDeviceMemoryPointer *> { + static constexpr bool value = true; +}; + +template <> +struct IsDeviceMemoryPointer { + static constexpr bool value = true; +}; + +// Whether T is a DeviceMemory-family value-like thing (which includes a +// reference). This trait is useful because we pack values in the same manner as +// references. +template +struct IsDeviceMemoryValueLike { + static constexpr bool value = false; +}; + +template +struct IsDeviceMemoryValueLike &> { + static constexpr bool value = true; +}; + +// We need to treat SharedDeviceMemory types differently than other DeviceMemory +// types (since they maintain no allocations), hence these specializations. +template +struct IsDeviceMemoryValueLike &> { + static constexpr bool value = false; +}; + +template <> +struct IsDeviceMemoryValueLike { + static constexpr bool value = true; +}; + +template +struct IsDeviceMemoryValueLike> { + static constexpr bool value = true; +}; + +template +struct IsDeviceMemoryValueLike> { + static constexpr bool value = false; +}; + +template <> +struct IsDeviceMemoryValueLike { + static constexpr bool value = true; +}; + +template +struct IsSharedDeviceMemory { + static constexpr bool value = false; +}; + +template +struct IsSharedDeviceMemory &> { + static constexpr bool value = true; +}; + +template +struct IsSharedDeviceMemory> { + static constexpr bool value = true; +}; + +// Basic data about a kernel argument. +struct KernelArg { + bool is_shared; + const void *address; + size_t size; +}; + +// An iterator for traversing all the arguments of a KernelArgsArray. +class KernelArgIterator { + public: + KernelArgIterator(int number_of_argument_addresses, + int number_of_shared_memory_arguments, + const void *const *arg_addresses_data, + const size_t *arg_sizes_data, + const size_t *shmem_bytes_data, + const size_t *shmem_indices_data) + : arg_index_(0), + number_of_arguments_(number_of_argument_addresses + + number_of_shared_memory_arguments), + arg_address_iter_(arg_addresses_data), + arg_size_iter_(arg_sizes_data), + shmem_bytes_iter_(shmem_bytes_data), + shmem_indices_iter_(shmem_indices_data), + shmem_indices_end_(shmem_indices_data + + number_of_shared_memory_arguments) {} + + // Returns true if another argument is present in the iterator. + bool has_next() { return arg_index_ < number_of_arguments_; } + + // Returns the next argument in the iterator. + // + // Returns a default-constructed KernelArg if there is no next argument. + KernelArg next() { + KernelArg result = {}; + if (!has_next()) { + return result; + } else if ((shmem_indices_iter_ != shmem_indices_end_) && + (arg_index_ == *shmem_indices_iter_)) { + result.is_shared = true; + result.address = nullptr; + result.size = *shmem_bytes_iter_; + ++shmem_indices_iter_; + ++shmem_bytes_iter_; + } else { + result.is_shared = false; + result.address = *arg_address_iter_; + result.size = *arg_size_iter_; + ++arg_address_iter_; + ++arg_size_iter_; + } + ++arg_index_; + return result; + } + + private: + size_t arg_index_; + size_t number_of_arguments_; + const void *const *arg_address_iter_; + const size_t *arg_size_iter_; + const size_t *shmem_bytes_iter_; + const size_t *shmem_indices_iter_; + const size_t *const shmem_indices_end_; +}; + +// Base class for KernelArgsArray. +// +// Supports all the getter methods that do not depend on the compile-time number +// of arguments template parameter. +// +// This class exists as a way to pass kernel arguments to +// StreamExecutorInterface::Launch. That Launch method is virtual, so it can't +// be templated to accept any KernelArgsArray type, therefore a reference to +// this base type is passed instead. +// +// Performance is not a concern here because each of these methods will be +// called at most once per kernel launch. Past performance concerns with +// KernelArgsArray have been in reference to the argument packing routines which +// are called once per kernel argument. Those packing routines are now handled +// by the templated KernelArgsArray subclass of this class where they can take +// advantage of compile-time knowledge of the number of arguments in order to be +// very efficient. +class KernelArgsArrayBase { + public: + virtual ~KernelArgsArrayBase() = default; + + // Gets the number of arguments added so far, including shared memory + // arguments. + virtual size_t number_of_arguments() const = 0; + + // Gets the total number of shared memory bytes added so far. + virtual uint64_t number_of_shared_bytes() const = 0; + + // Gets the list of argument addresses. + virtual absl::Span argument_addresses() const = 0; + + // Gets an iterator to the arguments in the array. + virtual KernelArgIterator arg_iterator() const = 0; +}; + +// A list of arguments for a kernel call. +// +// The template parameter kNumArgs is the maximum number of arguments which can +// be stored in the list. +// +// Contains a list of addresses for non-shared-memory arguments and a list of +// sizes for shared-memory arguments. Since the shared-memory arguments may be +// interspersed with the non-shared-memory arguments, it also stores a list of +// the indices at which the shared-memory arguments appeared. +// +// For example, if the argument address list contains {a, b, c, d, e}, the +// shared-memory arguments list contains the sizes of {A, B, C}, and the +// shared-memory indices list contains {0, 3, 5}, then the original list of +// arguments was {A, a, b, B, c, C, d, e}. +// +// This way of storing the arguments makes CUDA kernel calls efficient because +// they only require the argument address list and the total number of shared +// bytes, but it also makes it possible for OpenCL kernel calls because they +// depend on the location of each shared-memory argument and its size. +// +// Note that the code for adding arguments has been identified as a performance +// hotspot in some real-world applications so this structure has been optimized +// for the performance of argument adding. +template +class KernelArgsArray : public KernelArgsArrayBase { + public: + static constexpr int kMaxGenericArgSize = 8; + + // Adds an argument to the list. + template + void add_argument(const T &arg) { + static_assert(sizeof(T) <= kMaxGenericArgSize, + "Please adjust kMaxGenericArgSize"); + static_assert(std::is_pod::value, "Only pod types supported!"); + char *generic_arg_storage = + &generic_arguments_[number_of_generic_arguments_++ * + kMaxGenericArgSize]; + + CHECK_EQ(reinterpret_cast(generic_arg_storage) % alignof(T), 0); + std::memcpy(generic_arg_storage, &arg, sizeof(T)); + + argument_addresses_[number_of_argument_addresses_] = generic_arg_storage; + argument_sizes_[number_of_argument_addresses_] = sizeof(arg); + ++number_of_argument_addresses_; + } + + // Adds a device memory argument to the list. + void add_device_memory_argument(const DeviceMemoryBase &arg) { + const void **copy_ptr = + &device_memory_opaque_pointers_[number_of_argument_addresses_]; + *copy_ptr = arg.opaque(); + argument_addresses_[number_of_argument_addresses_] = copy_ptr; + argument_sizes_[number_of_argument_addresses_] = sizeof(void *); + ++number_of_argument_addresses_; + } + + // Adds a shared memory argument to the list. + // + // The only significant information about a shared argument is its size, so + // that is the only parameter in this function. + void add_shared_bytes(size_t number_of_bytes) { + shared_memory_indices_[number_of_shared_memory_arguments_] = + number_of_argument_addresses_ + number_of_shared_memory_arguments_; + shared_memory_bytes_[number_of_shared_memory_arguments_] = number_of_bytes; + ++number_of_shared_memory_arguments_; + total_shared_memory_bytes_ += number_of_bytes; + } + + // Gets the number of arguments added so far, including shared memory + // arguments. + size_t number_of_arguments() const override { + return number_of_argument_addresses_ + number_of_shared_memory_arguments_; + } + + // Gets the total number of shared memory bytes added so far. + uint64_t number_of_shared_bytes() const override { + return total_shared_memory_bytes_; + } + + // Gets the list of argument addresses. + absl::Span argument_addresses() const override { + return absl::Span(argument_addresses_.data(), + number_of_argument_addresses_); + } + + // Gets an iterator to the arguments in the array. + KernelArgIterator arg_iterator() const override { + return KernelArgIterator( + number_of_argument_addresses_, number_of_shared_memory_arguments_, + argument_addresses_.data(), argument_sizes_.data(), + shared_memory_bytes_.data(), shared_memory_indices_.data()); + } + + private: + // A place to store copies of opaque pointers from device memory arguments. + std::array device_memory_opaque_pointers_; + + // Addresses for non-shared-memory arguments. + std::array argument_addresses_; + + // Storage for arguments of templated type. + alignas(kMaxGenericArgSize) + std::array generic_arguments_; + + // Sizes for non-shared-memory arguments. + std::array argument_sizes_; + + // Size in bytes for each shared memory argument. + std::array shared_memory_bytes_; + + // Indices in the arguments array for shared memory arguments. + std::array shared_memory_indices_; + + // Total of all shared memory sizes. + size_t total_shared_memory_bytes_ = 0; + + // Number of significant entries in argument_addresses_ and argument_sizes_. + size_t number_of_argument_addresses_ = 0; + + // Number of significant entries in shared_memory_bytes_ and + // shared_memory_indices_. + size_t number_of_shared_memory_arguments_ = 0; + + // The number of generic arguments that have been added to generic_arguments_. + size_t number_of_generic_arguments_ = 0; +}; + +template +std::unique_ptr MakeKernelArgs( + absl::Span args, uint32_t shared_mem_bytes) { + auto kernel_args = std::make_unique>(); + for (const DeviceMemoryBase &buf : args) { + kernel_args->add_device_memory_argument(buf); + } + if (shared_mem_bytes > 0) { + kernel_args->add_shared_bytes(shared_mem_bytes); + } + return kernel_args; +} + +// Typed variant of KernelBase, like a typed device function pointer. See the +// file comment for details and example usage. +// +// This class contains template metaprogramming magic to type check the +// parameters passed to a kernel launch are acceptable, and subsequently pack +// them into a form which can be used by the StreamExecutorInterface +// implementation. (i.e. CUDA and OpenCL both bind void*s with associated +// sizes as kernel arguments.) +// +// Thread-compatible. +template +class TypedKernel : public KernelBase { + public: + static constexpr size_t kNumberOfParameters = sizeof...(Params); + + // Delegates to KernelBase::KernelBase(), see that constructor. + explicit TypedKernel(StreamExecutor *parent) : KernelBase(parent) {} + + // Test-only constructor that can take a mock KernelInterface implementation. + // Takes ownership of implementation, it should not be null. + TypedKernel(StreamExecutor *parent, internal::KernelInterface *implementation) + : KernelBase(parent, implementation) {} + + // This is the main entry point into the magic. Packs the parameters (which + // must type check against the class template) into the args and sizes + // arrays. + // + // Const refs are taken as parameters on all of the handlers to avoid + // implicit type promotion of integers. + // + // WARNING: as a performance optimization this method may store pointers to + // some of the input parameters in the kernel args structure, so any params + // passed into this method must live at least as long as the kernel args + // structure. + void PackParams(KernelArgsArray *args, + const Params &...params) const { + PackOneParamFromList(args, params...); + } + + private: + // Stream needs access to the specific parameter-packing functionality that + // the TypedKernel provides for its corresponding type signature (and no other + // type signatures). + friend class Stream; + + template + void PackOneParamFromList(KernelArgsArray *args, + const T &arg, const RestOfParams &...rest) const { + PackOneParam(args, arg); + PackOneParamFromList(args, rest...); + } + + // Base case for variadic template expansion - nothing to do! + void PackOneParamFromList(KernelArgsArray *args) const {} + + // Packs one (non-DeviceMemoryBase) parameter into the arg and sizes array. + // The enable_if<> is for excluding DeviceMemoryBase args, which have a + // separate implementation below. + template + void PackOneParam( + KernelArgsArray *args, const T &arg, + typename std::enable_if::value && + !IsDeviceMemoryPointer::value && + !IsSharedDeviceMemory::value>::type * = + nullptr) const { + static_assert(!std::is_pointer::value, + "cannot pass raw pointer to the device"); + static_assert(!std::is_convertible::value, + "cannot pass device memory as a normal value"); + args->add_argument(arg); + } + + // DeviceMemoryBase family reference override. + template + void PackOneParam( + KernelArgsArray *args, const T &arg, + typename std::enable_if::value>::type * = + nullptr) const { + args->add_device_memory_argument(arg); + } + + // DeviceMemoryBase family pointer override. + template + void PackOneParam( + KernelArgsArray *args, T arg, + typename std::enable_if::value>::type * = + nullptr) const { + DeviceMemoryBase *ptr = static_cast(arg); + args->add_device_memory_argument(*ptr); + } + + // Dynamic shared device memory has a size, but no associated allocation on + // the host; internally, the device will allocate storage. + template + void PackOneParam( + KernelArgsArray *args, T arg, + typename std::enable_if::value>::type * = + nullptr) const { + args->add_shared_bytes(arg.size()); + } + + TypedKernel(const TypedKernel &) = delete; + void operator=(const TypedKernel &) = delete; +}; + +// Template metaprogramming helper type that helps us produce better error +// messages at compile time when the are mismatches between the parameter +// type list and the argument type list. +template +struct KernelInvocationChecker { + // Whether the parameter tuple and argument tuple match in length. + static constexpr bool kLengthMatches = + std::tuple_size::value == std::tuple_size::value; + + // The (matching) length of the parameters and arguments type lists. + static constexpr int kTupleLength = + static_cast(std::tuple_size::value); + + // Helper trait to say whether the parameter wants a DeviceMemory-reference + // compatible type. This is for inexact type matches, so that it doesn't have + // to be precisely a const DeviceMemory&, but can also be a value that + // represents the same. + template + struct IsCompatibleDeviceMemoryRef { + static constexpr bool value = false; + }; + + // See type trait definition above. + template + struct IsCompatibleDeviceMemoryRef &, DeviceMemory> { + static constexpr bool value = true; + }; + + // See type trait definition above. + template + struct IsCompatibleDeviceMemoryRef &, + SharedDeviceMemory> { + static constexpr bool value = true; + }; + + // Returns whether ParamT and ArgT are compatible for data parallel kernel + // parameter packing without any assert functionality. + template + static constexpr bool CompatibleNoAssert() { + return std::is_same::type, + ArgT>::value || + IsCompatibleDeviceMemoryRef::value; + } + + // Checks whether ParamT and ArgT are compatible for data parallel kernel + // parameter packing. kArgumentNumber is unused, it just for error display. + // + // NOTE: if you encounter an error here, you can see the mismatch by looking + // at the end of the last error message, which will be of the form: + // + // ...::Compatible &, + // stream_executor::DeviceMemory, true, + // 0>' + // requested here + // + // This means that the 0th argument you passed to the kernel invocation should + // have been DeviceMemory but was observed to be + // DeviceMemory. + template + static constexpr bool Compatible() { + static_assert( + kShouldStaticAssert ? CompatibleNoAssert() : true, + "parameter type (LHS) is not compatible with argument type (RHS)"); + return CompatibleNoAssert(); + } + + // Checks the parameter/argument match at kArgumentNumber for an out of bounds + // argument number. + // + // This is the base case: we've run out of argument to check, so we're all + // good. + template + static constexpr bool CheckParam( + typename std::enable_if<(kArgumentNumber < 0)>::type *dummy = nullptr) { + return true; + } + + // Checks the parameter/argument match at kArgumentNumber. + // kShouldStaticAssert determines whether to assert out on a mismatch, or just + // yield the constexpr boolean value. + template + static constexpr bool CheckParam( + typename std::enable_if= 0>::type *dummy = nullptr) { + typedef + typename std::tuple_element::type ParamT; + typedef typename std::tuple_element::type ArgT; + return Compatible() && + CheckParam(); + } + + // Checks the parameters/arguments for match, but doesn't static assert out. + // This is useful for testing/inspecting whether a set of parameters match in + // things like tests. + static constexpr bool CheckAllNoStaticAssert() { + return kLengthMatches && CheckParam(); + } + + // Checks the parameters and static asserts out with a helpful error message + // (and useful template parameters in the instantiation stack) if there is an + // error. + static constexpr bool CheckAllStaticAssert() { + static_assert(kLengthMatches, + "argument length mismatched against typed kernel parameters"); + return kLengthMatches && CheckParam(); + } +}; + +// This is a convenience type for checking whether a typed kernel matches +// against a type list. +template +struct KernelParamsOk { + static constexpr bool kResult = false; +}; + +// See above. +template +struct KernelParamsOk, Args...> { + static constexpr bool kResult = + KernelInvocationChecker, + std::tuple>::CheckAllNoStaticAssert(); +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel_cache_config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel_cache_config.h new file mode 100644 index 0000000000000000000000000000000000000000..f72b3fcbf53fe3247f7caa2ab9c893ac49c8a38a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel_cache_config.h @@ -0,0 +1,42 @@ +/* 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. +==============================================================================*/ + +// This file contains declarations relating to kernel cache configuration +// parameters recognized by the StreamExecutor. +#ifndef XLA_STREAM_EXECUTOR_KERNEL_CACHE_CONFIG_H_ +#define XLA_STREAM_EXECUTOR_KERNEL_CACHE_CONFIG_H_ + +namespace stream_executor { + +// This enum represents potential configurations of L1/shared memory when +// running a particular kernel. These values represent user preference, and +// the runtime is not required to respect these choices. +enum class KernelCacheConfig { + // Indicates no preference for device L1/shared memory configuration. + kNoPreference, + + // Indicates a preference for more shared memory than L1 cache. + kPreferShared, + + // Indicates a preference for more L1 cache than shared memory. + kPreferL1, + + // Indicates a preference for equal amounts of L1 cache and shared memory. + kPreferEqual, +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_KERNEL_CACHE_CONFIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..68f45a0ee07f4df19349e12ca2e3932f81cf8ddc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/kernel_spec.h @@ -0,0 +1,316 @@ +/* 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. +==============================================================================*/ + +// Kernel-loader specs are structures that describe how to load a data-parallel +// kernel on a given platform for subsequent launching. Headers that instantiate +// these data structures will typically be auto-generated. However, users can +// also instantiate them by hand. +// +// A kernel with the same exact functionality and type signature may be +// implemented on several different platforms. Typical usage is to create a +// singleton that describes how to load a kernel on the various supported +// platforms: +// +// static const MultiKernelLoaderSpec &SaxpySpec() { +// static auto *mkls = +// (new MultiKernelLoaderSpec{4 /* = arity */}) +// ->AddCudaPtxOnDisk(ptx_file_path, ptx_kernel_name); +// }; +// +// return *mkls; +// } +// +// This lazily instantiates an object that describes how to load CUDA PTX +// present on disk that implements saxpy for the CUDA platform. The +// CudaPtxOnDisk object is a subtype of KernelLoaderSpec -- KernelLoaderSpec +// describes how to load a kernel for subsequent launching on a single platform. +// +// For the loader functionality that accepts these KernelLoaderSpecs in order +// to grab the kernel appropriately, see StreamExecutor::GetKernel(). + +#ifndef XLA_STREAM_EXECUTOR_KERNEL_SPEC_H_ +#define XLA_STREAM_EXECUTOR_KERNEL_SPEC_H_ + +#include + +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { + +// Describes how to load a kernel on a target platform. +// +// This is an abstract base class, subclassed for specific platforms. +// The filename_or_text field represents the program location (i.e. PTX or +// OpenCL loadable translation unit path) and is simply stored; whether it is a +// filename or text is exposed via more specifically named accessors in +// subclasses. +// +// These kernel loader specifications are typically auto-generated into header +// files at build time, but can also be specified manually. +class KernelLoaderSpec { + public: + virtual ~KernelLoaderSpec() {} + + // Returns the kernel name to load out of the program. + const std::string &kernel_name() const { return kernel_name_; } + + protected: + explicit KernelLoaderSpec(absl::string_view kernel_name); + + private: + // The kernel name that should be loaded out of the program description given + // above. + std::string kernel_name_; + + KernelLoaderSpec(const KernelLoaderSpec &) = delete; + void operator=(const KernelLoaderSpec &) = delete; +}; + +// An abstract kernel loader spec that has an associated file path, where +// there's a canonical suffix for the filename; e.g. see CudaPtxOnDisk whose +// canonical filename suffix is ".ptx". +class OnDiskKernelLoaderSpec : public KernelLoaderSpec { + public: + ~OnDiskKernelLoaderSpec() override {} + + // Returns the path to the on-disk loadable kernel file. + const std::string &filename() const { return filename_; } + + // Returns the canonical suffix for this on-disk kernel loader spec format; + // e.g. PTX files on disk have a canonical suffix of ".ptx". + virtual const char *CanonicalSuffix() const = 0; + + protected: + OnDiskKernelLoaderSpec(absl::string_view filename, + absl::string_view kernel_name); + + std::string filename_; + + private: + OnDiskKernelLoaderSpec(const OnDiskKernelLoaderSpec &) = delete; + void operator=(const OnDiskKernelLoaderSpec &) = delete; +}; + +// Kernel loader specification for PTX text that resides on disk. +class CudaPtxOnDisk : public OnDiskKernelLoaderSpec { + public: + CudaPtxOnDisk(absl::string_view filename, absl::string_view kernel_name); + ~CudaPtxOnDisk() override {} + + const char *CanonicalSuffix() const override { return ".ptx"; } + + private: + CudaPtxOnDisk(const CudaPtxOnDisk &) = delete; + void operator=(const CudaPtxOnDisk &) = delete; +}; + +// Kernel loader specification for CUBIN binary that resides on disk. +class CudaCubinOnDisk : public OnDiskKernelLoaderSpec { + public: + CudaCubinOnDisk(absl::string_view filename, absl::string_view kernel_name); + ~CudaCubinOnDisk() override {} + + const std::string &filename() const { return filename_; } + + const char *CanonicalSuffix() const override { return ".cubin"; } + + private: + std::string filename_; + + CudaCubinOnDisk(const CudaCubinOnDisk &) = delete; + void operator=(const CudaCubinOnDisk &) = delete; +}; + +// Kernel loader specification for PTX text that resides in memory. +class CudaPtxInMemory : public KernelLoaderSpec { + public: + // Components: compute capability major number, compute capability minor + // number, and PTX source. + typedef std::tuple PtxSpec; + + // Single-PTX constructor. Adds the provided PTX version with an unknown + // compute capability. Since the CC is unknown, the PTX is assumed to be very + // generally usable - in other words, PTX specified in this manner is VERY + // likely to be used as the default! Note that the PTX can be compressed, + // which is indicated by the argument ptx_compressed. + // + // Warning: the string backing the provided absl::string_view ptx must outlive + // this instance. + CudaPtxInMemory(absl::string_view ptx, absl::string_view kernel_name, + bool ptx_compressed = false); + + // Multiple-PTX-version constructor. Adds each item in spec_list to this + // object. Note that the PTX can be compressed, which is indicated by the + // argument ptx_compressed. + CudaPtxInMemory(const std::initializer_list &spec_list, + absl::string_view kernel_name, bool ptx_compressed = false); + ~CudaPtxInMemory() override {} + + // Add the PTX implementation described by ptx_spec to this object. On + // collision (i.e., if a version with the same compute_capability already + // exists), the existing implementation will be overwritten. + void AddSpec(PtxSpec ptx_spec); + + // Returns pointer to the ptx of available implementation with the + // lowest-valued compute capability. For example, if PTX written to CC2.0, + // 3.0, and 3.5 are all available, the version for CC2.0 will be set. Returns + // nullptr on failed lookup (if any version is not available). + // When the ptx is compressed, returns the decompressed ptx. + const char *default_text() const; + + // Similar to default_text(). + // When the ptx is compressed, returns the decompressed ptx. + const char *original_default_text() const; + + // Returns pointer to the ptx for the requested compute capability. + // Returns nullptr on failed lookup (if the requested version is not + // available). + // When the ptx is compressed, returns the decompressed ptx. + const char *text(int compute_capability_major, + int compute_capability_minor) const; + + // Similar to text(). + // When the ptx is compressed, returns the original compressed ptx. + const char *original_text(int compute_capability_major, + int compute_capability_minor) const; + + // Decompresses the PTX string using bzip2. + static std::string DecompressPtx(const char *ptx); + + private: + // PTX translation unit text contents in memory. The key is of as a tuple + // ",", i.e., "2,0", "3,0", "3,5". Because CC's + // represented in this way have a clear sorting order, map::begin() will give + // the lowest-numbered version available, i.e. the default. + std::map, const char *, + bool (*)(const std::tuple &, const std::tuple &)> + ptx_by_compute_capability_; + + // Stores all decompressed ptx strings, with original ptx string as keys. + // It is marked as mutable for lazy decompression. + mutable std::map decompressed_ptx_; + mutable absl::Mutex mu_; + + // Defines the minimum compute capability possible. Used when PTX has no + // compute capability specified (in the single-PTX constructor). + static const std::tuple kMinimumCapability; + + CudaPtxInMemory(const CudaPtxInMemory &) = delete; + void operator=(const CudaPtxInMemory &) = delete; +}; + +// Kernel loader specification for a CUBIN blob that resides in memory. +class CudaCubinInMemory : public KernelLoaderSpec { + public: + CudaCubinInMemory(const char *bytes, absl::string_view kernel_name); + ~CudaCubinInMemory() override {} + + const char *bytes() const { return bytes_; } + + private: + const char *bytes_; + + CudaCubinInMemory(const CudaCubinInMemory &) = delete; + void operator=(const CudaCubinInMemory &) = delete; +}; + +// Describes how to load a kernel on any subset of a number of target platforms. +class MultiKernelLoaderSpec { + public: + explicit MultiKernelLoaderSpec(size_t arity); + + // Returns the number of arguments that this kernel accepts. + size_t arity() const { return arity_; } + + // Convenience getters for testing whether these platform variants have + // kernel loader specifications available. + bool has_cuda_ptx_on_disk() const { return cuda_ptx_on_disk_ != nullptr; } + bool has_cuda_cubin_on_disk() const { return cuda_cubin_on_disk_ != nullptr; } + bool has_cuda_cubin_in_memory() const { + return cuda_cubin_in_memory_ != nullptr; + } + bool has_cuda_ptx_in_memory() const { return cuda_ptx_in_memory_ != nullptr; } + + // Accessors for platform variant kernel load specifications. + // Precondition: corresponding has_* is true. + const CudaPtxOnDisk &cuda_ptx_on_disk() const { + CHECK(has_cuda_ptx_on_disk()); + return *cuda_ptx_on_disk_; + } + const CudaCubinOnDisk &cuda_cubin_on_disk() const { + CHECK(has_cuda_cubin_on_disk()); + return *cuda_cubin_on_disk_; + } + const CudaCubinInMemory &cuda_cubin_in_memory() const { + CHECK(has_cuda_cubin_in_memory()); + return *cuda_cubin_in_memory_; + } + const CudaPtxInMemory &cuda_ptx_in_memory() const { + CHECK(has_cuda_ptx_in_memory()); + return *cuda_ptx_in_memory_; + } + // Builder-pattern-like methods for use in initializing a + // MultiKernelLoaderSpec. Each of these should be used at most once for a + // single MultiKernelLoaderSpec object. See file comment for example usage. + // + // Note that the kernel_name parameter must be consistent with the kernel in + // the PTX being loaded. Also be aware that in CUDA C++ the kernel name may be + // mangled by the compiler if it is not declared in an extern "C" scope. + MultiKernelLoaderSpec *AddCudaPtxOnDisk(absl::string_view filename, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCubinOnDisk(absl::string_view filename, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCubinInMemory(const char *cubin_bytes, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaPtxInMemory(absl::string_view ptx, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCompressedPtxInMemory( + absl::string_view ptx, absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaPtxInMemory( + std::initializer_list spec_list, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCompressedPtxInMemory( + std::initializer_list spec_list, + absl::string_view kernel_name); + + private: + std::unique_ptr + cuda_ptx_on_disk_; // PTX text that resides in a file. + std::unique_ptr + cuda_cubin_on_disk_; // Binary CUDA program in a file. + std::unique_ptr + cuda_cubin_in_memory_; // Binary CUDA program in memory. + std::unique_ptr + cuda_ptx_in_memory_; // PTX text that resides in memory. + + // Number of parameters that the kernel takes. (This is nicer to have in a + // constexpr than having to determine it from the types via template + // metaprogramming). + size_t arity_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_KERNEL_SPEC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/launch_dim.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/launch_dim.h new file mode 100644 index 0000000000000000000000000000000000000000..ef7d03311bb6239d76aae5523b1f3a400cd37da2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/launch_dim.h @@ -0,0 +1,75 @@ +/* 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. +==============================================================================*/ + +// Types to express dimensionality of a kernel launch. Blocks and threads +// are (up to) 3-dimensional. +// +// A thread is conceptually like a SIMD lane. Some number, typically 32 +// (though that fact should not be relied on) SIMD lanes are tied together with +// a single PC in a unit called a warp. There is a maximum number of threads +// that can execute in a shared-context entity called a block. Presently, that +// number is 1024 -- again, something that should not be relied on from this +// comment, but checked via stream_executor::DeviceDescription. +// +// For additional information, see +// http://docs.nvidia.com/cuda/kepler-tuning-guide/#device-utilization-and-occupancy +// +// Because of that modest thread-per-block limit, a kernel can be launched with +// multiple blocks. Each block is indivisibly scheduled onto a single core. +// Blocks can also be used in a multi-dimensional configuration, and the block +// count has much less modest limits -- typically they're similar to the maximum +// amount of addressable memory. + +#ifndef XLA_STREAM_EXECUTOR_LAUNCH_DIM_H_ +#define XLA_STREAM_EXECUTOR_LAUNCH_DIM_H_ + +#include +#include + +#include "absl/strings/str_cat.h" + +namespace stream_executor { + +// Thread dimensionality for use in a kernel launch. See file comment for +// details. +struct ThreadDim { + explicit ThreadDim(uint64_t x = 1, uint64_t y = 1, uint64_t z = 1) + : x(x), y(y), z(z) {} + + // Returns a string representation of the thread dimensionality. + std::string ToString() const { + return absl::StrCat("ThreadDim{", x, ", ", y, ", ", z, "}"); + } + + uint64_t x, y, z; +}; + +// Block dimensionality for use in a kernel launch. See file comment for +// details. +struct BlockDim { + explicit BlockDim(uint64_t x = 1, uint64_t y = 1, uint64_t z = 1) + : x(x), y(y), z(z) {} + + // Returns a string representation of the block dimensionality. + std::string ToString() const { + return absl::StrCat("BlockDim{", x, ", ", y, ", ", z, "}"); + } + + uint64_t x, y, z; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_LAUNCH_DIM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/lazy_op_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/lazy_op_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..2c390d75f921486c7463d20496943a34ce967bae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/lazy_op_runner.h @@ -0,0 +1,301 @@ +/* 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_STREAM_EXECUTOR_LAZY_OP_RUNNER_H_ +#define XLA_STREAM_EXECUTOR_LAZY_OP_RUNNER_H_ + +#include +#include +#include +#include +#include + +#include "absl/base/call_once.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/stream.h" + +namespace stream_executor { +namespace dnn { + +// A lazily-initialized OpRunner from an AlgorithmDesc. +// +// This exists to hold a choice of conv algorithm for a particular config, +// initialize its OpRunner at most once, and defer that initialization until the +// config is first needed. This allows AoT autotuning to load configurations +// for all convolutions it knows about, without doing expensive initialization +// (e.g. runtime codegen) and retaining non-negligible resources (e.g. compiled +// kernels) for potentially irrelevant configurations. It also enables XLA conv +// thunks to defer binding to a particular stream executor until the first run. +// +// `Op` must satisfy the following "concept": +// +// struct Op { +// // The function type signature parameter of an OpRunner. +// using Signature = _; +// +// // The parameter to be used by GetOrCreateRunner. +// struct Config; +// +// // Use a StreamExecutor to create an OpRunner. +// static StatusOr> OpRunnerFromDesc( +// const AlgorithmDesc& desc, Config config, StreamExecutor* stream); +// }; +template +class LazyOpRunner { + public: + // Construct from a pre-initialized OpRunner; all calls to GetOrCreateRunner + // will return a pointer to exactly this runner. + static tsl::StatusOr> FromOpRunner( + std::unique_ptr> runner) { + if (!runner) { + return tsl::errors::Internal("Null runner argument to FromOpRunner"); + } + TF_ASSIGN_OR_RETURN(auto desc, runner->ToAlgorithmDesc()); + // Private constructor cannot be called by make_unique :( + return {std::unique_ptr( + new LazyOpRunner(desc, std::move(runner)))}; + } + + // Construct from an AlgorithmDesc, with no pre-initialized OpRunner; it will + // be created on the first call to GetOrCreateRunner. + explicit LazyOpRunner(AlgorithmDesc desc) : LazyOpRunner(desc, nullptr) {} + + // Returns an already-initialized OpRunner if available, or creates one. + // + // Invariant: a particular instance of this class shall only receive calls + // with identical `config`s and `stream_executor`s. If the config is changed, + // only the first config it sees will have any effect, and second and + // subsequent configs will be ignored. If the stream executor is changed, + // some operations on the returned `OpRunner` using the changed stream + // executor will be errors. + // + // The result is owned by LazyOpRunner. + tsl::StatusOr*> GetOrCreateRunner( + typename Op::Config config, Stream* stream) { + absl::call_once(once_flag_, [&] { + if (runner_) return; // runner was passed via constructor argument + + auto r = Op::RunnerFromAlgorithmDesc(desc_, std::move(config), stream); + if (!r.ok()) { + error_ = std::move(r).status(); + } else { + runner_ = std::move(r).value(); + } + }); + + if (!error_.ok()) return error_; + return runner_.get(); + } + + // Get the contained runner with the invariant that it's already initialized. + tsl::StatusOr*> GetRunner() { + if (auto* runner = runner_ptr_.load(std::memory_order_acquire)) { + return runner; + } + return tsl::errors::Internal("LazyOpRunner::GetRunner: not initialized"); + } + + bool operator==(const LazyOpRunner& other) const { + return desc_ == other.desc_; + } + + std::string ToString() const { return desc_.ToString(); } + + const AlgorithmDesc& ToAlgorithmDesc() const { return desc_; } + + private: + LazyOpRunner(AlgorithmDesc desc, + std::unique_ptr> runner) + : desc_(std::move(desc)), + error_(tsl::OkStatus()), + runner_(std::move(runner)), + runner_ptr_(runner_.get()) {} + + AlgorithmDesc desc_; + + // We use absl::call_once to lazily initialize `runner_` (or `error_`). + absl::once_flag once_flag_; + tsl::Status error_; // holds error if runner can't be initialized + std::unique_ptr> runner_; + + // Once we initialize `runner_` we publish a pointer through atomic so that + // `GetRunner` can read it without data races with initialization. + std::atomic*> runner_ptr_; +}; + +// Implementation of the concept required by LazyOpRunner, for ConvRunner. +struct ConvOp { + using Signature = ConvSignature; + + struct Config { + ConvolutionKind kind; + DataType input_type, output_type; + const BatchDescriptor& input_descriptor; + const FilterDescriptor& filter_descriptor; + const BatchDescriptor& output_descriptor; + const ConvolutionDescriptor& convolution_descriptor; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->ConvolveRunnerFromDesc( + desc, config.kind, config.input_type, config.output_type, + config.input_descriptor, config.filter_descriptor, + config.output_descriptor, config.convolution_descriptor); + } +}; + +// Implementation of the concept required by LazyOpRunner, for +// GraphConvolveRunner. +struct GraphConvOp { + using Signature = GraphConvSignature; + + struct Config { + ConvolutionKind kind; + DataType input_type, output_type; + const BatchDescriptor& input_descriptor; + const FilterDescriptor& filter_descriptor; + const BatchDescriptor& output_descriptor; + const ConvolutionDescriptor& convolution_descriptor; + std::string serialized_graph; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->GraphConvolveRunnerFromDesc( + desc, config.kind, config.input_type, config.output_type, + config.input_descriptor, config.filter_descriptor, + config.output_descriptor, config.convolution_descriptor, + config.serialized_graph); + } +}; + +// Implementation of the concept required by LazyOpRunner, for LazyConvRunner. +struct FusedConvOp { + using Signature = FusedConvSignature; + + struct Config { + ConvolutionKind kind; + DataType input_type, bias_type, output_type; + double conv_scale, side_input_scale, leakyrelu_alpha; + const BatchDescriptor& input_descriptor; + const FilterDescriptor& filter_descriptor; + const BatchDescriptor& bias_descriptor; + const BatchDescriptor& output_descriptor; + const ConvolutionDescriptor& convolution_descriptor; + ActivationMode activation_mode; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->FusedConvolveRunnerFromDesc( + desc, config.kind, config.input_type, config.bias_type, + config.output_type, config.conv_scale, config.side_input_scale, + config.leakyrelu_alpha, config.input_descriptor, + config.filter_descriptor, config.bias_descriptor, + config.output_descriptor, config.convolution_descriptor, + config.activation_mode); + } +}; + +// Implementation of the concept required by LazyOpRunner, for FusedMatmul. +struct FusedMatmulOp { + using Signature = FusedMatmulSignature; + + // Config is mainly used in RunnerFromAlgorithmDesc() to lazily create the + // runner. At this moment we only get existing runners and don't implement + // this feature. + struct Config {}; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return tsl::errors::Unimplemented("Unimplemented"); + } +}; + +struct FusedMHAOp { + using Signature = FusedMHASignature; + struct Config { + FusedMHAKind kind; + double scale; + const MatmulTensorDescriptor& bmm1_lhs_descriptor; + const MatmulTensorDescriptor& bmm1_rhs_descriptor; + const MatmulTensorDescriptor& bmm2_rhs_descriptor; + const MatmulTensorDescriptor& intermediate_bmm2_lhs_descriptor; + const TensorDescriptor& output_descriptor; + std::optional bias_descriptor; + std::optional mask_descriptor; + std::optional activation_descriptor; + std::optional dropout_rate; + std::optional seed; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->FusedMHARunnerFromDesc( + desc, config.kind, config.bmm1_lhs_descriptor, + config.bmm1_rhs_descriptor, config.bmm2_rhs_descriptor, + config.intermediate_bmm2_lhs_descriptor, config.output_descriptor, + config.activation_descriptor, config.mask_descriptor, + config.bias_descriptor, config.scale, config.dropout_rate, config.seed); + } +}; + +struct FusedMHABackwardOp { + using Signature = FusedMHABackwardSignature; + + struct Config { + FusedMHAKind kind; + double scale; + const MatmulTensorDescriptor& bmm1_grad_gemm1_rhs_descriptor; + const MatmulTensorDescriptor& bmm1_grad_gemm2_rhs_descriptor; + const MatmulTensorDescriptor& bmm2_grad_gemm1_lhs_descriptor; + const MatmulTensorDescriptor& bmm2_grad_gemm2_rhs_descriptor; + const MatmulTensorDescriptor& d_output_descriptor; + const TensorDescriptor& d_bmm1_lhs_descriptor; + const TensorDescriptor& d_bmm1_rhs_descriptor; + const TensorDescriptor& d_bmm2_rhs_descriptor; + const TensorDescriptor& d_s_descriptor; + std::optional mask_descriptor; + std::optional d_bias_descriptor; + std::optional dropout_rate; + std::optional seed; + }; + + static tsl::StatusOr< + std::unique_ptr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->FusedMHABackwardRunnerFromDesc( + desc, config.kind, config.bmm1_grad_gemm1_rhs_descriptor, + config.bmm1_grad_gemm2_rhs_descriptor, + config.bmm2_grad_gemm1_lhs_descriptor, + config.bmm2_grad_gemm2_rhs_descriptor, config.d_output_descriptor, + config.d_bmm1_lhs_descriptor, config.d_bmm1_rhs_descriptor, + config.d_bmm2_rhs_descriptor, config.d_s_descriptor, + config.mask_descriptor, config.d_bias_descriptor, config.scale, + config.dropout_rate, config.seed); + } +}; + +} // namespace dnn +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_LAZY_OP_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/module_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/module_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..cfee31e514c14d4a72d6f6d01ec3f1d1798e4b70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/module_spec.h @@ -0,0 +1,92 @@ +/* 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_STREAM_EXECUTOR_MODULE_SPEC_H_ +#define XLA_STREAM_EXECUTOR_MODULE_SPEC_H_ + +#include + +#include "absl/types/span.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { + +//===----------------------------------------------------------------------===// +// ModuleHandle +//===----------------------------------------------------------------------===// + +// An opaque handle to a loaded module. +// +// An instance of this is returned from StreamExecutor::GetModule. +class ModuleHandle { + public: + explicit ModuleHandle(void* id = nullptr) : id_(id) {} + + // A ModuleHandle with id() == nullptr is an invalid module handle, akin to a + // null pointer. + void* id() const { return id_; } + + explicit operator bool() const { return id() != nullptr; } + + private: + void* id_; +}; + +//===----------------------------------------------------------------------===// +// MultiModuleLoaderSpec +//===----------------------------------------------------------------------===// + +// Describes how to load a module on a target platform. +// +// The exact meaning of a "module" may differ from platform to platform but +// loosely speaking a module a collection of kernels and global variables. It +// corresponds to CUmodule when running on CUDA. +class MultiModuleLoaderSpec { + public: + bool has_cuda_cubin_in_memory() const { return has_cuda_cubin_in_memory_; } + absl::Span cuda_cubin_in_memory() const { + CHECK(has_cuda_cubin_in_memory()); + return {cuda_cubin_in_memory_.data(), cuda_cubin_in_memory_.size()}; + } + + bool has_cuda_ptx_in_memory() const { return has_cuda_ptx_in_memory_; } + const char* cuda_ptx_in_memory() const { + CHECK(has_cuda_ptx_in_memory()); + return cuda_ptx_in_memory_; + } + + void AddCudaCubinInMemory(absl::Span cubin_bytes) { + CHECK(!cubin_bytes.empty()); + has_cuda_cubin_in_memory_ = true; + cuda_cubin_in_memory_ = cubin_bytes; + } + + void AddCudaPtxInMemory(const char* ptx) { + has_cuda_ptx_in_memory_ = true; + // The CUDA driver does not like getting an empty string as PTX. + cuda_ptx_in_memory_ = *ptx ? ptx : nullptr; + } + + private: + absl::Span cuda_cubin_in_memory_; + bool has_cuda_cubin_in_memory_ = false; + const char* cuda_ptx_in_memory_; + bool has_cuda_ptx_in_memory_ = false; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_MODULE_SPEC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/multi_platform_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/multi_platform_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f428bbf9bd81b8e13e297bc130d4acb6f7a243ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/multi_platform_manager.h @@ -0,0 +1,158 @@ +/* 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. +==============================================================================*/ + +// This is a registration-oriented interface for multiple platforms. It will +// replace the MachineManager singleton interface, as MachineManager does not +// currently support simultaneous use of multiple platforms. +// +// Usage: +// +// In your BUILD rule, add a dependency on a platform plugin that you'd like +// to use, such as: +// +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:cuda_platform +// //third_party/tensorflow/compiler/xla/stream_executor/opencl:opencl_platform +// +// This will register platform plugins that can be discovered via this +// interface. Sample API usage: +// +// tsl::StatusOr platform_status = +// se::MultiPlatformManager::PlatformWithName("OpenCL"); +// if (!platform_status.ok()) { ... } +// Platform* platform = platform_status.value(); +// LOG(INFO) << platform->VisibleDeviceCount() << " devices visible"; +// if (platform->VisibleDeviceCount() <= 0) { return; } +// +// for (int i = 0; i < platform->VisibleDeviceCount(); ++i) { +// tsl::StatusOr executor_status = +// platform->ExecutorForDevice(i); +// if (!executor_status.ok()) { +// LOG(INFO) << "could not retrieve executor for device ordinal " << i +// << ": " << executor_status.status(); +// continue; +// } +// LOG(INFO) << "found usable executor: " << executor_status.value(); +// } +// +// A few things to note: +// - There is no standard formatting/practice for identifying the name of a +// platform. Ideally, a platform will list its registered name in its header +// or in other associated documentation. +// - Platform name lookup is case-insensitive. "OpenCL" or "opencl" (or even +// ("OpEnCl") would work correctly in the above example. +// +// And similarly, for standard interfaces (BLAS, etc.) you can add +// dependencies on support libraries, e.g.: +// +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:pluton_blas_plugin +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:cudnn_plugin +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:cublas_plugin + +#ifndef XLA_STREAM_EXECUTOR_MULTI_PLATFORM_MANAGER_H_ +#define XLA_STREAM_EXECUTOR_MULTI_PLATFORM_MANAGER_H_ + +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/initialize.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +// Manages multiple platforms that may be present on the current machine. +class MultiPlatformManager { + public: + // Registers a platform object, returns an error status if the platform is + // already registered. The associated listener, if not null, will be used to + // trace events for ALL executors for that platform. + // Takes ownership of platform. + static tsl::Status RegisterPlatform(std::unique_ptr platform); + + // Retrieves the platform registered with the given platform name (e.g. + // "CUDA", "OpenCL", ...) or id (an opaque, comparable value provided by the + // Platform's Id() method). + // + // If the platform has not already been initialized, it will be initialized + // with a default set of parameters. + // + // If the requested platform is not registered, an error status is returned. + // Ownership of the platform is NOT transferred to the caller -- + // the MultiPlatformManager owns the platforms in a singleton-like fashion. + static tsl::StatusOr PlatformWithName(absl::string_view target); + static tsl::StatusOr PlatformWithId(const Platform::Id& id); + + // Same functions as above, but allows platforms to be returned without + // initialization if initialize_platform == false. + static tsl::StatusOr PlatformWithName(absl::string_view target, + bool initialize_platform); + + // Retrieves the platform registered with the given platform id (an opaque, + // comparable value provided by the Platform's Id() method). + // + // The platform will be initialized with the given options. If the platform + // was already initialized, an error will be returned. + // + // If the requested platform is not registered, an error status is returned. + // Ownership of the platform is NOT transferred to the caller -- + // the MultiPlatformManager owns the platforms in a singleton-like fashion. + static tsl::StatusOr InitializePlatformWithId( + const Platform::Id& id, + const std::map& options); + + // Retrieves the platforms satisfying the given filter, i.e. returns true. + // Returned Platforms are always initialized. + static tsl::StatusOr> PlatformsWithFilter( + const std::function& filter); + + static tsl::StatusOr> PlatformsWithFilter( + const std::function& filter, + bool initialize_platform); + + // Although the MultiPlatformManager "owns" its platforms, it holds them as + // undecorated pointers to prevent races during program exit (between this + // object's data and the underlying platforms (e.g., CUDA, OpenCL). + // Because certain platforms have unpredictable deinitialization + // times/sequences, it is not possible to strucure a safe deinitialization + // sequence. Thus, we intentionally "leak" allocated platforms to defer + // cleanup to the OS. This should be acceptable, as these are one-time + // allocations per program invocation. + // The MultiPlatformManager should be considered the owner + // of any platforms registered with it, and leak checking should be disabled + // during allocation of such Platforms, to avoid spurious reporting at program + // exit. +}; + +} // namespace stream_executor + +// multi_platform_manager.cc will define these instances. +// +// Registering a platform: +// REGISTER_MODULE_INITIALIZER_SEQUENCE(my_platform, multi_platform_manager); +// REGISTER_MODULE_INITIALIZER_SEQUENCE(multi_platform_manager_listener, +// my_platform); +// +// Registering a listener: +// REGISTER_MODULE_INITIALIZER_SEQUENCE(my_listener, +// multi_platform_manager_listener); +DECLARE_MODULE_INITIALIZER(multi_platform_manager); +DECLARE_MODULE_INITIALIZER(multi_platform_manager_listener); + +#endif // XLA_STREAM_EXECUTOR_MULTI_PLATFORM_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/numeric_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/numeric_options.h new file mode 100644 index 0000000000000000000000000000000000000000..f75dfb54ff65b33c76965ce01cad9d7c18ea0e71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/numeric_options.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 XLA_STREAM_EXECUTOR_NUMERIC_OPTIONS_H_ +#define XLA_STREAM_EXECUTOR_NUMERIC_OPTIONS_H_ + +namespace stream_executor { + +// Options that specify the numeric behavior of operations like matrix +// multiplications and convolutions +struct NumericOptions { + NumericOptions(bool require_determinism, bool allow_tf32) + : require_determinism(require_determinism), allow_tf32(allow_tf32) {} + + NumericOptions() : require_determinism(false), allow_tf32(true) {} + + // If true, the op must be deterministic + bool require_determinism; + // If true, float32 inputs can be rounded to TensorFloat-32 precision + bool allow_tf32; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_NUMERIC_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..b03d046220bbbc72efadf6fc94b3750b31eff507 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform.h @@ -0,0 +1,153 @@ +/* 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. +==============================================================================*/ + +// Defines types and declares functions for identifying and extracting +// information about the types of platforms and supporting libraries for which +// StreamExecutor implementations exist. +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_H_ + +#include +#include +#include + +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class StreamExecutor; +class DeviceDescription; + +// An enum to represent different levels of stream priorities. +// This is to avoid platform-specific representations in abstractions. +enum class StreamPriority { Default = 0, Lowest, Highest }; + +// Returns a printable description of StreamPriority. +std::string StreamPriorityToString(StreamPriority priority); + +// StreamExecutorConfig encapsulates the set of options for constructing a +// StreamExecutor for a given platform. +struct StreamExecutorConfig { + // Sets members to defaults: -1 for ordinal (must be changed), and default + // PluginConfig and DeviceOptions. + StreamExecutorConfig(); + + // Simple ordinal-setting constructor. + explicit StreamExecutorConfig(int ordinal); + + // The GPU stream for which we are searching the executor. + // If this field is specified for the search, others will be ignored. + void* gpu_stream = nullptr; + + // The ordinal of the device to be managed by the returned StreamExecutor. + int ordinal; + + // The DeviceOptions for the returned StreamExecutor. + DeviceOptions device_options; +}; + +// Abstract base class for a platform registered with the MultiPlatformManager. +class Platform { + public: + virtual ~Platform(); + + // A platform ID is a unique identifier for each registered platform type - + // each platform is required to expose an ID to ensure unique registration and + // as a target against which plugins can register. + // + // The macro below is provided to help generate a [process-unique] identifier. + using Id = void*; + +// Helper macro to define a plugin ID. To be used only inside plugin +// implementation files. Works by "reserving" an address/value (guaranteed to be +// unique) inside a process space. +#define PLATFORM_DEFINE_ID(ID_VAR_NAME) \ + namespace { \ + int plugin_id_value; \ + } \ + const ::stream_executor::Platform::Id ID_VAR_NAME = &plugin_id_value; + + // Returns a key uniquely identifying this platform. + virtual Id id() const = 0; + + // Name of this platform. + virtual const std::string& Name() const = 0; + + // Returns the number of devices accessible on this platform. + // + // Note that, though these devices are visible, if there is only one userspace + // context allowed for the device at a time and another process is using this + // device, a call to ExecutorForDevice may return an error status. + virtual int VisibleDeviceCount() const = 0; + + // Returns true iff the platform has been initialized. + virtual bool Initialized() const; + + // Initializes the platform with a custom set of options. The platform must be + // initialized before obtaining StreamExecutor objects. The interpretation of + // the platform_options argument is implementation specific. This method may + // return an error if unrecognized options are provided. If using + // MultiPlatformManager, this method will be called automatically by + // InitializePlatformWithId/InitializePlatformWithName. + virtual tsl::Status Initialize( + const std::map& platform_options); + + // Returns a populated DeviceDescription for the device at the given ordinal. + // This should not require device initialization. Note that not all platforms + // may support acquiring the DeviceDescription indirectly. + // + // Alternatively callers may call GetDeviceDescription() on the StreamExecutor + // which returns a cached instance specific to the initialized StreamExecutor. + virtual tsl::StatusOr> + DescriptionForDevice(int ordinal) const = 0; + + // Returns a device with the given ordinal on this platform with a default + // plugin configuration or, if none can be found with the given ordinal or + // there is an error in opening a context to communicate with the device, an + // error status is returned. + // + // Ownership of the executor is NOT transferred to the caller -- + // the Platform owns the executors in a singleton-like fashion. + virtual tsl::StatusOr ExecutorForDevice(int ordinal) = 0; + + // Returns a device constructed with the options specified in "config". + // Ownership of the executor is NOT transferred to the caller. + virtual tsl::StatusOr GetExecutor( + const StreamExecutorConfig& config) = 0; + + // Returns a device constructed with the options specified in "config" without + // looking in or storing to the Platform's executor cache. + // Ownership IS transferred to the caller. + virtual tsl::StatusOr> GetUncachedExecutor( + const StreamExecutorConfig& config) = 0; + + protected: + // SE_DISALLOW_COPY_AND_ASSIGN declares a constructor, which suppresses the + // presence of the default constructor. This statement re-enables it, which + // simplifies subclassing. + Platform() = default; + + private: + Platform(const Platform&) = delete; + void operator=(const Platform&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/default/dso_loader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/default/dso_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..baf9de18876c676604b5c0b2136fb8b2318a9cc2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/default/dso_loader.h @@ -0,0 +1,86 @@ +/* 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. +==============================================================================*/ + +// Common DSO loading functionality: exposes callables that dlopen DSOs +// in either the runfiles directories + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_DSO_LOADER_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_DSO_LOADER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "tsl/platform/dso_loader.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace internal { + +namespace DsoLoader { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::internal::DsoLoader::GetCublasDsoHandle; +using tsl::internal::DsoLoader::GetCublasLtDsoHandle; +using tsl::internal::DsoLoader::GetCudaDriverDsoHandle; +using tsl::internal::DsoLoader::GetCudaRuntimeDsoHandle; +using tsl::internal::DsoLoader::GetCudnnDsoHandle; +using tsl::internal::DsoLoader::GetCufftDsoHandle; +using tsl::internal::DsoLoader::GetCuptiDsoHandle; +using tsl::internal::DsoLoader::GetCusolverDsoHandle; +using tsl::internal::DsoLoader::GetCusparseDsoHandle; +using tsl::internal::DsoLoader::GetHipDsoHandle; +using tsl::internal::DsoLoader::GetHipfftDsoHandle; +using tsl::internal::DsoLoader::GetHipsolverDsoHandle; +using tsl::internal::DsoLoader::GetHipsparseDsoHandle; +using tsl::internal::DsoLoader::GetMiopenDsoHandle; +using tsl::internal::DsoLoader::GetNvInferDsoHandle; +using tsl::internal::DsoLoader::GetNvInferPluginDsoHandle; +using tsl::internal::DsoLoader::GetRocblasDsoHandle; +using tsl::internal::DsoLoader::GetRocrandDsoHandle; +using tsl::internal::DsoLoader::GetRocsolverDsoHandle; +using tsl::internal::DsoLoader::GetRoctracerDsoHandle; +using tsl::internal::DsoLoader::MaybeTryDlopenGPULibraries; +using tsl::internal::DsoLoader::TryDlopenTensorRTLibraries; +// NOLINTEND(misc-unused-using-decls) +} // namespace DsoLoader + +namespace CachedDsoLoader { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::internal::CachedDsoLoader::GetCublasDsoHandle; +using tsl::internal::CachedDsoLoader::GetCublasLtDsoHandle; +using tsl::internal::CachedDsoLoader::GetCudaDriverDsoHandle; +using tsl::internal::CachedDsoLoader::GetCudaRuntimeDsoHandle; +using tsl::internal::CachedDsoLoader::GetCudnnDsoHandle; +using tsl::internal::CachedDsoLoader::GetCufftDsoHandle; +using tsl::internal::CachedDsoLoader::GetCuptiDsoHandle; +using tsl::internal::CachedDsoLoader::GetCusolverDsoHandle; +using tsl::internal::CachedDsoLoader::GetCusparseDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipblasltDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipfftDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipsolverDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipsparseDsoHandle; +using tsl::internal::CachedDsoLoader::GetMiopenDsoHandle; +using tsl::internal::CachedDsoLoader::GetRocblasDsoHandle; +using tsl::internal::CachedDsoLoader::GetRocrandDsoHandle; +using tsl::internal::CachedDsoLoader::GetRocsolverDsoHandle; +using tsl::internal::CachedDsoLoader::GetRoctracerDsoHandle; +// NOLINTEND(misc-unused-using-decls) +} // namespace CachedDsoLoader + +} // namespace internal +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_DSO_LOADER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/default/initialize.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/default/initialize.h new file mode 100644 index 0000000000000000000000000000000000000000..6928d6adbb0c23668d0fc13d5f1d41e095cff81e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/default/initialize.h @@ -0,0 +1,62 @@ +/* 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_STREAM_EXECUTOR_PLATFORM_DEFAULT_INITIALIZE_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_INITIALIZE_H_ + +#undef REGISTER_MODULE_INITIALIZER +#undef DECLARE_MODULE_INITIALIZER +#undef REGISTER_MODULE_INITIALIZER_SEQUENCE + +namespace stream_executor { +namespace port { + +class Initializer { + public: + typedef void (*InitializerFunc)(); + explicit Initializer(InitializerFunc func) { func(); } + + struct Dependency { + Dependency(const char *n, Initializer *i) : name(n), initializer(i) {} + const char *const name; + Initializer *const initializer; + }; + + struct DependencyRegisterer { + DependencyRegisterer(const char *type, const char *name, + Initializer *initializer, + const Dependency &dependency); + }; +}; + +} // namespace port +} // namespace stream_executor + +#define REGISTER_INITIALIZER(type, name, body) \ + static void google_init_##type##_##name() { body; } \ + ::stream_executor::port::Initializer google_initializer_##type##_##name( \ + google_init_##type##_##name) + +#define REGISTER_MODULE_INITIALIZER(name, body) \ + REGISTER_INITIALIZER(module, name, body) + +#define DECLARE_INITIALIZER(type, name) \ + extern ::stream_executor::port::Initializer google_initializer_##type##_##name + +#define DECLARE_MODULE_INITIALIZER(name) DECLARE_INITIALIZER(module, name) + +#define REGISTER_MODULE_INITIALIZER_SEQUENCE(name1, name2) + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_INITIALIZE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/dso_loader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/dso_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..41538c0ef067ace7585cb10cc0abd92a781486ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/dso_loader.h @@ -0,0 +1,31 @@ +/* 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_STREAM_EXECUTOR_PLATFORM_DSO_LOADER_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_DSO_LOADER_H_ + +#include "xla/stream_executor/platform/platform.h" + +// Include appropriate platform-dependent implementations +#if defined(PLATFORM_GOOGLE) || defined(PLATFORM_CHROMIUMOS) +#include "xla/stream_executor/platform/google/dso_loader.h" +#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) || \ + defined(PLATFORM_GOOGLE_ANDROID) || defined(PLATFORM_WINDOWS) +#include "xla/stream_executor/platform/default/dso_loader.h" +#else +#error Define the appropriate PLATFORM_ macro for this platform +#endif + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_DSO_LOADER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/initialize.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/initialize.h new file mode 100644 index 0000000000000000000000000000000000000000..d56bda8383ae2b3a2b0aa8aeccb871d1f9adcece --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/initialize.h @@ -0,0 +1,27 @@ +/* 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_STREAM_EXECUTOR_PLATFORM_INITIALIZE_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_INITIALIZE_H_ + +#include "xla/stream_executor/platform/platform.h" + +#if defined(PLATFORM_GOOGLE) || defined(PLATFORM_CHROMIUMOS) +#include "xla/stream_executor/platform/google/initialize.h" // IWYU pragma: export +#else +#include "xla/stream_executor/platform/default/initialize.h" // IWYU pragma: export +#endif + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_INITIALIZE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..3ea6fa66d362fc2396710fcf53ff8453702f8250 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/platform.h @@ -0,0 +1,43 @@ +/* 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_STREAM_EXECUTOR_PLATFORM_PLATFORM_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_PLATFORM_H_ + +#if !defined(PLATFORM_POSIX) && !defined(PLATFORM_GOOGLE) && \ + !defined(PLATFORM_POSIX_ANDROID) && !defined(PLATFORM_GOOGLE_ANDROID) && \ + !defined(PLATFORM_WINDOWS) && !defined(PLATFORM_CHROMIUMOS) + +// Choose which platform we are on. +#if defined(ANDROID) || defined(__ANDROID__) +#define PLATFORM_POSIX_ANDROID + +#elif defined(__APPLE__) +#define PLATFORM_POSIX + +#elif defined(_WIN32) +#define PLATFORM_WINDOWS + +#elif defined(__TF_CHROMIUMOS__) +#define PLATFORM_CHROMIUMOS + +#else +// If no platform specified, use: +#define PLATFORM_POSIX + +#endif +#endif + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/port.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/port.h new file mode 100644 index 0000000000000000000000000000000000000000..dfb9c1997baf3a7dfcdcea4fb88444fb10f4104a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/platform/port.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. +==============================================================================*/ + +// IWYU pragma: private, include "third_party/tensorflow/compiler/xla/stream_executor/stream_executor.h" + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_PORT_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_PORT_H_ + +#include "tsl/platform/macros.h" +#include "tsl/platform/types.h" + +namespace stream_executor { + +using tsl::int16; +using tsl::int32; +using tsl::int8; + +using tsl::uint16; +using tsl::uint32; +using tsl::uint64; +using tsl::uint8; + +#if !defined(PLATFORM_GOOGLE) +using std::string; +#endif + +#define SE_FALLTHROUGH_INTENDED TF_FALLTHROUGH_INTENDED + +} // namespace stream_executor + +// DEPRECATED: directly use the macro implementation instead. +#define SE_DISALLOW_COPY_AND_ASSIGN TF_DISALLOW_COPY_AND_ASSIGN + +#define SE_MUST_USE_RESULT TF_MUST_USE_RESULT +#define SE_PREDICT_TRUE TF_PREDICT_TRUE +#define SE_PREDICT_FALSE TF_PREDICT_FALSE + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_PORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/plugin.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..cb90171ac82bd1210ad6f1a73b36e79ad444e6eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/plugin.h @@ -0,0 +1,31 @@ +/* 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 XLA_STREAM_EXECUTOR_PLUGIN_H_ +#define XLA_STREAM_EXECUTOR_PLUGIN_H_ + +namespace stream_executor { + +// Enumeration to list the supported types of plugins / support libraries. +enum class PluginKind { + kInvalid, + kBlas, + kDnn, + kFft, +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLUGIN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/plugin_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/plugin_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..26ddf0bd60f080902ab262cac6b51782c62539cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/plugin_registry.h @@ -0,0 +1,122 @@ +/* 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 XLA_STREAM_EXECUTOR_PLUGIN_REGISTRY_H_ +#define XLA_STREAM_EXECUTOR_PLUGIN_REGISTRY_H_ + +#include + +#include "absl/base/macros.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/plugin.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +namespace internal { +class StreamExecutorInterface; +} + +// The PluginRegistry is a singleton that maintains the set of registered +// "support library" plugins. Currently, there are four kinds of plugins: +// BLAS, DNN, and FFT. Each interface is defined in the corresponding +// gpu_{kind}.h header. +// +// At runtime, a StreamExecutor object will query the singleton registry to +// retrieve the plugin kind that StreamExecutor was configured with (refer to +// the StreamExecutor declarations). +// +// Plugin libraries are best registered using REGISTER_MODULE_INITIALIZER, +// but can be registered at any time. When registering a DSO-backed plugin, it +// is usually a good idea to load the DSO at registration time, to prevent +// late-loading from distorting performance/benchmarks as much as possible. +class PluginRegistry { + public: + typedef blas::BlasSupport* (*BlasFactory)(internal::StreamExecutorInterface*); + typedef dnn::DnnSupport* (*DnnFactory)(internal::StreamExecutorInterface*); + typedef fft::FftSupport* (*FftFactory)(internal::StreamExecutorInterface*); + + // Gets (and creates, if necessary) the singleton PluginRegistry instance. + static PluginRegistry* Instance(); + + // Registers the specified factory with the specified platform. + // Returns a non-successful status if the factory has already been registered + // with that platform (but execution should be otherwise unaffected). + template + tsl::Status RegisterFactory(Platform::Id platform_id, const std::string& name, + FactoryT factory); + + // Return true if the factory/kind has been registered for the + // specified platform and plugin kind and false otherwise. + bool HasFactory(Platform::Id platform_id, PluginKind plugin_kind) const; + + // Retrieves the factory registered for the specified kind, + // or a tsl::Status on error. + template + tsl::StatusOr GetFactory(Platform::Id platform_id); + + private: + // Containers for the sets of registered factories, by plugin kind. + struct Factories { + std::optional blas; + std::optional dnn; + std::optional fft; + }; + + PluginRegistry(); + + // Actually performs the work of registration. + template + tsl::Status RegisterFactoryInternal(const std::string& plugin_name, + FactoryT factory, + std::optional* factories); + + // Returns true if the specified plugin has been registered with the specified + // platform factories. Unlike the other overload of this method, this does + // not implicitly examine the default factory lists. + bool HasFactory(const Factories& factories, PluginKind plugin_kind) const; + + // The singleton itself. + static PluginRegistry* instance_; + + // The set of registered factories, keyed by platform ID. + std::map factories_; + + PluginRegistry(const PluginRegistry&) = delete; + void operator=(const PluginRegistry&) = delete; +}; + +// Explicit specializations are defined in plugin_registry.cc. +#define DECLARE_PLUGIN_SPECIALIZATIONS(FACTORY_TYPE) \ + template <> \ + tsl::Status PluginRegistry::RegisterFactory( \ + Platform::Id platform_id, const std::string& name, \ + PluginRegistry::FACTORY_TYPE factory); \ + template <> \ + tsl::StatusOr PluginRegistry::GetFactory( \ + Platform::Id platform_id) + +DECLARE_PLUGIN_SPECIALIZATIONS(BlasFactory); +DECLARE_PLUGIN_SPECIALIZATIONS(DnnFactory); +DECLARE_PLUGIN_SPECIALIZATIONS(FftFactory); +#undef DECL_PLUGIN_SPECIALIZATIONS + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLUGIN_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/rocm/rocm_platform_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/rocm/rocm_platform_id.h new file mode 100644 index 0000000000000000000000000000000000000000..2ee37660ddea0b3d83c668eee270e15f64ecb559 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/rocm/rocm_platform_id.h @@ -0,0 +1,34 @@ +/* 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_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_ID_H_ +#define XLA_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_ID_H_ + +#include "xla/stream_executor/platform.h" + +namespace stream_executor { +namespace rocm { + +// Opaque and unique identifier for the ROCm platform. +// This is needed so that plugins can refer to/identify this platform without +// instantiating a ROCmPlatform object. +// This is broken out here to avoid a circular dependency between ROCmPlatform +// and ROCmExecutor. +extern const Platform::Id kROCmPlatformId; + +} // namespace rocm +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/scratch_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/scratch_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..c3a321e9e5e8a8f1a5fb10d869ca5ef13e3e6500 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/scratch_allocator.h @@ -0,0 +1,115 @@ +/* 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 XLA_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_ + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/temporary_device_memory.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; + +// Interface for "scratch" allocator for device memory, which deallocates all +// buffers it has allocated at destruction. Returned memory pointers are not +// owning. +// +// Used by stream operations (e.g. Stream::ThenConvolveWithScratch) to +// optionally request scratch space to speed up the operation. +class ScratchAllocator { + public: + virtual ~ScratchAllocator() {} + + // Returns a limit of memory this scratch allocator wants to produce, in + // bytes. This information may be used to help select an algorithm. + // + // Returns values < 0 to indicate that there is no recommended limit. + virtual int64_t GetMemoryLimitInBytes() = 0; + + // Returns an allocation on byte_size bytes for use in an operation on stream. + // + // This is a temporary allocation, and the caller is responsible for + // deallocating at some known-safe point. See the class comment above. + virtual tsl::StatusOr> AllocateBytes( + int64_t byte_size) = 0; +}; + +// Allocates a single temporary memory allocation -- this memory is deallocated +// at the next stream synchronization point after this object has gone out of +// scope. This satisfies the lifetime and deallocation properties given in the +// class comment above. +// +// Thread-compatible, but not thread-safe (use in scenarios where only one +// thread will request the scratch allocation). +class OneTimeScratchAllocator : public ScratchAllocator { + public: + explicit OneTimeScratchAllocator(Stream* stream) : stream_(stream) {} + + int64_t GetMemoryLimitInBytes() override { return -1; } + + tsl::StatusOr> AllocateBytes( + int64_t byte_size) override; + + private: + std::unique_ptr> temporary_; + Stream* stream_; + + OneTimeScratchAllocator(const OneTimeScratchAllocator&) = delete; + void operator=(const OneTimeScratchAllocator&) = delete; +}; + +// Can allocate several times -- this memory is deallocated when the scratch +// allocator is destroyed. +// +// Thread-compatible, but not thread-safe (use in scenarios where only one +// thread will request the scratch allocation). +template +class OwningScratchAllocator : public ScratchAllocator { + public: + OwningScratchAllocator(int device_ordinal, DeviceMemoryAllocator* allocator) + : device_ordinal_(device_ordinal), allocator_(allocator) {} + + int64_t GetMemoryLimitInBytes() override { return -1; } + + tsl::StatusOr> AllocateBytes( + int64_t byte_size) override { + TF_ASSIGN_OR_RETURN(OwningDeviceMemory buffer, + allocator_->Allocate(device_ordinal_, byte_size, + /*retry_on_failure=*/false)); + buffers_.push_back(std::move(buffer)); + return *buffers_.back(); + } + + private: + int device_ordinal_; + DeviceMemoryAllocator* allocator_; + absl::InlinedVector buffers_; + + OwningScratchAllocator(const OwningScratchAllocator&) = delete; + void operator=(const OwningScratchAllocator&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..41a7435c30b67d0aa16e13a3eee05b74edeebede --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream.h @@ -0,0 +1,1570 @@ +/* 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 Stream is used in conjunction with the StreamExecutor "parent" to +// perform actions with a linear stream of dependencies. Dependencies can also +// be created between Streams to do task management (i.e. limit which tasks +// can be performed concurrently and specify what task dependencies exist). + +#ifndef XLA_STREAM_EXECUTOR_STREAM_H_ +#define XLA_STREAM_EXECUTOR_STREAM_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/functional/any_invocable.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor_pimpl.h" +#include "xla/stream_executor/temporary_memory_manager.h" + +namespace stream_executor { + +namespace internal { +class StreamInterface; +} // namespace internal + +class DeviceMemoryBase; +template +class DeviceMemory; + +namespace dnn { +class BatchDescriptor; +class FilterDescriptor; +class ConvolutionDescriptor; +class ProfileResult; +class AlgorithmDesc; +} // namespace dnn + +class StreamExecutor; +class ScratchAllocator; + +namespace detail { + +// Helper to return if `T` is the same type as `First` or any or `Rest`. +template +constexpr bool is_any_of() { + return false; +} + +template +constexpr bool is_any_of() { + return std::is_same_v || is_any_of(); +} + +} // namespace detail + +// Convert a type to the corresponding QuantizedActivationMode. +template +struct Quantization; + +// Represents a stream of dependent computations on a GPU device. +// +// The operations within a stream execute linearly and asynchronously until +// BlockHostUntilDone() is invoked, which synchronously joins host code with +// the execution of the stream. +// +// If any given operation fails when entraining work for the stream, ok() will +// indicate that an error has occurred. After initialization, once a stream is +// !ok(), it will never be ok(). +// +// Thread-safe post-initialization. +class Stream { + public: + // Platform specific handle for the underlying resources behind a Stream + // implementation (e.g. it gives access to CUstream for CUDA platform). + struct PlatformSpecificHandle { + void *stream = nullptr; // will be nullptr if not supported + }; + + // Instantiate a stream tied to parent as a platform executor. Work + // entrained onto this stream will be launched/managed on that + // StreamExecutor's platform. + explicit Stream(StreamExecutor *parent); + + // Deallocates any stream resources that the parent StreamExecutor has + // bestowed + // upon this object. + ~Stream(); + + // TODO(ezhulenev): Consider removing this platform-specific accessor and + // forward all users to platform-specific headers, however it requires careful + // build rules set up to avoid leaking even more implementation details. + PlatformSpecificHandle platform_specific_handle() const; + + // Returns whether any errors have occurred while entraining work for this + // stream. + bool ok() const { return !InErrorState(); } + + // Retrieves execution status back into the stream from the underlying + // implementation without blocking the stream. + // + // Normally, Stream::BlockHostUntilDone is used to get execution status. + // However, some devices use out-of-band mechnanisms to ensure their streams + // have finished on-device work, without needing to block the streams. (These + // devices should also override AllowsSyncOnCompletion to return false.) For + // these devices, this method can be used after work is finished to retrieve + // execution status. + tsl::Status RefreshStatus() TF_LOCKS_EXCLUDED(mu_); + + // Initialize the stream. This must be performed before entraining any other + // operations. + Stream &Init() TF_LOCKS_EXCLUDED(mu_); + + // Get or create a sub-stream from this stream. If there is any sub-stream in + // the pool that can be reused then just return this sub-stream. Otherwise + // create a new sub-stream. + // + // TODO(b/112196569): The semantics of failed sub-streams is error-prone. + Stream *GetOrCreateSubStream() TF_LOCKS_EXCLUDED(mu_); + + // Return the sub-stream back to the host stream so that it can be reused + // later. Sub-streams that are !ok() will not be reused. + // + // TODO(b/112196569): The semantics of failed sub-streams is error-prone. + void ReturnSubStream(Stream *sub_stream) TF_LOCKS_EXCLUDED(mu_); + + // Allocate temporary memories. The stream will deallocate them when blocked + // or destroyed. + template + tsl::StatusOr>> + AllocateTemporaryArray(uint64_t element_count); + + // Entrains onto the stream of operations: a kernel launch with the given + // (variadic) parameters for the invocation. These arguments can be things + // like DeviceMemory or primitive types such as int. What arguments you may + // pass to a given kernel are noted as the template parameters to the + // TypedKernel type that the machocc compiler generates. + // + // Template parameters: + // Params... The type list of formal parameters that the typed kernel + // expects, which is matched against Args... + // Args... The deduced type list for passed actual arguments + // + // Implementation: A compile-time compatibility check is performed that has + // some leniency versus an exact parameter pack match -- for example, + // `const DeviceMemory` is considered "pack compatible" with a + // `const DeviceMemory&` formal parameter; in part, because we don't have + // perfect forwarding support without rvalue references. It also attempts to + // spit out helpful static_assert error traces with information as to the + // argument number and types that were mismatched. + template + tsl::Status ThenLaunch(ThreadDim thread_dims, BlockDim block_dims, + const TypedKernel &kernel, Args... args); + + // Create a dependency for this stream's next work on the other stream + // completing. Does not take ownership of other, and other must not be + // null. + // + // Checks that a stream does not wait for itself, and it is up to the + // user to guarantee that a stream does not come to wait on itself in a + // cyclic manner; in that case, behavior is undefined. + // + // N.B. Base recursion case for the variadic ThenWaitFor. + Stream &ThenWaitFor(Stream *other); + + // Waits for all streams values in others. + // Checks that there is no shallow circular wait (i.e. that "this" is not in + // others) + template + Stream &ThenWaitFor(P others) { + for (auto &stream : *others) { + CHECK_NE(stream.get(), this); + ThenWaitFor(stream.get()); + } + return *this; + } + + // Waits for an event object to be set. + // Note that ThenRecordEvent must have been called on the event before + // you call this function; otherwise the event will be considered complete + // and this wait will do nothing. + Stream &ThenWaitFor(Event *event); + + // Inserts the specified event into the end of this stream. Once the stream + // has processed all events prior to the insertion point, the event will be + // marked as completed. + // The stream does not take ownership of event - meaning that event's lifetime + // must extend past the point at which it is marked complete! + Stream &ThenRecordEvent(Event *event); + + //////////////// + // DNN support + // + // See DnnSupport::* for comments on the following methods. + + Stream &ThenBatchNormalizationForward( + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, + const DeviceMemory &estimated_mean, + const DeviceMemory &estimated_variance, + const DeviceMemory &side_input, const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory *y, + DeviceMemory *batch_mean, DeviceMemory *batch_var, + DeviceMemory *saved_mean, DeviceMemory *saved_inv_var, + bool is_training, ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationBackward( + const DeviceMemory &y_backprop, const DeviceMemory &x, + const DeviceMemory &scale, const DeviceMemory &offset, + const DeviceMemory &mean, const DeviceMemory &inv_var, + const DeviceMemory &y, const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory *x_backprop, + DeviceMemory *scale_backprop, DeviceMemory *offset_backprop, + DeviceMemory *side_input_backprop, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationForward( + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, + const DeviceMemory &estimated_mean, + const DeviceMemory &estimated_variance, + const DeviceMemory &side_input, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory *y, + DeviceMemory *batch_mean, DeviceMemory *batch_var, + DeviceMemory *saved_mean, DeviceMemory *saved_inv_var, + bool is_training, ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationBackward( + const DeviceMemory &y_backprop, + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, const DeviceMemory &mean, + const DeviceMemory &inv_var, const DeviceMemory &y, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory *x_backprop, + DeviceMemory *scale_backprop, DeviceMemory *offset_backprop, + DeviceMemory *side_input_backprop, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationForward( + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, + const DeviceMemory &estimated_mean, + const DeviceMemory &estimated_variance, + const DeviceMemory &side_input, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory *y, + DeviceMemory *batch_mean, DeviceMemory *batch_var, + DeviceMemory *saved_mean, DeviceMemory *saved_inv_var, + bool is_training, ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationBackward( + const DeviceMemory &y_backprop, + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, const DeviceMemory &mean, + const DeviceMemory &inv_var, + const DeviceMemory &y, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory *x_backprop, + DeviceMemory *scale_backprop, DeviceMemory *offset_backprop, + DeviceMemory *side_input_backprop, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator); + + Stream &ThenConvolve(const dnn::BatchDescriptor &input_descriptor, + const DeviceMemory &input_data, + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_data, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output); + + Stream &ThenConvolveQuantized( + const dnn::BatchDescriptor &input_descriptor, + const DeviceMemory &input_data, + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_coefficients, + const DeviceMemory &coefficient_scales, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output_data); + + template + tsl::Status ConvolveWithAlgorithm( + dnn::ConvolutionKind kind, const dnn::BatchDescriptor &input_descriptor, + DeviceMemory input_data, + const dnn::FilterDescriptor &filter_descriptor, + DeviceMemory filter_data, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory output_data, + const dnn::ConvolutionDescriptor &convolution_descriptor, + ScratchAllocator *scratch_allocator, + const dnn::AlgorithmConfig &algorithm_config, + dnn::ProfileResult *output_profile_result) { + DeviceMemory scratch_memory; + dnn::AlgorithmDesc algorithm_desc; + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + TF_RETURN_IF_ERROR(dnn->PrepareForConvolution( + kind, this, input_descriptor, input_data, filter_descriptor, + filter_data, output_descriptor, output_data, convolution_descriptor, + algorithm_config, scratch_allocator, &algorithm_desc, + &scratch_memory)); + return dnn->DoConvolve(kind, dnn::ToDataType::value, + dnn::ToDataType::value, this, + input_descriptor, input_data, filter_descriptor, + filter_data, output_descriptor, output_data, + convolution_descriptor, algorithm_desc, + scratch_memory, output_profile_result); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + template + tsl::Status FusedConvolveWithAlgorithm( + const dnn::BatchDescriptor &conv_input_descriptor, + const DeviceMemory &conv_input_data, ScaleT conv_input_scale, + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_data, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const DeviceMemory &side_input_data, ScaleT side_input_scale, + const dnn::BatchDescriptor &bias_descriptor, + const DeviceMemory &biases, dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output, ScratchAllocator *scratch_allocator, + const dnn::AlgorithmConfig &algorithm_config, + dnn::ProfileResult *output_profile_result) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoFusedConvolve( + this, dnn::ToDataType::value, + dnn::ToDataType::value, dnn::ToDataType::value, + dnn::ToDataType::value, conv_input_descriptor, + conv_input_data, conv_input_scale, filter_descriptor, filter_data, + convolution_descriptor, side_input_data, side_input_scale, + bias_descriptor, biases, activation_mode, output_descriptor, *output, + scratch_allocator, algorithm_config, output_profile_result); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + tsl::Status CudnnReorderConvolutionFilterAndBias( + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_input, + DeviceMemory *filter_output, + std::optional> bias_input, + std::optional> bias_output) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->CudnnReorderConvolutionFilterAndBias( + this, filter_descriptor, filter_input, filter_output, + std::move(bias_input), std::move(bias_output)); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + tsl::StatusOr> ConvolveRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType output_type, + const dnn::BatchDescriptor &input_descriptor, + const dnn::FilterDescriptor &filter_descriptor, + const dnn::BatchDescriptor &output_descriptor, + const dnn::ConvolutionDescriptor &convolution_descriptor) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return tsl::errors::Unimplemented("DNN library is not found."); + } + return dnn_support->ConvolveRunnerFromDesc( + this, algorithm_desc, kind, element_type, output_type, input_descriptor, + filter_descriptor, output_descriptor, convolution_descriptor); + } + + tsl::StatusOr> + GraphConvolveRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType output_type, + const dnn::BatchDescriptor &input_descriptor, + const dnn::FilterDescriptor &filter_descriptor, + const dnn::BatchDescriptor &output_descriptor, + const dnn::ConvolutionDescriptor &convolution_descriptor, + std::string serialized_graph) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return tsl::errors::Unimplemented("DNN library is not found."); + } + return dnn_support->GraphConvolveRunnerFromDesc( + this, algorithm_desc, kind, element_type, output_type, input_descriptor, + filter_descriptor, output_descriptor, convolution_descriptor, + serialized_graph); + } + + tsl::StatusOr> + FusedConvolveRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_input_scale, + double side_input_scale, double leakyrelu_alpha, + const dnn::BatchDescriptor &input_descriptor, + const dnn::FilterDescriptor &filter_descriptor, + const dnn::BatchDescriptor &bias_descriptor, + const dnn::BatchDescriptor &output_descriptor, + const dnn::ConvolutionDescriptor &convolution_descriptor, + dnn::ActivationMode activation_mode) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return tsl::errors::Unimplemented("DNN library is not found."); + } + return dnn_support->FusedConvolveRunnerFromDesc( + this, algorithm_desc, kind, element_type, bias_type, output_type, + conv_input_scale, side_input_scale, leakyrelu_alpha, input_descriptor, + filter_descriptor, bias_descriptor, output_descriptor, + convolution_descriptor, activation_mode); + } + + tsl::StatusOr> + FusedMHARunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor &bmm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor &intermediate_bmm2_lhs_descriptor, + const dnn::TensorDescriptor &output_descriptor, + std::optional activation_descriptor, + std::optional mask_descriptor, + std::optional bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return absl::UnimplementedError("DNN library is not found."); + } + return dnn_support->FusedMHARunnerFromDesc( + this, algorithm_desc, kind, bmm1_lhs_descriptor, bmm1_rhs_descriptor, + bmm2_rhs_descriptor, intermediate_bmm2_lhs_descriptor, + output_descriptor, activation_descriptor, mask_descriptor, + bias_descriptor, scale, dropout_rate, seed); + } + + tsl::StatusOr> + FusedMHABackwardRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor &bmm1_grad_gemm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm1_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm2_grad_gemm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm2_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor &d_output_descriptor, + const dnn::TensorDescriptor &d_bmm1_lhs_descriptor, + const dnn::TensorDescriptor &d_bmm1_rhs_descriptor, + const dnn::TensorDescriptor &d_bmm2_rhs_descriptor, + const dnn::TensorDescriptor &d_s_descriptor, + std::optional mask_descriptor, + std::optional d_bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return absl::UnimplementedError("DNN library is not found."); + } + return dnn_support->FusedMHABackwardRunnerFromDesc( + this, algorithm_desc, kind, bmm1_grad_gemm1_rhs_descriptor, + bmm1_grad_gemm2_rhs_descriptor, bmm2_grad_gemm1_lhs_descriptor, + bmm2_grad_gemm2_rhs_descriptor, d_output_descriptor, + d_bmm1_lhs_descriptor, d_bmm1_rhs_descriptor, d_bmm2_rhs_descriptor, + d_s_descriptor, mask_descriptor, d_bias_descriptor, scale, dropout_rate, + seed); + } + + Stream &ThenSeparableConvolve( + const dnn::BatchDescriptor &input_descriptor, + const DeviceMemory &input_data, + const dnn::FilterDescriptor &filter_descriptor, int depth_multiplier, + const DeviceMemory &first_weights, + const DeviceMemory &second_weights, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output); + + Stream &ThenMatMul(const DeviceMemory &input_data, + const DeviceMemory &weights, + const dnn::BatchDescriptor &input_dimensions, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenMatMulQuantized(const DeviceMemory &input_data, + const DeviceMemory &weights, + const DeviceMemory &weight_scales, + const dnn::BatchDescriptor &input_dimensions, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenMatMulQuantized(const DeviceMemory &input_data, + const DeviceMemory &weights, + const DeviceMemory &weight_scales, + const dnn::BatchDescriptor &input_dimensions, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenBiasAdd(const DeviceMemory &input_data, + const DeviceMemory &biases, + const dnn::BatchDescriptor &dimensions, + DeviceMemory *output_data); + + template + tsl::Status ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions, + const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data, + ScratchAllocator *workspace_allocator = nullptr) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoPoolForward(dnn::ToDataType::value, this, + pooling_dimensions, input_dimensions, + input_data, output_dimensions, *output_data, + workspace_allocator); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + template + tsl::Status ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions, + const NumericOptions &numeric_options, + const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data, + ScratchAllocator *workspace_allocator = nullptr) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoPoolForward(dnn::ToDataType::value, this, + pooling_dimensions, numeric_options, + input_dimensions, input_data, output_dimensions, + *output_data, workspace_allocator); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + template + tsl::Status ThenPoolBackward( + const dnn::PoolingDescriptor &pooling_dimensions, + const NumericOptions &numeric_options, + const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::BatchDescriptor &output_dimensions, + const DeviceMemory &output_data, + const DeviceMemory &input_diff_data, + DeviceMemory *output_diff_data, + ScratchAllocator *workspace_allocator = nullptr) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoPoolBackward( + dnn::ToDataType::value, this, pooling_dimensions, + numeric_options, input_dimensions, input_data, output_dimensions, + output_data, input_diff_data, *output_diff_data, workspace_allocator); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + Stream &ThenNormalizeWithDimensions( + const dnn::NormalizeDescriptor &normalize_descriptor, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, DeviceMemory *output_data); + + Stream &ThenNormalizeBackwardWithDimensions( + const dnn::NormalizeDescriptor &normalize_descriptor, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &raw_data, + const DeviceMemory &normalized_data, + const DeviceMemory &normalized_variable_gradient, + DeviceMemory *raw_variable_gradient, + ScratchAllocator *workspace_allocator = nullptr); + + Stream &ThenActivate(dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, + DeviceMemory *output_data); + + // Same as ThenActivate, but also takes an options argument that can be used + // for platform-specific option flags. + Stream &ThenActivateWithOptions(dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, + DeviceMemory *output_data, + uint64_t options); + + Stream &ThenDepthConcatenate( + absl::Span input_dimensions, + absl::Span *const> input_data, + DeviceMemory *output_data); + + // Depth to space takes an X by Y image with depth D*M² and changes it to an + // MX x MY image with depth D. Each input location (x,y) with depth D*M² in + // the input image is changed to an MxM contiguous area in the output image, + // with the values being laid out in raster order specified by + // DepthToSpaceLayout, and will have a new depth of D. + // See the DoDepthToSpace comment for more information. + Stream &ThenDepthToSpace(const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::DepthToSpaceLayout &depth_to_space_layout, + const int sqrt_depth_reduction, + DeviceMemory *output_data); + + Stream &ThenElementwiseOperate( + dnn::ElementwiseOperation operation, + absl::Span input_dimensions, + absl::Span *const> input_data, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenXYPad(const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, int64_t left_pad, + int64_t right_pad, int64_t top_pad, int64_t bottom_pad, + DeviceMemory *output_data); + + Stream &ThenXYSlice(const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, int64_t left_trim, + int64_t right_trim, int64_t top_trim, int64_t bottom_trim, + DeviceMemory *output_data); + + // Grows the input tensor by replicating the X and Y dimensions. The batch and + // depth/feature_map dimensions are unchanged. Currently, the input tensor is + // limited to X=1 and Y=1. + Stream &ThenXYBroadcast(const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, + int64_t replicate_x, int64_t replicate_y, + DeviceMemory *output_data); + + // See DnnSupport::DoMemcpyD2HQuantized. + Stream &ThenMemcpyD2HQuantized(const DeviceMemory &gpu_unquantized_src, + dnn::QuantizedActivationMode mode, + void *host_dst, uint64_t size); + + // Template version of ThenMemcpyD2HQuantized that takes a mutable span and + // uses the Quantization trait to call the generic version of + // ThenMemcpyD2HQuantized with the correct QuantizedActivationMode. + template + Stream &ThenMemcpyD2HQuantized(const DeviceMemory &gpu_unquantized_src, + absl::Span host_dst) { + return ThenMemcpyD2HQuantized( + gpu_unquantized_src, Quantization::kModeId, + host_dst.data(), host_dst.size() * sizeof(ElementType)); + } + + // See DnnSupport::DoMemcpyH2DQuantized. + Stream &ThenMemcpyH2DQuantized(const void *host_src, uint64_t size, + dnn::QuantizedActivationMode mode, + DeviceMemory *gpu_unquantized_dst); + + // Template version of ThenMemcpyH2DQuantized that takes an array slice + // and uses the Quantization trait to call the generic version of + // ThenMemcpyH2DQuantized with the correct QuantizedActivationMode. + template + Stream &ThenMemcpyH2DQuantized(absl::Span host_src, + DeviceMemory *gpu_unquantized_dst) { + return ThenMemcpyH2DQuantized( + host_src.data(), host_src.size() * sizeof(ElementType), + Quantization::kModeId, gpu_unquantized_dst); + } + + ///////////////// + // BLAS support + + // See BlasSupport::DoBlasAxpy. Note that, even for the case where alpha is + // present in DeviceMemory, it must be an execution-time constant (i.e. a + // value + // that the stream does not change or populate during the course of + // execution). The value is effectively captured at stream-enqueue time. + Stream &ThenBlasAxpy(uint64_t elem_count, float alpha, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy); + + // See BlasSupport::DoBlasCopy. + Stream &ThenBlasCopy(uint64_t elem_count, const DeviceMemory &x, + int incx, DeviceMemory *y, int incy); + + // See BlasSupport::DoBlasScal. + Stream &ThenBlasScal(uint64_t elem_count, float alpha, DeviceMemory *x, + int incx); + Stream &ThenBlasScal(uint64_t elem_count, double alpha, + DeviceMemory *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, float alpha, + DeviceMemory> *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, double alpha, + DeviceMemory> *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, std::complex alpha, + DeviceMemory> *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, std::complex alpha, + DeviceMemory> *x, int incx); + + // See BlasSupport::DoBlasGemv. + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, float alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, float beta, + DeviceMemory *y, int incy); + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, + double alpha, const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, double beta, + DeviceMemory *y, int incy); + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy); + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy); + + // See BlasSupport::DoBlasSbmv. + Stream &ThenBlasSbmv(blas::UpperLower uplo, uint64_t n, uint64 k, float alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, float beta, + DeviceMemory *y, int incy); + + template + tsl::Status ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, + const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, + DeviceMemory *c, int ldc, + const NumericOptions &numeric_options) { + InputType alpha{1.0}; + InputType beta{0.0}; + return ThenBlasGemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, + ldc, numeric_options); + } + + template + tsl::Status ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, ConstantType alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, + ConstantType beta, DeviceMemory *c, + int ldc, const NumericOptions &numeric_options) { + static_assert( + detail::is_any_of, + std::complex>(), + "Input can be int8_t, half, bf16, float, double, std::complex " + "or " + "std::complex"); + static_assert(!std::is_same_v || + detail::is_any_of(), + "If input is Eigen::half, constant has to be either " + "Eigen::half or float"); + static_assert(detail::is_any_of(), + "If input is not int8_t, Eigen::half, constant and input " + "types have to match"); + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + + return blas->DoBlasGemm(this, transa, transb, m, n, k, + blas::ToDataType::value, alpha_ptr, a, + lda, b, ldb, beta_ptr, c, ldc, numeric_options); + } + + // TODO(reedwm): Update all callers to pass correct NumericOptions. + template + tsl::Status ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, ConstantType alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, + ConstantType beta, DeviceMemory *c, + int ldc) { + return ThenBlasGemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, + ldc, NumericOptions{}); + } + + template + tsl::Status ThenBlasGemmWithAlgorithm( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, DeviceMemory *c, + int ldc, blas::ComputationType computation_type, + blas::AlgorithmType algorithm, + blas::ProfileResult *output_profile_result) { + OutputType alpha{1}; + OutputType beta{0}; + return ThenBlasGemmWithAlgorithm( + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + computation_type, algorithm, NumericOptions{}, output_profile_result); + } + + template + tsl::Status ThenBlasGemmWithAlgorithm( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, ConstantType alpha, const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, ConstantType beta, + DeviceMemory *c, int ldc, + blas::ComputationType computation_type, blas::AlgorithmType algorithm, + const NumericOptions &numeric_options, + blas::ProfileResult *output_profile_result) { + TF_RETURN_IF_ERROR( + CheckTypesForExtendedBlas( + computation_type)); + + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + + tsl::Status st = blas->DoBlasGemmWithAlgorithm( + this, transa, transb, m, n, k, alpha_ptr, a, + blas::ToDataType::value, lda, b, + blas::ToDataType::value, ldb, beta_ptr, c, + blas::ToDataType::value, ldc, computation_type, algorithm, + numeric_options, output_profile_result); + if (output_profile_result) { + // The error is recorded in the profile. + return ::tsl::OkStatus(); + } + return st; + } + + template + tsl::Status ThenBlasGemmStridedBatchedWithAlgorithm( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, ConstantType alpha, const DeviceMemory &a, int lda, + int64_t stride_a, const DeviceMemory &b, int ldb, + int64_t stride_b, ConstantType beta, DeviceMemory *c, int ldc, + int64_t stride_c, int batch_count, blas::ComputationType computation_type, + blas::AlgorithmType algorithm, const NumericOptions &numeric_options, + blas::ProfileResult *output_profile_result) { + TF_RETURN_IF_ERROR( + CheckTypesForExtendedBlas( + computation_type)); + + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + tsl::Status st = blas->DoBlasGemmStridedBatchedWithAlgorithm( + this, transa, transb, m, n, k, alpha_ptr, a, + blas::ToDataType::value, lda, stride_a, b, + blas::ToDataType::value, ldb, stride_b, beta_ptr, c, + blas::ToDataType::value, ldc, stride_c, batch_count, + computation_type, algorithm, numeric_options, output_profile_result); + if (output_profile_result) { + // The error is recorded in the profile. + return ::tsl::OkStatus(); + } + return st; + } + + template + using DeviceMemorySlice = absl::Span *const>; + + // See BlasSupport::DoBlasGemmBatched. + Stream &ThenBlasGemmBatched(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, float beta, + DeviceMemorySlice c, int ldc, + int batch_count, + const NumericOptions &numeric_options); + Stream &ThenBlasGemmBatched(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64_t k, + std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, + DeviceMemorySlice> c, int ldc, + int batch_count, + const NumericOptions &numeric_options); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, float alpha, DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, float beta, + DeviceMemorySlice c, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, float alpha, DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, float beta, + DeviceMemorySlice c, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch(blas::Transpose transa, + blas::Transpose transb, uint64_t m, + uint64 n, uint64_t k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, double alpha, DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, double beta, + DeviceMemorySlice c, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + + template + tsl::Status ThenBlasGemmStridedBatched( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, ConstantType alpha, const DeviceMemory &a, int lda, + int64_t stride_a, const DeviceMemory &b, int ldb, + int64_t stride_b, ConstantType beta, DeviceMemory *c, int ldc, + int64_t stride_c, int batch_count, + const NumericOptions &numeric_options) { + static_assert( + detail::is_any_of, + std::complex>(), + "Unsupported input type"); + static_assert(std::is_same_v || + (detail::is_any_of() && + std::is_same_v), + "Mismatched input and alpha/beta types"); + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + + return blas->DoBlasGemmStridedBatched( + this, transa, transb, m, n, k, blas::ToDataType::value, + alpha_ptr, a, lda, stride_a, b, ldb, stride_b, beta_ptr, c, ldc, + stride_c, batch_count, numeric_options); + } + + // See BlasSupport::DoBlasTrsm. + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, float alpha, const DeviceMemory &a, + int lda, DeviceMemory *b, int ldb); + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, double alpha, const DeviceMemory &a, + int lda, DeviceMemory *b, int ldb); + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb); + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb); + + // See BlasSupport::DoBlasTrsmBatched. + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, float alpha, + const DeviceMemory &as, int lda, + DeviceMemory *bs, int ldb, + int batch_count); + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, double alpha, + const DeviceMemory &as, int lda, + DeviceMemory *bs, int ldb, + int batch_count); + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, std::complex alpha, + const DeviceMemory *> &as, + int lda, DeviceMemory *> *bs, + int ldb, int batch_count); + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, std::complex alpha, + const DeviceMemory *> &as, + int lda, DeviceMemory *> *bs, + int ldb, int batch_count); + + // See FftSupport::DoFft. + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, const DeviceMemory &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, const DeviceMemory &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output); + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output); + + // Entrain onto the stream: a memcpy to a host destination from a GPU source + // of the given target size. host_dst must be a pointer to host memory + // allocated by StreamExecutor::HostMemoryAllocate or otherwise allocated and + // then registered with StreamExecutor::HostMemoryRegister. + Stream &ThenMemcpy(void *host_dst, const DeviceMemoryBase &gpu_src, + uint64_t size); + + // Entrain onto the stream: a memcpy to a GPU destination from a host source + // of the given target size. host_src must be a pointer to host memory + // allocated by StreamExecutor::HostMemoryAllocate or otherwise allocated and + // then registered with StreamExecutor::HostMemoryRegister. + Stream &ThenMemcpy(DeviceMemoryBase *gpu_dst, const void *host_src, + uint64_t size); + + // Alternative interface for memcpying from device to host that takes an + // array slice. Checks that the destination size can accommodate the host + // slice size. + template + Stream &ThenMemcpyD2H(const DeviceMemory &gpu_src, + absl::Span host_dst) { + auto host_size = host_dst.size() * sizeof(T); + CHECK(gpu_src.size() == 0 || host_size >= gpu_src.size()); + return ThenMemcpy(host_dst.begin(), gpu_src, host_size); + } + + // Alternative interface for memcpying from host to device that takes an + // array slice. Checks that the destination size can accommodate the host + // slice size. + template + Stream &ThenMemcpyH2D(absl::Span host_src, + DeviceMemory *gpu_dst) { + auto host_size = host_src.size() * sizeof(T); + CHECK(gpu_dst->size() == 0 || gpu_dst->size() >= host_size); + return ThenMemcpy(gpu_dst, host_src.begin(), host_size); + } + + // Entrain onto the stream: a memcpy to a GPU destination from a GPU source + // of the given target size. gpu_src/dst must be pointers to GPU memory and + // peer access must be enabled between their owning StreamExecutors. + Stream &ThenMemcpy(DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src, + uint64_t size); + + // Calls to the device-to-device copy overload of ThenMemcpy -- useful for + // ensuring that the host pointer isn't getting confused accidentally with a + // device pointer if you're not doing metaprogramming against the API. + Stream &ThenMemcpyD2D(DeviceMemoryBase *gpu_dst, + const DeviceMemoryBase &gpu_src, uint64_t size) { + return ThenMemcpy(gpu_dst, gpu_src, size); + } + + // Entrain onto the stream: a memset of zero at a GPU location of size bytes. + // The location must not be null. + Stream &ThenMemZero(DeviceMemoryBase *location, uint64_t size); + + // Entrain onto the stream: a memset of a 32-bit pattern at a GPU location of + // size bytes, where bytes must be evenly 32-bit sized (i.e. evenly divisible + // by 4). The location must not be null. + Stream &ThenMemset32(DeviceMemoryBase *location, uint32_t pattern, + uint64_t size); + + // Enqueue a forward operation of the RNN model onto the stream. + // See DnnSupport::DoRnnForward for more details. + Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + DeviceMemory *output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + DeviceMemory *output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + DeviceMemory *output_c_data, + bool is_training, + ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + DeviceMemory *output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + DeviceMemory *output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + DeviceMemory *output_c_data, bool is_training, + ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + DeviceMemory *output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + DeviceMemory *output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + DeviceMemory *output_c_data, bool is_training, + ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + // Enqueue a backward operation of the RNN model onto the stream. + // See DnnSupport::DoRnnBackward for more details. + Stream &ThenRnnBackward( + const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + const DeviceMemory &output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + const DeviceMemory &output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + const DeviceMemory &output_c_data, + const DeviceMemory &output_backprop_data, + const DeviceMemory &output_h_backprop_data, + const DeviceMemory &output_c_backprop_data, + DeviceMemory *input_backprop_data, + DeviceMemory *input_h_backprop_data, + DeviceMemory *input_c_backprop_data, + DeviceMemory *params_backprop_data, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnBackward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + const DeviceMemory &output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + const DeviceMemory &output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + const DeviceMemory &output_c_data, + const DeviceMemory &output_backprop_data, + const DeviceMemory &output_h_backprop_data, + const DeviceMemory &output_c_backprop_data, + DeviceMemory *input_backprop_data, + DeviceMemory *input_h_backprop_data, + DeviceMemory *input_c_backprop_data, + DeviceMemory *params_backprop_data, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnBackward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + const DeviceMemory &output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + const DeviceMemory &output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + const DeviceMemory &output_c_data, + const DeviceMemory &output_backprop_data, + const DeviceMemory &output_h_backprop_data, + const DeviceMemory &output_c_backprop_data, + DeviceMemory *input_backprop_data, + DeviceMemory *input_h_backprop_data, + DeviceMemory *input_c_backprop_data, + DeviceMemory *params_backprop_data, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + // Enqueue a CTCLoss operation onto the stream. + // See DnnSupport::DoCtcLoss for more details. + Stream &ThenCtcLoss(const dnn::RnnStateTensorDescriptor &probs_desc, + const DeviceMemory &probs_data, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions &numeric_options, + DeviceMemory *costs_data, + const dnn::RnnStateTensorDescriptor &grads_desc, + DeviceMemory *grads_data, + ScratchAllocator *workspace_allocator); + + // Enqueue onto the stream a operation that transforms a tensor. + // See DnnSupport::DoTransformTensor for more details. + Stream &ThenTransformTensor(const dnn::BatchDescriptor &input_desc, + dnn::DataType input_type, + const DeviceMemoryBase &input_data, + const dnn::BatchDescriptor &output_desc, + dnn::DataType output_type, float scale, + DeviceMemoryBase *output_data); + + // (Synchronously) block the host code waiting for the operations + // entrained on the stream (enqueued to this point in program + // execution) to complete. + // + // Returns an OK status if the blocking was successful and the stream is ok(). + // Otherwise returns an error describing why the blocking failed. + tsl::Status BlockHostUntilDone() TF_LOCKS_EXCLUDED(mu_); + + // Warning! This method interacts with internal threads in + // sometimes-unpredictable ways and is intended for GPU-Executor-internal + // use + // only. Please check with a member of the FASTR team before making use of + // this method. + // + // Entrains onto the stream a function to be executed on the host at some + // point in the future. + // Async host callbacks DO NOT block the stream as device functions (or as + // synchronous host callbacks). No synchronization is possible with + // asynchronous callbacks; they are strictly fire-and-forget. + // This method is private due to the potential for undefined behavior with + // synchronization using OpenCL user events. + // The ONLY lifetime guarantee in these calls is that the StreamExecutor + // parameter will still be valid - this Stream may not be! + // Any callbacks requiring device API calls must use this method. + Stream &ThenEnqueueOnBackgroundThread( + std::function task); + + // Returns the (opaque) platform-specific backing object. Ownership is not + // transferred to the caller. + internal::StreamInterface *implementation() { return implementation_.get(); } + + // Entrains onto the stream a callback to the host (from the device). + // Behaves as ThenDoHostCallbackWithStatus below, but the callback should + // never fail or its failure is inconsequential. + // + // This is kept for backward compatibility. Future code should use + // ThenDoHostCallbackWithStatus and explicitly return a success status. + // TODO(b/112125301): Eventually remove this method. + Stream &ThenDoHostCallback(absl::AnyInvocable callback); + + // Entrains onto the stream a callback to the host (from the device). + // Host callbacks block/occupy the stream just as device functions + // (execute one at a time, block later stream operations). + // Whether the callback return status affects the result of BlockHostUntilDone + // is platform-dependent. + // + // Behavior is undefined when synchronizing using OpenCL user events. + // Behavior is undefined if host callbacks call device routines or insert + // them into any stream. + // + // On certain platforms, ThenDoHostCallback is expected to have significant + // negative effects on performance. + Stream &ThenDoHostCallbackWithStatus( + absl::AnyInvocable callback); + + // Returns the StreamExecutor (parent object) associated with this stream. + StreamExecutor *parent() const { + CHECK(parent_ != nullptr); + return parent_; + } + + // + CudaComputeCapability GetCudaComputeCapability() const { + return parent()->GetDeviceDescription().cuda_compute_capability(); + } + + RocmComputeCapability GetRocmComputeCapability() const { + return parent()->GetDeviceDescription().rocm_compute_capability(); + } + // Returns the (internal usage) temporary-memory-allocation manager associated + // with this stream. + internal::TemporaryMemoryManager *temporary_memory_manager(); + + // Returns a debugging string "[stream=0x...,impl=0x...]". + std::string DebugStreamPointers() const; + + void SetPriority(StreamPriority priority); + void SetPriority(int priority); + + std::variant priority() const; + + private: + template + friend struct ThenBlasImpl; // for implementing ThenBlasXXX. + + // Checks whether types match before a call to extended BLAS version. + template + tsl::Status CheckTypesForExtendedBlas( + blas::ComputationType computation_type) { + static_assert( + detail::is_any_of, std::complex>(), + "The only buffer types supported are: Eigen::half, float, " + "double, int8, std::complex and std::complex"); + static_assert( + std::is_same_v || + (std::is_same_v && + detail::is_any_of()), + "Mismatched alpha/beta and output types"); + + bool valid_computation_type = [computation_type] { + switch (computation_type) { + case blas::ComputationType::kF16: + return std::is_same_v; + case blas::ComputationType::kF32: + return detail::is_any_of>(); + case blas::ComputationType::kF64: + return detail::is_any_of>(); + case blas::ComputationType::kI32: + return std::is_same_v; + case blas::ComputationType::kF16AsF32: // fall-through + case blas::ComputationType::kBF16AsF32: // fall-through + case blas::ComputationType::kTF32AsF32: + return detail::is_any_of>(); + } + }(); + + if (!valid_computation_type) { + return tsl::errors::Internal( + "Invalid computation type ", + blas::ComputationTypeString(computation_type), " for output type: ", + blas::DataTypeString(blas::ToDataType::value)); + } + return ::tsl::OkStatus(); + } + + bool InErrorState() const TF_LOCKS_EXCLUDED(mu_) { + absl::ReaderMutexLock lock(&mu_); + return !status_.ok(); + } + + // Sets the error state if operation_retcode is false. + // This is a useful shorthand for many stream routines. + void CheckError(bool operation_retcode) TF_LOCKS_EXCLUDED(mu_); + + // Checks the status and logs the error message, if any. + void CheckStatus(tsl::Status status) TF_LOCKS_EXCLUDED(mu_); + + void SetError() { CheckError(false /* = operation_retcode */); } + + void SetErrorAndLogNoDnnSupport() { + SetError(); + LOG(WARNING) << "attempting to perform DNN operation using StreamExecutor " + "without DNN support"; + } + + // Runs the set of callbacks that are intended to run after + // BlockHostUntilDone. + void RunAfterBlockHostUntilDoneCallbacks(); + + // The StreamExecutor that supports the operation of this stream. + StreamExecutor *parent_; + + // The platform-dependent implementation that the StreamExecutor interface + // delegates to. + std::unique_ptr implementation_; + + // mutex that guards the allocation / error state flags. + // Mutable so that it can be obtained via const reader lock. + mutable absl::Mutex mu_; + + // Whether Init() was successfully called to allocate this stream on the + // underlying platform. It simply flips from 0 to 1 with a sanity check. + // See StreamExecutor::AllocateStream. + bool allocated_ ABSL_GUARDED_BY(mu_); + + // The last error (if any) of all method calls. + tsl::Status status_ ABSL_GUARDED_BY(mu_); + + // Sub-streams that are generated from this stream. Each element has a pointer + // to sub-stream and a boolean value indicating if this substream is ready to + // be reused. + std::vector, bool>> sub_streams_ + ABSL_GUARDED_BY(mu_); + + // Streams can allocate temporary memories to help with work they enqueue + // (e.g. for scratch memory spaces). This member tracks those allocations and + // notes when they can be reclaimed -- reclamation is attempted when + // BlockHostUntilDone() is called. + internal::TemporaryMemoryManager temporary_memory_manager_; + + // Callbacks enqueued to be run after the next call to BlockHostUntilDone(). + std::vector> + after_block_host_until_done_callbacks_ ABSL_GUARDED_BY(mu_); + + // Non-extended BLAS interface requires alpha/beta to be floats when input + // type is Eigen::half. However, for consistency purposes it is convenient + // for the interface to accept Eigen::half. + template + void UpcastHalfToFloat(void **alpha_ptr, void **beta_ptr, + float *alpha_storage, float *beta_storage) { + if (std::is_same::value) { + *alpha_storage = + static_cast(*reinterpret_cast(*alpha_ptr)); + *beta_storage = + static_cast(*reinterpret_cast(*beta_ptr)); + *alpha_ptr = alpha_storage; + *beta_ptr = beta_storage; + } else if (std::is_same::value) { + *alpha_storage = + static_cast(*reinterpret_cast(*alpha_ptr)); + *beta_storage = + static_cast(*reinterpret_cast(*beta_ptr)); + *alpha_ptr = alpha_storage; + *beta_ptr = beta_storage; + } + } + + Stream(const Stream &) = delete; + void operator=(const Stream &) = delete; +}; + +//////////// +// Inlines + +template +inline tsl::Status Stream::ThenLaunch(ThreadDim thread_dims, + BlockDim block_dims, + const TypedKernel &kernel, + Args... args) { + KernelInvocationChecker, + std::tuple>::CheckAllStaticAssert(); + + // This is the core that allows type-safe kernel launching. + // Since the platforms take kernel arguments as tuples of (void *, size), + // we pack the variadic parameters passed as ...args into the desired + // tuple form and pass that packed form to the StreamExecutor::Launch() + // implementation. + KernelArgsArray kernel_args; + kernel.PackParams(&kernel_args, args...); + TF_RETURN_IF_ERROR( + parent_->Launch(this, thread_dims, block_dims, kernel, kernel_args)); + return ::tsl::OkStatus(); +} + +template +inline tsl::StatusOr>> +Stream::AllocateTemporaryArray(uint64_t element_count) { + return temporary_memory_manager_.AllocateArray(element_count); +} + +inline internal::TemporaryMemoryManager *Stream::temporary_memory_manager() { + return &temporary_memory_manager_; +} + +template <> +struct Quantization { + static constexpr dnn::QuantizedActivationMode kModeId = + dnn::QuantizedActivationMode::k8Bit; +}; + +template <> +struct Quantization { + static constexpr dnn::QuantizedActivationMode kModeId = + dnn::QuantizedActivationMode::k16Bit; +}; + +template <> +struct Quantization { + static constexpr dnn::QuantizedActivationMode kModeId = + dnn::QuantizedActivationMode::k32Bit; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..76b9921b24052366fbeaa9a2dbddde435f9e61b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor.h @@ -0,0 +1,37 @@ +/* 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 StreamExecutor is a single-device abstraction for: +// +// * Loading/launching data-parallel-kernels +// * Invoking pre-canned high-performance library routines (like matrix +// multiply) + +#ifndef XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_H_ +#define XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_H_ + +#include "xla/stream_executor/device_description.h" // IWYU pragma: export +#include "xla/stream_executor/device_memory.h" // IWYU pragma: export +#include "xla/stream_executor/device_options.h" // IWYU pragma: export +#include "xla/stream_executor/event.h" // IWYU pragma: export +#include "xla/stream_executor/kernel.h" // IWYU pragma: export +#include "xla/stream_executor/kernel_spec.h" // IWYU pragma: export +#include "xla/stream_executor/launch_dim.h" // IWYU pragma: export +#include "xla/stream_executor/multi_platform_manager.h" // IWYU pragma: export +#include "xla/stream_executor/platform.h" // IWYU pragma: export +#include "xla/stream_executor/stream.h" // IWYU pragma: export +#include "xla/stream_executor/stream_executor_pimpl.h" // IWYU pragma: export + +#endif // XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor_internal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..47cd7de5bc19e8dd366693f5f4aa37784824d6c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor_internal.h @@ -0,0 +1,439 @@ +/* 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. +==============================================================================*/ + +// Interfaces for platform-dependent implementations to satisfy. This are +// delegated to from the StreamExecutor in pointer-to-implementation style; i.e. +// the StreamExecutor is just a husk that delegates calls to the +// platform-specific objects which implement the interfaces defined here. + +#ifndef XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_INTERNAL_H_ +#define XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_INTERNAL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/status/status.h" +#include "xla/stream_executor/allocator_stats.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/kernel_cache_config.h" +#include "xla/stream_executor/kernel_spec.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/module_spec.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/plugin_registry.h" +#include "xla/stream_executor/trace_listener.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; + +namespace internal { + +//===----------------------------------------------------------------------===// +// EventInterface +//===----------------------------------------------------------------------===// + +// Platform-dependent interface class for the generic Events interface, in +// the PIMPL style. +class EventInterface { + public: + EventInterface() = default; + virtual ~EventInterface() = default; + + private: + EventInterface(const EventInterface&) = delete; + void operator=(const EventInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// KernelInterface +//===----------------------------------------------------------------------===// + +// Pointer-to-implementation object type (i.e. the KernelBase class delegates to +// this interface) with virtual destruction. This class exists for the +// platform-dependent code to hang any kernel data/resource info/functionality +// off of. +class KernelInterface { + public: + // Default constructor for the abstract interface. + KernelInterface() = default; + + // Default destructor for the abstract interface. + virtual ~KernelInterface() = default; + + // Returns the number of formal parameters that this kernel accepts. + virtual unsigned Arity() const = 0; + + // Sets the preferred cache configuration. + virtual void SetPreferredCacheConfig(KernelCacheConfig config) = 0; + + // Gets the preferred cache configuration. + virtual KernelCacheConfig GetPreferredCacheConfig() const = 0; + + private: + KernelInterface(const KernelInterface&) = delete; + void operator=(const KernelInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// CommandBufferInterface +//===----------------------------------------------------------------------===// + +// Platform-dependent interface class for implementing generic CommandBuffer. +// +// TODO(ezhulenev): Currently we assume that all operations between barriers +// can execute concurrently, and it's up to the caller to insert barriers to +// guarantee correctness. Consider adding finer grained synchronization +// mechanism between different commands. +// +// TODO(ezhulenev): Currently command buffers do no support updates, and once +// finalized can be executed as recorded. We need to support cheap command +// buffer updates that in GPU backend will be mapped to CUDA/HIP graph node +// updates. +class CommandBufferInterface { + public: + CommandBufferInterface() = default; + virtual ~CommandBufferInterface() = default; + + // Traces `function` invocation by recording all operations on the `stream` + // into the command buffer. Command buffer must be empty. + virtual tsl::Status Trace(Stream* stream, + absl::AnyInvocable function) = 0; + + // Adds a kernel launch command to the command buffer. + virtual tsl::Status Launch(const ThreadDim& threads, const BlockDim& blocks, + const KernelBase& kernel, + const KernelArgsArrayBase& args) = 0; + + // Adds a device-to-device memory copy to the command buffer. + virtual tsl::Status MemcpyDeviceToDevice(DeviceMemoryBase* dst, + const DeviceMemoryBase& src, + uint64_t size) = 0; + + // Finalizes command buffer and makes it executable. Once command buffer is + // finalized no commands can be added to it. + virtual tsl::Status Finalize() = 0; + + // Begins command buffer update. Command buffer update should be finalized + // before it can be executed. + virtual tsl::Status Update() = 0; + + // Returns command buffer execution mode. + virtual CommandBuffer::Mode mode() const = 0; + + // Returns command buffer state. + virtual CommandBuffer::State state() const = 0; + + private: + CommandBufferInterface(const CommandBufferInterface&) = delete; + void operator=(const CommandBufferInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// StreamInterface +//===----------------------------------------------------------------------===// + +// Pointer-to-implementation object type (i.e. the Stream class delegates to +// this interface) with virtual destruction. This class exists for the +// platform-dependent code to hang any kernel data/resource info/functionality +// off of. +class StreamInterface { + public: + // Default constructor for the abstract interface. + StreamInterface() = default; + + // Default destructor for the abstract interface. + virtual ~StreamInterface() = default; + + // Sets priority for a stream. + virtual void SetPriority(StreamPriority priority) { + LOG(ERROR) << "SetPriority unimplemented for this stream."; + } + + virtual void SetPriority(int priority) { + LOG(ERROR) << "SetPriority unimplemented for this stream."; + } + + // Gets priority for a stream. + virtual std::variant priority() const { + return StreamPriority::Default; + } + + // Returns the GPU stream associated with this platform's stream + // implementation, or nullptr otherwise. + virtual void* GpuStreamHack() { return nullptr; } + + // Returns a pointer to a GPU stream associated with this platform's stream, + // or a nullptr. + virtual void** GpuStreamMemberHack() { return nullptr; } + + private: + StreamInterface(const StreamInterface&) = delete; + void operator=(const StreamInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// StreamExecutorInterface +//===----------------------------------------------------------------------===// + +// Interface for the different StreamExecutor platforms (i.e. CUDA, OpenCL). +// +// Various platforms will provide an implementation that satisfy this interface. +class StreamExecutorInterface { + public: + // Default constructor for the abstract interface. + StreamExecutorInterface() = default; + + // Default destructor for the abstract interface. + virtual ~StreamExecutorInterface() = default; + + // Returns the (transitively) wrapped executor if this executor is + // wrapping another executor; otherwise, returns this. + virtual StreamExecutorInterface* GetUnderlyingExecutor() { return this; } + + // See the StreamExecutor interface for comments on the same-named methods. + virtual tsl::Status Init(int device_ordinal, + DeviceOptions device_options) = 0; + + // This value is cached by the wrapping StreamExecutor instance, so it's OK if + // this function is slow. + // + // The wrapping StreamExecutor will use the platform name if this is nullopt. + virtual std::optional MakeDeviceDescriptionStr() const { + return std::nullopt; + } + + virtual tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, + KernelBase* kernel) { + return absl::UnimplementedError("Not Implemented"); + } + virtual bool UnloadModule(ModuleHandle module_handle) { return false; } + virtual tsl::Status LoadModule(const MultiModuleLoaderSpec& spec, + ModuleHandle* module_handle) { + return absl::UnimplementedError("Not Implemented"); + } + virtual tsl::StatusOr> + CreateOrShareConstant(Stream* stream, const std::vector& content) { + return absl::UnimplementedError("Not Implemented"); + } + virtual tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& k, + const KernelArgsArrayBase& args) { + return absl::UnimplementedError("Not Implemented"); + } + + virtual tsl::Status Submit(Stream* stream, + const CommandBuffer& command_buffer) { + return absl::UnimplementedError("Not Implemented"); + } + + // Releases any state associated with the kernel. + virtual void UnloadKernel(const KernelBase* kernel) {} + virtual DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space) = 0; + DeviceMemoryBase Allocate(uint64_t size) { + return Allocate(size, /*memory_space=*/0); + } + virtual void* GetSubBuffer(DeviceMemoryBase* parent, uint64_t offset, + uint64_t size) = 0; + virtual void Deallocate(DeviceMemoryBase* mem) = 0; + // Allocates unified memory space of the given size, if supported. + // See + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#um-unified-memory-programming-hd + // for more details on unified memory. + virtual void* UnifiedMemoryAllocate(uint64_t size) { return nullptr; } + + // Deallocates unified memory space previously allocated with + // UnifiedMemoryAllocate. + virtual void UnifiedMemoryDeallocate(void* mem) {} + virtual void* HostMemoryAllocate(uint64_t size) = 0; + virtual void HostMemoryDeallocate(void* mem) = 0; + virtual bool HostMemoryRegister(void* mem, uint64_t size) = 0; + virtual bool HostMemoryUnregister(void* mem) = 0; + virtual bool SynchronizeAllActivity() = 0; + virtual tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemSet(DeviceMemoryBase* location, int value, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemcpy(DeviceMemoryBase* gpu_dst, + const void* host_src, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemcpy(void* host_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemcpyDeviceToDevice( + DeviceMemoryBase* gpu_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) = 0; + virtual tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) = 0; + virtual tsl::Status Memset(Stream* stream, DeviceMemoryBase* location, + uint8 pattern, uint64_t size) { + return tsl::errors::Internal("Not implemented"); + } + virtual tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size) = 0; + virtual bool Memcpy(Stream* stream, void* host_dst, + const DeviceMemoryBase& gpu_src, uint64_t size) = 0; + virtual bool Memcpy(Stream* stream, DeviceMemoryBase* gpu_dst, + const void* host_src, uint64_t size) = 0; + virtual bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) = 0; + virtual bool HostCallback(Stream* stream, + absl::AnyInvocable callback) = 0; + virtual tsl::Status AllocateEvent(Event* event) = 0; + virtual tsl::Status DeallocateEvent(Event* event) = 0; + virtual tsl::Status RecordEvent(Stream* stream, Event* event) = 0; + virtual tsl::Status WaitForEvent(Stream* stream, Event* event) = 0; + virtual tsl::Status WaitForEventOnExternalStream(std::intptr_t stream, + Event* event) { + return absl::UnimplementedError( + "WaitForEventOnExternalStream not supported on this executor."); + } + virtual Event::Status PollForEventStatus(Event* event) = 0; + virtual bool AllocateStream(Stream* stream) = 0; + virtual void DeallocateStream(Stream* stream) = 0; + virtual bool CreateStreamDependency(Stream* dependent, Stream* other) = 0; + virtual tsl::Status BlockHostUntilDone(Stream* stream) = 0; + virtual tsl::Status GetStatus(Stream* stream) { + return absl::UnimplementedError( + "GetStatus is not supported on this executor."); + } + virtual tsl::Status EnablePeerAccessTo(StreamExecutorInterface* other) = 0; + virtual bool CanEnablePeerAccessTo(StreamExecutorInterface* other) = 0; + + virtual int64_t GetDeviceLoad() { return -1; } + + virtual bool DeviceMemoryUsage(int64_t* free, int64_t* total) const { + return false; + } + + // Retrieves device pointer and size for a symbol. The device pointer is + // stored at mem, and the size is stored at size. Either mem or bytes can be + // null, however, both of them cannot be null at the same time. To use + // constant memory in CUDA, GetSymbol has to be used. Returns true if symbol + // is found. + // + // If ModuleHandle is set then we search for `symbol_name` only within the + // module corresponding to `module_handle`. Otherwise all loaded modules are + // searched. + virtual bool GetSymbol(const std::string& symbol_name, + ModuleHandle module_handle, void** mem, + size_t* bytes) { + return false; + } + + // Creates a new DeviceDescription object. Ownership is transferred to the + // caller. + virtual tsl::StatusOr> + CreateDeviceDescription() const = 0; + + // Attempts to register the provided TraceListener with the device-specific + // Executor implementation. When this is called, the PIMPL interface has + // already taken ownership of the object and is managing the generic tracing + // events. The device-specific implementation must determine if the passed + // listener is of a type appropriate for it to trace during registration (and + // before dispatching events to it). + // Returns true if the listener was successfully registered, false otherwise. + // Does not take ownership of listener. + virtual bool RegisterTraceListener(TraceListener* listener) { return false; } + + // Unregisters the specified listener from the device-specific Executor. + // Returns true if the listener was successfully registered, false otherwise. + virtual bool UnregisterTraceListener(TraceListener* listener) { + return false; + } + + // Creates a new BlasSupport object, ownership is transferred to the caller. + // + // This may return null if the BLAS initialization fails or this object does + // not support BLAS. + virtual blas::BlasSupport* CreateBlas() { return nullptr; } + + // Creates a new fft::FftSupport object, ownership is transferred to the + // caller. + // This may return null if the FFT initialization fails or this object does + // not support FFT. + virtual fft::FftSupport* CreateFft() { return nullptr; } + + // Creates a new DnnSupport object, ownership is transferred to the caller. + // This may return null if the DNN initialization fails or this object does + // not support Dnns. + virtual dnn::DnnSupport* CreateDnn() { return nullptr; } + + // Each call creates a new instance of the platform-specific implementation of + // the corresponding interface type. + virtual std::unique_ptr CreateEventImplementation() = 0; + virtual std::unique_ptr CreateKernelImplementation() = 0; + virtual std::unique_ptr GetStreamImplementation() = 0; + + virtual tsl::StatusOr> + GetCommandBufferImplementation(CommandBuffer::Mode mode) { + return absl::UnimplementedError("Command buffers are not implemented"); + } + + // Returns the CUDA or ROCm context associated with this StreamExecutor + // platform implementation. + // + // WARNING: checks that the underlying platform is, in fact, CUDA or ROCm, + // causing a fatal error if it is not. This hack is made available solely for + // use from distbelief code, which temporarily has strong ties to CUDA or ROCm + // as a platform. + virtual void* GpuContextHack() { return nullptr; } + + // Return allocator statistics. + virtual std::optional GetAllocatorStats() { + return std::nullopt; + } + + // If implemented, clears the internal stats except for the `in_use` fields + // and sets the `peak_bytes_in_use` to be equal to the `bytes_in_use`. Returns + // true if implemented. + // + // REQUIRES: GetAllocatorStats is overridden. + virtual bool ClearAllocatorStats() { return false; } + + // Clears the compilation cache from volatile memory. Returns OK if no + // compilation cache exists or if clearing the compilation cache is + // unsupported. Caches in non-volatile storage are unaffected. + virtual tsl::Status FlushCompilationCache() { return ::tsl::OkStatus(); } + + // Returns a stream allocated by this executor, or nullptr if not found. + // Performs linear search over alive GPU streams. + virtual Stream* FindAllocatedStream(void* /*gpu_stream*/) { return nullptr; } + + private: + StreamExecutorInterface(const StreamExecutorInterface&) = delete; + void operator=(const StreamExecutorInterface&) = delete; +}; + +} // namespace internal +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_INTERNAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor_pimpl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor_pimpl.h new file mode 100644 index 0000000000000000000000000000000000000000..f8903f1c946ff5b6d476fcce4b481f1394757ae2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/stream_executor_pimpl.h @@ -0,0 +1,752 @@ +/* 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 XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_PIMPL_H_ +#define XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_PIMPL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/attributes.h" +#include "absl/base/thread_annotations.h" +#include "absl/functional/any_invocable.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "xla/stream_executor/allocator_stats.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/kernel_spec.h" +#include "xla/stream_executor/module_spec.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/trace_listener.h" +#include "tsl/platform/status.h" +#include "tsl/platform/threadpool.h" +#include "tsl/protobuf/dnn.pb.h" + +// TODO(ezhulenev): Remove include of internal header. Currently we have too +// many targets depending on transitive dependencies. +#include "xla/stream_executor/stream_executor_internal.h" + +namespace stream_executor { + +class Stream; + +namespace internal { +class StreamExecutorInterface; +} // namespace internal + +// Forward declaration of private friend class. +template +class ScopedTracer; + +// A StreamExecutor manages a single device, in terms of executing work (kernel +// launches) and memory management (allocation/deallocation, memory copies to +// and from the device). It is conceptually the "handle" for a device -- Stream +// objects, which are used to enqueue work to run on the +// coprocessor have a StreamExecutor instance as their "parent" object. +// +// StreamExecutor objects have an underlying platform that is specified up +// front; +// e.g. either it is a CUDA or OpenCL executor. +// +// Thread-safe after initialization. +// StreamExecutor interface should not be invoked from a signal handler. +class StreamExecutor { + public: + StreamExecutor( + const Platform* platform, + std::unique_ptr implementation, + int device_ordinal); + + ~StreamExecutor(); + + tsl::Status Init(); + tsl::Status Init(DeviceOptions device_options); + + // Returns a reference to the platform that created this executor. + const Platform* platform() const { return platform_; } + + // Retrieves (loads) a kernel for the platform this StreamExecutor is acting + // upon, if one exists. + // + // Parameters: + // spec: The MultiKernelLoaderSpec is usually generated as a compile-time + // constant into an appropriate namespace. For example, see + // stream_executor::executor_sample::kKernelLoaderSpecs, from which a + // MultiKernelLoaderSpec is selected. + // kernel: Outparam that the kernel is loaded into. A given Kernel + // instantiation should not be loaded into more than once. + // + // If an error occurs, or there is no kernel available for the StreamExecutor + // platform, error status is returned. + tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, KernelBase* kernel); + + // Releases any state associated with the previously loaded kernel. + void UnloadKernel(const KernelBase* kernel); + + // Loads a module for the platform this StreamExecutor is acting upon. + // + // `spec` describes the module to be loaded. On success writes the handle for + // the loaded module to `module_handle` and returns OkStatus(). Otherwise, + // returns the error which has occurred. + tsl::Status LoadModule(const MultiModuleLoaderSpec& spec, + ModuleHandle* module_handle); + + // Unloads the module with handle `module_handle`. + bool UnloadModule(ModuleHandle module_handle); + + tsl::StatusOr> CreateOrShareConstant( + Stream* stream, const std::vector& content); + + // Synchronously allocates an array on the device of type T with element_count + // elements. + template + DeviceMemory AllocateArray(uint64_t element_count, + int64_t memory_space = 0); + + // As AllocateArray(), but returns a ScopedDeviceMemory. + template + ScopedDeviceMemory AllocateOwnedArray(uint64_t element_count) { + return ScopedDeviceMemory(this, AllocateArray(element_count)); + } + + // Convenience wrapper that allocates space for a single element of type T in + // device memory. + template + DeviceMemory AllocateScalar() { + return AllocateArray(1); + } + + // As AllocateScalar(), but returns a ScopedDeviceMemory. + template + ScopedDeviceMemory AllocateOwnedScalar() { + return AllocateOwnedArray(1); + } + + // Allocate a memory region inside another allocated memory region. + // Offset and size are specified in terms of T elements. + // Warning: Do not free a parent buffer before its sub-buffers; this may cause + // use-after-free issues (the specific behavior is not consistent across + // platforms). + // - Note: OpenCL uses refcounting to manage buffer lifetimes, so use of a + // sub-buffer after parent deallocation is expected to be safe. This will + // render your code non-platform-portable, however. + template + DeviceMemory GetSubBuffer(DeviceMemory* parent, uint64_t element_offset, + uint64_t element_count); + + // An untyped version of GetSymbol. + tsl::StatusOr GetUntypedSymbol( + const std::string& symbol_name, ModuleHandle module_handle); + + // Deallocate the DeviceMemory previously allocated via this interface. + // Deallocation of a nullptr-representative value is permitted. + // + // Resets the internal contents of mem to be null-representative, but this + // null-out effect should not be relied upon in client code. + void Deallocate(DeviceMemoryBase* mem); + + // Allocates unified memory space of the given size, if supported. + // See + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#um-unified-memory-programming-hd + // for more details on unified memory. + void* UnifiedMemoryAllocate(uint64_t bytes); + + // Deallocates unified memory space previously allocated with + // UnifiedMemoryAllocate. + void UnifiedMemoryDeallocate(void* location); + + // Allocates a region of host memory and registers it with the platform API. + // Memory allocated in this manner (or allocated and registered with + // HostMemoryRegister() is required for use in asynchronous memcpy operations, + // such as Stream::ThenMemcpy. + void* HostMemoryAllocate(uint64_t size); + + // Deallocates a region of host memory allocated by HostMemoryAllocate(). + void HostMemoryDeallocate(void* location); + + // Synchronizes all activity occurring in the StreamExecutor's context (most + // likely a whole device). + bool SynchronizeAllActivity() ABSL_MUST_USE_RESULT; + + // Blocks the caller while "size" bytes are zeroed out (in POD fashion) at the + // given location in device memory. + tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) ABSL_MUST_USE_RESULT; + + // Same as SynchronousMemcpy(DeviceMemoryBase*, ...) above. + tsl::Status SynchronousMemcpyH2D(const void* host_src, int64_t size, + DeviceMemoryBase* device_dst); + + // Alternative interface for memcpying from host to device that takes an + // array slice. Checks that the destination size can accommodate the host + // slice size. + template + tsl::Status SynchronousMemcpyH2D(absl::Span host_src, + DeviceMemoryBase* device_dst) { + auto host_size = host_src.size() * sizeof(T); + CHECK(device_dst->size() == 0 || device_dst->size() >= host_size); + return SynchronousMemcpyH2D(host_src.begin(), host_size, device_dst); + } + + // Same as SynchronousMemcpy(void*, ...) above. + tsl::Status SynchronousMemcpyD2H(const DeviceMemoryBase& device_src, + int64_t size, void* host_dst); + + // Blocks the caller while a data segment of the given size is copied from the + // device source to the device destination. + bool SynchronousMemcpy(DeviceMemoryBase* device_dst, + const DeviceMemoryBase& device_src, + uint64_t size) ABSL_MUST_USE_RESULT; + + // Enqueues an operation onto stream to zero out size bytes at the given + // device memory location. Neither stream nor location may be null. Returns + // whether the operation was successfully enqueued onto the stream. + tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) ABSL_MUST_USE_RESULT; + + // Enqueues an operation onto stream to set 32-bit patterns starting at + // location, for byte count given by size. size must be 32-bit quantified + // (i.e. evently divisible by 4). Returns whether the operation was + // successfully enqueued onto the stream. + tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size); + + // Enables peer access from this StreamExecutor to memory + // allocated by other, such that launched device code, memcpies, etc may + // access it directly. + // + // Both this StreamExecutor and other must be backed by the same platform (as + // in + // CUDA vs OpenCL) implementation. + tsl::Status EnablePeerAccessTo(StreamExecutor* other); + + // Returns whether it's possible to enable peer access from this + // StreamExecutor + // to memory allocated by another. + // + // Even when this returns true, EnablePeerAccessTo may fail for other reasons; + // this is more an up-front test as to whether it's expressly forbidden. + bool CanEnablePeerAccessTo(StreamExecutor* other); + + // Obtains metadata about the underlying device. + // The value is cached on first use. + const DeviceDescription& GetDeviceDescription() const; + + // If implemented, returns device specific measurement of load + // (e.g. pending requests). + int64_t GetDeviceLoad() const; + + // Returns the underlying device memory usage information, if it is available. + // If it is not available (false is returned), free/total may not be + // initialized. + // + // Note: "Free" reflects the amount of free memory on the underlying device, + // so allocations via other StreamExecutors that have the same underlying + // device + // will be reflected in "free". + bool DeviceMemoryUsage(int64_t* free, int64_t* total) const; + + // Returns the supported algorithms / execution plans for a convolution. + tsl::Status GetConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, ScratchAllocator* scratch_allocator, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + tsl::Status GetGraphConvolveRunners( + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, const NumericOptions& numeric_options, + std::vector>* out_exec_plans, + std::string serialized_graph); + + tsl::Status GetFusedConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_input_scale, + double side_input_scale, double leakyrelu_alpha, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, dnn::ActivationMode activation_mode, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + tsl::Status GetFusedMatmulRunners( + bool use_cudnn_frontend, dnn::DataType input_type, + dnn::DataType bias_type, dnn::DataType output_type, Stream* stream, + bool trans_a, bool trans_b, uint64_t m, uint64_t n, uint64_t k, + int64_t lda, int64_t ldb, int64_t ldc, + dnn::ActivationMode activation_mode, bool use_fallback, + const NumericOptions& numeric_options, + std::vector>* + out_exec_plans); + + // Returns the list of supported algorithms for the forward convolution + // operation. + bool GetMIOpenConvolveAlgorithms( + dnn::ConvolutionKind kind, dnn::DataType element_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + ScratchAllocator* scratch_allocator, + std::vector* out_algorithms); + + // Returns the list of supported algorithms for rnn operation. + bool GetRnnAlgorithms(std::vector* out_algorithms); + + // Get the list of supported algorithms for BLAS gemm. + bool GetBlasGemmAlgorithms(Stream* stream, + std::vector* out_algorithms); + + // Create an RNN descriptor based on model shapes and configurations. + // The caller retains the ownership of the descriptor. + tsl::StatusOr> createRnnDescriptor( + int num_layers, int hidden_size, int input_size, int cell_size, + int batch_size, dnn::RnnInputMode input_mode, + dnn::RnnDirectionMode direction_mode, dnn::RnnMode rnn_mode, + dnn::DataType data_type, const dnn::AlgorithmConfig& algorithm_config, + const NumericOptions& numeric_options, float dropout, uint64_t seed, + ScratchAllocator* state_allocator, bool use_padded_io); + + // Create a RNN sequence descriptor that specifies either the input or output + // sequence. The caller retains the ownership of the returned descriptor. + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, dnn::DataType data_type); + + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + const absl::Span& seq_lengths, + bool time_major, dnn::DataType data_type); + + // Create an RNN state descriptor that specifies the input or hidden state. + // The caller retains the ownership of the returned descriptor. + tsl::StatusOr> + createRnnStateTensorDescriptor(int num_layer, int batch_size, int data_size, + dnn::DataType data_type); + + // Returns the device ordinal that this StreamExecutor was initialized with. + // Meaningless before initialization. + int device_ordinal() const { return device_ordinal_; } + + // Returns a borrowed pointer to the underlying StreamExecutor implementation. + internal::StreamExecutorInterface* implementation(); + + // Creates a kernel which can be launched with stream.ThenLaunch, such that + // the types of the arguments provided for launch would have to match + // types of the arguments provided at creation time. + // + // The kernel has a name kernel_name, and is based from provided PTX in ptx, + // and (optional) compiled PTX in cubin_data. + // The canonical storage for both ptx and cubin_data should outlive the + // lifetime of the kernel. + template + tsl::StatusOr>> CreateTypedKernel( + absl::string_view kernel_name, absl::string_view ptx, + absl::Span cubin_data); + + // Warning: use Stream::ThenLaunch instead, this method is not for general + // consumption. However, this is the only way to launch a kernel for which + // the type signature is only known at runtime; say, if an application + // supports loading/launching kernels with arbitrary type signatures. + // In this case, the application is expected to know how to do parameter + // packing that obeys the contract of the underlying platform implementation. + // + // Launches a data parallel kernel with the given thread/block + // dimensionality and already-packed args/sizes to pass to the underlying + // platform driver. + // + // This is called by Stream::Launch() to delegate to the platform's launch + // implementation in StreamExecutorInterface::Launch(). + tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& kernel, + const KernelArgsArrayBase& args); + + // Submits command buffer for execution to the underlying platform driver. + tsl::Status Submit(Stream* stream, const CommandBuffer& command_buffer); + + // Gets-or-creates (creates with memoization) a FftSupport datatype that can + // be used to execute FFT routines on the current platform. + // + // Ownership and user-facing is the same as AsBlas() below. + // + // Returns null if there was an error initializing the FFT support for the + // underlying platform. + fft::FftSupport* AsFft(); + + // Gets-or-creates (creates with memoization) a DnnSupport datatype that can + // be used for neural network routines on the current platform. + // + // Ownership and user-facing is the same as AsBlas() below. + // + // Returns null if there was an error initializing the DNN support for the + // underlying platform. + dnn::DnnSupport* AsDnn(); + + // Gets-or-creates (creates with memoization) a BlasSupport datatype that can + // be used to execute BLAS routines on the current platform. This is typically + // not user-facing, as users will use the Stream::ThenBlas* family of routines + // to entrain BLAS operations. See blas.h for additional details. + // + // Ownership is not transferred to the caller -- ownership is retained by this + // object for memoization. This BLAS interface is also only expected to be + // used by a Stream for entraining calls to BLAS functionality. + // + // Returns null if there was an error initializing the BLAS support for the + // underlying platform. + blas::BlasSupport* AsBlas(); + + // Registers a trace listener to receive callbacks for only a single + // StreamExecutor instance. + // To register a listener for all executors for a given platform, see + // Platform::RegisterTraceListener(). + // Does not take ownership of listener. + void RegisterTraceListener(TraceListener* listener); + + // Removes a TraceListener from this StreamExecutor instance. + // Returns false (and logs) in cases where the argument listener was not + // previously registered. + bool UnregisterTraceListener(TraceListener* listener); + + // Return allocator statistics. + std::optional GetAllocatorStats(); + + // Clears the internal stats except for the `in_use` fields + // and sets the `peak_bytes_in_use` to be equal to the `bytes_in_use`. + bool ClearAllocatorStats(); + + // Return an allocator which delegates to this stream executor for memory + // allocation. + StreamExecutorMemoryAllocator* GetAllocator() { return &allocator_; } + + // Returns a stream allocated by this executor, or nullptr if not found. + // Performs linear search over alive GPU streams. + Stream* FindAllocatedStream(void* gpu_stream); + + private: + template + friend class ScopedTracer; + friend class Event; + friend class Stream; + template + friend class TypedKernel; + template + friend struct ThenBlasImpl; + + // Synchronously allocates size bytes on the underlying platform and returns + // a DeviceMemoryBase representing that allocation. In the case of failure, + // nullptr is returned. + DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space); + + void* GetUntypedSubBuffer(DeviceMemoryBase* parent, uint64_t offset, + uint64_t size); + + // Causes the host code to synchronously wait for operations entrained + // onto stream to complete. Effectively a join on the asynchronous device + // operations enqueued on the stream before this program point. + tsl::Status BlockHostUntilDone(Stream* stream); + + // Without blocking the device, retrieve the current stream status. + tsl::Status GetStatus(Stream* stream); + + // Finds and retrieves device memory for the symbol on the underlying + // platform. + bool GetSymbol(const std::string& symbol_name, ModuleHandle module_handle, + void** mem, size_t* bytes); + + // Entrains a memcpy operation onto stream, with a host destination location + // host_dst and a device memory source, with target size size. + bool Memcpy(Stream* stream, void* host_dst, + const DeviceMemoryBase& device_src, uint64_t size); + + // Entrains a memcpy operation onto stream, with a device destination location + // and a host memory source, with target size size. + bool Memcpy(Stream* stream, DeviceMemoryBase* device_dst, + const void* host_src, uint64_t size); + + // Entrains a memcpy operation onto stream, with a device destination location + // and a device source location, with target size size. Peer access should + // have been enabled between the StreamExecutors owning the device memory + // regions. + bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* device_dst, + const DeviceMemoryBase& device_src, uint64_t size); + + // Entrains on a stream a user-specified function to be run on the host. + // See Stream::ThenDoHostCallback for full details. + // This is the preferred form for a callback that may return an error. + bool HostCallback(Stream* stream, + absl::AnyInvocable callback); + + // Performs platform-specific allocation and initialization of an event. + tsl::Status AllocateEvent(Event* event); + + // Performs platform-specific deallocation and cleanup of an event. + tsl::Status DeallocateEvent(Event* event); + + // Inserts the specified event at the end of the specified stream. + tsl::Status RecordEvent(Stream* stream, Event* event); + + // Wait for the specified event at the end of the specified stream. + tsl::Status WaitForEvent(Stream* stream, Event* event); + + // Wait for the specified event at the end of the raw platform-specific + // stream. Currently only implemented for GPU, where stream is a + // GpuStreamHandle (e.g. cudaStream_t). + tsl::Status WaitForEventOnExternalStream(std::intptr_t stream, Event* event); + + // Requests the current status of the event from the underlying platform. + Event::Status PollForEventStatus(Event* event); + + // Allocates stream resources on the underlying platform and initializes its + // internals. + bool AllocateStream(Stream* stream); + + // Deallocates stream resources on the underlying platform. + void DeallocateStream(Stream* stream); + + // Causes dependent to not begin execution until other has finished its + // last-enqueued work. + bool CreateStreamDependency(Stream* dependent, Stream* other); + + // Allocates a new metadata object, appropriately populated, on the heap, with + // ownership transfer to caller. + std::unique_ptr CreateDeviceDescription() const; + + // Adds a task to the tsl::thread::ThreadPool work queue. These tasks must be + // fire-and-forget and have no external data or timing dependencies; their + // execution order and completion time have no guarantees. + // For an example of an appropriate task, see HostBlas::DoBlasGemmInternal; + // there, temporary internal buffers are freed using this method. + void EnqueueOnBackgroundThread(std::function task); + + // Calls the relevant TraceListener routine to begin tracing for the specified + // asynchronous method. + template + void SubmitTrace(TraceCallT trace_call, ArgsT&&... args); + + // Reader/writer lock for class-static StreamExecutor members. + static absl::Mutex static_mu_; + + // Reader/writer lock for mutable data structures on this StreamExecutor. + // + // Mutable so that caching functions (like DeviceDescription, AsBlas, etc.) + // can acquire the lock on their first (mutating) call as well. + mutable absl::Mutex mu_; + + // Reference to the platform that created this executor. + const Platform* platform_; + + // Pointer to the platform-specific-interface implementation. This is + // delegated to by the interface routines in pointer-to-implementation + // fashion. + std::unique_ptr implementation_; + + // Memoized BLAS support object -- we only want to create this once when asked + // for a BLAS interface. + std::unique_ptr blas_ ABSL_GUARDED_BY(mu_); + + // Memoized DNN support object -- we only want to create this once when asked + // for an DNN interface. + std::unique_ptr dnn_ ABSL_GUARDED_BY(mu_); + + // Memoized FFT support object -- we only want to create this once when asked + // for a FFT interface. + std::unique_ptr fft_; + + // Slot to cache the owned DeviceDescription for the underlying device + // once it has been queried from DeviceDescription(). + mutable std::unique_ptr device_description_ + ABSL_GUARDED_BY(mu_); + + // The device ordinal that this object was initialized with. + // + // Immutable post-initialization. + int device_ordinal_; + + // Executor for handling host callback work that cannot be performed + // by a host callback thread - for example, cleanup after a host BLAS routine + // (which may make device API calls). This work cannot block the host + // callback thread, will be completed asynchronously, and should be treated + // as fire-and-forget. Assume no ordering guarantees WRT the tasks enqueued + // here. + // + // Immutable post-initialization. Object is thread-safe. + std::unique_ptr background_threads_; + + // Counter for the current number of live streams. This is used to check + // for accidentally-outstanding streams at StreamExecutor teardown time, as + // well + // as to indicate leaks (via a large outstanding count being logged) in the + // case we can't allocate more streams. + std::atomic_int_fast32_t live_stream_count_; + + // Only one worker thread is needed; little work will be done by the + // executor. + static constexpr int kNumBackgroundThreads = 1; + + // Indicates if StreamExecutor operation tracing should be performed. + bool tracing_enabled_; + + // The set of TraceListeners registered for this StreamExecutor. + std::set listeners_ ABSL_GUARDED_BY(mu_); + + // Memory limit in bytes. Value less or equal to 0 indicates there is no + // limit. + int64_t memory_limit_bytes_; + + StreamExecutorMemoryAllocator allocator_; + + StreamExecutor(const StreamExecutor&) = delete; + void operator=(const StreamExecutor&) = delete; +}; + +// A wrapper around ModuleHandle that uses RAII to manage its lifetime. +class ScopedModuleHandle { + public: + explicit ScopedModuleHandle(StreamExecutor* executor, + ModuleHandle module_handle) + : executor_(executor), module_handle_(module_handle) {} + + ScopedModuleHandle(ScopedModuleHandle&& other) { + executor_ = other.executor_; + module_handle_ = other.module_handle_; + other.executor_ = nullptr; + other.module_handle_ = ModuleHandle(); + } + + ScopedModuleHandle& operator=(ScopedModuleHandle&& other) { + executor_ = other.executor_; + module_handle_ = other.module_handle_; + other.executor_ = nullptr; + other.module_handle_ = ModuleHandle(); + return *this; + } + + ~ScopedModuleHandle() { + if (static_cast(module_handle_)) { + CHECK(executor_->UnloadModule(module_handle_)); + } + } + + private: + StreamExecutor* executor_; + ModuleHandle module_handle_; + + ScopedModuleHandle(const ScopedModuleHandle&) = delete; + void operator=(const ScopedModuleHandle&) = delete; +}; + +//////////// +// Inlines + +template +inline tsl::StatusOr>> +StreamExecutor::CreateTypedKernel(absl::string_view kernel_name, + absl::string_view ptx, + absl::Span cubin_data) { + auto kernel_base = std::make_unique>(this); + MultiKernelLoaderSpec loader_spec(kernel_base->kNumberOfParameters); + loader_spec.AddCudaPtxInMemory(ptx, kernel_name); + + if (!cubin_data.empty()) { + loader_spec.AddCudaCubinInMemory( + reinterpret_cast(cubin_data.data()), kernel_name); + } + + TF_RETURN_IF_ERROR(GetKernel(loader_spec, kernel_base.get())); + return std::move(kernel_base); +} + +template +inline DeviceMemory StreamExecutor::AllocateArray(uint64_t element_count, + int64_t memory_space) { + uint64_t bytes = sizeof(T) * element_count; + return DeviceMemory(Allocate(bytes, memory_space)); +} + +template +ScopedDeviceMemory::ScopedDeviceMemory(StreamExecutor* parent, + DeviceMemoryBase value) + : wrapped_(value), + device_ordinal_(parent->device_ordinal()), + allocator_(parent->GetAllocator()) {} + +template +ScopedDeviceMemory::ScopedDeviceMemory( + StreamExecutor* parent, std::initializer_list values) + : ScopedDeviceMemory(parent, parent->AllocateArray(values.size())) { + if (ptr() != nullptr) { + std::vector local(values); + if (!parent->SynchronousMemcpy(ptr(), const_cast(&local[0]), + ptr()->size())) { + TF_CHECK_OK(Free()); + } + } +} + +template +DeviceMemory StreamExecutor::GetSubBuffer(DeviceMemory* parent, + uint64_t element_offset, + uint64_t element_count) { + if (element_offset + element_count > parent->ElementCount()) { + LOG(ERROR) << "requested sub-buffer allocation (offset + size) is greater " + << "than parent allocation size: (" << element_offset << " + " + << element_count << ") vs. (" << parent->ElementCount() << ")"; + return DeviceMemory{}; + } + + void* opaque = GetUntypedSubBuffer(parent, sizeof(T) * element_offset, + sizeof(T) * element_count); + if (opaque == nullptr) { + return DeviceMemory{}; + } + return DeviceMemory(DeviceMemoryBase(opaque, sizeof(T) * element_count)); +} + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_PIMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/temporary_device_memory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/temporary_device_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..b12fd2efceb2c49809511d7a632fbc519bcee2a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/temporary_device_memory.h @@ -0,0 +1,136 @@ +/* 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. +==============================================================================*/ + +// Temporary memories are used to allocate scratch space required by an +// operation about to be enqueued onto a stream. +// +// std::unique_ptr> temporary_memory = +// stream.AllocateTemporaryArray(1024).value(); +// // ... enqueue stuff onto the stream using the temporary memory ... +// // Note that the memory is accessible via +// // temporary_memory->device_memory() and similar. +// +// // Finalize the temporary memory. The underlying device memory may +// // be released any time after this program point, as another thread may +// // call Stream::BlockHostUntilDone, causing synchronization. This +// // finalization also happens automatically for the user if the unique_ptr +// // goes out of scope. +// temporary_memory.Finalize(); +// +// WARNING: do NOT hold onto the device memory associated with temporary_memory +// after finalization. If temporary_memory->device_memory() is used after the +// temporary memory is finalized, it will cause a DCHECK failure. +// +// Note that standard usage takes advantage of the type-safe wrapper, +// TemporaryDeviceMemory, defined below. +// +// Also see tests for executable sample usage. + +#ifndef XLA_STREAM_EXECUTOR_TEMPORARY_DEVICE_MEMORY_H_ +#define XLA_STREAM_EXECUTOR_TEMPORARY_DEVICE_MEMORY_H_ + +#include "xla/stream_executor/device_memory.h" + +namespace stream_executor { + +class Stream; +namespace internal { +class TemporaryMemoryManager; +} + +// Untyped base class (analogous to a void*) for temporary device memory +// allocations associated with a stream. +class TemporaryDeviceMemoryBase { + public: + // Marks the temporary memory as finalized if it is not already marked as + // such. + ~TemporaryDeviceMemoryBase(); + + // Precondition: !IsFinalized() + DeviceMemoryBase* mutable_device_memory(); + + // Precondition: !IsFinalized() + const DeviceMemoryBase& device_memory() const; + + // "Finalizes" this temporary memory, making it acceptable to release at the + // next stream synchronization point -- the device memory can be reclaimed at + // any time after the temporary memory is marked as finalized (e.g. if a + // separate thread is calls Stream::BlockHostUntilDone). This may only be + // called once -- see the precondition below. + // + // Precondition: !IsFinalized() + void Finalize(); + + // Returns true iff the temporary memory is finalized (that is, the user is + // done referring to the temporary device memory, and thus it can be released + // at the next stream synchronization point). + bool IsFinalized() const; + + // Returns true iff the temporary memory is still allocated. + // + // Note: this is a polling call, no guarantee is made that the temporary + // memory is still allocated after the call has completed. + bool IsAllocated() const; + + private: + friend class internal::TemporaryMemoryManager; + friend class TemporaryDeviceMemoryTest; + + // Note: construction DCHECKs that the memory is known-allocated in the + // stream's temporary-allocation-manager. + TemporaryDeviceMemoryBase(Stream* parent, DeviceMemoryBase device_memory, + uint64_t allocation_generation); + + // The device memory region that has allocated. + DeviceMemoryBase device_memory_; + + // The generation counter value for the temporary memory record in the + // temporary memory manager. + uint64_t allocation_generation_; + + // The stream that this temporary memory was allocated for. + Stream* parent_; +}; + +// Type-safe wrapper around the base type (which is analogous to a void*). +template +class TemporaryDeviceMemory : public TemporaryDeviceMemoryBase { + public: + // Type-safe wrapper around TemporaryDeviceMemoryBase::mutable_device_memory. + DeviceMemory* mutable_device_memory() { + StaticSlicingAssertionDummy(); + return reinterpret_cast*>( + TemporaryDeviceMemoryBase::mutable_device_memory()); + } + + // Type-safe wrapper around TemporaryDeviceMemoryBase::device_memory. + const DeviceMemory& device_memory() const { + StaticSlicingAssertionDummy(); + return reinterpret_cast&>( + TemporaryDeviceMemoryBase::device_memory()); + } + + private: + static void StaticSlicingAssertionDummy() { + static_assert( + sizeof(TemporaryDeviceMemory) == sizeof(TemporaryDeviceMemoryBase), + "derived class is simply a wrapper, no members may be added due to " + "slicing"); + } +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TEMPORARY_DEVICE_MEMORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/temporary_memory_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/temporary_memory_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..6a82fe0667235a5b3da7fc4a8624fa3e11d96066 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/temporary_memory_manager.h @@ -0,0 +1,153 @@ +/* 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 temporary-memory-manager is a helper class for a Stream to keep track of +// temporary allocations. These allocations defer their deallocation to the next +// Stream::BlockHostUntilDone call for efficiency purposes (as deallocation +// itself generally forces synchronization to occur). + +#ifndef XLA_STREAM_EXECUTOR_TEMPORARY_MEMORY_MANAGER_H_ +#define XLA_STREAM_EXECUTOR_TEMPORARY_MEMORY_MANAGER_H_ + +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/temporary_device_memory.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace internal { + +// Record used inside the TemporaryMemoryManager as metadata for a given device +// memory region. +struct TemporaryMemoryRecord { + // What "generation" this record was allocated in. + // + // Currently the generation counter is bumped for every allocation, but this + // could be made coarser if necessary. + uint64_t allocation_generation; + + // Notes whether the temporary memory has been marked as finalized, such that + // we can release the DeviceMemory associated with this record at + // synchronization time. + bool finalized; +}; + +// Manages temporary memories associated with a stream -- keeps records of +// outstanding temporaries and their state, and can deallocate them +// appropriately at points in the Stream lifecycle (e.g. BlockHostUntilDone, +// destruction). +class TemporaryMemoryManager { + public: + explicit TemporaryMemoryManager(Stream* stream) : stream_(stream) {} + + // Allocates a temporary array that is then managed by this object. + template + tsl::StatusOr>> AllocateArray( + uint64_t element_count); + + // Forces deallocation of all managed temporary memory regions. + // + // Called, for example, when the Stream owning this temporary memory manager + // is destroyed. + // + // Note: These calls to Deallocate will likely force synchronization. + void ForceDeallocateAll(); + + // Marks the given memory region as finalized. + // + // If must_exist is set, this will check-fail if the temporary memory record + // is not found. + void MarkFinalized(const DeviceMemoryBase& device_memory, uint64_t generation, + bool must_exist); + + // Deallocates temporary memories that have been finalized. + // + // Note: These calls to Deallocate will likely force synchronization, so it is + // meant to be called before a "BlockHostUntilDone" is about to be performed. + void DeallocateFinalizedTemporaries(); + + // Returns whether the provided device_memory is finalized. + // + // In the vacuous case where the device memory doesn't appear in the temporary + // memory records, it is either not a temporary at all, or has already been + // deallocated, and thus returns true. + bool IsFinalized(const DeviceMemoryBase& device_memory, + uint64_t allocation_generation) const; + + // Returns whether the manager has a live allocation record for the given + // device memory pointer with the given generation counter. + // + // Note: this is a polling call -- there is no guarantee that the region is + // still allocated once the call has completed. + bool HasAllocated(const DeviceMemoryBase& device_memory, + uint64_t generation) const; + + private: + // Allocates an array without type parameterization, so that the + // implementation can live in the source file. Without this base allocation + // method, we incur a circular dependency between the StreamExecutor + // definition and this class' definition. + tsl::StatusOr> AllocateArrayBase( + uint64_t element_count, uint64 element_size); + + // Mutex to guard temporary record state. + mutable absl::Mutex mutex_; + + // Mapping from device memory to the current (live) temporary memory record. + // + // If a device memory is not in this mapping, it is not a temporary currently + // allocated and owned by this temporary memory manager. + std::map records_ + ABSL_GUARDED_BY(mutex_); + + // Allocation generation -- we bump this counter to distinguish temporary + // memory handles that have been deallocated and later reallocated at the same + // device memory address. + uint64_t generation_ ABSL_GUARDED_BY(mutex_); + + // The stream (parent object) for this temporary memory manager -- allocations + // are performed through this stream handle. + Stream* stream_; + + TemporaryMemoryManager(const TemporaryMemoryManager&) = delete; + void operator=(const TemporaryMemoryManager&) = delete; +}; + +//////////// +// Inlines + +template +tsl::StatusOr>> +TemporaryMemoryManager::AllocateArray(uint64_t element_count) { + tsl::StatusOr> temporary_memory = + AllocateArrayBase(element_count, sizeof(T)); + if (!temporary_memory.ok()) { + return temporary_memory.status(); + } + + return std::unique_ptr>( + reinterpret_cast*>(temporary_memory->release())); +} + +} // namespace internal +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TEMPORARY_MEMORY_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tf_allocator_adapter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tf_allocator_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..5293e4639dc82de48a8d730cd051c984ebb81242 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tf_allocator_adapter.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_STREAM_EXECUTOR_TF_ALLOCATOR_ADAPTER_H_ +#define XLA_STREAM_EXECUTOR_TF_ALLOCATOR_ADAPTER_H_ + +#include +#include +#include +#include + +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/stream.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +// Adapter class that wraps a Tensorflow allocator. +// +// Assumes that the Tensorflow allocator permits asynchronous deallocation: +// see comment on `AllowsAsynchronousDeallocation()`. +class TfAllocatorAdapter : public DeviceMemoryAllocator { + public: + // stream: a Stream on which the allocator can only be used. If non-null, the + // allocator can not be used on any other stream. + TfAllocatorAdapter(tsl::Allocator *wrapped, Stream *stream); + + // Constructor for the cases where `stream` can not be provided. + TfAllocatorAdapter(tsl::Allocator *wrapped, Platform *platform); + + ~TfAllocatorAdapter() override; + + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure, + int64_t memory_space) override; + + tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) override; + + // The Tensorflow BFC allocator used on GPU allows host-side deallocation + // before GPU execution takes place. Tensorflow uses the ordering of the main + // compute stream to enforce a happens-before relationship between a memory + // allocation and code that reuses the same memory. If Tensorflow adds + // support for multiple GPU streams or allocators with different ordering + // requirements, this code may need to change. + // (This attribute has no effect on CPU.) + bool AllowsAsynchronousDeallocation() const override { return true; } + + tsl::StatusOr GetStream(int device_ordinal) override; + + tsl::StatusOr GetAllocator(int device_ordinal); + + private: + tsl::Allocator *wrapped_; + Stream *stream_; +}; + +// Adapter class that wraps per-device TF allocators with corresponding streams +// as a TfAllocatorAdapter. Assumes that the Tensorflow allocator permits +// asynchronous deallocation; see comment on `AllowsAsynchronousDeallocation()`. +class MultiDeviceAdapter : public DeviceMemoryAllocator { + public: + using AllocatorWithStream = + std::pair, Stream *>; + using AllocatorWithLogicalIdAndStream = + std::tuple, int, Stream *>; + + MultiDeviceAdapter(const Platform *platform, + std::vector tf_allocators) + : DeviceMemoryAllocator(platform) { + tf_allocators_.reserve(tf_allocators.size()); + for (AllocatorWithStream &p : tf_allocators) { + int device_ordinal = p.second->parent()->device_ordinal(); + if (per_device_allocators_.size() <= device_ordinal) { + per_device_allocators_.resize(device_ordinal + 1); + } + CHECK(!per_device_allocators_[device_ordinal]); + per_device_allocators_[device_ordinal] = + std::make_unique(p.first.get(), p.second); + tf_allocators_.push_back(std::move(p.first)); + } + } + + MultiDeviceAdapter(const Platform *platform, + std::vector tf_allocators) + : DeviceMemoryAllocator(platform) { + tf_allocators_.reserve(tf_allocators.size()); + for (AllocatorWithLogicalIdAndStream &t : tf_allocators) { + const int device_ordinal = std::get<1>(t); + Stream *stream = std::get<2>(t); + if (per_device_allocators_.size() <= device_ordinal) { + per_device_allocators_.resize(device_ordinal + 1); + } + CHECK(!per_device_allocators_[device_ordinal]); + per_device_allocators_[device_ordinal] = + std::make_unique(std::get<0>(t).get(), stream); + tf_allocators_.push_back(std::move(std::get<0>(t))); + } + } + + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure, + int64_t memory_space) override { + CHECK_LT(device_ordinal, per_device_allocators_.size()); + return per_device_allocators_[device_ordinal]->Allocate( + device_ordinal, size, retry_on_failure, memory_space); + } + + tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) override { + CHECK_LT(device_ordinal, per_device_allocators_.size()); + return per_device_allocators_[device_ordinal]->Deallocate(device_ordinal, + mem); + } + + // The Tensorflow BFC allocator used on GPU allows host-side deallocation + // before GPU execution takes place. Tensorflow uses the ordering of the main + // compute stream to enforce a happens-before relationship between a memory + // allocation and code that reuses the same memory. If Tensorflow adds + // support for multiple GPU streams or allocators with different ordering + // requirements, this code may need to change. + // (This attribute has no effect on CPU.) + bool AllowsAsynchronousDeallocation() const override { return true; } + + tsl::StatusOr GetStream(int device_ordinal) override { + return per_device_allocators_[device_ordinal]->GetStream(device_ordinal); + } + + tsl::StatusOr GetAllocator(int device_ordinal) { + return per_device_allocators_[device_ordinal]->GetAllocator(device_ordinal); + } + + private: + std::vector> per_device_allocators_; + // The wrapped TF allocators backing per_device_allocators_ + // (TfAllocatorAdapter does not take ownership of its underlying Allocator). + std::vector> tf_allocators_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TF_ALLOCATOR_ADAPTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_conversions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_conversions.h new file mode 100644 index 0000000000000000000000000000000000000000..47b9f99551dcd24315bef12fee9a2655fcf722bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_conversions.h @@ -0,0 +1,161 @@ +/* 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_STREAM_EXECUTOR_TPU_C_API_CONVERSIONS_H_ +#define XLA_STREAM_EXECUTOR_TPU_C_API_CONVERSIONS_H_ + +#include +#include +#include + +#include "xla/executable_run_options.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/literal.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/maybe_owning_device_memory.h" +#include "xla/service/shaped_buffer.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/tpu/c_api_decl.h" + +// APIs for converting between internal and external versions of +// XLA/StreamExecutor data structures. +namespace ApiConverter { + +absl::Span MakeSpan(const FloatList& src_list); +void CreateVector(absl::Span src, FloatList* dst); +void Destroy(FloatList* float_list); + +absl::Span MakeSpan(const Int64List& src_list); +void CreateVector(absl::Span src, Int64List* dst); + +absl::Span MakeSpan(const IntList& src_list); +void CreateVector(absl::Span src, IntList* dst); + +absl::Span MakeSpan(const BoolList& src_list); +void CreateVector(absl::Span src, BoolList* dst); + +void CreateVector(absl::Span src, IntList* dst); + +// se::DeviceMemoryBase +SE_DeviceMemoryBase ToC(const stream_executor::DeviceMemoryBase& base); +void ToC(const stream_executor::DeviceMemoryBase& base, + SE_DeviceMemoryBase* se_base); +stream_executor::DeviceMemoryBase FromC(const SE_DeviceMemoryBase& se_base); +void Destroy(SE_DeviceMemoryBase*); + +// xla::Tile +xla::Tile FromC(const XLA_Tile* c_tile); +void ToC(const xla::Tile& xla_tile, XLA_Tile* c_tile); +void Destroy(XLA_Tile* c_tile); + +// xla::Layout +xla::Layout FromC(const XLA_Layout* c_layout); +void ToC(const xla::Layout& xla_layout, XLA_Layout* c_layout); +void Destroy(XLA_Layout* c_layout); + +// xla::Shape +xla::Shape FromC(const XLA_Shape* c_shape); +void ToC(const xla::Shape& xla_shape, XLA_Shape* c_shape); +void Destroy(XLA_Shape* c_shape); + +// xla::ShapeIndex +XLA_ShapeIndex ToC(const xla::ShapeIndex& xla_shape); +xla::ShapeIndex FromC(XLA_ShapeIndex* c_shape); +void Destroy(XLA_ShapeIndex*); + +// Literal +void ToC(const xla::LiteralSlice& literal, XLA_Literal* c_literal); +xla::MutableBorrowingLiteral FromC(XLA_Literal* c_literal); +void Destroy(XLA_Literal* c_literal); + +// ShapedBuffer +void ToC(const xla::ShapedBuffer& buffer, XLA_ShapedBuffer* c_device_buffer); +xla::ShapedBuffer FromC(XLA_ShapedBuffer* c_buffer); +void Destroy(XLA_ShapedBuffer* c_buffer); + +// se::DeviceMemoryBase +SE_DeviceMemoryBase ToC(const stream_executor::DeviceMemoryBase& base); +stream_executor::DeviceMemoryBase FromC(const SE_DeviceMemoryBase& se_base); +void Destroy(SE_DeviceMemoryBase*); + +// Literal +void ToC(const xla::LiteralSlice& literal, XLA_Literal* c_literal); +xla::MutableBorrowingLiteral FromC(XLA_Literal* c_literal); +void Destroy(XLA_Literal* c_literal); + +// ShapedBuffer +void ToC(const xla::ShapedBuffer& buffer, XLA_ShapedBuffer* c_device_buffer); +xla::ShapedBuffer FromC(XLA_ShapedBuffer* c_buffer); +void Destroy(XLA_ShapedBuffer* c_buffer); + +// TpuEmbeddingEngineParametersData +struct TpuEmbeddingEngineParametersData { + // Backing vector for struct + std::array, 8> vectors; + TpuEmbeddingEngineParameters c_params; +}; + +std::unique_ptr Create(int num_tables); + +xla::MaybeOwningDeviceMemory FromC( + SE_MaybeOwningDeviceMemory* se_mem, + stream_executor::DeviceMemoryAllocator* allocator); + +// DeviceMemoryAllocator +SE_DeviceMemoryAllocator ToC(stream_executor::DeviceMemoryAllocator* allocator); + +// OwningDeviceMemory +SE_MaybeOwningDeviceMemory ToC(stream_executor::OwningDeviceMemory* mem); +// mem.HasOwnership() may be true if the buffer is aliased and shouldn't be +// released. 'aliased' should be true in this case. 'aliased' has no effect if +// 'mem' is unowned. +SE_MaybeOwningDeviceMemory ToC(xla::MaybeOwningDeviceMemory& mem, bool aliased); + +// HloModule +XLA_HloModule ToC(const xla::HloModule& module); +xla::StatusOr> FromC( + const XLA_HloModule& c_module); +void Destroy(XLA_HloModule* c_module); + +// HloModuleConfig +XLA_HloModuleConfig ToC(const xla::HloModuleConfig& config); +xla::HloModuleConfig FromC(const XLA_HloModuleConfig& c_config); +void Destroy(XLA_HloModuleConfig* c_config); + +// Helper for managing stack based C -> C++ conversions. +template +struct StackHelper { + explicit StackHelper() {} + + template + explicit StackHelper(const CppType& t) { + ::ApiConverter::ToC(t, &value); + } + ~StackHelper() { ::ApiConverter::Destroy(&value); } + + template + CppType AsCpp() const { + return ::ApiConverter::FromC(&value); + } + + mutable CType value; +}; + +} // namespace ApiConverter + +#endif // XLA_STREAM_EXECUTOR_TPU_C_API_CONVERSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_decl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_decl.h new file mode 100644 index 0000000000000000000000000000000000000000..bbeb12472ea8b00490928e453830d1ddb1ad4350 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_decl.h @@ -0,0 +1,362 @@ +/* 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_STREAM_EXECUTOR_TPU_C_API_DECL_H_ +#define XLA_STREAM_EXECUTOR_TPU_C_API_DECL_H_ + +#include +#include + +#include "xla/stream_executor/tpu/libtftpu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct TSL_Status TF_Status; + +// Maximum number of array elements to inline into structs for performance. +#define TPU_C_API_MAX_INLINED 6 + +typedef enum TpuCoreTypeEnum { + kTensorCore, + kEmbeddingV1, + kEmbeddingV2, +} TpuCoreTypeEnum; + +typedef enum TpuVersionEnum { + kUnknownTpuVersion, + kTpuV2, + kTpuV3, + kTpuV4, + // BEGIN-INTERNAL + // reserved for internal use + // END-INTERNAL +} TpuVersionEnum; + +typedef struct TpuRuntimeVersion { + // The three version numbers are: major, minor, patch + int version[3]; + const char* metadata; + size_t metadata_size; +} TpuRuntimeVersion; + +typedef struct SE_Platform SE_Platform; +typedef struct SE_StreamExecutor SE_StreamExecutor; +typedef struct SE_Stream SE_Stream; +typedef struct SE_Event SE_Event; + +typedef struct TpuSerializedProto { + const char* bytes; + size_t size; +} TpuSerializedProto; + +typedef struct SE_PlatformId { + void* id; // aka stream_executor::Platform::Id +} SE_PlatformId; +typedef struct SE_StreamExecutorConfig SE_StreamExecutorConfig; +typedef struct SE_DeviceOptions SE_DeviceOptions; +typedef TF_Status* (*SE_StatusCallback)(void*); + +typedef struct SE_DeviceMemoryBase { + void* opaque; + uint64_t size; + uint64_t payload; +} SE_DeviceMemoryBase; + +typedef struct SE_ScopedDeviceMemory { + SE_DeviceMemoryBase wrapped; + int device_ordinal; +} SE_ScopedDeviceMemory; + +typedef struct SE_AllocatorStats { + int64_t num_allocs; + int64_t bytes_in_use; + int64_t peak_bytes_in_use; + int64_t largest_alloc_size; + + bool has_bytes_limit; + int64_t bytes_limit; + + int64_t bytes_reserved; + int64_t peak_bytes_reserved; + + bool has_bytes_reservable_limit; + int64_t bytes_reservable_limit; + + int64_t largest_free_block_bytes; +} SE_AllocatorStats; + +// Note, due to the... odd way in which DeviceMemoryAllocator is used in TF, we +// cannot simply wrap an underlying pointer. Instead, we reverse the call +// direction and request memory via a callback. +typedef void (*SE_AllocateFn)(void* ctx, int device_ordinal, uint64_t size, + bool retry_on_failure, int64_t memory_space, + SE_ScopedDeviceMemory* result, TF_Status* status); + +typedef void (*SE_DeallocateFn)(void* ctx, SE_DeviceMemoryBase* base, + int device_ordinal, TF_Status* status); + +typedef struct SE_DeviceMemoryAllocator { + SE_Platform* platform; + void* ctx; + SE_AllocateFn allocate; + SE_DeallocateFn deallocate; +} SE_DeviceMemoryAllocator; + +typedef struct SE_DeviceDescription { + char* device_vendor; + char* platform_version; + char* driver_version; + char* runtime_version; + char* pci_bus_id; + char* name; + + int64_t thread_dim_limit_x; + int64_t thread_dim_limit_y; + int64_t thread_dim_limit_z; + int64_t block_dim_limit_x; + int64_t block_dim_limit_y; + int64_t block_dim_limit_z; + + int64_t threads_per_core_limit; + int64_t threads_per_block_limit; + int64_t threads_per_warp; + + int64_t registers_per_core_limit; + int64_t registers_per_block_limit; + + int64_t device_address_bits; + int64_t device_memory_size; + int64_t memory_bandwidth; + + int64_t shared_memory_per_core; + int64_t shared_memory_per_block; + + float clock_rate_ghz; + + int cuda_compute_capability_major; + int cuda_compute_capability_minor; + + int numa_node; + int core_count; + bool ecc_enabled; +} SE_DeviceDescription; + +typedef struct Tpu_Compiler Tpu_Compiler; +typedef struct SE_Executable SE_Executable; + +typedef struct SE_ExecutableRunOptions { + SE_DeviceMemoryAllocator allocator; + int device_ordinal; + SE_Stream* stream; + SE_Stream* host_to_device_stream; + TpuSerializedProto device_assignment; + int rng_seed; + int64_t run_id; + int launch_id; +} SE_ExecutableRunOptions; + +typedef struct SE_ExecutableSerializationHandle + SE_ExecutableSerializationHandle; + +typedef struct SE_MaybeOwningDeviceMemory { + SE_DeviceMemoryBase memory; + bool owned; + + // Set if owned + int device_ordinal; + SE_DeviceMemoryAllocator allocator; +} SE_MaybeOwningDeviceMemory; + +typedef struct IntList { + union { + int* heap; // owned + int inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} IntList; + +typedef struct Int64List { + union { + int64_t* heap; // owned + int64_t inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} Int64List; + +typedef struct FloatList { + union { + float* heap; // owned + float inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} FloatList; + +typedef struct BoolList { + union { + bool* heap; // owned + bool inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} BoolList; + +typedef struct FloatListRef { + float* ptr; // not owned + int64_t size; +} FloatListRef; + +typedef struct TpuEmbeddingEngineParameters { + FloatListRef** parameters[8]; + size_t num_tables; +} TpuEmbeddingEngineParameters; + +typedef struct XLA_Tile { + Int64List dimensions; +} XLA_Tile; + +typedef struct TileList { + union { + XLA_Tile* heap; // owned + XLA_Tile inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} TileList; + +typedef struct XLA_Layout { + Int64List minor_to_major; + IntList dim_level_types; + IntList dim_unique; + IntList dim_ordered; + TileList tiles; + int index_primitive_type; + int pointer_primitive_type; + int64_t element_size_in_bits; + int64_t memory_space; + int64_t dynamic_shape_metadata_prefix_bytes; +} XLA_Layout; + +// Represents an XLA shape tree. +typedef struct XLA_Shape { + int element_type; + Int64List dimensions; + BoolList dynamic_dimensions; + struct XLA_Shape* tuple_shapes; // owned + int ntuple_shapes; + bool has_layout; + XLA_Layout layout; +} XLA_Shape; + +// Represents a leaf node for a XLA shaped buffer. +typedef struct XLA_ShapedBuffer { + XLA_Shape on_device_shape; + int device_ordinal; + + SE_DeviceMemoryBase* bases; + size_t count; +} XLA_ShapedBuffer; + +// Represents a leaf XLA literal. +typedef struct XLA_Literal { + char** buffers; + size_t* sizes; + size_t count; + XLA_Shape shape; +} XLA_Literal; + +typedef struct XLA_MaybeOwningDeviceMemoryShapeTree { + XLA_Shape shape; + SE_MaybeOwningDeviceMemory* buffers; +} XLA_MaybeOwningDeviceMemoryShapeTree; + +typedef struct XLA_ShapeIndex { + int64_t indices[8]; + int64_t count; +} XLA_ShapeIndex; + +typedef struct SE_ExecutionInput { + XLA_MaybeOwningDeviceMemoryShapeTree shape_tree; + XLA_ShapeIndex* unowned_indices; + int unowned_indices_size; + XLA_Shape dynamic_shape; +} SE_ExecutionInput; + +typedef struct SE_ExecutionOutput { + XLA_ShapedBuffer result; + SE_MaybeOwningDeviceMemory* to_be_released; + int to_be_released_size; + XLA_ShapeIndex* aliased_indices; + int aliased_indices_size; +} SE_ExecutionOutput; + +typedef struct XLA_ComputationLayout { + int parameter_count; + XLA_Shape* parameter_layouts; + XLA_Shape result_layout; +} XLA_ComputationLayout; + +typedef struct XLA_HloModuleConfig { + uint64_t seed; + int32_t launch_id; + int64_t replica_count; + int64_t num_partitions; + bool use_spmd_partitioning; + bool use_auto_spmd_partitioning; + Int64List auto_spmd_partitioning_mesh_shape; + Int64List auto_spmd_partitioning_mesh_ids; + TpuSerializedProto debug_options; + bool has_static_device_assignment; + TpuSerializedProto static_device_assignment; + bool has_entry_computation_layout; + XLA_ComputationLayout entry_computation_layout; + BoolList allow_spmd_sharding_propagation_to_output; +} XLA_HloModuleConfig; + +typedef struct SE_HloExecutionProfile SE_HloExecutionProfile; + +typedef struct SE_StreamExecutorList { + SE_StreamExecutor** exec; + int count; +} SE_StreamExecutorList; + +typedef struct XLA_HloModuleGroup { + TpuSerializedProto proto; + XLA_HloModuleConfig* module_config; +} XLA_HloModuleGroup; + +typedef struct XLA_HloModule { + TpuSerializedProto proto; + XLA_HloModuleConfig module_config; +} XLA_HloModule; + +typedef struct XLA_TransferManager XLA_TransferManager; +typedef struct XLA_TpuMeshState XLA_TpuMeshState; + +typedef struct XLA_ComputationPlacer XLA_ComputationPlacer; + +typedef void (*XLA_CallbackFn)(void*); +typedef void (*XLA_StatusCallbackFn)(void*, TF_Status*); + +typedef struct SE_TpuTopology SE_TpuTopology; +typedef struct SE_TpuTopology_Core SE_TpuTopology_Core; +typedef struct SE_TpuTopology_Core SE_TpuTopology_Host; + +typedef struct SE_OutsideCompilationParams SE_OutsideCompilationParams; + +#ifdef __cplusplus +} +#endif + +#endif // XLA_STREAM_EXECUTOR_TPU_C_API_DECL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_defn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_defn.h new file mode 100644 index 0000000000000000000000000000000000000000..8e4707fcbbda044df8c5e21e103f0fdd717824b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/c_api_defn.h @@ -0,0 +1,66 @@ +/* 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_STREAM_EXECUTOR_TPU_C_API_DEFN_H_ +#define XLA_STREAM_EXECUTOR_TPU_C_API_DEFN_H_ + +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/stream.h" +#include "xla/stream_executor/stream_executor.h" + +// Definitions for XLA API data structures. Any underlying C++ data structures +// are implementation details and should only be used from within the stream +// executor implementation. + +namespace stream_executor { +class Platform; +class StreamExecutor; +} // namespace stream_executor + +struct SE_Platform { + stream_executor::Platform* platform; +}; + +struct SE_StreamExecutor { + stream_executor::StreamExecutor* executor; +}; + +struct SE_Stream { + explicit SE_Stream(stream_executor::StreamExecutor* parent) + : stream(parent) {} + stream_executor::Stream stream; +}; + +struct SE_Event { + explicit SE_Event(stream_executor::StreamExecutor* parent) : event(parent) {} + stream_executor::Event event; +}; + +struct SE_StreamExecutorConfig { + stream_executor::StreamExecutorConfig config; +}; + +struct SE_DeviceOptions { + stream_executor::DeviceOptions options; +}; + +// Ignored -- these are just used to enforce the interface types +struct XLA_TransferManager {}; +struct XLA_ComputationPlacer {}; +struct SE_TpuTopology {}; +struct SE_TpuTopology_Core {}; + +#endif // XLA_STREAM_EXECUTOR_TPU_C_API_DEFN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/libtftpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/libtftpu.h new file mode 100644 index 0000000000000000000000000000000000000000..c5e3fb59a4a5dfab04dcf07227e0a753433bd936 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/libtftpu.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. +==============================================================================*/ + +#include + +#ifndef XLA_STREAM_EXECUTOR_TPU_LIBTFTPU_H_ +#define XLA_STREAM_EXECUTOR_TPU_LIBTFTPU_H_ + +#ifndef __cplusplus +#define decltype(expr) __typeof__(expr) +#endif + +// Unfortunately we have to add an Fn suffix because we cannot have the same +// name for both a function and a element within a struct in the global +// namespace in gcc. This restriction doesn't exist in clang. +#define TFTPU_ADD_FN_IN_STRUCT(FnName) decltype(FnName)* FnName##Fn; + +#ifdef SWIG +#define TFTPU_CAPI_EXPORT +#else +#if defined(_WIN32) +#ifdef TF_COMPILE_LIBRARY +#define TFTPU_CAPI_EXPORT __declspec(dllexport) +#else +#define TFTPU_CAPI_EXPORT __declspec(dllimport) +#endif // TF_COMPILE_LIBRARY +#else +#define TFTPU_CAPI_EXPORT __attribute__((visibility("default"))) +#endif // _WIN32 +#endif // SWIG + +#ifdef __cplusplus +extern "C" { +#endif + +TFTPU_CAPI_EXPORT void TfTpu_Initialize(bool init_library, int num_args, + const char** args); + +#ifdef __cplusplus +} +#endif + +struct TfTpu_BaseFn { + TFTPU_ADD_FN_IN_STRUCT(TfTpu_Initialize); +}; + +#endif // XLA_STREAM_EXECUTOR_TPU_LIBTFTPU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/proto_helper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/proto_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..b4f505ed135d84a004e06c500adc66d3fcc29c73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/proto_helper.h @@ -0,0 +1,83 @@ +/* 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_STREAM_EXECUTOR_TPU_PROTO_HELPER_H_ +#define XLA_STREAM_EXECUTOR_TPU_PROTO_HELPER_H_ + +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep + +extern "C" { + +void StreamExecutor_Tpu_FreeSerializedProto(const TpuSerializedProto* proto); + +} // extern "C" + +namespace stream_executor { +namespace tpu { + +using SerializedProto = TpuSerializedProto; + +// Serializes a `proto` and put the result in the given `SerializedProtoType*` +// argument. +// +// Users should call SerializedProto_Free on `serialized_proto` afterwards. +template +inline void SerializeProto(const ProtoType& proto, + SerializedProtoType* serialized_proto) { + auto size = proto.ByteSizeLong(); + auto bytes = new char[size]; + CHECK(proto.SerializeToArray(bytes, size)); + serialized_proto->size = size; + serialized_proto->bytes = bytes; +} + +// Serializes a proto and return the result as a SerializedProto value. +// +// Users should call SerializedProto_Free on the return value afterwards. +template +inline SerializedProto SerializeProto(const ProtoType& proto) { + SerializedProto serialized_proto; + SerializeProto(proto, &serialized_proto); + return serialized_proto; +} + +// Deserializes a buffer and return the corresponding proto. If the buffer is +// empty, return an empty proto. +template +inline ProtoType DeserializeProto(const SerializedProtoType& serialized_proto) { + ProtoType proto; + if (serialized_proto.bytes != nullptr) { + CHECK_GT(serialized_proto.size, 0); + CHECK(proto.ParseFromArray(serialized_proto.bytes, serialized_proto.size)) + << "Invalid buffer, failed to deserialize buffer."; + } + return proto; +} + +// Releases the memory allocated for serialized protos. +template +inline void SerializedProto_Free(const SerializedProtoType& serialized_proto) { + CHECK_NE(serialized_proto.bytes, nullptr); + CHECK_GT(serialized_proto.size, 0); + delete[] serialized_proto.bytes; +} + +} // namespace tpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TPU_PROTO_HELPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_api.h new file mode 100644 index 0000000000000000000000000000000000000000..9a3cf2b330abc9bd48cd545fc43b8ca4a3ae7397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_api.h @@ -0,0 +1,36 @@ +/* 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_STREAM_EXECUTOR_TPU_TPU_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_API_H_ + +#include "xla/stream_executor/tpu/libtftpu.h" +#include "xla/stream_executor/tpu/tpu_executor_api.h" +#include "xla/stream_executor/tpu/tpu_ops_c_api.h" +#include "xla/stream_executor/tpu/tpu_profiler_c_api.h" + +namespace stream_executor { +namespace tpu { + +TfTpu_BaseFn* InitializeApiFn(); + +const TfTpu_OpsApiFn* OpsApiFn(); + +const TfTpu_ProfilerApiFn* ProfilerApiFn(); + +} // namespace tpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_executor_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_executor_api.h new file mode 100644 index 0000000000000000000000000000000000000000..34989709c31a64d09762f259539a43611fa3e602 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_executor_api.h @@ -0,0 +1,38 @@ +/* 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_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_API_H_ + +#include "xla/stream_executor/tpu/libtftpu.h" +#include "xla/stream_executor/tpu/tpu_executor_c_api.h" + +namespace stream_executor { +namespace tpu { + +TfTpu_ExecutorApiFn* ExecutorApiFn(); + +// Returns whether function pointers in `executor_api_fn` have been set and +// stream_executor is enabled. +bool IsStreamExecutorEnabled(TfTpu_ExecutorApiFn* executor_api_fn); + +// Returns whether function pointers in `executor_api_fn` have been set. If +// false, it probably means an appropriate initializer needs to be linked in. +bool IsInitialized(TfTpu_ExecutorApiFn* executor_api_fn); + +} // namespace tpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_executor_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_executor_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..f2dc3e3918948d90f6adae094ae838ef995bd0fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_executor_c_api.h @@ -0,0 +1,532 @@ +/* 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_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_C_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_C_API_H_ + +#include +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "xla/stream_executor/tpu/libtftpu.h" + +extern "C" { + +SE_Platform* TpuPlatform_New(); +void TpuPlatform_Free(SE_Platform* platform); +void TpuPlatform_Initialize(SE_Platform* platform, size_t options_size, + const char** options_key, + const char** options_value, TF_Status* status); +bool TpuPlatform_Initialized(SE_Platform* platform); +SE_StreamExecutor* TpuPlatform_GetExecutor(SE_Platform* platform, + SE_StreamExecutorConfig* config, + TF_Status* status); +SE_PlatformId TpuPlatform_Id(SE_Platform* platform); +int64_t TpuPlatform_VisibleDeviceCount(SE_Platform* platform); +bool TpuPlatform_ShouldRegisterTpuDeviceToDeviceCopy(SE_Platform* platform); +SE_TpuTopology* TpuPlatform_GetTopologyPtr(SE_Platform* platform); +SE_TpuTopology_Host* TpuPlatform_GetHostLocation(SE_Platform* platform); +TpuRuntimeVersion TpuPlatform_GetRuntimeVersion(SE_Platform* platform); + +void TpuExecutor_Init(SE_StreamExecutor* executor, int device_ordinal, + SE_DeviceOptions* device_options, TF_Status* status); +void TpuExecutor_Free(SE_StreamExecutor* executor); + +SE_DeviceMemoryBase TpuExecutor_Allocate(SE_StreamExecutor* executor, + uint64_t size, int64_t memory_space); +void TpuExecutor_Deallocate(SE_StreamExecutor* executor, + SE_DeviceMemoryBase* memory); +bool TpuExecutor_GetAllocatorStats(SE_StreamExecutor* executor, + SE_AllocatorStats* stats); +bool TpuExecutor_DeviceMemoryUsage(SE_StreamExecutor* executor, int64_t* free, + int64_t* total); + +bool TpuExecutor_AllocateStream(SE_StreamExecutor* executor, SE_Stream* stream); +void TpuExecutor_DeallocateStream(SE_StreamExecutor* executor, + SE_Stream* stream); +bool TpuExecutor_CreateStreamDependency(SE_StreamExecutor* executor, + SE_Stream* dependent, SE_Stream* other); +void TpuExecutor_GetStatus(SE_StreamExecutor* executor, SE_Stream* stream, + TF_Status* status); + +SE_TpuTopology_Core* TpuExecutor_GetCoreLocation(SE_StreamExecutor* executor); + +void TpuExecutor_AllocateEvent(SE_StreamExecutor* executor, SE_Event* event, + TF_Status* status); +void TpuExecutor_DeallocateEvent(SE_StreamExecutor* executor, SE_Event* event, + TF_Status* status); +int TpuExecutor_PollForEventStatus(SE_StreamExecutor* executor, + SE_Event* event); +void TpuExecutor_RecordEvent(SE_StreamExecutor* executor, SE_Stream* stream, + SE_Event* event, TF_Status* status); +void TpuExecutor_WaitForEvent(SE_StreamExecutor* executor, SE_Stream* stream, + SE_Event* event, TF_Status* status); + +void TpuExecutor_SynchronousMemcpyToHost(SE_StreamExecutor* executor, + void* host_dst, + const SE_DeviceMemoryBase* device_src, + uint64_t size, TF_Status* status); +void TpuExecutor_SynchronousMemcpyFromHost(SE_StreamExecutor* executor, + SE_DeviceMemoryBase* device_dst, + const void* host_src, uint64_t size, + TF_Status* status); +bool TpuExecutor_MemcpyToHost(SE_StreamExecutor* executor, SE_Stream* stream, + void* host_dst, + const SE_DeviceMemoryBase* device_src, + uint64_t size); + +bool TpuExecutor_MemcpyFromHost(SE_StreamExecutor* executor, SE_Stream* stream, + SE_DeviceMemoryBase* device_dst, + const void* host_src, uint64_t size); + +void TpuExecutor_EnqueueInfeed(SE_StreamExecutor* executor, + int32_t infeed_queue_index, const uint8_t* data, + int64_t size, TF_Status* status); +void TpuExecutor_DequeueOutfeed(SE_StreamExecutor* executor, + int32_t outfeed_queue_index, uint8_t* data, + int64_t size, TF_Status* status); +void TpuExecutor_WaitForInfeedReady(SE_StreamExecutor* executor, + int32_t infeed_queue_index, + TF_Status* status); +void TpuExecutor_WaitForOutfeedReady(SE_StreamExecutor* executor, + int32_t outfeed_queue_index, + TF_Status* status); + +void TpuExecutor_BlockHostUntilDone(SE_StreamExecutor* executor, + SE_Stream* stream, TF_Status* status); +void TpuExecutor_BlockUntilDoneOrFailed(SE_StreamExecutor* executor, + TF_Status* status); +void TpuExecutor_SyncAndForgetFailedStreams(SE_StreamExecutor* executor); +bool TpuExecutor_SynchronizeAllActivity(SE_StreamExecutor* executor); + +void TpuExecutor_UnloadAllPrograms(SE_StreamExecutor* executor, + TF_Status* status); +void TpuExecutor_EnqueueCompactionOnStreamForHbm(SE_StreamExecutor* executor, + SE_Stream* compaction_stream, + TF_Status* status); + +SE_Stream* TpuStream_New(SE_StreamExecutor* parent); +void TpuStream_Free(SE_Stream*); +void* TpuStream_Stream(SE_Stream*); +bool TpuStream_Status(SE_Stream*); +bool TpuStream_IsSameSharedMemoryLocation(SE_Stream*, SE_Stream*); +void TpuStream_EnqueueTransferHostToDevice(SE_Stream* stream, + SE_DeviceMemoryBase device_dst, + void* host_src, uint64_t size, + TF_Status* status); +void TpuStream_EnqueueTransferDeviceToHost(SE_Stream* stream, + SE_DeviceMemoryBase device_src, + void* host_dst, uint64_t size, + TF_Status* status); +void TpuStream_TpuEnqueueOnDeviceSendRecvLocal(SE_Stream* stream, + SE_DeviceMemoryBase send_buffer, + SE_DeviceMemoryBase recv_buffer, + TF_Status* status); + +SE_Event* TpuEvent_New(SE_StreamExecutor* parent); +void TpuEvent_Free(SE_Event*); + +TF_Status* TpuStatus_New(); +TF_Status* TpuStatus_Create(int32_t code, const char* msg); +void TpuStatus_Set(TF_Status* status, int32_t code, const char* msg, + int32_t len); +void TpuStatus_Free(TF_Status* status); +const char* TpuStatus_Message(TF_Status* status); +int TpuStatus_Code(TF_Status* status); +bool TpuStatus_Ok(TF_Status* status); + +SE_StreamExecutorConfig* TpuStreamExecutorConfig_Default(); +void TpuStreamExecutorConfig_SetOrdinal(SE_StreamExecutorConfig*, int ordinal); +void TpuStreamExecutorConfig_Free(SE_StreamExecutorConfig*); + +SE_DeviceDescription* TpuDeviceDescription_New(); +void TpuDeviceDescription_Free(SE_DeviceDescription* description); +void TpuExecutor_CreateDeviceDescription(SE_StreamExecutor* executor, + SE_DeviceDescription* description, + TF_Status* status); + +SE_DeviceOptions* TpuExecutor_NewDeviceOptions(unsigned flags); +void TpuExecutor_FreeDeviceOptions(SE_DeviceOptions* options); + +bool TpuExecutor_HostCallback(SE_StreamExecutor* executor, SE_Stream* stream, + SE_StatusCallback callback_fn, void* ctx); + +XLA_TransferManager* TpuTransferManager_New(); +void TpuTransferManager_Free(XLA_TransferManager* manager); +SE_PlatformId TpuTransferManager_PlatformId(XLA_TransferManager* manager); +void TpuTransferManager_HostShapeToDeviceShape(XLA_TransferManager* manager, + XLA_Shape* host_shape, + XLA_Shape* device_shape); +void TpuTransferManager_TransferLiteralToDeviceAsync( + XLA_TransferManager* manager, SE_Stream* stream, XLA_Literal* literal, + XLA_ShapedBuffer* device_buffer, TF_Status* status); +void TpuTransferManager_TransferLiteralFromDevice( + XLA_TransferManager* manager, SE_Stream* stream, + XLA_ShapedBuffer* device_buffer, XLA_Literal* literal, + XLA_StatusCallbackFn callback, void* ctx); +int64_t TpuTransferManager_GetByteSizeRequirement(XLA_TransferManager* manager, + XLA_Shape* shape); +void TpuTransferManager_ChooseCompactLayoutForShape( + XLA_TransferManager* manager, XLA_Shape* host_shape, XLA_Shape* output, + TF_Status* status); +bool TpuTransferManager_CanShapedBufferBeAccessedNow( + XLA_TransferManager* manager, SE_StreamExecutor* executor, + XLA_ShapedBuffer* device_buffer); +bool TpuTransferManager_CanBufferBeAccessedNow( + XLA_TransferManager* manager, SE_StreamExecutor* executor, + SE_DeviceMemoryBase* device_buffer); +void TpuTransferManager_WriteSingleTupleIndexTable( + XLA_TransferManager* manager, SE_Stream* stream, + SE_DeviceMemoryBase* elements, size_t elements_len, XLA_Shape* shape, + SE_DeviceMemoryBase* region, TF_Status* status); +void TpuTransferManager_GetInfeedLayout(XLA_Shape* shape, + XLA_Shape* infeed_shape); +void TpuTransferManager_LinearizeToBuffers( + XLA_TransferManager* manager, XLA_Literal* c_literal, + XLA_Shape* c_device_shape, char*** buffers_array, int64_t** buffers_size, + int64_t* buffers_array_size, TF_Status* status); +void TpuTransferManager_FreeBuffers(char** buffers_array, int64_t* buffers_size, + int64_t buffers_array_size); +void TpuTransferManager_TransferLiteralToInfeed(XLA_TransferManager* manager, + SE_StreamExecutor* executor, + XLA_Literal* c_literal, + TF_Status* status); +void TpuTransferManager_TransferBuffersToInfeed(XLA_TransferManager* manager, + SE_StreamExecutor* executor, + uint32_t** buffers_array, + int64_t* buffers_size_in_uint32, + int64_t buffers_array_size, + TF_Status* status); +void TpuTransferManager_TransferLiteralFromOutfeed( + XLA_TransferManager* manager, SE_StreamExecutor* executor, + XLA_Shape* shape /*deprecated*/, XLA_Literal* c_literal, TF_Status* status); +void TpuTransferManager_ResetDevices(XLA_TransferManager* manager, + SE_StreamExecutor** executors, + int64_t num_executors, TF_Status* status); +void TpuTransferManager_ReadDynamicShapes(SE_Stream* stream, + XLA_ShapedBuffer* buffer, + const XLA_Shape& original_shape, + XLA_Shape* updated_shape, + TF_Status* status); + +XLA_ComputationPlacer* TpuComputationPlacer_New(); +void TpuComputationPlacer_Free(XLA_ComputationPlacer* placer); +// `assignment` should be a preallocated array of size `replicate_count` * +// `computation_count`. The assignment will be constructed as a 2D array where +// assignment[replica][computation] = device_id. +void TpuComputationPlacer_AssignDevices(XLA_ComputationPlacer* placer, + int replica_count, + int computation_count, int* assignment, + TF_Status* status); +void TpuComputationPlacer_AssignLocalDevices(SE_TpuTopology_Host* host, + int replica_count, + int computation_count, + int* assignment, + TF_Status* status); + +int TpuTopology_LogicalDevicesPerHost(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type); +int TpuTopology_LogicalDevicesPerChip(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type); +int TpuTopology_HostCount(SE_TpuTopology* tpu_topology); +int TpuTopology_ChipsPerHost(SE_TpuTopology* tpu_topology); + +int TpuTopology_ChipBounds_X(SE_TpuTopology* tpu_topology); +int TpuTopology_ChipBounds_Y(SE_TpuTopology* tpu_topology); +int TpuTopology_ChipBounds_Z(SE_TpuTopology* tpu_topology); +bool TpuTopology_HasChip(SE_TpuTopology* tpu_topology, int x, int y, int z); +SE_TpuTopology_Core* TpuTopology_CoreForId(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type, + int id); +SE_TpuTopology_Core* TpuTopology_Core(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type, int x, + int y, int z, int index); +int TpuTopology_NumCores(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type); +// 'cores' should be a preallocated array of size TpuTopology_NumCores. +void TpuTopology_Cores(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type, + SE_TpuTopology_Core** cores); +int TpuTopology_IdForHost(SE_TpuTopology* tpu_topology, int x, int y, int z); +TpuVersionEnum TpuTopology_Version(SE_TpuTopology* tpu_topology); +void TpuCoreLocation_ChipCoordinates(SE_TpuTopology_Core* tpu_core_location, + int* x, int* y, int* z); +void TpuCoreLocation_HostCoordinates(SE_TpuTopology_Core* tpu_core_location, + int* x, int* y, int* z); +int TpuCoreLocation_Index(SE_TpuTopology_Core* tpu_core_location); +int TpuCoreLocation_Id(SE_TpuTopology_Core* tpu_core_location); + +int TpuHostLocation_Id(SE_TpuTopology_Host* tpu_host_location); +int TpuHostLocation_NumCores(SE_TpuTopology_Host* tpu_host_location, + TpuCoreTypeEnum tpu_core_type); +// 'cores' should be a preallocated array of size TpuHostLocation_NumCores. +void TpuHostLocation_Cores(SE_TpuTopology_Host* tpu_host_location, + TpuCoreTypeEnum tpu_core_type, + SE_TpuTopology_Core** cores); + +// Async collective offloading. +// Safe to call multiple times. +void TpuAsyncCollectiveOffloadHelper_Init(); +// Must be called after TpuAsyncCollectiveOffloadHelper_Init. +void TpuAsyncCollectiveOffloadHelper_Shutdown(); + +// C API for XLA::Compiler interface + +TFTPU_CAPI_EXPORT Tpu_Compiler* TpuCompiler_New(); +TFTPU_CAPI_EXPORT void TpuCompiler_Free(Tpu_Compiler* compiler); + +TFTPU_CAPI_EXPORT void TpuCompiler_RunHloPasses( + Tpu_Compiler* compiler, XLA_HloModule* se_hlo_module, + SE_StreamExecutor* stream_executor, SE_DeviceMemoryAllocator* allocator, + XLA_HloModule* result, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuCompiler_RunBackend( + Tpu_Compiler* compiler, XLA_HloModule* se_hlo_module, + SE_StreamExecutor* stream_executor, SE_DeviceMemoryAllocator* allocator, + SE_Executable** result, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuCompiler_Compile( + Tpu_Compiler* compiler, XLA_HloModuleGroup* se_hlo_module_group, + SE_StreamExecutorList* stream_exec_lists, int num_lists, + SE_DeviceMemoryAllocator* allocator, SE_Executable** executables, + TF_Status* status); + +TFTPU_CAPI_EXPORT int64_t TpuCompiler_ShapeSize(Tpu_Compiler* compiler, + XLA_Shape* c_shape); + +TFTPU_CAPI_EXPORT void TpuCompiler_DefaultDeviceShapeRepresentation( + Tpu_Compiler* compiler, XLA_Shape* host_shape, XLA_Shape* device_shape); + +TFTPU_CAPI_EXPORT void TpuExecutable_ExecuteAsyncOnStream( + SE_Executable* executable, SE_ExecutableRunOptions* se_options, + SE_ExecutionInput** se_arguments, int se_arguments_size, + SE_HloExecutionProfile* hlo_execution_profile, + SE_ExecutionOutput* se_output, TF_Status* status); + +// This frees the XLA_ShapeIndex* array allocated when se_output is returned by +// TpuExecutable_ExecuteAsyncOnStream. +TFTPU_CAPI_EXPORT void TpuExecutable_FreeXlaShapeIndexArray( + XLA_ShapeIndex* array); + +// This frees the SE_MaybeOwningDeviceMemory* array allocated when se_output is +// returned by TpuExecutable_ExecuteAsyncOnStream. +// Note that this only frees the heap-allocated array itself, and does not +// free any of the underlying device memory. +TFTPU_CAPI_EXPORT void TpuExecutable_FreeMaybeOwningDeviceMemoryArray( + SE_MaybeOwningDeviceMemory* array); + +TFTPU_CAPI_EXPORT void TpuExecutable_Fingerprint(SE_Executable* executable, + const char** fingerprint, + size_t* size); + +// The serialization format is not guaranteed to be stable over time and has no +// compatibility guarantees (i.e. this is not a suitable long-term storage +// format). TpuExecutableSerialize_FreeHandle should be called after 'handle' is +// no longer needed. 'handle' is set to nullptr on error. +TFTPU_CAPI_EXPORT void TpuExecutable_Serialize( + SE_Executable* executable, SE_ExecutableSerializationHandle** handle, + TF_Status* status); + +// Returns the size of the serialized executable in bytes, i.e. the size of the +// array that should be passed to TpuExecutableSerialize_WriteToArray. `handle` +// must be non-null. +TFTPU_CAPI_EXPORT size_t +TpuExecutableSerialize_GetByteSize(SE_ExecutableSerializationHandle* handle); + +// Writes the serialized executable to `serialized`, which must be of size +// `serialized_size`. `serialized_size` should must be at least +// `TpuExecutableSerialize_GetByteSize(handle)`. `handle` must be non-null. +TFTPU_CAPI_EXPORT void TpuExecutableSerialize_WriteToArray( + SE_ExecutableSerializationHandle* handle, int serialized_size, + uint8_t* serialized, TF_Status* status); + +// Safe to call if 'handle' is null. +TFTPU_CAPI_EXPORT void TpuExecutableSerialize_FreeHandle( + SE_ExecutableSerializationHandle* handle); + +TFTPU_CAPI_EXPORT void TpuExecutable_Deserialize(int serialized_size, + const uint8_t* serialized, + SE_Executable** executable, + TF_Status* status); + +// Caller is responsible for freeing the returned module's proto and its +// config's proto. +TFTPU_CAPI_EXPORT XLA_HloModule +TpuExecutable_HloModule(SE_Executable* executable); + +TFTPU_CAPI_EXPORT void TpuExecutable_Free(SE_Executable*); + +// Converts an XLA `Shape` into its equivalent TPU `Shape` representation. +TFTPU_CAPI_EXPORT void XlaShapeToTpuShapeRepresentation( + XLA_Shape* serialized_xla_shape, int data_type, bool use_fast_memory, + XLA_Shape* serialized_tpu_shape, TF_Status* status); + +TFTPU_CAPI_EXPORT void XlaShapeToTpuPaddedShape(XLA_Shape* serialized_xla_shape, + XLA_Shape* padded_shape, + TF_Status* status); + +struct TfTpu_ExecutorApiFn { + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_New); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Initialize); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Initialized); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetExecutor); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Id); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_VisibleDeviceCount); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_ShouldRegisterTpuDeviceToDeviceCopy); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetTopologyPtr); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetHostLocation); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetRuntimeVersion); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Init); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Allocate); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Deallocate); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_GetAllocatorStats); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DeviceMemoryUsage); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_AllocateStream); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DeallocateStream); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_CreateStreamDependency); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_GetStatus); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_GetCoreLocation); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_AllocateEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DeallocateEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_PollForEventStatus); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_RecordEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_WaitForEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_SynchronousMemcpyToHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_SynchronousMemcpyFromHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_MemcpyToHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_MemcpyFromHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_EnqueueInfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DequeueOutfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_BlockHostUntilDone); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_SynchronizeAllActivity); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_UnloadAllPrograms); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_EnqueueCompactionOnStreamForHbm); + + TFTPU_ADD_FN_IN_STRUCT(TpuStream_New); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_Stream); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_Status); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_IsSameSharedMemoryLocation); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_EnqueueTransferHostToDevice); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_EnqueueTransferDeviceToHost); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_TpuEnqueueOnDeviceSendRecvLocal); + + TFTPU_ADD_FN_IN_STRUCT(TpuEvent_New); + TFTPU_ADD_FN_IN_STRUCT(TpuEvent_Free); + + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_New); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Set); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Message); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Code); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Ok); + + TFTPU_ADD_FN_IN_STRUCT(TpuStreamExecutorConfig_Default); + TFTPU_ADD_FN_IN_STRUCT(TpuStreamExecutorConfig_SetOrdinal); + TFTPU_ADD_FN_IN_STRUCT(TpuStreamExecutorConfig_Free); + + TFTPU_ADD_FN_IN_STRUCT(TpuDeviceDescription_New); + TFTPU_ADD_FN_IN_STRUCT(TpuDeviceDescription_Free); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_CreateDeviceDescription); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_NewDeviceOptions); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_FreeDeviceOptions); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_HostCallback); + + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_New); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_PlatformId); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_HostShapeToDeviceShape); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralToDeviceAsync); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralFromDevice); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_GetByteSizeRequirement); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_ChooseCompactLayoutForShape); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_CanShapedBufferBeAccessedNow); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_CanBufferBeAccessedNow); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_WriteSingleTupleIndexTable); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_GetInfeedLayout); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_LinearizeToBuffers); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_FreeBuffers); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralToInfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferBuffersToInfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralFromOutfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_ResetDevices); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_ReadDynamicShapes); + + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_New); + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_AssignDevices); + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_AssignLocalDevices); + + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_LogicalDevicesPerHost); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_LogicalDevicesPerChip); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_HostCount); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipsPerHost); + + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipBounds_X); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipBounds_Y); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipBounds_Z); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_HasChip); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_CoreForId); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_Core); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_NumCores); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_Cores); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_IdForHost); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_Version); + + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_ChipCoordinates); + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_HostCoordinates); + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_Index); + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_Id); + + TFTPU_ADD_FN_IN_STRUCT(TpuHostLocation_Id); + TFTPU_ADD_FN_IN_STRUCT(TpuHostLocation_NumCores); + TFTPU_ADD_FN_IN_STRUCT(TpuHostLocation_Cores); + + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_New); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_RunHloPasses); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_RunBackend); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_Compile); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_ShapeSize); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_DefaultDeviceShapeRepresentation); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_ExecuteAsyncOnStream); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_FreeXlaShapeIndexArray); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_FreeMaybeOwningDeviceMemoryArray); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Fingerprint); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Serialize); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutableSerialize_GetByteSize); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutableSerialize_WriteToArray); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutableSerialize_FreeHandle); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Deserialize); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_HloModule); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Free); + + TFTPU_ADD_FN_IN_STRUCT(XlaShapeToTpuShapeRepresentation); + TFTPU_ADD_FN_IN_STRUCT(XlaShapeToTpuPaddedShape); + + TFTPU_ADD_FN_IN_STRUCT(TpuAsyncCollectiveOffloadHelper_Init); + TFTPU_ADD_FN_IN_STRUCT(TpuAsyncCollectiveOffloadHelper_Shutdown); +}; +} + +// extern "C" + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_ops_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_ops_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..65bfbabeb15f7641dba58616fd6c463a10ee10b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_ops_c_api.h @@ -0,0 +1,828 @@ +/* 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_STREAM_EXECUTOR_TPU_TPU_OPS_C_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_OPS_C_API_H_ + +#include + +#include +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "xla/stream_executor/tpu/libtftpu.h" + +typedef struct TpuSerializedProto TpuSerializedProto; + +namespace tensorflow { + +class TpuMeshCommonState; +class TpuEmbeddingEngineState; +class ResourceMgr; + +} // namespace tensorflow + +extern "C" { + +typedef struct XLA_TpuProgram XLA_TpuProgram; + +// Enum for choosing sharding/unsharding program from a `XLA_TpuProgram` obj. +enum TpuProgramShardingType { kInvalid = 0, kMain, kSharding, kUnsharding }; + +struct TpuProgramFingerprint { + const char* bytes; + size_t size; +}; + +struct TpuExecutableSerializedProto { + const char* bytes; + size_t size; +}; + +struct CompilerMetadataSerializedProto { + const char* bytes; + size_t size; +}; + +struct HostComputeMetadataSerializedProto { + const char* bytes; + size_t size; +}; + +typedef struct XLA_TpuMeshState XLA_TpuMeshState; + +typedef struct XLA_TpuEmbeddingEngineState XLA_TpuEmbeddingEngineState; + +typedef struct TpuEmbedding_TensorBatchFixedState + TpuEmbedding_TensorBatchFixedState; + +typedef struct XLA_DeviceAssignment { + const char* bytes; + size_t size; +} XLA_DeviceAssignment; + +// Property for creating compilation cache key. +struct CompilationCacheKeyProperty { + const char* config_prefix; + const char* shapes_prefix; + const char* function_name; + uint64_t mlir_module_fingerprint; + const int32_t* device_ids; + size_t device_ids_size; + int32_t guaranteed_constants_size; + uint64_t function_library_fingerprint; + int32_t num_cores_per_replica; + int32_t num_replicas; + const XLA_TpuMeshState* mesh_state; + uint64_t session_id; + tensorflow::ResourceMgr* resource_mgr; +}; + +// Compilation cache key result returning both the key and a more verbose debug +// version. +struct CompilationCacheKeyResult { + const char* key; + const char* debug_string; +}; + +typedef struct XLA_TpuNodeContext XLA_TpuNodeContext; + +typedef struct TfTpu_OrdinalSelector TfTpuOrdinalSelector; + +struct TpuPartitionedCall_Params { + bool input_shape_opt; + bool group_tensors_for_packing; + int32_t minimum_input_tensors_packing; + int32_t minimum_output_tensors_packing; + + // Whether to attempt to automatically shard inputs by adding an + // XlaSharding op after each input. + bool enable_auto_xla_input_sharding; + + // The dimension of each input to shard if + // enable_auto_xla_input_sharding is set to true. Negative numbers are + // allowed and refers to dimensions starting from the end. + int32_t auto_xla_input_sharding_dim; + + // If true, only create one variable on the TPU for each variable on the CPU. + bool enable_variable_deduplication; +}; + +// Compiles Mlir or TF function computation by lowering into HLO IR and returns +// `count` number of TPU programs ready for execution. +// The API allocates the `XLA_TpuProgram*[]` array `tpu_programs` and creates +// `XLA_TpuProgram` object(s) using the `TpuProgram_New` API. The caller is +// responsible to deallocate both the `XLA_TpuProgram*[]` array and the +// `XLA_TpuProgram` object(s) using `TpuProgram_FreeArray` and `TpuProgram_Free` +// API respectively. +TFTPU_CAPI_EXPORT void TpuCompile_CompileAndBuild( + TpuSerializedProto compilation_request, const XLA_TpuMeshState* mesh_state, + XLA_TpuProgram** tpu_programs[], size_t* count, TF_Status* status); + +// Compiles a HLO IR and returns `count` number of TPU programs ready for +// execution. The API allocates the `XLA_TpuProgram*[]` array `tpu_programs` and +// creates `XLA_TpuProgram` object(s) using the `TpuProgram_New` API. The caller +// is responsible to deallocate both the `XLA_TpuProgram*[]` array and the +// `XLA_TpuProgram` object(s) using `TpuProgram_FreeArray` and `TpuProgram_Free` +// API respectively. +TFTPU_CAPI_EXPORT void TpuCompile_XrtCompileAndBuild( + TpuSerializedProto xrt_computation, const XLA_TpuMeshState* mesh_state, + XLA_TpuProgram** tpu_programs[], size_t* count, TF_Status* status); + +// Creates a new TPU mesh state object. +TFTPU_CAPI_EXPORT XLA_TpuMeshState* TpuMeshState_Create(); + +// Deletes the given TPU `mesh_state` object. Once deleted the object is +// unusable. +TFTPU_CAPI_EXPORT void TpuMeshState_Free(XLA_TpuMeshState* mesh_state); + +// Returns a pointer to an opaque mesh data structure used internally. +TFTPU_CAPI_EXPORT void* TpuMeshState_MeshCommonState( + XLA_TpuMeshState* mesh_state); + +// Creates a new TPU embedding engine state object. +TFTPU_CAPI_EXPORT XLA_TpuEmbeddingEngineState* TpuEmbeddingEngineState_Create(); + +// Delete the given TPU embedding engine state object. Once deleted the object +// is unusable. +TFTPU_CAPI_EXPORT void TpuEmbeddingEngineState_Free( + XLA_TpuEmbeddingEngineState* engine_state); + +// Returns a pointer to an opaque embedding engine state data structure used +// internally. +TFTPU_CAPI_EXPORT void* TpuEmbeddingEngineState_GetState( + XLA_TpuEmbeddingEngineState* engine_state); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_Create( + TfTpuOrdinalSelector** ordinal_selector, int num_cores_per_replica); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_Destroy( + TfTpuOrdinalSelector* ordinal_selector); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_GetOrdinal( + TfTpuOrdinalSelector* ordinal_selector, std::optional key, + int64_t* req_id, int64_t* ordinal); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_DequeueFromCoreSelector( + TfTpuOrdinalSelector* ordinal_selector, int32_t device_ordinal, + int64_t req_id); + +TFTPU_CAPI_EXPORT void TfTpu_GetTpuPartitionedCallParams( + TpuPartitionedCall_Params* params); + +typedef struct TpuExecutable_LoadProgramAndEnqueueToStream_Params { + int32_t struct_size; + void* priv; + + const XLA_TpuProgram* program; + SE_DeviceMemoryBase* arguments; + size_t arguments_len; + SE_DeviceMemoryBase* result; + size_t cross_program_prefetch_addrs_len; + SE_DeviceMemoryBase* cross_program_prefetch_addrs; + size_t cross_program_prefetch_offsets_len; + const uint32_t* cross_program_prefetch_offsets; + int32_t rng_seed; + XLA_DeviceAssignment* device_assignment; + SE_Stream* stream; + SE_OutsideCompilationParams* outside_compilation_params; + + TF_Status* status; // out +} TpuExecutable_LoadProgramAndEnqueueToStream_Params; + +#define TpuExecutable_LoadProgramAndEnqueueToStream_Params_SIZE \ + (sizeof(struct TpuExecutable_LoadProgramAndEnqueueToStream_Params)) + +TFTPU_CAPI_EXPORT void TpuExecutable_LoadProgramAndEnqueueToStream( + TpuExecutable_LoadProgramAndEnqueueToStream_Params* params); + +TFTPU_CAPI_EXPORT void HardwareLayout_HostShapeToDeviceShape( + XLA_Shape* host_shape, XLA_Shape* device_shape); +TFTPU_CAPI_EXPORT int64_t HardwareLayout_ShapeSize(XLA_Shape* shape); +TFTPU_CAPI_EXPORT int64_t HardwareLayout_ShapeSizeCompact(XLA_Shape* shape); +TFTPU_CAPI_EXPORT int64_t HardwareLayout_ShapeSizeCompactRaw(XLA_Shape* shape); + +typedef struct TpuExecute_RuntimeInputToPaddedData_Params { + int32_t struct_size; + void* priv; + + uint32_t* runtime_input_ptr; + size_t runtime_input_size; + int8_t* padded_data_ptr; + size_t padded_data_size; + XLA_Shape* runtime_shape; + XLA_Shape* compile_time_shape; + + TF_Status* status; // out +} TpuExecute_RuntimeInputToPaddedData_Params; + +#define TpuExecute_RuntimeInputToPaddedData_Params_SIZE \ + (sizeof(struct TpuExecute_RuntimeInputToPaddedData_Params)) + +TFTPU_CAPI_EXPORT void TpuExecute_RuntimeInputToPaddedData( + TpuExecute_RuntimeInputToPaddedData_Params* params); + +TFTPU_CAPI_EXPORT void TpuExecute_GetTpuEmbeddingMemoryAllocations( + int device_ordinal, SE_DeviceMemoryBase** addrs, size_t* addrs_count, + TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuExecute_FreeTpuEmbeddingMemoryAllocations( + int device_ordinal, SE_DeviceMemoryBase* addrs); + +typedef struct ConfigureDistributedTpuOp_DoWork_Params { + int32_t struct_size; + void* priv; + + size_t num_cores_per_host_size; + const int32_t* num_cores_per_host; + size_t server_address_size; + const char* server_address; + + size_t* host_config_output_size; // out + char** host_config_output; // out + TF_Status* status; // out +} ConfigureDistributedTpuOp_DoWork_Params; + +#define ConfigureDistributedTpuOp_DoWork_Params_SIZE \ + (sizeof(struct ConfigureDistributedTpuOp_DoWork_Params)) + +TFTPU_CAPI_EXPORT void ConfigureDistributedTpuOp_DoWork( + ConfigureDistributedTpuOp_DoWork_Params* params); + +typedef struct WaitForDistributedTpuOp_DoWork_Params { + int32_t struct_size; + void* priv; + + size_t num_hosts; + size_t num_cores_per_host; + const int32_t** host_ordinal_to_global_core_id_map; + tensorflow::TpuMeshCommonState* tpu_mesh_common_state; + + size_t* tpu_topology_output_size; // out + char** tpu_topology_output; // out + TF_Status* status; // out +} WaitForDistributedTpuOp_DoWork_Params; + +#define WaitForDistributedTpuOp_DoWork_Params_SIZE \ + (sizeof(struct WaitForDistributedTpuOp_DoWork_Params)) + +TFTPU_CAPI_EXPORT void WaitForDistributedTpuOp_DoWork( + WaitForDistributedTpuOp_DoWork_Params* params); + +typedef struct InitializeHostForDistributedTpuOp_DoWork_Params { + int32_t struct_size; + void* priv; + + size_t tpu_host_config_size; + const char* tpu_host_config; + bool enable_whole_mesh_compilations; + bool is_master_worker; + + size_t* core_id_output_size; // out + int32_t** core_id_output; // out + TF_Status* status; // out +} InitializeHostForDistributedTpuOp_DoWork_Params; + +#define InitializeHostForDistributedTpuOp_DoWork_Params_SIZE \ + (sizeof(struct InitializeHostForDistributedTpuOp_DoWork_Params)) + +TFTPU_CAPI_EXPORT void InitializeHostForDistributedTpuOp_DoWork( + InitializeHostForDistributedTpuOp_DoWork_Params* params); + +TFTPU_CAPI_EXPORT void SetGlobalTPUArrayOp_DoWork( + const size_t tpu_topology_size, const char* tpu_topology, + TF_Status* status); + +TFTPU_CAPI_EXPORT void DisconnectDistributedTpuChipsOp_DoWork( + int32_t* number_of_chips_output, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuConfigurationApi_FreeCharArray(char* output); +TFTPU_CAPI_EXPORT void TpuConfigurationApi_FreeInt32Array(int32_t* output); + +TFTPU_CAPI_EXPORT bool TpuConfigurationApi_HasTPUPodState(); + +TFTPU_CAPI_EXPORT void TpuConfigurationApi_TpusPerHost(int32_t* tpus, + TF_Status* status); +TFTPU_CAPI_EXPORT void TpuConfigurationApi_TpuMemoryLimit(int64_t* memory_limit, + TF_Status* status); +TFTPU_CAPI_EXPORT void TpuConfigurationApi_RemoteCompilationCacheSizeInBytes( + int64_t* cache_size_in_bytes); + +typedef struct TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params { + int32_t struct_size; + void* priv; + + size_t tpu_host_config_size; + const char* tpu_host_config; + + size_t* server_address_output_size; // out + char** server_address_output; // out + TF_Status* status; // out +} TpuConfigurationApi_CompilationCacheServerAddressFromConfig_Params; + +#define TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params_SIZE \ + (sizeof( \ + struct TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params)) + +TFTPU_CAPI_EXPORT +void TpuConfigurationApi_CompilationCacheServerAddressFromConfig( + TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params* params); + +typedef struct TpuConfigurationApi_GetServerAddressAndPort_Params { + int32_t struct_size; + void* priv; + + size_t* server_address_output_size; // out + char** server_address_output; // out + int* port_output; // out + TF_Status* status; // out +} TpuConfigurationApi_GetServerAddressAndPort_Params; + +#define TpuConfigurationApi_GetServerAddressAndPort_Params_SIZE \ + (sizeof(struct TpuConfigurationApi_GetServerAddressAndPort_Params)) + +TFTPU_CAPI_EXPORT void TpuConfigurationApi_GetServerAddressAndPort( + TpuConfigurationApi_GetServerAddressAndPort_Params* params); + +// Creates a new TPU program. +TFTPU_CAPI_EXPORT XLA_TpuProgram* TpuProgram_New(); + +// Destroys the `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_Free(XLA_TpuProgram* tpu_program); + +// Creates an array of `XLA_TpuProgram*`. +TFTPU_CAPI_EXPORT XLA_TpuProgram** TpuProgram_NewArray(size_t count); + +// Destroys an array of `XLA_TpuProgram*`. +TFTPU_CAPI_EXPORT void TpuProgram_FreeArray(XLA_TpuProgram* tpu_program[]); + +// Unloads and destroys the `tpu_program`. Once the TPU program is unloaded and +// destroyed, it is in an unusable state. +TFTPU_CAPI_EXPORT void TpuProgram_UnloadAndDestroy(XLA_TpuProgram* tpu_program, + TF_Status* status); + +// Gets TPU program size in bytes from the `tpu_program`. +TFTPU_CAPI_EXPORT int64_t +TpuProgram_GetProgramSize(const XLA_TpuProgram* tpu_program); + +// Logs the summary of current memory state snapshot of the `tpu_program`. +TFTPU_CAPI_EXPORT bool TpuProgram_LogProgramMemorySummary( + const XLA_TpuProgram* tpu_program); + +// Gets TPU program executable info from the `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_GetExecutableInfo( + const XLA_TpuProgram* tpu_program, TpuSerializedProto* executable_info, + TF_Status* status); + +// Gets host transfer info proto. +TFTPU_CAPI_EXPORT void TpuProgram_GetHostTransferInfo( + const XLA_TpuProgram* tpu_program, TpuSerializedProto* host_transfer_info, + TF_Status* status); + +// Gets HLO metadata proto. +TFTPU_CAPI_EXPORT void TpuProgram_GetHloMetadata( + const XLA_TpuProgram* tpu_program, TpuSerializedProto* hlo_metadata, + TF_Status* status); + +// Gets may modify variables boolean value. +TFTPU_CAPI_EXPORT void TpuProgram_GetMayModifyVariables( + const XLA_TpuProgram* tpu_program, bool* may_modify_variables); + +// Checks if TPU program has sharding. +TFTPU_CAPI_EXPORT bool TpuProgram_HasSharding( + const XLA_TpuProgram* tpu_program); + +// Gets TPU program by sharding type. Return value is valid only when the +// `status.status()` returns `OK`. +TFTPU_CAPI_EXPORT XLA_TpuProgram* TpuProgram_GetTpuProgram( + XLA_TpuProgram* tpu_program, TpuProgramShardingType type); + +// Gets TPU executable proto from a `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_SerializeTpuExecutable( + const XLA_TpuProgram* tpu_program, TpuExecutableSerializedProto* executable, + TF_Status* status); + +// Gets compilation metadata proto from a `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_SerializeCompilerMetadata( + const XLA_TpuProgram* tpu_program, + CompilerMetadataSerializedProto* compiler_metadata, TF_Status* status); + +// Deserializes the `GetTpuProgramResponse` proto into an `XLA_TpuProgram`. +TFTPU_CAPI_EXPORT void TpuProgram_DeserializeFromGetTpuProgramResponseProto( + TpuSerializedProto get_tpu_program_response, XLA_TpuProgram* tpu_program, + TF_Status* status); + +TFTPU_CAPI_EXPORT TpuProgramFingerprint +TpuProgram_GetFingerprint(const XLA_TpuProgram* tpu_program); + +TFTPU_CAPI_EXPORT void TpuProgram_DestroyFingerprint( + TpuProgramFingerprint fingerprint); + +// Checks if whether a TPU compilation is enabled. +TFTPU_CAPI_EXPORT bool TpuCompile_IsTpuCompilationEnabled(); + +// XLA compilation cannot be cancelled. To avoid hanging the TF worker will exit +// when cancellation is requested for an XLA compile op. Some tests require this +// behavior to be disabled, and we test for this condition with the following +// flag function. +TFTPU_CAPI_EXPORT bool TpuCompile_ShouldTpuCompileOpIgnoreCancellation(); + +// Returns the number of available TPU core count. +TFTPU_CAPI_EXPORT int TpuTopology_AvailableCoreCount( + const XLA_TpuMeshState* mesh_state, TpuCoreTypeEnum tpu_core_type); + +// Recycle unused service port. +TFTPU_CAPI_EXPORT void TpuNetUtil_RecycleUnusedPort(int port); + +// Creates a unique compilation cache `key` used for `put` and `get` operations. +// Returned buffers are heap-allocated and must be owned. +TFTPU_CAPI_EXPORT CompilationCacheKeyResult +TpuCompile_CreateCompilationCacheKey(CompilationCacheKeyProperty property); + +// Destroys the CompilationCacheKeyResult returned by calling the +// `TpuCompile_CreateCompilationCacheKey` API. +TFTPU_CAPI_EXPORT void TpuCompile_DestroyCompilationCacheKey( + CompilationCacheKeyResult result); + +// Creates a guaranteed const fingerprint. Guarantee const is normally used in +// TPU inference to avoid re-copying unchanged variables onto the TPU device. +// It promises the value is identical for every execution in the same session +// even if the actual value changes in later executions. +TFTPU_CAPI_EXPORT uint64_t TpuCompile_CreateGuaranteedConstFingerprint( + uint64_t fingerprint, const char* data, size_t size); + +// Returns a pointer to the TPU topology struct. +TFTPU_CAPI_EXPORT SE_TpuTopology* TpuUtil_GetTopologyPtr(); + +// Returns XLA pad size from TPU topology. +TFTPU_CAPI_EXPORT size_t TpuUtil_GetXlaPadSizeFromTpuTopology(); + +XLA_TpuNodeContext* TpuNodeContext_Create(int device_ordinal, + TF_Status* status); +void TpuNodeContext_Free(XLA_TpuNodeContext* node_context); + +void TpuNodeContext_CloseTpuHost(TF_Status* status); + +void TpuNodeContext_Initialize(int device_ordinal, TF_Status* status); + +bool TpuNodeContext_CompactionSupported(int device_ordinal); + +// Globally initialize the TPU system for inference. +TFTPU_CAPI_EXPORT void TfTpu_InitializeTpuModelServer(); + +typedef struct TpuEmbeddingEngine_ExecutePartitioner_Params { + int32_t struct_size; + void* priv; + TpuSerializedProto tpu_embedding_config; + + // out + size_t* common_config_size; + char** common_config; + TF_Status* status; +} TpuEmbeddingEngine_ExecutePartitioner_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ExecutePartitioner( + TpuEmbeddingEngine_ExecutePartitioner_Params* params); + +typedef struct TpuEmbeddingEngine_ConfigureMemory_Params { + int32_t struct_size; + void* priv; + + int num_inputs; + size_t common_config_size; + const char* common_config; + + // out + size_t* memory_config_size; + char** memory_config; + TF_Status* status; +} TpuEmbeddingEngine_ConfigureMemory_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ConfigureMemory( + TpuEmbeddingEngine_ConfigureMemory_Params* params); + +typedef struct TpuEmbeddingEngine_CollateMemory_Params { + int32_t struct_size; + void* priv; + + size_t memory_configs_size; + const TpuSerializedProto* memory_configs; + + // out + size_t* merged_memory_config_size; + char** merged_memory_config; + TF_Status* status; +} TpuEmbeddingEngine_CollateMemory_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_CollateMemory( + TpuEmbeddingEngine_CollateMemory_Params* params); + +typedef struct TpuEmbeddingEngine_ConfigureHost_Params { + int32_t struct_size; + void* priv; + + int num_inputs; + size_t common_config_size; + const char* common_config; + size_t memory_config_size; + const char* memory_config; + TpuSerializedProto tpu_embedding_config; + + // out + size_t* network_config_size; + char** network_config; + TF_Status* status; +} TpuEmbeddingEngine_ConfigureHost_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ConfigureHost( + TpuEmbeddingEngine_ConfigureHost_Params* params); + +typedef struct TpuEmbeddingEngine_ConnectHosts_Params { + int32_t struct_size; + void* priv; + + size_t network_configs_size; + const TpuSerializedProto* network_configs; + + // out + TF_Status* status; +} TpuEmbeddingEngine_ConnectHosts_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ConnectHosts( + TpuEmbeddingEngine_ConnectHosts_Params* params); + +typedef struct TpuEmbeddingEngine_Finalize_Params { + int32_t struct_size; + void* priv; + const XLA_TpuMeshState* tpu_mesh_state; + + size_t common_config_size; + const char* common_config; + size_t memory_config_size; + const char* memory_config; + + // out + TF_Status* status; +} TpuEmbeddingEngine_Finalize_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_Finalize( + TpuEmbeddingEngine_Finalize_Params* params); + +typedef struct TpuEmbeddingEngine_IsInitialized_Params { + int32_t struct_size; + void* priv; + + size_t config_string_size; + const char* config_string; + + // out + bool* is_tpu_embedding_initialized; + TF_Status* status; +} TpuEmbeddingEngine_IsInitialized_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_IsInitialized( + TpuEmbeddingEngine_IsInitialized_Params* params); + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_WriteParameters( + TpuEmbeddingEngineParameters* params, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ReadParameters( + TpuEmbeddingEngineParameters* params, TF_Status* status); + +typedef struct TF_Tensor TF_Tensor; + +typedef struct TpuEmbeddingEngine_EnqueueTensorBatch_Params { + int32_t struct_size; + void* priv; + + int32_t mode; + int32_t local_device_ordinal; + TpuEmbedding_TensorBatchFixedState* fixed_state; + + TF_Tensor** sample_indices_tensors; + size_t sample_indices_tensors_size; + TF_Tensor** embedding_indices_tensors; + size_t embedding_indices_tensors_size; + TF_Tensor** aggregation_weights_tensors; + size_t aggregation_weights_tensors_size; + TF_Status* status; +} TpuEmbeddingEngine_EnqueueTensorBatch_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_EnqueueTensorBatch( + TpuEmbeddingEngine_EnqueueTensorBatch_Params* params); + +typedef struct TpuEmbedding_TensorBatchFixedState_Create_Params { + int32_t struct_size; + void* priv; + + size_t combiners_size; + char** combiners; + + // out + TF_Status* status; +} TpuEmbedding_TensorBatchFixedState_Create_Params; + +TFTPU_CAPI_EXPORT TpuEmbedding_TensorBatchFixedState* +TpuEmbeddingTensorBatchFixedState_Create( + TpuEmbedding_TensorBatchFixedState_Create_Params* params); +TFTPU_CAPI_EXPORT void TpuEmbeddingTensorBatchFixedState_Destroy( + TpuEmbedding_TensorBatchFixedState* fixed_state); + +typedef struct TpuEmbeddingEngine_RecvActivationsComputation_Params { + int32_t struct_size; + void* priv; + + TpuSerializedProto tpu_embedding_config; + XLA_Shape* deduplication_data_shape; + TpuSerializedProto* op_sharding; + + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_RecvActivationsComputation_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_RecvActivationsComputation( + TpuEmbeddingEngine_RecvActivationsComputation_Params* params); + +typedef struct + TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation_Params { + int32_t struct_size; + void* priv; + + TpuSerializedProto tpu_embedding_config; + TpuSerializedProto* op_sharding; + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation_Params; + +TFTPU_CAPI_EXPORT void +TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation( + TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation_Params* + params); + +typedef struct TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation_Params { + int32_t struct_size; + void* priv; + + int32_t num_inputs; + TpuSerializedProto tpu_embedding_config; + XLA_Shape* learning_rate_tuple_shape; + XLA_Shape* deduplication_data_shape; + XLA_Shape* gradient_tuple_shape; + TpuSerializedProto* op_sharding; + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation( + TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation_Params* params); + +typedef struct TpuEmbeddingEngine_DedupDataTupleMaskComputation_Params { + int32_t struct_size; + void* priv; + + TpuSerializedProto tpu_embedding_config; + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_DedupDataTupleMaskComputation_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_DedupDataTupleMaskComputation( + TpuEmbeddingEngine_DedupDataTupleMaskComputation_Params* params); + +typedef struct SparseCore_GetMaxIdsAndUniques_Params { + size_t struct_size; + void* priv; + const char* program_key; + const char* table_name; + int64_t num_samples_per_sparse_core; + int64_t feature_width; + // out + TF_Status* status; + int64_t max_ids_per_partition; + int64_t max_unique_ids_per_partition; +} SparseCore_GetMaxIdsAndUniques_Params; + +TFTPU_CAPI_EXPORT void SparseCore_GetMaxIdsAndUniques( + SparseCore_GetMaxIdsAndUniques_Params* params); + +struct TfTpu_OpsApiFn { + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_CompileAndBuild); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_XrtCompileAndBuild); + + TFTPU_ADD_FN_IN_STRUCT(TpuMeshState_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuMeshState_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuMeshState_MeshCommonState); + + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngineState_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngineState_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngineState_GetState); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_LoadProgramAndEnqueueToStream); + + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_HostShapeToDeviceShape); + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_ShapeSize); + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_ShapeSizeCompact); + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_ShapeSizeCompactRaw); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecute_RuntimeInputToPaddedData); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecute_GetTpuEmbeddingMemoryAllocations); + TFTPU_ADD_FN_IN_STRUCT(TpuExecute_FreeTpuEmbeddingMemoryAllocations); + + TFTPU_ADD_FN_IN_STRUCT(ConfigureDistributedTpuOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(WaitForDistributedTpuOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(InitializeHostForDistributedTpuOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(SetGlobalTPUArrayOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(DisconnectDistributedTpuChipsOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_FreeCharArray); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_FreeInt32Array); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_HasTPUPodState); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_TpusPerHost); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_TpuMemoryLimit); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_RemoteCompilationCacheSizeInBytes); + TFTPU_ADD_FN_IN_STRUCT( + TpuConfigurationApi_CompilationCacheServerAddressFromConfig); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_GetServerAddressAndPort); + + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_New); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_NewArray); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_FreeArray); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_UnloadAndDestroy); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetProgramSize); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_LogProgramMemorySummary); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetExecutableInfo); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetHostTransferInfo); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetHloMetadata); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetMayModifyVariables); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_HasSharding); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetTpuProgram); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_SerializeTpuExecutable); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_SerializeCompilerMetadata); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_DeserializeFromGetTpuProgramResponseProto); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetFingerprint); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_DestroyFingerprint); + + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_IsTpuCompilationEnabled); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_ShouldTpuCompileOpIgnoreCancellation); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_AvailableCoreCount); + TFTPU_ADD_FN_IN_STRUCT(TpuNetUtil_RecycleUnusedPort); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_CreateCompilationCacheKey); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_DestroyCompilationCacheKey); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_CreateGuaranteedConstFingerprint); + TFTPU_ADD_FN_IN_STRUCT(TpuUtil_GetTopologyPtr); + TFTPU_ADD_FN_IN_STRUCT(TpuUtil_GetXlaPadSizeFromTpuTopology); + + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_CloseTpuHost); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_Initialize); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_CompactionSupported); + + TFTPU_ADD_FN_IN_STRUCT(TfTpu_InitializeTpuModelServer); + + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_Create); + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_Destroy); + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_GetOrdinal); + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_DequeueFromCoreSelector); + TFTPU_ADD_FN_IN_STRUCT(TfTpu_GetTpuPartitionedCallParams); + + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ExecutePartitioner); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ConfigureMemory); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_CollateMemory); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ConfigureHost); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ConnectHosts); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_Finalize); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_IsInitialized); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_WriteParameters); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ReadParameters); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingTensorBatchFixedState_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingTensorBatchFixedState_Destroy); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_EnqueueTensorBatch); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_RecvActivationsComputation); + TFTPU_ADD_FN_IN_STRUCT( + TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation); + TFTPU_ADD_FN_IN_STRUCT( + TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_DedupDataTupleMaskComputation); + + TFTPU_ADD_FN_IN_STRUCT(SparseCore_GetMaxIdsAndUniques); +}; + +} // extern "C" + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_OPS_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_profiler_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_profiler_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..efb81d37acc14b5ac22f4147d11e4e4186dbdf08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/tpu/tpu_profiler_c_api.h @@ -0,0 +1,84 @@ +/* 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_STREAM_EXECUTOR_TPU_TPU_PROFILER_C_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_PROFILER_C_API_H_ + +#include + +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "xla/stream_executor/tpu/libtftpu.h" + +extern "C" { + +typedef struct TpuProfiler TpuProfiler; + +// Creates a TPU profiler that is ready to start profiling. +TFTPU_CAPI_EXPORT void TpuProfiler_Create(TpuProfiler** tpu_profiler, + TF_Status* status); +// Destroys the given TPU profiler. +TFTPU_CAPI_EXPORT void TpuProfiler_Destroy(TpuProfiler* tpu_profiler); +// Starts profiling if not already started, returns an error otherwise. +TFTPU_CAPI_EXPORT void TpuProfiler_Start(TpuProfiler* tpu_profiler, + TF_Status* status); +// Stops profiling if not already stopped, returns an error otherwise. +TFTPU_CAPI_EXPORT void TpuProfiler_Stop(TpuProfiler* tpu_profiler, + TF_Status* status); +// Serializes profiled data into `buffer` and returns the size of `buffer`. The +// profile data held by the TPU driver will be cleared after retrieval. +// +// Step 1. Query the size of buffer required into `size_in_bytes`. +// +// size_t size_in_bytes; +// TpuProfiler_CollectData(profiler, status, nullptr, &size_in_bytes); +// +// Step 2. Retrieve the data into a `buffer` of size `size_in_bytes`. +// Subsequently,The TPU driver clears its copy of the profile data. +// +// uint8_t buffer = new uint8_t[size_in_bytes]; +// TpuProfiler_CollectData(profiler, status, buffer, size_in_bytes); +// +// Step 3. Unpack the data into an XSpace. +// +// tensorflow::profiler::XSpace space; +// space.ParseFromArray(buffer, size_in_bytes); +// +TFTPU_CAPI_EXPORT void TpuProfiler_CollectData(TpuProfiler* tpu_profiler, + TF_Status* status, + uint8_t* buffer, + size_t* size_in_bytes); + +// Status helpers to create TFStatus for Profiler. +TF_Status* TpuStatus_New(); +void TpuStatus_Free(TF_Status* status); +const char* TpuStatus_Message(TF_Status* status); +int TpuStatus_Code(TF_Status* status); + +struct TfTpu_ProfilerApiFn { + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Destroy); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Start); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Stop); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_CollectData); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_New); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Message); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Code); +}; + +} // extern "C" + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_PROFILER_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/trace_listener.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/trace_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..5b1340dc7cfbb89f4b725f789e23db9a48e0d77c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/stream_executor/trace_listener.h @@ -0,0 +1,74 @@ +/* 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. +==============================================================================*/ + +// This file defines the StreamExecutor trace listener, used for inserting +// non-device-specific instrumentation into the StreamExecutor. +#ifndef XLA_STREAM_EXECUTOR_TRACE_LISTENER_H_ +#define XLA_STREAM_EXECUTOR_TRACE_LISTENER_H_ + +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "tsl/platform/status.h" + +namespace stream_executor { + +class Stream; + +// Traces StreamExecutor PIMPL-level events. +// The few StreamExecutor interfaces that are synchronous have both Begin and +// Complete versions of their trace calls. Asynchronous operations only have +// Submit calls, as execution of the underlying operations is device-specific. +// As all tracing calls mirror StreamExecutor routines, documentation here is +// minimal. +// +// All calls have default implementations that perform no work; subclasses +// should override functionality of interest. Keep in mind that these routines +// are not called on a dedicated thread, so callbacks should execute quickly. +// +// Note: This API is constructed on an as-needed basis. Users should add +// support for further StreamExecutor operations as required. By enforced +// convention (see SCOPED_TRACE in stream_executor_pimpl.cc), synchronous +// tracepoints should be named NameBegin and NameComplete. +class TraceListener { + public: + virtual ~TraceListener() {} + + virtual void LaunchSubmit(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, + const KernelBase& kernel, + const KernelArgsArrayBase& args) {} + + virtual void SynchronousMemcpyH2DBegin(int64_t correlation_id, + const void* host_src, int64_t size, + DeviceMemoryBase* gpu_dst) {} + virtual void SynchronousMemcpyH2DComplete(int64_t correlation_id, + const tsl::Status* result) {} + + virtual void SynchronousMemcpyD2HBegin(int64_t correlation_id, + const DeviceMemoryBase& gpu_src, + int64_t size, void* host_dst) {} + virtual void SynchronousMemcpyD2HComplete(int64_t correlation_id, + const tsl::Status* result) {} + + virtual void BlockHostUntilDoneBegin(int64_t correlation_id, Stream* stream) { + } + virtual void BlockHostUntilDoneComplete(int64_t correlation_id, + const tsl::Status* result) {} +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TRACE_LISTENER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/attribute_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/attribute_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..cd88cd95010e43805796fa47f6ceb08cefeadc17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/attribute_importer.h @@ -0,0 +1,79 @@ +/* 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_TRANSLATE_HLO_TO_MHLO_ATTRIBUTE_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_ATTRIBUTE_IMPORTER_H_ + +#include +#include + +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Converts an XLA PrecisionConfig to the corresponding MLIR attribute. +mlir::ArrayAttr ConvertPrecisionConfig(const PrecisionConfig* config, + mlir::Builder* builder); + +// Converts the gather dimensions to attributes. +mlir::mhlo::GatherDimensionNumbersAttr ConvertGatherDimensionNumbers( + const xla::GatherDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the scatter dimensions to attributes. +mlir::mhlo::ScatterDimensionNumbersAttr ConvertScatterDimensionNumbers( + const xla::ScatterDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the dot dimensions to attributes. +mlir::mhlo::DotDimensionNumbersAttr ConvertDotDimensionNumbers( + const DotDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the conv dimensions to attributes. +mlir::mhlo::ConvDimensionNumbersAttr ConvertConvDimensionNumbers( + const xla::ConvolutionDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the output operand aliasing to attributes. +mlir::ArrayAttr ConvertOutputOperandAliasing( + const std::vector>>& aliaInfo, + mlir::Builder* builder); + +StatusOr ConvertFftType(FftType type); +StatusOr ConvertTranspose( + TriangularSolveOptions_Transpose transpose); + +StatusOr ConvertCustomCallApiVersion( + xla::CustomCallApiVersion api_version); + +// Extracts layouts from shapes and converts it into layout attributes (array of +// rank-1 index tensors). Returns an error if any of the shapes is a tuple. +StatusOr ExtractLayoutsFromShapes( + const absl::Span shapes_with_layouts, mlir::Builder* builder); + +// Extracts the layouts of each element from a tuple shape and returns them as +// an array of rank-1 index tensors. Returns an error in presence of nested +// tuple shapes. +StatusOr ExtractLayoutsFromTuple(const xla::Shape shape, + mlir::Builder* builder); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_ATTRIBUTE_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_function_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_function_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..66794a4bf80480637a12005e9c2e71e6ad5c8e74 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_function_importer.h @@ -0,0 +1,301 @@ +/* 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_TRANSLATE_HLO_TO_MHLO_HLO_FUNCTION_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_FUNCTION_IMPORTER_H_ + +#include +#include + +#include "absl/types/optional.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/comparison_util.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/hlo.pb.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +class HloModule; +class HloComputation; +class HloInstruction; +class Shape; + +// HLO bounded dynamic shapes can be converted to either MLIR dynamic shapes +// (which lose the bound information) or casted to static shape using the +// bounds. +enum class DynamicShapeHandlingMode { kDynamic, kConvertToStatic }; + +// Helper class for importing HloComputations. +class HloFunctionImporter { + public: + // Imports the given computation as a function in the given symbol table and + // returns the FuncOp. This also imports any computations referred by + // instructions in this computation. + static StatusOr ImportAsFunc( + const xla::HloComputation& computation, mlir::SymbolTable& symbol_table, + std::unordered_map* + function_map, + mlir::Builder* builder, bool is_main); + + // Imports the given hlo computation to the specified region. If + // 'flatten_region_arg_tuple' is true, then flatten the tuple-typed region + // argument(s) and return value(s). + static Status ImportAsRegion(const xla::HloComputation& computation, + mlir::SymbolTable& symbol_table, + mlir::Region* region, mlir::Builder* builder, + bool flatten_region_arg_tuple = false); + + // Imports the given computation to the given place specified by `builder`. + // `arguments` contains values for all parameters. + static StatusOr ImportInstructions( + const xla::HloComputation& computation, + const llvm::SmallVectorImpl& arguments, + mlir::SymbolTable& symbol_table, mlir::OpBuilder* builder); + + static StatusOr ImportInstruction( + const xla::HloInstruction* instr, + const llvm::SmallVectorImpl& operands, + mlir::SymbolTable& symbol_table, mlir::OpBuilder* builder, + DynamicShapeHandlingMode mode = DynamicShapeHandlingMode::kDynamic); + + static void SetLayoutForMlir(mlir::Operation* op, const Shape& shape, + llvm::StringRef attr_name); + + // TODO(b/179166199): move this to attribute_importer.h. + // Converts XLA instruction source target pairs to MLIR attribute. + static mlir::NamedAttribute ConvertSourceTargetPairs( + const std::vector>& source_target_pairs, + mlir::Builder* builder); + + // TODO(b/179166199): move this to attribute_importer.h. + // Converts replica groups to attribute + static mlir::NamedAttribute ConvertReplicaGroups( + absl::Span replica_groups, mlir::Builder* builder); + + // For mlir::IfOp or mlir::CaseOp, replace the uses of their region's block + // arguments with 'implicit_operands'. Here | implicit_operands | == sum of + // the number of arguments in all the regions in IfOp or CaseOp. + void ReplaceBlockArgumentsWithImplicitOperands( + mlir::Operation* op, llvm::ArrayRef implicit_operands); + + // Create a TupleOp using the results of 'op' if 'type' is a mlir::TupleType. + // Otherwise, return 'op'. + mlir::Operation* CreateTupleFromOpResults(mlir::OpBuilder* func_builder, + mlir::Location loc, + mlir::Operation* op, + mlir::Type type); + + // FlattenTupleType flattens the types in (nested) tuple-type 'type' and + // stores them in 'types'. + static void FlattenTupleType( + mlir::Type type, llvm::SmallVectorImpl& flattened_types); + + // FlattenTupleValue flattens the values in (nested) tuple-typed 'value' and + // stores them in 'flattened_values'. + static void FlattenTupleValue( + mlir::OpBuilder* func_builder, mlir::Location loc, mlir::Value value, + llvm::SmallVectorImpl& flattened_values); + + // CreateTupleValue creates a root TupleOp of (nested) tuple-type 'type' using + // the non-tuple-typed values in 'flatten_values'. + // + // e.g., Given 'flatten_values': [V1, V2, V3] &'type': tuple>, + // The function returns %t2 such that: + // %t1 = mhlo.tuple(V2,V3) : (T2,T3) -> tuple + // %t2 = mhlo.tuple(V1,%t1): (T1,tuple) -> tuple> + // + // Note: 1. FlattenTupleValue and CreateTupleValue is a pair of functions to + // resp. flatten and create tuples in the exact same order. + // 2. `flatten_values`, initially storing the flattened values, will be + // mutated to a 0-length array by the end of function invocation. + static mlir::Value CreateTupleValue( + mlir::OpBuilder* func_builder, mlir::Location loc, + llvm::MutableArrayRef& flatten_values, mlir::Type type); + + private: + HloFunctionImporter(mlir::SymbolTable& symbol_table, + std::unordered_map* function_map, + mlir::Builder* builder) + : context_(symbol_table.getOp()->getContext()), + symbol_table_(symbol_table), + builder_(builder), + function_map_(function_map) { + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + } + + // Imports the given computation as a new function, if it hasn't been already + // imported. + StatusOr ImportAsFunc( + const xla::HloComputation& computation, bool is_main); + + // Imports the given computation in the specified region. + Status ImportAsRegion(const HloComputation& computation, mlir::Region* region, + bool flatten_region_arg_tuple = false); + + // Imports instructions from the given computation in the specified block. + // Assumes that the block already has correct arguments populated. + Status ImportInstructions(const HloComputation& computation, + mlir::Block* block, bool flatten_region_arg_tuple); + StatusOr ImportInstructionsImpl( + const xla::HloComputation& computation, + const llvm::SmallVectorImpl& arguments, + mlir::OpBuilder* builder); + + // Imports an instruction. + StatusOr ImportInstructionWithLayout( + const xla::HloInstruction* instruction, + const llvm::SmallVectorImpl& operands, + mlir::OpBuilder* func_builder, + DynamicShapeHandlingMode mode = DynamicShapeHandlingMode::kDynamic); + + StatusOr ImportInstructionImpl( + const HloInstruction* instruction, + const llvm::SmallVectorImpl& operands, + mlir::OpBuilder* func_builder, + DynamicShapeHandlingMode mode = DynamicShapeHandlingMode::kDynamic); + + // Gets the MLIR operand values from an HLO Instruction. + StatusOr> GetOperands( + const xla::HloInstruction* instruction); + + // Converts xla Tensor type to the corresponding MLIR type. + StatusOr ConvertTensorType(const xla::Shape& shape); + + // Converts an XLA shape/layout to the corresponding MLIR layout, in + // flattened_attr, while flattening the tuple layout. + Status ConvertShapeToMlirLayout( + const xla::Shape& shape, + llvm::SmallVectorImpl& flattened_attr); + + // Returns the output type of an HloInstruction. + StatusOr GetReturnType(const xla::HloInstruction* instruction); + + // Takes a list of HloInstructions and generates the list of types used for + // input, bypassing tuples to subsets. + Status GetMlirTypes(absl::Span instructions, + llvm::SmallVectorImpl* types); + + // Returns the Mlir Value for the corresponding HloInstruction. + StatusOr GetMlirValue(const xla::HloInstruction* instruction); + + // Converts an XLA ComparisonDirection to the corresponding MLIR attribute. + mlir::NamedAttribute ConvertComparisonDirection( + ComparisonDirection direction); + + // Converts an XLA Comparison::Type to the corresponding MLIR attribute. + mlir::NamedAttribute ConvertComparisonType(Comparison::Type type); + + // Converts an XLA CustomCallSchedule to the corresponding MLIR attribute. + mlir::NamedAttribute ConvertCustomCallSchedule( + xla::CustomCallSchedule schedule); + + // Converts the dimensions of an HLO instruction into an MLIR attribute. + mlir::DenseIntElementsAttr ConvertDimensions( + absl::Span op_dimensions); + + // Converts Array ref to an DenseIntElementsAttr. + mlir::DenseIntElementsAttr Convert(llvm::ArrayRef elements); + + // Converts Array ref of bools to a DenseIntElementsAttr of I1 type. + mlir::DenseIntElementsAttr Convert(llvm::ArrayRef elements); + + // Converts Array ref to padding attribute. Input is a flattened list of + // padding low and padding high for each of the spatial dimensions. + mlir::NamedAttribute ConvertPadding(llvm::ArrayRef padding); + + // Converts channel id to attribute + mlir::NamedAttribute ConvertChannelHandle(std::optional channel_id); + + // Convert use global device ids flag to attribute + mlir::NamedAttribute ConvertUseGlobalDeviceIds(); + + // Converts channel handle to attribute + mlir::NamedAttribute ConvertChannelHandle(const xla::ChannelHandle& channel); + + // ============ + // Imports an old-style async start op. E.g. an HLO all-gather-start + // instruction is imported as an async-start associated with an all-gather + // computation. + // + // Eventually, old-style async ops (e.g. all-gather-start) and new-style async + // ops (i.e. async-start, async-update and async-done) will converge on the + // HLO side, so we decided to not introduce new MHLO ops for all-gather-start + // and friends. + // + // In the end, there may be new ops added in the old-style because they're not + // compatible with the new-style async semantics, but those should be handled + // on their own, rather than this function which "upgrades" ops to the + // new-style async API. + // ============ + template + StatusOr ImportOldStyleAsyncStart( + llvm::SmallVectorImpl& attributes, + const llvm::SmallVectorImpl& operands, mlir::Location loc, + mlir::Type result_type, mlir::OpBuilder* func_builder, + std::string func_name, std::function mutate_op); + + // Imports an old-style async done op + StatusOr ImportOldStyleAsyncDone( + llvm::SmallVectorImpl& attributes, + const llvm::SmallVectorImpl& operands, mlir::Location loc, + mlir::Type result_type, mlir::OpBuilder* func_builder); + + mlir::MLIRContext* context_; + + // SymbolTable to which new functions should be inserted. + mlir::SymbolTable& symbol_table_; + + mlir::Builder* builder_; + + // Mapping from HloComputation to the created MLIR function. + std::unordered_map* + function_map_; + + // Mapping from HloInstructions to the associative MLIR values. + std::unordered_map + instruction_value_map_; +}; + +// Returns a StringAttr that carries a prettyprinted representation of the +// given HLO C++ sharding. +// Always succeeds and returns a non-empty attribute. +mlir::Attribute ConvertSharding(const xla::HloSharding& sharding, + mlir::Builder* builder); + +// Returns a StringAttr that carries a prettyprinted representation of the +// given HLO proto sharding. +// Will fail and return an empty attribute if the proto sharding cannot be +// converted to the C++ sharding. +mlir::Attribute ConvertSharding(const xla::OpSharding& sharding, + mlir::Builder* builder); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_FUNCTION_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_module_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_module_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..ac42e28f3f2123d946ce40d09011158a6dc72e20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_module_importer.h @@ -0,0 +1,67 @@ +/* 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_TRANSLATE_HLO_TO_MHLO_HLO_MODULE_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_MODULE_IMPORTER_H_ + +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/SymbolTable.h" // from @llvm-project +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/status.h" +#include "xla/xla_data.pb.h" + +namespace xla { +class HloModule; +class HloModuleProto; +class HloComputation; +class HloInstruction; +class Shape; + +// Importer that takes an HloModule and imports it as an MLIR module in the XLA +// dialect. HloModuleImporter does not take ownership. +class HloModuleImporter { + public: + explicit HloModuleImporter(mlir::ModuleOp module, + bool import_all_computation = false); + + // Import the HloModule into the MLIR Module. + Status Import(const xla::HloModule& module); + + // Import the HloModuleProto into the MLIR Module. + Status Import(const xla::HloModuleProto& module); + + private: + void ImportFrontendAttributes(const xla::HloModule& hlo_module, + mlir::ModuleOp module); + + bool import_all_computation_; + mlir::SymbolTable symbol_table_; + mlir::Builder builder_; + + // Map for tracking which MLIR function map to which HLO Computation. This + // tracks functions as they are imported and provides a quick lookup for + // functions invoked by control flow related operations (e.g. while, call). + std::unordered_map + function_map_; +}; + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_MODULE_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h new file mode 100644 index 0000000000000000000000000000000000000000..21b3c1589c0bd7384baa2262f66abb4b719fc320 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h @@ -0,0 +1,44 @@ +/* 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_TRANSLATE_HLO_TO_MHLO_HLO_TO_MLIR_HLO_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_TO_MLIR_HLO_H_ + +#include "xla/status.h" + +namespace mlir { +class ModuleOp; +} // namespace mlir + +namespace xla { +class HloModule; +class HloModuleProto; + +// Converts an HLO module proto to a MLIR module in HLO dialect. +// If import_all_computation is set to true, imports all computations +// irrespective if transitively called from entry computation. +Status ConvertHloToMlirHlo(mlir::ModuleOp module, + xla::HloModuleProto const* hlo_module, + bool import_all_computations = false); + +// Converts an HLO module to a MLIR module in HLO dialect. +// If import_all_computation is set to true, imports all computations +// irrespective if transitively called from entry computation. +Status ConvertHloToMlirHlo(mlir::ModuleOp module, xla::HloModule* hlo_module, + bool import_all_computations = false); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_TO_MLIR_HLO_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..42682a251385aeb82b97bb3f64378f1dfc377539 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/hlo_utils.h @@ -0,0 +1,174 @@ +/* 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 helpers useful when creating or manipulating lhlo/hlo. + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_HLO_UTILS_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_UTILS_H_ + +#include "llvm/ADT/STLExtras.h" +#include "mlir/Dialect/SparseTensor/IR/Enums.h" // from @llvm-project +#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/mlir_hlo/utils/convert_op_folder.h" +#include "xla/util.h" + +namespace xla { + +StatusOr CreateDenseElementsAttrFromLiteral( + const LiteralBase& literal, mlir::Builder builder); + +Status CopyDenseElementsDataToXlaFormat(mlir::DenseElementsAttr data, + std::vector* output); + +StatusOr GetElementTypeBytes(mlir::Type type); + +// Creates an DenseIntElementsAttr using the elements of the vector and the +// optional shape. +mlir::DenseIntElementsAttr CreateDenseIntElementsAttrFromVector( + const llvm::ArrayRef vector, mlir::Builder builder, + llvm::ArrayRef shape = {}); + +StatusOr ConvertPrimitiveTypeToMLIRType(PrimitiveType element_type, + mlir::Builder builder); + +mlir::mhlo::GatherDimensionNumbersAttr CreateGatherDimensionNumbers( + const GatherDimensionNumbers& input, mlir::Builder builder); + +// Converts the given XLA shape for tensors to the template MLIR type. +template +static StatusOr ConvertTensorShapeToType(const Shape& xla_ty, + mlir::Builder builder) { + auto element_type_or = + ConvertPrimitiveTypeToMLIRType(xla_ty.element_type(), builder); + if (!element_type_or.ok()) return element_type_or.status(); + + bool is_dynamic = false; + int64_t rank = xla_ty.rank(); + llvm::SmallVector shape(rank, mlir::ShapedType::kDynamic); + llvm::SmallVector bounds(rank, mlir::ShapedType::kDynamic); + for (int64_t dim = 0; dim < rank; ++dim) { + int64_t dim_size = xla_ty.dimensions(dim); + if (xla_ty.is_dynamic_dimension(dim)) { + bounds[dim] = dim_size; + is_dynamic = true; + } else { + shape[dim] = dim_size; + } + } + using mlir::mhlo::TypeExtensionsAttr; + mlir::Attribute encoding; + if (is_dynamic) { + encoding = TypeExtensionsAttr::get(builder.getContext(), bounds); + } + + using mlir::sparse_tensor::SparseTensorEncodingAttr; + // TODO(b/238903065): We don't yet support bounded dynamism shapes and + // sparsity at the same time, as we can currently only have one `encoding` on + // a RankedTensorType, and we don't currently have a meet of + // SparseTensorEncodingAttr and TypeExtensionsAttr (which holds bounds). + // + // For example, we wouldn't be able to represent the xla type + // `f32[4,<=4]{1,0:D(D,C)}`. + if (xla_ty.has_layout()) { + auto layout = xla_ty.layout(); + if (LayoutUtil::IsSparse(layout)) { + if (is_dynamic) + return Unimplemented( + "MHLO doesn't support bounded dynamic shapes for sparse tensors"); + llvm::SmallVector dlts; + for (size_t i = 0, e = layout.dim_level_types().size(); i < e; ++i) { + auto dlt = layout.dim_level_types()[i]; + bool ordered = + i < layout.dim_ordered().size() ? layout.dim_ordered()[i] : true; + bool unique = + i < layout.dim_unique().size() ? layout.dim_unique()[i] : true; + switch (dlt) { + case DimLevelType::DIM_DENSE: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::Dense, ordered, unique)); + break; + case DimLevelType::DIM_COMPRESSED: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::Compressed, ordered, unique)); + break; + case DimLevelType::DIM_SINGLETON: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::Singleton, ordered, unique)); + break; + case DimLevelType::DIM_LOOSE_COMPRESSED: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::LooseCompressed, ordered, + unique)); + break; + default: + return InvalidArgument("Unknown DimLevelType from HLO"); + } + } + auto ordering = layout.minor_to_major(); + llvm::SmallVector major_to_minor = {ordering.rbegin(), + ordering.rend()}; + auto id_map = mlir::AffineMap::getPermutationMap(major_to_minor, + builder.getContext()); + // TODO(atondwal): support sizes other than 32 when XLA does + encoding = SparseTensorEncodingAttr::get( + builder.getContext(), dlts, id_map, mlir::AffineMap(), 32, 32); + } + } + return TypeT::get(shape, element_type_or.value(), encoding); +} + +StatusOr ConvertTensorShapeToMemRefType( + const Shape& shape, mlir::Builder builder); + +template <> +inline StatusOr ConvertTensorShapeToType( + const Shape& shape, mlir::Builder builder) { + if (shape.is_dynamic()) { + return FailedPrecondition( // NOLINT + "MemRefType don't support dynamic shapes"); + } + return ConvertTensorShapeToMemRefType(shape, builder); +} + +// Converts the given XLA shape to the template MLIR type. +template +static StatusOr ConvertShapeToType(const Shape& shape, + mlir::Builder builder) { + if (shape.IsTuple()) { + llvm::SmallVector contents; + contents.reserve(shape.tuple_shapes_size()); + for (const auto& subtype : shape.tuple_shapes()) { + TF_ASSIGN_OR_RETURN(auto mlir_subtype, + ConvertShapeToType(subtype, builder)); + contents.push_back(mlir_subtype); + } + return builder.getTupleType(contents); + } + if (shape.IsToken()) { + return mlir::mhlo::TokenType::get(builder.getContext()); + } + return ConvertTensorShapeToType(shape, builder); +} + +::xla::StatusOr<::xla::HloOpcode> MhloToHloOpcode(mlir::Operation* op); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/location_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/location_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..1cfc4ab39bfde89d19fbcb28de3a4fc3b785d442 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/location_importer.h @@ -0,0 +1,33 @@ +/* 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_TRANSLATE_HLO_TO_MHLO_LOCATION_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_LOCATION_IMPORTER_H_ + +#include "mlir/IR/Location.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" + +namespace mlir { +namespace mhlo { + +// Returns an MLIR Location generated from HLO Instruction. Uses instruction +// metadata if present or instruction name. +mlir::Location GenerateInstructionLocation( + const xla::HloInstruction* instruction, mlir::MLIRContext* context); + +} // namespace mhlo +} // namespace mlir + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_LOCATION_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/stack_location_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/stack_location_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..298f651ad86531da732e9c0ab252d11f8c4cecde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/hlo_to_mhlo/stack_location_utils.h @@ -0,0 +1,34 @@ +/* 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_TRANSLATE_HLO_TO_MHLO_STACK_LOCATION_UTILS_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_STACK_LOCATION_UTILS_H_ + +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo.pb.h" + +namespace mlir { +namespace mhlo { +// Construct MLIR location from frame index. +// Returns unknown location if frame is not presented. +mlir::Location GetLocationFromFrameIndex(int frame_id, mlir::Builder &builder, + const xla::HloModule *hlo_module); + +} // namespace mhlo +} // namespace mlir + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_STACK_LOCATION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/attribute_exporter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/attribute_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..3d58247b6d631807c76dbb810eecb8535df18298 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/attribute_exporter.h @@ -0,0 +1,77 @@ +/* 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_TRANSLATE_MHLO_TO_HLO_ATTRIBUTE_EXPORTER_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_ATTRIBUTE_EXPORTER_H_ + +#include + +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Converts the conv dimensions attribute to XLA HLO. +ConvolutionDimensionNumbers ConvertConvDimensionNumbers( + mlir::mhlo::ConvDimensionNumbersAttr input); + +StatusOr ConvertConvActivationMode( + mlir::lmhlo_gpu::Activation input); + +StatusOr> ConvertReplicaGroups( + mlir::DenseIntElementsAttr input); + +// Convert a (N, 2) dense attribute to a list of tuples. This is the way padding +// and source-target pairs are defined in HLO. +StatusOr>> ConvertNx2Attribute( + std::optional optional_attr); + +StatusOr ConvertFftType(llvm::StringRef type_string); +StatusOr ConvertTranspose( + llvm::StringRef transpose_string); + +StatusOr ConvertCustomCallSchedule( + mlir::mhlo::CustomCallSchedule schedule); + +StatusOr ConvertCustomCallApiVersion( + mlir::mhlo::CustomCallApiVersion api_version); + +StatusOr>>> +ConvertOutputOperandAliasing(mlir::ArrayAttr aliasArrayAttr); + +// Returns an OpSharding that represents the result of parsing the given string: +// first, as serialized protobuf, and then as prettyprinted representation. +// Will fail if both attempts at parsing failed. +std::optional ConvertSharding(mlir::StringRef sharding); + +DotDimensionNumbers ConvertDotDimensionNumbers( + mlir::mhlo::DotDimensionNumbersAttr input); + +DotDimensionNumbers ConvertDotDimensionNumbers( + absl::Span lhs_batch, absl::Span lhs_contract, + absl::Span rhs_batch, + absl::Span rhs_contract); + +StatusOr> ConvertMlirArrayAttrToInt64Array( + const mlir::ArrayAttr& array); +} // namespace xla +#endif // XLA_TRANSLATE_MHLO_TO_HLO_ATTRIBUTE_EXPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/layout_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/layout_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f8f175ba282c476251b8c1d7873897fd0fcc2937 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/layout_util.h @@ -0,0 +1,84 @@ +/* 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 working with XLA layout and shapes. + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_LAYOUT_UTIL_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_LAYOUT_UTIL_H_ + +#include +#include + +#include "xla/client/xla_builder.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace mlir { + +// XLA Layout preferences. Currently, when it comes to TPU, there are two +// primary layout choices for any XLA argumetns (parameter or resource): (1) +// CompactChunkPadded and (2) Linear. CompactChunkPadded is the native TPU +// layout while Linear is native host (CPU) layout. +// This enum allows the caller of XLA to progogate layout preference to the XLA +// compiler. +// kNoPreference: the generic layout where the XLA compiler has the freedom +// to assign any layout. +// kTpuPreferCompactChunkPaddedLayout: use native TPU layout on TPU. +// kTpuPreferLinearLayout: use native CPU layout on TPU. The compiler may +// insert transformation TPU kernels. +// As the layout of any argument will change from a native host layout to a +// native TPU layout either on host or on device, XLA compiler and TPU runtime +// must be in coordination to transform the parameters in a consistent way. +enum class XlaLayoutPreference { + kNoPreference = 0, + kTpuPreferCompactChunkPaddedLayout = 1, + kTpuPreferLinearLayout = 2 +}; + +// The following defines the layout preference of an xla tensor. +// The return value of LayoutPreferenceFn can be used in +// ShapeRepresentationFn. +typedef std::function( + const xla::Shape& shape)> + LayoutPreferenceFn; + +typedef std::function( + const xla::Shape& shape, bool fast_mem, + XlaLayoutPreference layout_preference)> + ShapeRepresentationFn; + +// Return a LayoutPreferenceFn that always uses kNoPreference layout. +LayoutPreferenceFn UseNoPreferenceLayoutFn(); + +// Rewrites the layout of xla_shape if there is tiled sharding. +xla::Status RewriteLayoutWithShardedShape( + const std::optional& sharding, bool use_fast_memory, + const LayoutPreferenceFn& layout_preference_fn, + const ShapeRepresentationFn& shape_representation_fn, + xla::Shape* xla_shape); + +// Adds reshapes to fix the layout of an output, if a shape_representation_fn or +// sharding is present. +xla::StatusOr ReshapeWithCorrectRepresentationAndSharding( + xla::XlaBuilder* builder, xla::XlaOp original, xla::Shape original_shape, + const LayoutPreferenceFn& layout_preference_fn, + const ShapeRepresentationFn& shape_representation_fn, + std::optional sharding, bool fast_mem); + +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_LAYOUT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/location_exporter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/location_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..69efa6dbc4f477d705b34f9b2a581cc55237cfd3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/location_exporter.h @@ -0,0 +1,44 @@ +/* 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_TRANSLATE_MHLO_TO_HLO_LOCATION_EXPORTER_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_LOCATION_EXPORTER_H_ + +#include + +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "xla/translate/mhlo_to_hlo/stack_frame_index_builder.h" +#include "xla/xla_data.pb.h" + +namespace mlir { +namespace mhlo { + +// Returns a OpMetadata proto based on the location of the op. If the location +// is unknown, an empty proto is returned. `op_name` are populated with the op +// location (converted). FileLineColLoc locations are populated by taking the +// file name and line number, and populating `source_file` and `source_line` +// respectively. +xla::OpMetadata CreateOpMetadataFromLocation( + Operation* op, StackFrameIndexBuilder* frame_index_builder); + +// Returns a name that can be used for debugging purposes, e.g., naming +// variable names in generated IR or producing logging output. +std::string GetDebugNameFromLocation(Location location); + +} // namespace mhlo +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_LOCATION_EXPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h new file mode 100644 index 0000000000000000000000000000000000000000..5cbdfdd398dabc4e46fe51d67d55bf45f874d773 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.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_TRANSLATE_MHLO_TO_HLO_MLIR_HLO_TO_HLO_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_MLIR_HLO_TO_HLO_H_ + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "xla/client/xla_builder.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/translate/mhlo_to_hlo/layout_util.h" + +namespace mlir { + +struct MlirToHloConversionOptions { + // Best-effort propagation of the layouts. These layouts serve as performance + // hints to the backend. + // + // Note that non-array shapes are not carrying layouts, and users have to + // figure out the proper layouts of them through context. This is one of the + // reasons why the attribute-based solution is temporary. + // + // TODO(timshen): Investigate the necessity of having layouts in MHLO. + bool propagate_layouts = false; + + // Propagate the source and result layouts from mhlo bitcast op into the + // backend config for the bitcast. This is required for XLA:GPU backend to + // use elemental IR emitters for fused bitcasts without propagating layouts. + bool propagate_bitcast_layouts_to_backend_config = false; + + LayoutPreferenceFn layout_preference_fn; + ShapeRepresentationFn shape_representation_fn; +}; + +// Converts a MLIR module in HLO dialect into a HloModuleProto. If +// use_tuple_args is set, then the entry computations's arguments are converted +// to a tuple and passed as a single parameter. +// Similarly, if return tuple is true, then the entry function's return values +// are converted to a tuple even when there is only a single return value. +// Multiple return values are always converted to a tuple and returned as a +// single value. +xla::Status ConvertMlirHloToHlo(mlir::ModuleOp module, + ::xla::HloProto* hlo_proto, bool use_tuple_args, + bool return_tuple, + MlirToHloConversionOptions options = {}); + +// Transforms a Block into HLO, where the HLO is represented as calls into an +// XlaBuilder. Callee functions are allowed in the Block's ancestor ModuleOp. +// xla_params are inputs to block. returns are the returned XlaOps. +xla::Status BuildHloFromMlirHlo(mlir::Block& block, xla::XlaBuilder& builder, + llvm::ArrayRef xla_params, + std::vector& returns, + MlirToHloConversionOptions options = {}); + +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_MLIR_HLO_TO_HLO_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..804795eb83f62e5725a863076646136749820df6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h @@ -0,0 +1,48 @@ +/* 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_TRANSLATE_MHLO_TO_HLO_STACK_FRAME_INDEX_BUILDER_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_STACK_FRAME_INDEX_BUILDER_H_ + +#include +#include +#include + +#include "mlir/IR/Location.h" // from @llvm-project +#include "xla/service/hlo.pb.h" + +namespace mlir { +class StackFrameIndexBuilder { + public: + constexpr static int kInvalidIndex = 0; + + xla::StackFrameIndexProto Build() const; + + int AddCallStackAndGetFirstFrameId(const mlir::Location &root_loc); + + private: + int AddStackFrameLocation(const mlir::NameLoc &name_location, + int parent_frame_id); + + xla::StackFrameIndexProto indexes_; + + std::map function_name_to_id_; + std::map file_name_to_id_; + std::map, int> file_location_to_id_; + std::map, int> frame_to_id_; +}; +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_STACK_FRAME_INDEX_BUILDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/type_to_shape.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/type_to_shape.h new file mode 100644 index 0000000000000000000000000000000000000000..39bfb6c5b409185a0a3a198f1c8052b99d97573c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_hlo/type_to_shape.h @@ -0,0 +1,35 @@ +/* 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_TRANSLATE_MHLO_TO_HLO_TYPE_TO_SHAPE_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_TYPE_TO_SHAPE_H_ + +#include "llvm/ADT/STLExtras.h" +#include "mlir/IR/Types.h" // from @llvm-project +#include "xla/shape.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Returns a XLA Shape equivalent of a MLIR Type, else returns empty shape. +Shape TypeToShape(mlir::Type type); + +// Returns a XLA PrimitiveType equivalent of a MLIR Type that represents a +// primitive type (e.g., i8, f32), else returns PRIMITIVE_TYPE_INVALID. +PrimitiveType TypeToPrimitiveType(mlir::Type type); + +} // namespace xla + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_TYPE_TO_SHAPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h new file mode 100644 index 0000000000000000000000000000000000000000..c355cb132fa63d0af79cc3e5fedc5de0f226bc61 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h @@ -0,0 +1,337 @@ +/* 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_TRANSLATE_MHLO_TO_LHLO_WITH_XLA_MHLO_TO_LHLO_WITH_XLA_H_ +#define XLA_TRANSLATE_MHLO_TO_LHLO_WITH_XLA_MHLO_TO_LHLO_WITH_XLA_H_ + +#include +#include +#include +#include + +#include "absl/types/optional.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/service/buffer_assignment.h" +#include "xla/shape_util.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace mlir { + +// This class will process an HloModule with the supplied BufferAssignment and +// populate the MLIR ModuleOp with the computation converted in the LHLO +// dialect. +class LhloDialectEmitter : public xla::ConstDfsHloVisitorWithDefault { + public: + // Initializes internal data structures. It must be called before calling any + // of the visitors. + tsl::Status Initialize(); + + LhloDialectEmitter(const xla::BufferAssignment& assignment, + const xla::HloComputation& computation, ModuleOp module) + : assignment_(assignment), + computation_(computation), + module_(module), + symbol_table_(module), + builder_(module.getContext()), + i8_type_(builder_.getIntegerType(8)) {} + + tsl::StatusOr EmitOp(const xla::HloInstruction* instr); + + static tsl::StatusOr + GetScatterDimensionNumbers(const xla::HloInstruction* instr, + mlir::MLIRContext* context); + + absl::flat_hash_map + ConsumeLhloToHloMap() { + return std::move(lhlo_to_hlo_); + } + + private: + tsl::StatusOr EmitSortOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitFusionOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitScatterOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitSelectAndScatterOp( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitCustomCallOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitCholesky( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitGemm( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitCublasLtMatmul( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitCublasLtMatmulF8( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitDnnConvolution( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitDnnConvolutionReorderVectorized( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitDnnBatchNorm( + const xla::HloCustomCallInstruction* custom_call); + xla::StatusOr EmitDnnfMHA( + const xla::HloCustomCallInstruction* custom_call); + xla::StatusOr EmitDnnfMHABackward( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitConstant( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitInfeedOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitOutfeedOp( + const xla::HloInstruction* instr); + + template + tsl::StatusOr EmitDoneOp(const xla::HloInstruction* instr); + + tsl::StatusOr EmitAllToAllStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllToAllDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllGatherStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllGatherDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllReduceStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllReduceDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAsyncStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAsyncDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitReduceScatterStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitReduceScatterDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr + EmitCollectivePermuteStartOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitCollectivePermuteDoneOp( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitRngGetAndUpdateStateOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitFftOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitTriangularSolveOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitBitcast(const xla::HloInstruction* instr); + + tsl::StatusOr EmitCaseOp(const xla::HloInstruction* instr); + + tsl::StatusOr EmitWhileOp(const xla::HloInstruction* instr); + + tsl::StatusOr EmitSendOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitSendDoneOp( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitRecvOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitRecvDoneOp( + const xla::HloInstruction* instr); + + tsl::Status ImportAsLmhloRegion(xla::HloComputation* computation, + mlir::Region* region); + + // Since LMHLO dialect does not define token types, this enum controls how + // token operand/results from XLA:HLO are lowered to MLIR. + enum class TokenLoweringMode { + kFailToLower, // Fail lowering if token inputs are encountered. + kUseNull, // Use a null Value in the operand list for each token. + // kSkip, // Skip any token inputs or outputs (not yet needed) + }; + + // Create LHLO operation operands given an XLA HLO instruction. By default, + // all XLA HLO operands and results are converted to MLIR and appended to + // `operands`. If `num_operands` is specified, only the first `num_operand` + // operands of the instruction are converted to MLIR. The function returns the + // actual number of operands and results generated for MLIR in `num_arguments` + // and `num_results`. + tsl::Status CreateOperands(const xla::HloInstruction* instr, + std::optional num_operands, + TokenLoweringMode token_mode, + SmallVectorImpl& operands, + size_t& num_arguments, size_t& num_results); + + template + tsl::StatusOr CreateOpWithoutAttrs( + const xla::HloInstruction* instr, + std::optional num_operands = std::nullopt) { + size_t unused; + return CreateOpWithoutAttrs(instr, unused, unused, num_operands); + } + + template + tsl::StatusOr CreateOpWithoutAttrs( + const xla::HloInstruction* instr, size_t& num_arguments, + size_t& num_results, std::optional num_operands = std::nullopt); + + template + OpType CreateOpWithoutAttrs(const xla::HloInstruction* instr, + ValueRange operands); + + template + DenseIntElementsAttr GetI64DenseElementsAttr(const T& container) { + return builder_.getI64TensorAttr( + {container.data(), static_cast(container.size())}); + } + + DenseIntElementsAttr GetWindowElements( + const xla::Window& window, + std::function getter) { + llvm::SmallVector elements; + elements.reserve(window.dimensions_size()); + for (const xla::WindowDimension& dim : window.dimensions()) { + elements.push_back(getter(dim)); + } + return GetI64DenseElementsAttr(elements); + } + + static mlir::DenseIntElementsAttr GetLayoutAttribute( + const xla::Layout& layout, Builder* builder); + + tsl::Status DefaultAction(const xla::HloInstruction* instr) final; + + // Computation parameters don't need any specific handling when they are + // visited, they are already processed when we enter a new computation. + tsl::Status HandleParameter(const xla::HloInstruction* instr) final { + return ::tsl::OkStatus(); + } + + // Helper function that recursively visits the tuple structure in + // `current_shape`, and reconstruct a matching lmhlo::TupleOp. + // Each leaf node is converted to an std.view op with corresponding offsets. + // If no tuple presents, it simply returns a view of the buffer. + tsl::Status GetOrCreateViewImpl(const xla::HloInstruction* instr, + const xla::Shape& current_shape, + xla::ShapeIndex* current_shape_index, + SmallVectorImpl* values, + TokenLoweringMode token_mode); + + // Helper function to create view/tuple of views to a buffer for a given + // instruction result. `result_subset` can be used to for instructions that + // have a tuple result and MLIR conversion needs to convert only one of the + // tuple elements. Note that if needed, this can be extended to take a list of + // ShapeIndex values in case we need finer control on what elements of the + // output tuple to be converted to MLIR. + tsl::Status GetOrCreateView( + const xla::HloInstruction* instr, SmallVectorImpl* values, + const xla::ShapeIndex& result_subset = {}, + TokenLoweringMode token_mode = TokenLoweringMode::kFailToLower); + + tsl::StatusOr GetOrCreateArrayView( + const xla::HloInstruction* instr, const xla::Shape& current_shape, + const xla::ShapeIndex& current_shape_index); + + tsl::StatusOr RewriteFusionOperand(const xla::HloInstruction* root, + const xla::Shape& shape, + xla::ShapeIndex* shape_index, + OpBuilder* b, Location loc); + + // Return an MLIR location for an HLO instruction. + Location getLocation(const xla::HloInstruction* inst) { + return NameLoc::get(builder_.getStringAttr(inst->name())); + } + + // This map provides access to MLIR buffers for each HLO buffer allocation. + // The MLIR buffers are all `memref<{size}xi8>` and correspond to function + // parameters. It is populated at the beginning of the processing with all + // the buffer allocations and is unchanged afterward. Every HLOInstruction + // is using a "slice" of the buffer allocation and providing shape, layout, + // and Dtype. An MLIR view is used separately to model slices into the + // allocations (see below). + llvm::DenseMap allocations_; + + // This map provides access to MLIR buffers constructed from memref arguments + // (allocations) using memref.view operation at the given offset (defined by + // slice) and result type (defined by shape). By using this cache we guarantee + // that we have a unique memref.view operation corresponding to each + // allocation slice. + absl::flat_hash_map, + Value> + allocation_slices_; + + // This map provides access to MLIR buffers for each HLO instruction, keyed + // instruction identity. A slice is contained in a BufferAllocation, and has + // an offset and a size. + // + // As for why we don't use HloInstruction*, see GetOrCreateView(), but + // mostly we want to leverage better of the aliased buffers. + // + // If the HloInstruction is a tuple, all leaf nodes are stored flattened. + // Otherwise, there will be a single buffer. + // + // An MLIR buffer is either an input parameter, or a ViewOp in the case + // where the slice is only part of its allocation. + // + // `instr_slices_` is populated lazily in the `GetOrCreateView()` helper as we + // process every instruction. + absl::flat_hash_map, + Value> + instr_slices_; + + // The BufferAssignment computed by XLA ahead of time. + const xla::BufferAssignment& assignment_; + + // The HLO module that will be converted. + const xla::HloComputation& computation_; + + // This is the MLIR module in which a function will be created for every HLO + // computation. + ModuleOp module_; + + // SymbolTable associated with the module. New functions should be added using + // this to avoid name conflicts. + mlir::SymbolTable symbol_table_; + + // The builder keeps track of the current insertion point in the MLIR + // module. + OpBuilder builder_; + // Convenient "cached" access to this widely used MLIR type (i8). + Type i8_type_; + + // Map ops returning tokens to their output (async collectives start ops, and + // point-to-point communication ops), to connect the correct done op. + absl::flat_hash_map ret_tokens_; + + // Maps each LHLO op created directly by this emitter to the corresponding HLO + // instruction. + // Note: this does not contain ops that are inside the bodies of fusions. + absl::flat_hash_map + lhlo_to_hlo_; +}; + +// Populate the MLIR `module` with the computation from the `hlo_module` using +// the provided buffer `assignment`. The returned `Status` indicates success +// or failure in the conversion. +// `lhlo_to_hlo_map`, if non-null, is populated with a mapping from generated +// top-level MLIR operations to the original HLO instructions. "top-level" means +// that ops inside the bodies of fusions are not included (but all fusions are). +tsl::Status HloToLhloModule( + const xla::BufferAssignment& assignment, const xla::HloModule& hlo_module, + ModuleOp module, + absl::flat_hash_map* + lhlo_to_hlo_map = nullptr); + +OwningOpRef HloTextToLhloTranslateFunction( + llvm::StringRef input, MLIRContext* context); + +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_LHLO_WITH_XLA_MHLO_TO_LHLO_WITH_XLA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391