diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_autotune_maps.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_autotune_maps.h new file mode 100644 index 0000000000000000000000000000000000000000..7c00348adfe1bafa548540bbd4314445dab99dfd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_autotune_maps.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. +==============================================================================*/ + +// For Google-internal use only. +// +// This file defines the map data structure for storing autotuning results for +// fused_conv2d_bias_activation_op_kernels. +// +// The key of the map uniquely identifies a convolution operation that runs on a +// particular device model while the value might be the autotuned algorithm we +// choose for the conv. +// +// This map will be merged after fused_conv2d_bias_activation_op_kernels is +// merged into conv_ops_fused_impl.h (b/177365158, b/189530096) + +#ifndef TENSORFLOW_CORE_UTIL_AUTOTUNE_MAPS_CONV_AUTOTUNE_MAPS_H_ +#define TENSORFLOW_CORE_UTIL_AUTOTUNE_MAPS_CONV_AUTOTUNE_MAPS_H_ + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include + +#include "tensorflow/core/kernels/gpu_utils.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/util/autotune_maps/conv_parameters.h" + +namespace tensorflow { + +// A dummy type to group forward convolution autotune results together. +struct ConvAutotuneGroup { + static string name() { return "Conv"; } +}; + +using ConvAutotuneMap = AutotuneSingleton>; + +// A dummy type to group fused convolution autotune results together. +struct ConvFusedAutotuneGroup { + static string name() { return "FusedConv"; } +}; + +using FusedConvAutotuneMap = + AutotuneSingleton>; + +} // namespace tensorflow +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +#endif // TENSORFLOW_CORE_UTIL_AUTOTUNE_MAPS_CONV_AUTOTUNE_MAPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.h new file mode 100644 index 0000000000000000000000000000000000000000..6658fa6e21c9cb65293ed5a702b305341bf34547 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.h @@ -0,0 +1,137 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_AUTOTUNE_MAPS_CONV_PARAMETERS_H_ +#define TENSORFLOW_CORE_UTIL_AUTOTUNE_MAPS_CONV_PARAMETERS_H_ + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "absl/types/optional.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/util/autotune_maps/conv_parameters.pb.h" + +namespace tensorflow { +// Uniquely identifies a convolution operation that runs on a particular device +// model. +// +// This can serve as a hashtable key, where the value might be the autotuned +// algorithm we choose for the conv. +// +// All of the data in this class other than the device_id is stored in the +// ConvParametersProto, so it can be easily serialized (for the purposes of +// ahead-of-time autotuning). +// +// When using the cudnn frontend API, two autotuning results for two different +// GPUs of the same model are not interchangeable, because an autotuning result +// includes a cudnn execution plan, which is tied to the GPU. As a result, we +// need to create separate ConvParameters objects for them. +class ConvParameters { + public: + struct FusionInfo { + // For some implementations (e.g. cuDNN new backend) these scales are part + // of the algorithm, not part of the parameters an algorithm take. They need + // to be used to distinguish different algorithms. + double conv_scale; + double side_input_scale; + double leakyrelu_alpha; + stream_executor::dnn::ActivationMode activation_mode; + bool is_contrib; + }; + + // LINT.IfChange(conv_parameters_version) + // A positive number that denotes the version of this class. Should be + // incremented everytime this class or ConvParametersProto are updated in a + // way that may invalidate autotune results. + static constexpr int kVersion = 3; + // LINT.ThenChange() + + // We have three kinds of convolutions today. Vanilla unfused convolutions, + // fused convolutions, and fused convolutions as implemented in the `contrib` + // directory. The two fused convolutions ultimately correspond to the same + // cudnn calls, but have slightly different semantics (e.g. they interpret + // padding differently). + ConvParameters( + se::StreamExecutor* stream_exec, int64_t batch, int64_t in_depths, + absl::Span in, int data_format, int64_t out_depths, + absl::Span filter, absl::Span dilation, + absl::Span stride, absl::Span padding, + DataType dtype, int group_count, + absl::optional fusion_info = absl::optional(), + // This argument should be set only for test use. + int version = kVersion); + + ConvParameters(int device_id, const ConvParametersProto& proto); + + ConvParameters(se::StreamExecutor* stream_exec, + const ConvParametersProto& proto) + : ConvParameters(stream_exec->device_ordinal(), proto) {} + + bool operator==(const ConvParameters& other) const; + + bool operator!=(const ConvParameters& other) const { + return !(*this == other); + } + uint64 hash() const { return hash_code_; } + + string ToString() const; + + const ConvParametersProto& proto() const { return proto_; } + + private: + int device_id_; + ConvParametersProto proto_; + uint64 hash_code_; +}; + +class MatmulParameters { + public: + // LINT.IfChange(matmul_parameters_version) + // A positive number that denotes the version of this class. Should be + // incremented everytime this class or ConvParametersProto are updated in a + // way that may invalidate autotune results. + static constexpr int kVersion = 2; + // LINT.ThenChange() + + MatmulParameters(se::StreamExecutor* stream_exec, DataType ab_dtype, + DataType c_dtype, bool trans_a, bool trans_b, uint64_t m, + uint64_t n, uint64_t k, int64_t lda, int64_t ldb, + int64_t ldc, + stream_executor::dnn::ActivationMode activation_mode, + // This argument should be set only for test use. + int version = kVersion); + + MatmulParameters(se::StreamExecutor* stream_exec, + const MatmulParametersProto& proto); + + bool operator==(const MatmulParameters& other) const; + + bool operator!=(const MatmulParameters& other) const { + return !(*this == other); + } + uint64 hash() const { return hash_code_; } + + string ToString() const; + + const MatmulParametersProto& proto() const { return proto_; } + + private: + int device_id_; + MatmulParametersProto proto_; + uint64 hash_code_; +}; + +} // namespace tensorflow +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +#endif // TENSORFLOW_CORE_UTIL_AUTOTUNE_MAPS_CONV_PARAMETERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..56271e1c425450d8cfd84b33246cc36b73b8f02e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/autotune_maps/conv_parameters.pb.h @@ -0,0 +1,1829 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/util/autotune_maps/conv_parameters.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_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 "tensorflow/core/framework/types.pb.h" +#include "tsl/protobuf/dnn.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto; +namespace tensorflow { +class ConvParametersProto; +struct ConvParametersProtoDefaultTypeInternal; +extern ConvParametersProtoDefaultTypeInternal _ConvParametersProto_default_instance_; +class ConvParametersProto_Fusion; +struct ConvParametersProto_FusionDefaultTypeInternal; +extern ConvParametersProto_FusionDefaultTypeInternal _ConvParametersProto_Fusion_default_instance_; +class MatmulParametersProto; +struct MatmulParametersProtoDefaultTypeInternal; +extern MatmulParametersProtoDefaultTypeInternal _MatmulParametersProto_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::ConvParametersProto* Arena::CreateMaybeMessage<::tensorflow::ConvParametersProto>(Arena*); +template<> ::tensorflow::ConvParametersProto_Fusion* Arena::CreateMaybeMessage<::tensorflow::ConvParametersProto_Fusion>(Arena*); +template<> ::tensorflow::MatmulParametersProto* Arena::CreateMaybeMessage<::tensorflow::MatmulParametersProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class ConvParametersProto_Fusion final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ConvParametersProto.Fusion) */ { + public: + inline ConvParametersProto_Fusion() : ConvParametersProto_Fusion(nullptr) {} + ~ConvParametersProto_Fusion() override; + explicit PROTOBUF_CONSTEXPR ConvParametersProto_Fusion(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ConvParametersProto_Fusion(const ConvParametersProto_Fusion& from); + ConvParametersProto_Fusion(ConvParametersProto_Fusion&& from) noexcept + : ConvParametersProto_Fusion() { + *this = ::std::move(from); + } + + inline ConvParametersProto_Fusion& operator=(const ConvParametersProto_Fusion& from) { + CopyFrom(from); + return *this; + } + inline ConvParametersProto_Fusion& operator=(ConvParametersProto_Fusion&& 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 ConvParametersProto_Fusion& default_instance() { + return *internal_default_instance(); + } + static inline const ConvParametersProto_Fusion* internal_default_instance() { + return reinterpret_cast( + &_ConvParametersProto_Fusion_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(ConvParametersProto_Fusion& a, ConvParametersProto_Fusion& b) { + a.Swap(&b); + } + inline void Swap(ConvParametersProto_Fusion* 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(ConvParametersProto_Fusion* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ConvParametersProto_Fusion* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ConvParametersProto_Fusion& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ConvParametersProto_Fusion& from) { + ConvParametersProto_Fusion::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(ConvParametersProto_Fusion* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ConvParametersProto.Fusion"; + } + protected: + explicit ConvParametersProto_Fusion(::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 { + kIsContribFieldNumber = 1, + kActivationModeFieldNumber = 2, + kConvScaleFieldNumber = 3, + kSideInputScaleFieldNumber = 4, + }; + // bool is_contrib = 1; + void clear_is_contrib(); + bool is_contrib() const; + void set_is_contrib(bool value); + private: + bool _internal_is_contrib() const; + void _internal_set_is_contrib(bool value); + public: + + // .stream_executor.dnn.ActivationMode activation_mode = 2; + 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: + + // double conv_scale = 3; + void clear_conv_scale(); + double conv_scale() const; + void set_conv_scale(double value); + private: + double _internal_conv_scale() const; + void _internal_set_conv_scale(double value); + public: + + // double side_input_scale = 4; + 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: + + // @@protoc_insertion_point(class_scope:tensorflow.ConvParametersProto.Fusion) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + bool is_contrib_; + int activation_mode_; + double conv_scale_; + double side_input_scale_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto; +}; +// ------------------------------------------------------------------- + +class ConvParametersProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ConvParametersProto) */ { + public: + inline ConvParametersProto() : ConvParametersProto(nullptr) {} + ~ConvParametersProto() override; + explicit PROTOBUF_CONSTEXPR ConvParametersProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ConvParametersProto(const ConvParametersProto& from); + ConvParametersProto(ConvParametersProto&& from) noexcept + : ConvParametersProto() { + *this = ::std::move(from); + } + + inline ConvParametersProto& operator=(const ConvParametersProto& from) { + CopyFrom(from); + return *this; + } + inline ConvParametersProto& operator=(ConvParametersProto&& 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 ConvParametersProto& default_instance() { + return *internal_default_instance(); + } + static inline const ConvParametersProto* internal_default_instance() { + return reinterpret_cast( + &_ConvParametersProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(ConvParametersProto& a, ConvParametersProto& b) { + a.Swap(&b); + } + inline void Swap(ConvParametersProto* 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(ConvParametersProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ConvParametersProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ConvParametersProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ConvParametersProto& from) { + ConvParametersProto::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(ConvParametersProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ConvParametersProto"; + } + protected: + explicit ConvParametersProto(::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 ConvParametersProto_Fusion Fusion; + + // accessors ------------------------------------------------------- + + enum : int { + kInFieldNumber = 4, + kFilterFieldNumber = 6, + kDilationFieldNumber = 7, + kStrideFieldNumber = 8, + kPaddingFieldNumber = 9, + kDeviceIdentifierFieldNumber = 12, + kFusionFieldNumber = 13, + kBatchFieldNumber = 1, + kInDepthsFieldNumber = 2, + kOutDepthsFieldNumber = 3, + kDataFormatFieldNumber = 5, + kDtypeFieldNumber = 10, + kGroupCountFieldNumber = 11, + kVersionFieldNumber = 14, + }; + // repeated int64 in = 4; + int in_size() const; + private: + int _internal_in_size() const; + public: + void clear_in(); + private: + int64_t _internal_in(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_in() const; + void _internal_add_in(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_in(); + public: + int64_t in(int index) const; + void set_in(int index, int64_t value); + void add_in(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + in() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_in(); + + // repeated int64 filter = 6; + int filter_size() const; + private: + int _internal_filter_size() const; + public: + void clear_filter(); + private: + int64_t _internal_filter(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_filter() const; + void _internal_add_filter(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_filter(); + public: + int64_t filter(int index) const; + void set_filter(int index, int64_t value); + void add_filter(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + filter() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_filter(); + + // repeated int64 dilation = 7; + int dilation_size() const; + private: + int _internal_dilation_size() const; + public: + void clear_dilation(); + private: + int64_t _internal_dilation(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_dilation() const; + void _internal_add_dilation(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_dilation(); + public: + int64_t dilation(int index) const; + void set_dilation(int index, int64_t value); + void add_dilation(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + dilation() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_dilation(); + + // repeated int64 stride = 8; + int stride_size() const; + private: + int _internal_stride_size() const; + public: + void clear_stride(); + private: + int64_t _internal_stride(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_stride() const; + void _internal_add_stride(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_stride(); + public: + int64_t stride(int index) const; + void set_stride(int index, int64_t value); + void add_stride(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + stride() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_stride(); + + // repeated int64 padding = 9; + int padding_size() const; + private: + int _internal_padding_size() const; + public: + void clear_padding(); + private: + int64_t _internal_padding(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_padding() const; + void _internal_add_padding(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_padding(); + public: + int64_t padding(int index) const; + void set_padding(int index, int64_t value); + void add_padding(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + padding() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_padding(); + + // string device_identifier = 12; + void clear_device_identifier(); + const std::string& device_identifier() const; + template + void set_device_identifier(ArgT0&& arg0, ArgT... args); + std::string* mutable_device_identifier(); + PROTOBUF_NODISCARD std::string* release_device_identifier(); + void set_allocated_device_identifier(std::string* device_identifier); + private: + const std::string& _internal_device_identifier() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device_identifier(const std::string& value); + std::string* _internal_mutable_device_identifier(); + public: + + // .tensorflow.ConvParametersProto.Fusion fusion = 13; + bool has_fusion() const; + private: + bool _internal_has_fusion() const; + public: + void clear_fusion(); + const ::tensorflow::ConvParametersProto_Fusion& fusion() const; + PROTOBUF_NODISCARD ::tensorflow::ConvParametersProto_Fusion* release_fusion(); + ::tensorflow::ConvParametersProto_Fusion* mutable_fusion(); + void set_allocated_fusion(::tensorflow::ConvParametersProto_Fusion* fusion); + private: + const ::tensorflow::ConvParametersProto_Fusion& _internal_fusion() const; + ::tensorflow::ConvParametersProto_Fusion* _internal_mutable_fusion(); + public: + void unsafe_arena_set_allocated_fusion( + ::tensorflow::ConvParametersProto_Fusion* fusion); + ::tensorflow::ConvParametersProto_Fusion* unsafe_arena_release_fusion(); + + // int64 batch = 1; + void clear_batch(); + int64_t batch() const; + void set_batch(int64_t value); + private: + int64_t _internal_batch() const; + void _internal_set_batch(int64_t value); + public: + + // int64 in_depths = 2; + void clear_in_depths(); + int64_t in_depths() const; + void set_in_depths(int64_t value); + private: + int64_t _internal_in_depths() const; + void _internal_set_in_depths(int64_t value); + public: + + // int64 out_depths = 3; + void clear_out_depths(); + int64_t out_depths() const; + void set_out_depths(int64_t value); + private: + int64_t _internal_out_depths() const; + void _internal_set_out_depths(int64_t value); + public: + + // int32 data_format = 5; + void clear_data_format(); + int32_t data_format() const; + void set_data_format(int32_t value); + private: + int32_t _internal_data_format() const; + void _internal_set_data_format(int32_t value); + public: + + // .tensorflow.DataType dtype = 10; + void clear_dtype(); + ::tensorflow::DataType dtype() const; + void set_dtype(::tensorflow::DataType value); + private: + ::tensorflow::DataType _internal_dtype() const; + void _internal_set_dtype(::tensorflow::DataType value); + public: + + // int32 group_count = 11; + void clear_group_count(); + int32_t group_count() const; + void set_group_count(int32_t value); + private: + int32_t _internal_group_count() const; + void _internal_set_group_count(int32_t value); + public: + + // int32 version = 14; + void clear_version(); + int32_t version() const; + void set_version(int32_t value); + private: + int32_t _internal_version() const; + void _internal_set_version(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.ConvParametersProto) + 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 > in_; + mutable std::atomic _in_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > filter_; + mutable std::atomic _filter_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > dilation_; + mutable std::atomic _dilation_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > stride_; + mutable std::atomic _stride_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > padding_; + mutable std::atomic _padding_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_identifier_; + ::tensorflow::ConvParametersProto_Fusion* fusion_; + int64_t batch_; + int64_t in_depths_; + int64_t out_depths_; + int32_t data_format_; + int dtype_; + int32_t group_count_; + int32_t version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto; +}; +// ------------------------------------------------------------------- + +class MatmulParametersProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.MatmulParametersProto) */ { + public: + inline MatmulParametersProto() : MatmulParametersProto(nullptr) {} + ~MatmulParametersProto() override; + explicit PROTOBUF_CONSTEXPR MatmulParametersProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + MatmulParametersProto(const MatmulParametersProto& from); + MatmulParametersProto(MatmulParametersProto&& from) noexcept + : MatmulParametersProto() { + *this = ::std::move(from); + } + + inline MatmulParametersProto& operator=(const MatmulParametersProto& from) { + CopyFrom(from); + return *this; + } + inline MatmulParametersProto& operator=(MatmulParametersProto&& 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 MatmulParametersProto& default_instance() { + return *internal_default_instance(); + } + static inline const MatmulParametersProto* internal_default_instance() { + return reinterpret_cast( + &_MatmulParametersProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(MatmulParametersProto& a, MatmulParametersProto& b) { + a.Swap(&b); + } + inline void Swap(MatmulParametersProto* 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(MatmulParametersProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + MatmulParametersProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const MatmulParametersProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const MatmulParametersProto& from) { + MatmulParametersProto::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(MatmulParametersProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.MatmulParametersProto"; + } + protected: + explicit MatmulParametersProto(::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 { + kDeviceIdentifierFieldNumber = 12, + kAbDtypeFieldNumber = 1, + kCDtypeFieldNumber = 2, + kMFieldNumber = 5, + kNFieldNumber = 6, + kTransAFieldNumber = 3, + kTransBFieldNumber = 4, + kActivationModeFieldNumber = 11, + kKFieldNumber = 7, + kLdaFieldNumber = 8, + kLdbFieldNumber = 9, + kLdcFieldNumber = 10, + kVersionFieldNumber = 14, + }; + // string device_identifier = 12; + void clear_device_identifier(); + const std::string& device_identifier() const; + template + void set_device_identifier(ArgT0&& arg0, ArgT... args); + std::string* mutable_device_identifier(); + PROTOBUF_NODISCARD std::string* release_device_identifier(); + void set_allocated_device_identifier(std::string* device_identifier); + private: + const std::string& _internal_device_identifier() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device_identifier(const std::string& value); + std::string* _internal_mutable_device_identifier(); + public: + + // .tensorflow.DataType ab_dtype = 1; + void clear_ab_dtype(); + ::tensorflow::DataType ab_dtype() const; + void set_ab_dtype(::tensorflow::DataType value); + private: + ::tensorflow::DataType _internal_ab_dtype() const; + void _internal_set_ab_dtype(::tensorflow::DataType value); + public: + + // .tensorflow.DataType c_dtype = 2; + void clear_c_dtype(); + ::tensorflow::DataType c_dtype() const; + void set_c_dtype(::tensorflow::DataType value); + private: + ::tensorflow::DataType _internal_c_dtype() const; + void _internal_set_c_dtype(::tensorflow::DataType value); + public: + + // uint64 m = 5; + void clear_m(); + uint64_t m() const; + void set_m(uint64_t value); + private: + uint64_t _internal_m() const; + void _internal_set_m(uint64_t value); + public: + + // uint64 n = 6; + void clear_n(); + uint64_t n() const; + void set_n(uint64_t value); + private: + uint64_t _internal_n() const; + void _internal_set_n(uint64_t value); + public: + + // bool trans_a = 3; + void clear_trans_a(); + bool trans_a() const; + void set_trans_a(bool value); + private: + bool _internal_trans_a() const; + void _internal_set_trans_a(bool value); + public: + + // bool trans_b = 4; + void clear_trans_b(); + bool trans_b() const; + void set_trans_b(bool value); + private: + bool _internal_trans_b() const; + void _internal_set_trans_b(bool value); + public: + + // .stream_executor.dnn.ActivationMode activation_mode = 11; + 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: + + // uint64 k = 7; + void clear_k(); + uint64_t k() const; + void set_k(uint64_t value); + private: + uint64_t _internal_k() const; + void _internal_set_k(uint64_t value); + public: + + // int64 lda = 8; + void clear_lda(); + int64_t lda() const; + void set_lda(int64_t value); + private: + int64_t _internal_lda() const; + void _internal_set_lda(int64_t value); + public: + + // int64 ldb = 9; + void clear_ldb(); + int64_t ldb() const; + void set_ldb(int64_t value); + private: + int64_t _internal_ldb() const; + void _internal_set_ldb(int64_t value); + public: + + // int64 ldc = 10; + void clear_ldc(); + int64_t ldc() const; + void set_ldc(int64_t value); + private: + int64_t _internal_ldc() const; + void _internal_set_ldc(int64_t value); + public: + + // int32 version = 14; + void clear_version(); + int32_t version() const; + void set_version(int32_t value); + private: + int32_t _internal_version() const; + void _internal_set_version(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.MatmulParametersProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_identifier_; + int ab_dtype_; + int c_dtype_; + uint64_t m_; + uint64_t n_; + bool trans_a_; + bool trans_b_; + int activation_mode_; + uint64_t k_; + int64_t lda_; + int64_t ldb_; + int64_t ldc_; + int32_t version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// ConvParametersProto_Fusion + +// bool is_contrib = 1; +inline void ConvParametersProto_Fusion::clear_is_contrib() { + _impl_.is_contrib_ = false; +} +inline bool ConvParametersProto_Fusion::_internal_is_contrib() const { + return _impl_.is_contrib_; +} +inline bool ConvParametersProto_Fusion::is_contrib() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.Fusion.is_contrib) + return _internal_is_contrib(); +} +inline void ConvParametersProto_Fusion::_internal_set_is_contrib(bool value) { + + _impl_.is_contrib_ = value; +} +inline void ConvParametersProto_Fusion::set_is_contrib(bool value) { + _internal_set_is_contrib(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.Fusion.is_contrib) +} + +// .stream_executor.dnn.ActivationMode activation_mode = 2; +inline void ConvParametersProto_Fusion::clear_activation_mode() { + _impl_.activation_mode_ = 0; +} +inline ::stream_executor::dnn::ActivationMode ConvParametersProto_Fusion::_internal_activation_mode() const { + return static_cast< ::stream_executor::dnn::ActivationMode >(_impl_.activation_mode_); +} +inline ::stream_executor::dnn::ActivationMode ConvParametersProto_Fusion::activation_mode() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.Fusion.activation_mode) + return _internal_activation_mode(); +} +inline void ConvParametersProto_Fusion::_internal_set_activation_mode(::stream_executor::dnn::ActivationMode value) { + + _impl_.activation_mode_ = value; +} +inline void ConvParametersProto_Fusion::set_activation_mode(::stream_executor::dnn::ActivationMode value) { + _internal_set_activation_mode(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.Fusion.activation_mode) +} + +// double conv_scale = 3; +inline void ConvParametersProto_Fusion::clear_conv_scale() { + _impl_.conv_scale_ = 0; +} +inline double ConvParametersProto_Fusion::_internal_conv_scale() const { + return _impl_.conv_scale_; +} +inline double ConvParametersProto_Fusion::conv_scale() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.Fusion.conv_scale) + return _internal_conv_scale(); +} +inline void ConvParametersProto_Fusion::_internal_set_conv_scale(double value) { + + _impl_.conv_scale_ = value; +} +inline void ConvParametersProto_Fusion::set_conv_scale(double value) { + _internal_set_conv_scale(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.Fusion.conv_scale) +} + +// double side_input_scale = 4; +inline void ConvParametersProto_Fusion::clear_side_input_scale() { + _impl_.side_input_scale_ = 0; +} +inline double ConvParametersProto_Fusion::_internal_side_input_scale() const { + return _impl_.side_input_scale_; +} +inline double ConvParametersProto_Fusion::side_input_scale() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.Fusion.side_input_scale) + return _internal_side_input_scale(); +} +inline void ConvParametersProto_Fusion::_internal_set_side_input_scale(double value) { + + _impl_.side_input_scale_ = value; +} +inline void ConvParametersProto_Fusion::set_side_input_scale(double value) { + _internal_set_side_input_scale(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.Fusion.side_input_scale) +} + +// ------------------------------------------------------------------- + +// ConvParametersProto + +// int64 batch = 1; +inline void ConvParametersProto::clear_batch() { + _impl_.batch_ = int64_t{0}; +} +inline int64_t ConvParametersProto::_internal_batch() const { + return _impl_.batch_; +} +inline int64_t ConvParametersProto::batch() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.batch) + return _internal_batch(); +} +inline void ConvParametersProto::_internal_set_batch(int64_t value) { + + _impl_.batch_ = value; +} +inline void ConvParametersProto::set_batch(int64_t value) { + _internal_set_batch(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.batch) +} + +// int64 in_depths = 2; +inline void ConvParametersProto::clear_in_depths() { + _impl_.in_depths_ = int64_t{0}; +} +inline int64_t ConvParametersProto::_internal_in_depths() const { + return _impl_.in_depths_; +} +inline int64_t ConvParametersProto::in_depths() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.in_depths) + return _internal_in_depths(); +} +inline void ConvParametersProto::_internal_set_in_depths(int64_t value) { + + _impl_.in_depths_ = value; +} +inline void ConvParametersProto::set_in_depths(int64_t value) { + _internal_set_in_depths(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.in_depths) +} + +// int64 out_depths = 3; +inline void ConvParametersProto::clear_out_depths() { + _impl_.out_depths_ = int64_t{0}; +} +inline int64_t ConvParametersProto::_internal_out_depths() const { + return _impl_.out_depths_; +} +inline int64_t ConvParametersProto::out_depths() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.out_depths) + return _internal_out_depths(); +} +inline void ConvParametersProto::_internal_set_out_depths(int64_t value) { + + _impl_.out_depths_ = value; +} +inline void ConvParametersProto::set_out_depths(int64_t value) { + _internal_set_out_depths(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.out_depths) +} + +// repeated int64 in = 4; +inline int ConvParametersProto::_internal_in_size() const { + return _impl_.in_.size(); +} +inline int ConvParametersProto::in_size() const { + return _internal_in_size(); +} +inline void ConvParametersProto::clear_in() { + _impl_.in_.Clear(); +} +inline int64_t ConvParametersProto::_internal_in(int index) const { + return _impl_.in_.Get(index); +} +inline int64_t ConvParametersProto::in(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.in) + return _internal_in(index); +} +inline void ConvParametersProto::set_in(int index, int64_t value) { + _impl_.in_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.in) +} +inline void ConvParametersProto::_internal_add_in(int64_t value) { + _impl_.in_.Add(value); +} +inline void ConvParametersProto::add_in(int64_t value) { + _internal_add_in(value); + // @@protoc_insertion_point(field_add:tensorflow.ConvParametersProto.in) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::_internal_in() const { + return _impl_.in_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::in() const { + // @@protoc_insertion_point(field_list:tensorflow.ConvParametersProto.in) + return _internal_in(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::_internal_mutable_in() { + return &_impl_.in_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::mutable_in() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ConvParametersProto.in) + return _internal_mutable_in(); +} + +// int32 data_format = 5; +inline void ConvParametersProto::clear_data_format() { + _impl_.data_format_ = 0; +} +inline int32_t ConvParametersProto::_internal_data_format() const { + return _impl_.data_format_; +} +inline int32_t ConvParametersProto::data_format() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.data_format) + return _internal_data_format(); +} +inline void ConvParametersProto::_internal_set_data_format(int32_t value) { + + _impl_.data_format_ = value; +} +inline void ConvParametersProto::set_data_format(int32_t value) { + _internal_set_data_format(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.data_format) +} + +// repeated int64 filter = 6; +inline int ConvParametersProto::_internal_filter_size() const { + return _impl_.filter_.size(); +} +inline int ConvParametersProto::filter_size() const { + return _internal_filter_size(); +} +inline void ConvParametersProto::clear_filter() { + _impl_.filter_.Clear(); +} +inline int64_t ConvParametersProto::_internal_filter(int index) const { + return _impl_.filter_.Get(index); +} +inline int64_t ConvParametersProto::filter(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.filter) + return _internal_filter(index); +} +inline void ConvParametersProto::set_filter(int index, int64_t value) { + _impl_.filter_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.filter) +} +inline void ConvParametersProto::_internal_add_filter(int64_t value) { + _impl_.filter_.Add(value); +} +inline void ConvParametersProto::add_filter(int64_t value) { + _internal_add_filter(value); + // @@protoc_insertion_point(field_add:tensorflow.ConvParametersProto.filter) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::_internal_filter() const { + return _impl_.filter_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::filter() const { + // @@protoc_insertion_point(field_list:tensorflow.ConvParametersProto.filter) + return _internal_filter(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::_internal_mutable_filter() { + return &_impl_.filter_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::mutable_filter() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ConvParametersProto.filter) + return _internal_mutable_filter(); +} + +// repeated int64 dilation = 7; +inline int ConvParametersProto::_internal_dilation_size() const { + return _impl_.dilation_.size(); +} +inline int ConvParametersProto::dilation_size() const { + return _internal_dilation_size(); +} +inline void ConvParametersProto::clear_dilation() { + _impl_.dilation_.Clear(); +} +inline int64_t ConvParametersProto::_internal_dilation(int index) const { + return _impl_.dilation_.Get(index); +} +inline int64_t ConvParametersProto::dilation(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.dilation) + return _internal_dilation(index); +} +inline void ConvParametersProto::set_dilation(int index, int64_t value) { + _impl_.dilation_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.dilation) +} +inline void ConvParametersProto::_internal_add_dilation(int64_t value) { + _impl_.dilation_.Add(value); +} +inline void ConvParametersProto::add_dilation(int64_t value) { + _internal_add_dilation(value); + // @@protoc_insertion_point(field_add:tensorflow.ConvParametersProto.dilation) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::_internal_dilation() const { + return _impl_.dilation_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::dilation() const { + // @@protoc_insertion_point(field_list:tensorflow.ConvParametersProto.dilation) + return _internal_dilation(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::_internal_mutable_dilation() { + return &_impl_.dilation_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::mutable_dilation() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ConvParametersProto.dilation) + return _internal_mutable_dilation(); +} + +// repeated int64 stride = 8; +inline int ConvParametersProto::_internal_stride_size() const { + return _impl_.stride_.size(); +} +inline int ConvParametersProto::stride_size() const { + return _internal_stride_size(); +} +inline void ConvParametersProto::clear_stride() { + _impl_.stride_.Clear(); +} +inline int64_t ConvParametersProto::_internal_stride(int index) const { + return _impl_.stride_.Get(index); +} +inline int64_t ConvParametersProto::stride(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.stride) + return _internal_stride(index); +} +inline void ConvParametersProto::set_stride(int index, int64_t value) { + _impl_.stride_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.stride) +} +inline void ConvParametersProto::_internal_add_stride(int64_t value) { + _impl_.stride_.Add(value); +} +inline void ConvParametersProto::add_stride(int64_t value) { + _internal_add_stride(value); + // @@protoc_insertion_point(field_add:tensorflow.ConvParametersProto.stride) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::_internal_stride() const { + return _impl_.stride_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::stride() const { + // @@protoc_insertion_point(field_list:tensorflow.ConvParametersProto.stride) + return _internal_stride(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::_internal_mutable_stride() { + return &_impl_.stride_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::mutable_stride() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ConvParametersProto.stride) + return _internal_mutable_stride(); +} + +// repeated int64 padding = 9; +inline int ConvParametersProto::_internal_padding_size() const { + return _impl_.padding_.size(); +} +inline int ConvParametersProto::padding_size() const { + return _internal_padding_size(); +} +inline void ConvParametersProto::clear_padding() { + _impl_.padding_.Clear(); +} +inline int64_t ConvParametersProto::_internal_padding(int index) const { + return _impl_.padding_.Get(index); +} +inline int64_t ConvParametersProto::padding(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.padding) + return _internal_padding(index); +} +inline void ConvParametersProto::set_padding(int index, int64_t value) { + _impl_.padding_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.padding) +} +inline void ConvParametersProto::_internal_add_padding(int64_t value) { + _impl_.padding_.Add(value); +} +inline void ConvParametersProto::add_padding(int64_t value) { + _internal_add_padding(value); + // @@protoc_insertion_point(field_add:tensorflow.ConvParametersProto.padding) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::_internal_padding() const { + return _impl_.padding_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +ConvParametersProto::padding() const { + // @@protoc_insertion_point(field_list:tensorflow.ConvParametersProto.padding) + return _internal_padding(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::_internal_mutable_padding() { + return &_impl_.padding_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +ConvParametersProto::mutable_padding() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ConvParametersProto.padding) + return _internal_mutable_padding(); +} + +// .tensorflow.DataType dtype = 10; +inline void ConvParametersProto::clear_dtype() { + _impl_.dtype_ = 0; +} +inline ::tensorflow::DataType ConvParametersProto::_internal_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.dtype_); +} +inline ::tensorflow::DataType ConvParametersProto::dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.dtype) + return _internal_dtype(); +} +inline void ConvParametersProto::_internal_set_dtype(::tensorflow::DataType value) { + + _impl_.dtype_ = value; +} +inline void ConvParametersProto::set_dtype(::tensorflow::DataType value) { + _internal_set_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.dtype) +} + +// int32 group_count = 11; +inline void ConvParametersProto::clear_group_count() { + _impl_.group_count_ = 0; +} +inline int32_t ConvParametersProto::_internal_group_count() const { + return _impl_.group_count_; +} +inline int32_t ConvParametersProto::group_count() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.group_count) + return _internal_group_count(); +} +inline void ConvParametersProto::_internal_set_group_count(int32_t value) { + + _impl_.group_count_ = value; +} +inline void ConvParametersProto::set_group_count(int32_t value) { + _internal_set_group_count(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.group_count) +} + +// string device_identifier = 12; +inline void ConvParametersProto::clear_device_identifier() { + _impl_.device_identifier_.ClearToEmpty(); +} +inline const std::string& ConvParametersProto::device_identifier() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.device_identifier) + return _internal_device_identifier(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ConvParametersProto::set_device_identifier(ArgT0&& arg0, ArgT... args) { + + _impl_.device_identifier_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.device_identifier) +} +inline std::string* ConvParametersProto::mutable_device_identifier() { + std::string* _s = _internal_mutable_device_identifier(); + // @@protoc_insertion_point(field_mutable:tensorflow.ConvParametersProto.device_identifier) + return _s; +} +inline const std::string& ConvParametersProto::_internal_device_identifier() const { + return _impl_.device_identifier_.Get(); +} +inline void ConvParametersProto::_internal_set_device_identifier(const std::string& value) { + + _impl_.device_identifier_.Set(value, GetArenaForAllocation()); +} +inline std::string* ConvParametersProto::_internal_mutable_device_identifier() { + + return _impl_.device_identifier_.Mutable(GetArenaForAllocation()); +} +inline std::string* ConvParametersProto::release_device_identifier() { + // @@protoc_insertion_point(field_release:tensorflow.ConvParametersProto.device_identifier) + return _impl_.device_identifier_.Release(); +} +inline void ConvParametersProto::set_allocated_device_identifier(std::string* device_identifier) { + if (device_identifier != nullptr) { + + } else { + + } + _impl_.device_identifier_.SetAllocated(device_identifier, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_identifier_.IsDefault()) { + _impl_.device_identifier_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ConvParametersProto.device_identifier) +} + +// .tensorflow.ConvParametersProto.Fusion fusion = 13; +inline bool ConvParametersProto::_internal_has_fusion() const { + return this != internal_default_instance() && _impl_.fusion_ != nullptr; +} +inline bool ConvParametersProto::has_fusion() const { + return _internal_has_fusion(); +} +inline void ConvParametersProto::clear_fusion() { + if (GetArenaForAllocation() == nullptr && _impl_.fusion_ != nullptr) { + delete _impl_.fusion_; + } + _impl_.fusion_ = nullptr; +} +inline const ::tensorflow::ConvParametersProto_Fusion& ConvParametersProto::_internal_fusion() const { + const ::tensorflow::ConvParametersProto_Fusion* p = _impl_.fusion_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_ConvParametersProto_Fusion_default_instance_); +} +inline const ::tensorflow::ConvParametersProto_Fusion& ConvParametersProto::fusion() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.fusion) + return _internal_fusion(); +} +inline void ConvParametersProto::unsafe_arena_set_allocated_fusion( + ::tensorflow::ConvParametersProto_Fusion* fusion) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.fusion_); + } + _impl_.fusion_ = fusion; + if (fusion) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.ConvParametersProto.fusion) +} +inline ::tensorflow::ConvParametersProto_Fusion* ConvParametersProto::release_fusion() { + + ::tensorflow::ConvParametersProto_Fusion* temp = _impl_.fusion_; + _impl_.fusion_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::ConvParametersProto_Fusion* ConvParametersProto::unsafe_arena_release_fusion() { + // @@protoc_insertion_point(field_release:tensorflow.ConvParametersProto.fusion) + + ::tensorflow::ConvParametersProto_Fusion* temp = _impl_.fusion_; + _impl_.fusion_ = nullptr; + return temp; +} +inline ::tensorflow::ConvParametersProto_Fusion* ConvParametersProto::_internal_mutable_fusion() { + + if (_impl_.fusion_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::ConvParametersProto_Fusion>(GetArenaForAllocation()); + _impl_.fusion_ = p; + } + return _impl_.fusion_; +} +inline ::tensorflow::ConvParametersProto_Fusion* ConvParametersProto::mutable_fusion() { + ::tensorflow::ConvParametersProto_Fusion* _msg = _internal_mutable_fusion(); + // @@protoc_insertion_point(field_mutable:tensorflow.ConvParametersProto.fusion) + return _msg; +} +inline void ConvParametersProto::set_allocated_fusion(::tensorflow::ConvParametersProto_Fusion* fusion) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.fusion_; + } + if (fusion) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(fusion); + if (message_arena != submessage_arena) { + fusion = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, fusion, submessage_arena); + } + + } else { + + } + _impl_.fusion_ = fusion; + // @@protoc_insertion_point(field_set_allocated:tensorflow.ConvParametersProto.fusion) +} + +// int32 version = 14; +inline void ConvParametersProto::clear_version() { + _impl_.version_ = 0; +} +inline int32_t ConvParametersProto::_internal_version() const { + return _impl_.version_; +} +inline int32_t ConvParametersProto::version() const { + // @@protoc_insertion_point(field_get:tensorflow.ConvParametersProto.version) + return _internal_version(); +} +inline void ConvParametersProto::_internal_set_version(int32_t value) { + + _impl_.version_ = value; +} +inline void ConvParametersProto::set_version(int32_t value) { + _internal_set_version(value); + // @@protoc_insertion_point(field_set:tensorflow.ConvParametersProto.version) +} + +// ------------------------------------------------------------------- + +// MatmulParametersProto + +// .tensorflow.DataType ab_dtype = 1; +inline void MatmulParametersProto::clear_ab_dtype() { + _impl_.ab_dtype_ = 0; +} +inline ::tensorflow::DataType MatmulParametersProto::_internal_ab_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.ab_dtype_); +} +inline ::tensorflow::DataType MatmulParametersProto::ab_dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.ab_dtype) + return _internal_ab_dtype(); +} +inline void MatmulParametersProto::_internal_set_ab_dtype(::tensorflow::DataType value) { + + _impl_.ab_dtype_ = value; +} +inline void MatmulParametersProto::set_ab_dtype(::tensorflow::DataType value) { + _internal_set_ab_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.ab_dtype) +} + +// .tensorflow.DataType c_dtype = 2; +inline void MatmulParametersProto::clear_c_dtype() { + _impl_.c_dtype_ = 0; +} +inline ::tensorflow::DataType MatmulParametersProto::_internal_c_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.c_dtype_); +} +inline ::tensorflow::DataType MatmulParametersProto::c_dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.c_dtype) + return _internal_c_dtype(); +} +inline void MatmulParametersProto::_internal_set_c_dtype(::tensorflow::DataType value) { + + _impl_.c_dtype_ = value; +} +inline void MatmulParametersProto::set_c_dtype(::tensorflow::DataType value) { + _internal_set_c_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.c_dtype) +} + +// bool trans_a = 3; +inline void MatmulParametersProto::clear_trans_a() { + _impl_.trans_a_ = false; +} +inline bool MatmulParametersProto::_internal_trans_a() const { + return _impl_.trans_a_; +} +inline bool MatmulParametersProto::trans_a() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.trans_a) + return _internal_trans_a(); +} +inline void MatmulParametersProto::_internal_set_trans_a(bool value) { + + _impl_.trans_a_ = value; +} +inline void MatmulParametersProto::set_trans_a(bool value) { + _internal_set_trans_a(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.trans_a) +} + +// bool trans_b = 4; +inline void MatmulParametersProto::clear_trans_b() { + _impl_.trans_b_ = false; +} +inline bool MatmulParametersProto::_internal_trans_b() const { + return _impl_.trans_b_; +} +inline bool MatmulParametersProto::trans_b() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.trans_b) + return _internal_trans_b(); +} +inline void MatmulParametersProto::_internal_set_trans_b(bool value) { + + _impl_.trans_b_ = value; +} +inline void MatmulParametersProto::set_trans_b(bool value) { + _internal_set_trans_b(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.trans_b) +} + +// uint64 m = 5; +inline void MatmulParametersProto::clear_m() { + _impl_.m_ = uint64_t{0u}; +} +inline uint64_t MatmulParametersProto::_internal_m() const { + return _impl_.m_; +} +inline uint64_t MatmulParametersProto::m() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.m) + return _internal_m(); +} +inline void MatmulParametersProto::_internal_set_m(uint64_t value) { + + _impl_.m_ = value; +} +inline void MatmulParametersProto::set_m(uint64_t value) { + _internal_set_m(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.m) +} + +// uint64 n = 6; +inline void MatmulParametersProto::clear_n() { + _impl_.n_ = uint64_t{0u}; +} +inline uint64_t MatmulParametersProto::_internal_n() const { + return _impl_.n_; +} +inline uint64_t MatmulParametersProto::n() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.n) + return _internal_n(); +} +inline void MatmulParametersProto::_internal_set_n(uint64_t value) { + + _impl_.n_ = value; +} +inline void MatmulParametersProto::set_n(uint64_t value) { + _internal_set_n(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.n) +} + +// uint64 k = 7; +inline void MatmulParametersProto::clear_k() { + _impl_.k_ = uint64_t{0u}; +} +inline uint64_t MatmulParametersProto::_internal_k() const { + return _impl_.k_; +} +inline uint64_t MatmulParametersProto::k() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.k) + return _internal_k(); +} +inline void MatmulParametersProto::_internal_set_k(uint64_t value) { + + _impl_.k_ = value; +} +inline void MatmulParametersProto::set_k(uint64_t value) { + _internal_set_k(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.k) +} + +// int64 lda = 8; +inline void MatmulParametersProto::clear_lda() { + _impl_.lda_ = int64_t{0}; +} +inline int64_t MatmulParametersProto::_internal_lda() const { + return _impl_.lda_; +} +inline int64_t MatmulParametersProto::lda() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.lda) + return _internal_lda(); +} +inline void MatmulParametersProto::_internal_set_lda(int64_t value) { + + _impl_.lda_ = value; +} +inline void MatmulParametersProto::set_lda(int64_t value) { + _internal_set_lda(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.lda) +} + +// int64 ldb = 9; +inline void MatmulParametersProto::clear_ldb() { + _impl_.ldb_ = int64_t{0}; +} +inline int64_t MatmulParametersProto::_internal_ldb() const { + return _impl_.ldb_; +} +inline int64_t MatmulParametersProto::ldb() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.ldb) + return _internal_ldb(); +} +inline void MatmulParametersProto::_internal_set_ldb(int64_t value) { + + _impl_.ldb_ = value; +} +inline void MatmulParametersProto::set_ldb(int64_t value) { + _internal_set_ldb(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.ldb) +} + +// int64 ldc = 10; +inline void MatmulParametersProto::clear_ldc() { + _impl_.ldc_ = int64_t{0}; +} +inline int64_t MatmulParametersProto::_internal_ldc() const { + return _impl_.ldc_; +} +inline int64_t MatmulParametersProto::ldc() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.ldc) + return _internal_ldc(); +} +inline void MatmulParametersProto::_internal_set_ldc(int64_t value) { + + _impl_.ldc_ = value; +} +inline void MatmulParametersProto::set_ldc(int64_t value) { + _internal_set_ldc(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.ldc) +} + +// .stream_executor.dnn.ActivationMode activation_mode = 11; +inline void MatmulParametersProto::clear_activation_mode() { + _impl_.activation_mode_ = 0; +} +inline ::stream_executor::dnn::ActivationMode MatmulParametersProto::_internal_activation_mode() const { + return static_cast< ::stream_executor::dnn::ActivationMode >(_impl_.activation_mode_); +} +inline ::stream_executor::dnn::ActivationMode MatmulParametersProto::activation_mode() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.activation_mode) + return _internal_activation_mode(); +} +inline void MatmulParametersProto::_internal_set_activation_mode(::stream_executor::dnn::ActivationMode value) { + + _impl_.activation_mode_ = value; +} +inline void MatmulParametersProto::set_activation_mode(::stream_executor::dnn::ActivationMode value) { + _internal_set_activation_mode(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.activation_mode) +} + +// string device_identifier = 12; +inline void MatmulParametersProto::clear_device_identifier() { + _impl_.device_identifier_.ClearToEmpty(); +} +inline const std::string& MatmulParametersProto::device_identifier() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.device_identifier) + return _internal_device_identifier(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void MatmulParametersProto::set_device_identifier(ArgT0&& arg0, ArgT... args) { + + _impl_.device_identifier_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.device_identifier) +} +inline std::string* MatmulParametersProto::mutable_device_identifier() { + std::string* _s = _internal_mutable_device_identifier(); + // @@protoc_insertion_point(field_mutable:tensorflow.MatmulParametersProto.device_identifier) + return _s; +} +inline const std::string& MatmulParametersProto::_internal_device_identifier() const { + return _impl_.device_identifier_.Get(); +} +inline void MatmulParametersProto::_internal_set_device_identifier(const std::string& value) { + + _impl_.device_identifier_.Set(value, GetArenaForAllocation()); +} +inline std::string* MatmulParametersProto::_internal_mutable_device_identifier() { + + return _impl_.device_identifier_.Mutable(GetArenaForAllocation()); +} +inline std::string* MatmulParametersProto::release_device_identifier() { + // @@protoc_insertion_point(field_release:tensorflow.MatmulParametersProto.device_identifier) + return _impl_.device_identifier_.Release(); +} +inline void MatmulParametersProto::set_allocated_device_identifier(std::string* device_identifier) { + if (device_identifier != nullptr) { + + } else { + + } + _impl_.device_identifier_.SetAllocated(device_identifier, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_identifier_.IsDefault()) { + _impl_.device_identifier_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.MatmulParametersProto.device_identifier) +} + +// int32 version = 14; +inline void MatmulParametersProto::clear_version() { + _impl_.version_ = 0; +} +inline int32_t MatmulParametersProto::_internal_version() const { + return _impl_.version_; +} +inline int32_t MatmulParametersProto::version() const { + // @@protoc_insertion_point(field_get:tensorflow.MatmulParametersProto.version) + return _internal_version(); +} +inline void MatmulParametersProto::_internal_set_version(int32_t value) { + + _impl_.version_ = value; +} +inline void MatmulParametersProto::set_version(int32_t value) { + _internal_set_version(value); + // @@protoc_insertion_point(field_set:tensorflow.MatmulParametersProto.version) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fautotune_5fmaps_2fconv_5fparameters_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_entry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_entry.h new file mode 100644 index 0000000000000000000000000000000000000000..c8a230369b7be2957ce4144af5eecf47969d3a75 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_entry.h @@ -0,0 +1,154 @@ +/* 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. +==============================================================================*/ +// LINT.IfChange + +#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_ENTRY_H_ +#define TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_ENTRY_H_ + +#include +#include +#include + +#include "Eigen/Core" // from @eigen_archive +#include "tensorflow/core/lib/gtl/flatmap.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/ctc/ctc_loss_util.h" + +namespace tensorflow { +namespace ctc { + +// The ctc_beam_search namespace holds several classes meant to be accessed only +// in case of extending the CTCBeamSearch decoder to allow custom scoring +// functions. +// +// BeamEntry is exposed through template arguments BeamScorer and BeamComparer +// of CTCBeamSearch (ctc_beam_search.h). +namespace ctc_beam_search { + +struct EmptyBeamState {}; + +template +struct BeamProbability { + BeamProbability() + : total(kLogZero()), blank(kLogZero()), label(kLogZero()) {} + void Reset() { + total = kLogZero(); + blank = kLogZero(); + label = kLogZero(); + } + T total; + T blank; + T label; +}; + +template +class BeamRoot; + +template +struct BeamEntry { + // BeamRoot::AddEntry() serves as the factory method. + friend BeamEntry* BeamRoot::AddEntry( + BeamEntry* p, int l); + inline bool Active() const { return newp.total != kLogZero(); } + // Return the child at the given index, or construct a new one in-place if + // none was found. + BeamEntry& GetChild(int ind) { + auto entry = children.emplace(ind, nullptr); + auto& child_entry = entry.first->second; + // If this is a new child, populate the BeamEntry*. + if (entry.second) { + child_entry = beam_root->AddEntry(this, ind); + } + return *child_entry; + } + std::vector LabelSeq(bool merge_repeated) const { + std::vector labels; + int prev_label = -1; + const BeamEntry* c = this; + while (c->parent != nullptr) { // Checking c->parent to skip root leaf. + if (!merge_repeated || c->label != prev_label) { + labels.push_back(c->label); + } + prev_label = c->label; + c = c->parent; + } + std::reverse(labels.begin(), labels.end()); + return labels; + } + + BeamEntry* parent; + int label; + // All instances of child BeamEntry are owned by *beam_root. + gtl::FlatMap*> children; + BeamProbability oldp; + BeamProbability newp; + CTCBeamState state; + + private: + // Constructor giving parent, label, and the beam_root. + // The object pointed to by p cannot be copied and should not be moved, + // otherwise parent will become invalid. + // This private constructor is only called through the factory method + // BeamRoot::AddEntry(). + BeamEntry(BeamEntry* p, int l, BeamRoot* beam_root) + : parent(p), label(l), beam_root(beam_root) {} + BeamRoot* beam_root; + BeamEntry(const BeamEntry&) = delete; + void operator=(const BeamEntry&) = delete; +}; + +// This class owns all instances of BeamEntry. This is used to avoid recursive +// destructor call during destruction. +template +class BeamRoot { + public: + BeamRoot(BeamEntry* p, int l) { + root_entry_ = AddEntry(p, l); + } + BeamRoot(const BeamRoot&) = delete; + BeamRoot& operator=(const BeamRoot&) = delete; + + BeamEntry* AddEntry(BeamEntry* p, int l) { + auto* new_entry = new BeamEntry(p, l, this); + beam_entries_.emplace_back(new_entry); + return new_entry; + } + BeamEntry* RootEntry() const { return root_entry_; } + + private: + BeamEntry* root_entry_ = nullptr; + std::vector>> beam_entries_; +}; + +// BeamComparer is the default beam comparer provided in CTCBeamSearch. +template +class BeamComparer { + public: + virtual ~BeamComparer() {} + virtual bool inline operator()(const BeamEntry* a, + const BeamEntry* b) const { + return a->newp.total > b->newp.total; + } +}; + +} // namespace ctc_beam_search + +} // namespace ctc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_ENTRY_H_ +// LINT.ThenChange(//tensorflow/lite/kernels/ctc/ctc_beam_entry.h) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_scorer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_scorer.h new file mode 100644 index 0000000000000000000000000000000000000000..1ea370f4117f15c14318d7860c99648cc9ffd11c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_scorer.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. +==============================================================================*/ +// LINT.IfChange + +// Collection of scoring classes that can be extended and provided to the +// CTCBeamSearchDecoder to incorporate additional scoring logic (such as a +// language model). +// +// To build a custom scorer extend and implement the pure virtual methods from +// BeamScorerInterface. The default CTC decoding behavior is implemented +// through BaseBeamScorer. + +#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SCORER_H_ +#define TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SCORER_H_ + +#include "tensorflow/core/util/ctc/ctc_beam_entry.h" + +namespace tensorflow { +namespace ctc { + +// Base implementation of a beam scorer used by default by the decoder that can +// be subclassed and provided as an argument to CTCBeamSearchDecoder, if complex +// scoring is required. Its main purpose is to provide a thin layer for +// integrating language model scoring easily. +template +class BaseBeamScorer { + public: + virtual ~BaseBeamScorer() {} + // State initialization. + virtual void InitializeState(CTCBeamState* root) const {} + // ExpandState is called when expanding a beam to one of its children. + // Called at most once per child beam. In the simplest case, no state + // expansion is done. + virtual void ExpandState(const CTCBeamState& from_state, int from_label, + CTCBeamState* to_state, int to_label) const {} + // ExpandStateEnd is called after decoding has finished. Its purpose is to + // allow a final scoring of the beam in its current state, before resorting + // and retrieving the TopN requested candidates. Called at most once per beam. + virtual void ExpandStateEnd(CTCBeamState* state) const {} + // GetStateExpansionScore should be an inexpensive method to retrieve the + // (cached) expansion score computed within ExpandState. The score is + // multiplied (log-addition) with the input score at the current step from + // the network. + // + // The score returned should be a log-probability. In the simplest case, as + // there's no state expansion logic, the expansion score is zero. + virtual T GetStateExpansionScore(const CTCBeamState& state, + T previous_score) const { + return previous_score; + } + // GetStateEndExpansionScore should be an inexpensive method to retrieve the + // (cached) expansion score computed within ExpandStateEnd. The score is + // multiplied (log-addition) with the final probability of the beam. + // + // The score returned should be a log-probability. + virtual T GetStateEndExpansionScore(const CTCBeamState& state) const { + return T(0); + } +}; + +} // namespace ctc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SCORER_H_ +// LINT.ThenChange(//tensorflow/lite/kernels/ctc/ctc_beam_scorer.h) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_search.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_search.h new file mode 100644 index 0000000000000000000000000000000000000000..74ab5370d8e34626f982bad71dbe2727d459010f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_beam_search.h @@ -0,0 +1,437 @@ +/* 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. +==============================================================================*/ +// LINT.IfChange + +#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SEARCH_H_ +#define TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SEARCH_H_ + +#include +#include +#include +#include +#include + +#include "Eigen/Core" // from @eigen_archive +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/top_n.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/ctc/ctc_beam_entry.h" +#include "tensorflow/core/util/ctc/ctc_beam_scorer.h" +#include "tensorflow/core/util/ctc/ctc_decoder.h" +#include "tensorflow/core/util/ctc/ctc_loss_util.h" + +namespace tensorflow { +namespace ctc { + +template > +class CTCBeamSearchDecoder : public CTCDecoder { + // Beam Search + // + // Example (GravesTh Fig. 7.5): + // a - + // P = [ 0.3 0.7 ] t = 0 + // [ 0.4 0.6 ] t = 1 + // + // Then P(l = -) = P(--) = 0.7 * 0.6 = 0.42 + // P(l = a) = P(a-) + P(aa) + P(-a) = 0.3*0.4 + ... = 0.58 + // + // In this case, Best Path decoding is suboptimal. + // + // For Beam Search, we use the following main recurrence relations: + // + // Relation 1: + // ---------------------------------------------------------- Eq. 1 + // P(l=abcd @ t=7) = P(l=abc @ t=6) * P(d @ 7) + // + P(l=abcd @ t=6) * (P(d @ 7) + P(- @ 7)) + // where P(l=? @ t=7), ? = a, ab, abc, abcd are all stored and + // updated recursively in the beam entry. + // + // Relation 2: + // ---------------------------------------------------------- Eq. 2 + // P(l=abc? @ t=3) = P(l=abc @ t=2) * P(? @ 3) + // for ? in a, b, d, ..., (not including c or the blank index), + // and the recurrence starts from the beam entry for P(l=abc @ t=2). + // + // For this case, the length of the new sequence equals t+1 (t + // starts at 0). This special case can be calculated as: + // P(l=abc? @ t=3) = P(a @ 0)*P(b @ 1)*P(c @ 2)*P(? @ 3) + // but we calculate it recursively for speed purposes. + typedef ctc_beam_search::BeamEntry BeamEntry; + typedef ctc_beam_search::BeamRoot BeamRoot; + typedef ctc_beam_search::BeamProbability BeamProbability; + + public: + typedef BaseBeamScorer DefaultBeamScorer; + + // The beam search decoder is constructed specifying the beam_width (number of + // candidates to keep at each decoding timestep) and a beam scorer (used for + // custom scoring, for example enabling the use of a language model). + // The ownership of the scorer remains with the caller. The default + // implementation, CTCBeamSearchDecoder<>::DefaultBeamScorer, generates the + // standard beam search. + CTCBeamSearchDecoder(int num_classes, int beam_width, + BaseBeamScorer* scorer, + int batch_size = 1, bool merge_repeated = false) + : CTCDecoder(num_classes, batch_size, merge_repeated), + beam_width_(beam_width), + leaves_(beam_width), + beam_scorer_(CHECK_NOTNULL(scorer)) { + Reset(); + } + + ~CTCBeamSearchDecoder() override {} + + // Run the hibernating beam search algorithm on the given input. + Status Decode(const typename CTCDecoder::SequenceLength& seq_len, + const std::vector::Input>& input, + std::vector::Output>* output, + typename CTCDecoder::ScoreOutput* scores) override; + + // Calculate the next step of the beam search and update the internal state. + template + void Step(const Vector& log_input_t); + + template + T GetTopK(const int K, const Vector& input, std::vector* top_k_logits, + std::vector* top_k_indices); + + // Retrieve the beam scorer instance used during decoding. + BaseBeamScorer* GetBeamScorer() const { + return beam_scorer_; + } + + // Set label selection parameters for faster decoding. + // See comments for label_selection_size_ and label_selection_margin_. + void SetLabelSelectionParameters(int label_selection_size, + T label_selection_margin) { + label_selection_size_ = label_selection_size; + label_selection_margin_ = label_selection_margin; + } + + // Reset the beam search + void Reset(); + + // Extract the top n paths at current time step + Status TopPaths(int n, std::vector>* paths, + std::vector* log_probs, bool merge_repeated) const; + + private: + int beam_width_; + + // Label selection is designed to avoid possibly very expensive scorer calls, + // by pruning the hypotheses based on the input alone. + // Label selection size controls how many items in each beam are passed + // through to the beam scorer. Only items with top N input scores are + // considered. + // Label selection margin controls the difference between minimal input score + // (versus the best scoring label) for an item to be passed to the beam + // scorer. This margin is expressed in terms of log-probability. + // Default is to do no label selection. + // For more detail: https://research.google.com/pubs/pub44823.html + int label_selection_size_ = 0; // zero means unlimited + T label_selection_margin_ = -1; // -1 means unlimited. + + gtl::TopN leaves_; + std::unique_ptr beam_root_; + BaseBeamScorer* beam_scorer_; + + CTCBeamSearchDecoder(const CTCBeamSearchDecoder&) = delete; + void operator=(const CTCBeamSearchDecoder&) = delete; +}; + +template +Status CTCBeamSearchDecoder::Decode( + const typename CTCDecoder::SequenceLength& seq_len, + const std::vector::Input>& input, + std::vector::Output>* output, + typename CTCDecoder::ScoreOutput* scores) { + // Storage for top paths. + std::vector> beams; + std::vector beam_log_probabilities; + int top_n = output->size(); + if (std::any_of(output->begin(), output->end(), + [this](const typename CTCDecoder::Output& output) -> bool { + return output.size() < this->batch_size_; + })) { + return errors::InvalidArgument( + "output needs to be of size at least (top_n, batch_size)."); + } + if (scores->rows() < this->batch_size_ || scores->cols() < top_n) { + return errors::InvalidArgument( + "scores needs to be of size at least (batch_size, top_n)."); + } + + for (int b = 0; b < this->batch_size_; ++b) { + int seq_len_b = seq_len[b]; + Reset(); + + for (int t = 0; t < seq_len_b; ++t) { + // Pass log-probabilities for this example + time. + Step(input[t].row(b)); + } // for (int t... + + // O(n * log(n)) + std::unique_ptr> branches(leaves_.Extract()); + leaves_.Reset(); + for (int i = 0; i < branches->size(); ++i) { + BeamEntry* entry = (*branches)[i]; + beam_scorer_->ExpandStateEnd(&entry->state); + entry->newp.total += + beam_scorer_->GetStateEndExpansionScore(entry->state); + leaves_.push(entry); + } + + Status status = + TopPaths(top_n, &beams, &beam_log_probabilities, this->merge_repeated_); + if (!status.ok()) { + return status; + } + + CHECK_EQ(top_n, beam_log_probabilities.size()); + CHECK_EQ(beams.size(), beam_log_probabilities.size()); + + for (int i = 0; i < top_n; ++i) { + // Copy output to the correct beam + batch + (*output)[i][b].swap(beams[i]); + (*scores)(b, i) = -beam_log_probabilities[i]; + } + } // for (int b... + return OkStatus(); +} + +template +template +T CTCBeamSearchDecoder::GetTopK( + const int K, const Vector& input, std::vector* top_k_logits, + std::vector* top_k_indices) { + // Find Top K choices, complexity nk in worst case. The array input is read + // just once. + CHECK_EQ(this->num_classes_, input.size()); + top_k_logits->clear(); + top_k_indices->clear(); + top_k_logits->resize(K, -INFINITY); + top_k_indices->resize(K, -1); + for (int j = 0; j < this->num_classes_ - 1; ++j) { + const T logit = input(j); + if (logit > (*top_k_logits)[K - 1]) { + int k = K - 1; + while (k > 0 && logit > (*top_k_logits)[k - 1]) { + (*top_k_logits)[k] = (*top_k_logits)[k - 1]; + (*top_k_indices)[k] = (*top_k_indices)[k - 1]; + k--; + } + (*top_k_logits)[k] = logit; + (*top_k_indices)[k] = j; + } + } + // Return max value which is in 0th index or blank character logit + return std::max((*top_k_logits)[0], input(this->num_classes_ - 1)); +} + +template +template +void CTCBeamSearchDecoder::Step( + const Vector& raw_input) { + std::vector top_k_logits; + std::vector top_k_indices; + const bool top_k = + (label_selection_size_ > 0 && label_selection_size_ < raw_input.size()); + // Number of character classes to consider in each step. + const int max_classes = + top_k ? label_selection_size_ : (this->num_classes_ - 1); + // Get max coefficient and remove it from raw_input later. + T max_coeff; + if (top_k) { + max_coeff = GetTopK(label_selection_size_, raw_input, &top_k_logits, + &top_k_indices); + } else { + max_coeff = raw_input.maxCoeff(); + } + // Get normalization term of softmax: log(sum(exp(logit[j]-max_coeff))). + T logsumexp = T(0.0); + for (int j = 0; j < raw_input.size(); ++j) { + logsumexp += Eigen::numext::exp(raw_input(j) - max_coeff); + } + logsumexp = Eigen::numext::log(logsumexp); + // Final normalization offset to get correct log probabilities. + T norm_offset = max_coeff + logsumexp; + + const T label_selection_input_min = + (label_selection_margin_ >= 0) ? (max_coeff - label_selection_margin_) + : -std::numeric_limits::infinity(); + + // Extract the beams sorted in decreasing new probability + CHECK_EQ(this->num_classes_, raw_input.size()); + + std::unique_ptr> branches(leaves_.Extract()); + leaves_.Reset(); + + for (BeamEntry* b : *branches) { + // P(.. @ t) becomes the new P(.. @ t-1) + b->oldp = b->newp; + } + + for (BeamEntry* b : *branches) { + if (b->parent != nullptr) { // if not the root + if (b->parent->Active()) { + // If last two sequence characters are identical: + // Plabel(l=acc @ t=6) = (Plabel(l=acc @ t=5) + // + Pblank(l=ac @ t=5)) + // else: + // Plabel(l=abc @ t=6) = (Plabel(l=abc @ t=5) + // + P(l=ab @ t=5)) + T previous = (b->label == b->parent->label) ? b->parent->oldp.blank + : b->parent->oldp.total; + b->newp.label = + LogSumExp(b->newp.label, + beam_scorer_->GetStateExpansionScore(b->state, previous)); + } + // Plabel(l=abc @ t=6) *= P(c @ 6) + b->newp.label += raw_input(b->label) - norm_offset; + } + // Pblank(l=abc @ t=6) = P(l=abc @ t=5) * P(- @ 6) + b->newp.blank = b->oldp.total + raw_input(this->blank_index_) - norm_offset; + // P(l=abc @ t=6) = Plabel(l=abc @ t=6) + Pblank(l=abc @ t=6) + b->newp.total = LogSumExp(b->newp.blank, b->newp.label); + + // Push the entry back to the top paths list. + // Note, this will always fill leaves back up in sorted order. + leaves_.push(b); + } + + // we need to resort branches in descending oldp order. + + // branches is in descending oldp order because it was + // originally in descending newp order and we copied newp to oldp. + + // Grow new leaves + for (BeamEntry* b : *branches) { + // A new leaf (represented by its BeamProbability) is a candidate + // iff its total probability is nonzero and either the beam list + // isn't full, or the lowest probability entry in the beam has a + // lower probability than the leaf. + auto is_candidate = [this](const BeamProbability& prob) { + return (prob.total > kLogZero() && + (leaves_.size() < beam_width_ || + prob.total > leaves_.peek_bottom()->newp.total)); + }; + + if (!is_candidate(b->oldp)) { + continue; + } + + for (int ind = 0; ind < max_classes; ind++) { + const int label = top_k ? top_k_indices[ind] : ind; + const T logit = top_k ? top_k_logits[ind] : raw_input(ind); + // Perform label selection: if input for this label looks very + // unpromising, never evaluate it with a scorer. + // We may compare logits instead of log probabilities, + // since the difference is the same in both cases. + if (logit < label_selection_input_min) { + continue; + } + BeamEntry& c = b->GetChild(label); + if (!c.Active()) { + // Pblank(l=abcd @ t=6) = 0 + c.newp.blank = kLogZero(); + // If new child label is identical to beam label: + // Plabel(l=abcc @ t=6) = Pblank(l=abc @ t=5) * P(c @ 6) + // Otherwise: + // Plabel(l=abcd @ t=6) = P(l=abc @ t=5) * P(d @ 6) + beam_scorer_->ExpandState(b->state, b->label, &c.state, c.label); + T previous = (c.label == b->label) ? b->oldp.blank : b->oldp.total; + c.newp.label = logit - norm_offset + + beam_scorer_->GetStateExpansionScore(c.state, previous); + // P(l=abcd @ t=6) = Plabel(l=abcd @ t=6) + c.newp.total = c.newp.label; + + if (is_candidate(c.newp)) { + // Before adding the new node to the beam, check if the beam + // is already at maximum width. + if (leaves_.size() == beam_width_) { + // Bottom is no longer in the beam search. Reset + // its probability; signal it's no longer in the beam search. + BeamEntry* bottom = leaves_.peek_bottom(); + bottom->newp.Reset(); + } + leaves_.push(&c); + } else { + // Deactivate child. + c.oldp.Reset(); + c.newp.Reset(); + } + } + } + } // for (BeamEntry* b... +} + +template +void CTCBeamSearchDecoder::Reset() { + leaves_.Reset(); + + // This beam root, and all of its children, will be in memory until + // the next reset. + beam_root_.reset(new BeamRoot(nullptr, -1)); + beam_root_->RootEntry()->newp.total = T(0.0); // ln(1) + beam_root_->RootEntry()->newp.blank = T(0.0); // ln(1) + + // Add the root as the initial leaf. + leaves_.push(beam_root_->RootEntry()); + + // Call initialize state on the root object. + beam_scorer_->InitializeState(&beam_root_->RootEntry()->state); +} + +template +Status CTCBeamSearchDecoder::TopPaths( + int n, std::vector>* paths, std::vector* log_probs, + bool merge_repeated) const { + CHECK_NOTNULL(paths)->clear(); + CHECK_NOTNULL(log_probs)->clear(); + if (n > beam_width_) { + return errors::InvalidArgument("requested more paths than the beam width."); + } + if (n > leaves_.size()) { + return errors::InvalidArgument( + "Less leaves in the beam search than requested."); + } + + gtl::TopN top_branches(n); + + // O(beam_width_ * log(n)), space complexity is O(n) + for (auto it = leaves_.unsorted_begin(); it != leaves_.unsorted_end(); ++it) { + top_branches.push(*it); + } + // O(n * log(n)) + std::unique_ptr> branches(top_branches.Extract()); + + for (int i = 0; i < n; ++i) { + BeamEntry* e((*branches)[i]); + paths->push_back(e->LabelSeq(merge_repeated)); + log_probs->push_back(e->newp.total); + } + return OkStatus(); +} + +} // namespace ctc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_BEAM_SEARCH_H_ +// LINT.ThenChange(//tensorflow/lite/kernels/ctc/ctc_beam_search.h) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_decoder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_decoder.h new file mode 100644 index 0000000000000000000000000000000000000000..76b3c19b0fea5eddc4c99222cf0bbc3612eb0e06 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_decoder.h @@ -0,0 +1,121 @@ +/* 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. +==============================================================================*/ +// LINT.IfChange + +#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_DECODER_H_ +#define TENSORFLOW_CORE_UTIL_CTC_CTC_DECODER_H_ + +#include +#include + +#include "Eigen/Core" // from @eigen_archive +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +namespace ctc { + +// The CTCDecoder is an abstract interface to be implemented when providing a +// decoding method on the timestep output of a RNN trained with CTC loss. +// +// The two types of decoding available are: +// - greedy path, through the CTCGreedyDecoder +// - beam search, through the CTCBeamSearchDecoder +template +class CTCDecoder { + public: + typedef Eigen::Map SequenceLength; + typedef Eigen::Map> + Input; + typedef std::vector> Output; + typedef Eigen::Map> + ScoreOutput; + + CTCDecoder(int num_classes, int batch_size, bool merge_repeated) + : num_classes_(num_classes), + blank_index_(num_classes - 1), + batch_size_(batch_size), + merge_repeated_(merge_repeated) {} + + virtual ~CTCDecoder() {} + + // Dimensionality of the input/output is expected to be: + // - seq_len[b] - b = 0 to batch_size_ + // - input[t].rows(b) - t = 0 to timesteps; b = 0 t batch_size_ + // - output.size() specifies the number of beams to be returned. + // - scores(b, i) - b = 0 to batch_size; i = 0 to output.size() + virtual Status Decode(const SequenceLength& seq_len, + const std::vector& input, + std::vector* output, ScoreOutput* scores) = 0; + + int batch_size() { return batch_size_; } + int num_classes() { return num_classes_; } + + protected: + int num_classes_; + int blank_index_; + int batch_size_; + bool merge_repeated_; +}; + +// CTCGreedyDecoder is an implementation of the simple best path decoding +// algorithm, selecting at each timestep the most likely class at each timestep. +template +class CTCGreedyDecoder : public CTCDecoder { + public: + typedef CTCDecoder Decoder; + CTCGreedyDecoder(int num_classes, int batch_size, bool merge_repeated) + : CTCDecoder(num_classes, batch_size, merge_repeated) {} + + Status Decode(const typename CTCDecoder::SequenceLength& seq_len, + const std::vector::Input>& input, + std::vector::Output>* output, + typename CTCDecoder::ScoreOutput* scores) override { + if (output->empty() || (*output)[0].size() < Decoder::batch_size_) { + return errors::InvalidArgument( + "output needs to be of size at least (1, batch_size)."); + } + if (scores->rows() < Decoder::batch_size_ || scores->cols() == 0) { + return errors::InvalidArgument( + "scores needs to be of size at least (batch_size, 1)."); + } + // For each batch entry, identify the transitions + for (int b = 0; b < Decoder::batch_size_; ++b) { + int seq_len_b = seq_len[b]; + // Only writing to beam 0 + std::vector& output_b = (*output)[0][b]; + + int prev_class_ix = -1; + (*scores)(b, 0) = 0; + for (int t = 0; t < seq_len_b; ++t) { + auto row = input[t].row(b); + int max_class_ix; + (*scores)(b, 0) += -row.maxCoeff(&max_class_ix); + if (max_class_ix != Decoder::blank_index_ && + !(Decoder::merge_repeated_ && max_class_ix == prev_class_ix)) { + output_b.push_back(max_class_ix); + } + prev_class_ix = max_class_ix; + } + } + return OkStatus(); + } +}; + +} // namespace ctc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_DECODER_H_ +// LINT.ThenChange(//tensorflow/lite/kernels/ctc/ctc_decoder.h) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_loss_calculator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_loss_calculator.h new file mode 100644 index 0000000000000000000000000000000000000000..42114ad4a40d8eba888d76918600d914450c0bf8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_loss_calculator.h @@ -0,0 +1,543 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_CALCULATOR_H_ +#define TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_CALCULATOR_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/util/ctc/ctc_loss_util.h" +#include "tensorflow/core/util/work_sharder.h" + +namespace tensorflow { +namespace ctc { + +template +class CTCLossCalculator { + // Connectionist Temporal Classification Loss + // + // Implementation by kanishkarao@, posenhuang@, and ebrevdo@. + // + // The CTC Loss layer learns a *transition* probability value for each + // input time step. The transitions are on the class alphabet + // {0, 1, ..., N-2} + // where N is the depth of the input layer (the size of the alphabet is N-1). + // Note: The token N-1 is reserved for the "no transition" output, so + // make sure that your input layer has a depth that's one larger than + // the set of classes you're training on. Also make sure that your + // training labels do not have a class value of N-1, as training will skip + // these examples. + // + // Reference materials: + // GravesTh: Alex Graves, "Supervised Sequence Labeling with Recurrent + // Neural Networks" (PhD Thesis), Technische Universit¨at M¨unchen. + public: + typedef std::vector> LabelSequences; + using Matrix = Eigen::Matrix; + // typedef Eigen::MatrixXd Matrix; + using Array = Eigen::Array; + // typedef Eigen::ArrayXd Array; + using InputMap = Eigen::Map; + // typedef Eigen::Map InputMap; + using OutputMap = Eigen::Map; + // typedef Eigen::Map OutputMap; + + CTCLossCalculator(int blank_index, int output_delay) + : blank_index_(blank_index), output_delay_(output_delay) {} + + template + Status CalculateLoss(const VectorIn& seq_len, const LabelSequences& labels, + const std::vector& inputs, + bool preprocess_collapse_repeated, + bool ctc_merge_repeated, + bool ignore_longer_outputs_than_inputs, VectorOut* loss, + std::vector* gradients, + DeviceBase::CpuWorkerThreads* workers = nullptr) const; + + private: + void CalculateForwardVariables(const std::vector& l_prime, + const Matrix& y, bool ctc_merge_repeated, + Matrix* log_alpha) const; + + void CalculateBackwardVariables(const std::vector& l_prime, + const Matrix& y, bool ctc_merge_repeated, + Matrix* log_beta) const; + + void CalculateGradient(const std::vector& l_prime, const Matrix& y, + const Matrix& log_alpha, const Matrix& log_beta, + T log_p_z_x, Matrix* dy) const; + + void GetLPrimeIndices(const std::vector& l, + std::vector* l_prime) const; + + // Helper function that calculates the l_prime indices for all + // batches at the same time, and identifies errors for any given + // batch. Return value: + // max_{b in batch_size} l_primes[b].size() + template + Status PopulateLPrimes(bool preprocess_collapse_repeated, + bool ignore_longer_outputs_than_inputs, int batch_size, + int num_classes, const Vector& seq_len, + const LabelSequences& labels, size_t* max_u_prime, + LabelSequences* l_primes) const; + + // Utility indices for the CTC algorithm. + int blank_index_; + + // Delay for target labels in time steps. + // The delay in time steps before the output sequence. + const int output_delay_; +}; + +template +template +Status CTCLossCalculator::CalculateLoss( + const VectorIn& seq_len, const LabelSequences& labels, + const std::vector& inputs, bool preprocess_collapse_repeated, + bool ctc_merge_repeated, bool ignore_longer_outputs_than_inputs, + VectorOut* loss, std::vector* gradients, + DeviceBase::CpuWorkerThreads* workers) const { + using Eigen::numext::log; + + auto num_time_steps = inputs.size(); + + if (loss == nullptr) { + return errors::InvalidArgument("loss == nullptr"); + } + + bool requires_backprop = (gradients != nullptr); + + auto batch_size = inputs[0].rows(); + auto num_classes = inputs[0].cols(); + + if (loss->size() != batch_size) { + return errors::InvalidArgument("loss.size() != batch_size"); + } + loss->setZero(); + + for (int t = 1; t < num_time_steps; ++t) { + if (inputs[t].rows() != batch_size) { + return errors::InvalidArgument("Expected batch size at t: ", t, + " to be: ", batch_size, + " but got: ", inputs[t].rows()); + } + if (inputs[t].cols() != num_classes) { + return errors::InvalidArgument("Expected class count at t: ", t, + " to be: ", num_classes, + " but got: ", inputs[t].cols()); + } + } + + // Check validity of sequence_length array values. + auto max_seq_len = seq_len(0); + for (int b = 0; b < batch_size; b++) { + if (seq_len(b) < 0) { + return errors::InvalidArgument("seq_len(", b, ") < 0"); + } + if (seq_len(b) > num_time_steps) { + return errors::InvalidArgument("seq_len(", b, ") > num_time_steps"); + } + max_seq_len = std::max(seq_len(b), max_seq_len); + } + + // Calculate the modified label sequence l' for each batch element, + // and calculate the maximum necessary allocation size. + LabelSequences l_primes(batch_size); + size_t max_u_prime = 0; + Status l_p_ret = PopulateLPrimes( + preprocess_collapse_repeated, ignore_longer_outputs_than_inputs, + batch_size, num_classes, seq_len, labels, &max_u_prime, &l_primes); + if (!l_p_ret.ok()) { + return l_p_ret; + } + + // Process each item in a batch in parallel, using at most kMaxThreads. + auto ComputeLossAndGradients = [this, num_classes, &labels, &l_primes, + &seq_len, &inputs, requires_backprop, + ctc_merge_repeated, + ignore_longer_outputs_than_inputs, &loss, + &gradients](int64_t start_row, + int64_t limit_row) { + for (int b = start_row; b < limit_row; b++) { + // Return zero gradient for empty sequences or sequences with labels + // longer than input, which is not supported by CTC. + if (seq_len(b) == 0 || + (ignore_longer_outputs_than_inputs && + labels[b].size() > seq_len(b) - this->output_delay_)) { + VLOG(1) << "The sequence length is either zero or shorter than the " + "target output (CTC works only with shorter target sequence " + "than input sequence). You can turn this into a warning by " + "using the flag ignore_longer_outputs_than_inputs - " + << b << ": " << str_util::Join(labels[b], " "); + continue; + } + + // For each batch element, log(alpha) and log(beta). + // row size is: u_prime == l_prime.size() + // col size is: seq_len[b] - output_delay_ + const std::vector& l_prime = l_primes[b]; + + Matrix log_alpha_b(l_prime.size(), seq_len(b) - this->output_delay_); + Matrix log_beta_b(l_prime.size(), seq_len(b) - this->output_delay_); + + // Work matrices, pre-allocated to the size required by this batch item. + Matrix y(num_classes, seq_len(b)); + Matrix dy; + if (requires_backprop) { + dy = Matrix::Zero(y.rows(), y.cols()); + } + + // For this batch, we'll only work with this shortened sequence_length. + Matrix y_b = y.leftCols(seq_len(b)); + + // Convert label from DistBelief + // y, prob are in num_classes x seq_len(b) + // Output activations. + Array y_b_col; + for (int t = 0; t < seq_len(b); t++) { + // Calculate the softmax of y_b. Use original precision + // arithmetic for the sum. + T max_coeff = inputs[t].row(b).maxCoeff(); + y_b_col = (inputs[t].row(b).array() - max_coeff).exp(); + y_b.col(t) = y_b_col / y_b_col.sum(); + } + + // Compute forward, backward. + // Forward variables. + CalculateForwardVariables(l_prime, y_b, ctc_merge_repeated, &log_alpha_b); + // Backward variables. + CalculateBackwardVariables(l_prime, y_b, ctc_merge_repeated, &log_beta_b); + + // The loss is computed as the log(p(z|x)) between the target and + // prediction. Do lazy evaluation of log_prob here. + T log_p_z_x = kLogZero(); + for (int u = 0; u < l_prime.size(); ++u) { + // (GravesTh) Eq 7.26, sum over all paths for t = 0. + log_p_z_x = LogSumExp(log_p_z_x, log_alpha_b(u, 0) + log_beta_b(u, 0)); + } + + (*loss)(b) = -log_p_z_x; // Use negative log loss for display. + + // We compute the derivative if needed. + if (requires_backprop) { + // Gradients with respect to input activations. + // Calculate gradient. + dy.setZero(); + CalculateGradient(l_prime, y_b, log_alpha_b, log_beta_b, log_p_z_x, + &dy); + + // Convert gradient for current sample to DistBelief. + for (int t = 0; t < seq_len(b); t++) { + (*gradients)[t].row(b).array() = dy.col(t); + } + } + } // for (int b = ... + }; + if (workers) { + // *Rough* estimate of the cost for one item in the batch. + // Forward, Backward: O(T * U (= 2L + 1)), Gradients: O(T * (U + L)). + // + // softmax: T * L * (Cost(Exp) + Cost(Div))softmax + + // fwd,bwd: T * 2 * (2*L + 1) * (Cost(LogSumExp) + Cost(Log)) + + // grad: T * ((2L + 1) * Cost(LogSumExp) + L * (Cost(Expf) + Cost(Add)). + const int64_t cost_exp = Eigen::internal::functor_traits< + Eigen::internal::scalar_exp_op>::Cost; + const int64_t cost_log = Eigen::internal::functor_traits< + Eigen::internal::scalar_log_op>::Cost; + const int64_t cost_log_sum_exp = + Eigen::TensorOpCost::AddCost() + cost_exp + cost_log; + const int64_t cost = + max_seq_len * num_classes * + (cost_exp + Eigen::TensorOpCost::DivCost()) + + max_seq_len * 2 * (2 * num_classes + 1) * + (cost_log_sum_exp + cost_log) + + max_seq_len * + ((2 * num_classes + 1) * cost_log_sum_exp + + num_classes * (cost_exp + Eigen::TensorOpCost::AddCost())); + Shard(workers->num_threads, workers->workers, batch_size, cost, + ComputeLossAndGradients); + } else { + ComputeLossAndGradients(0, batch_size); + } + return OkStatus(); +} + +template +template +Status CTCLossCalculator::PopulateLPrimes( + bool preprocess_collapse_repeated, bool ignore_longer_outputs_than_inputs, + int batch_size, int num_classes, const Vector& seq_len, + const LabelSequences& labels, size_t* max_u_prime, + LabelSequences* l_primes) const { + // labels is a Label array of size batch_size + if (labels.size() != batch_size) { + return errors::InvalidArgument( + "labels.size() != batch_size: ", labels.size(), " vs. ", batch_size); + } + + *max_u_prime = 0; // keep track of longest l' modified label sequence. + for (int b = 0; b < batch_size; b++) { + // Assume label is in Label proto + const std::vector& label = labels[b]; + if (label.size() == 0) { + return errors::InvalidArgument("Labels length is zero in batch ", b); + } + + // If debugging: output the labels coming into training. + // + VLOG(2) << "label for batch: " << b << ": " << str_util::Join(label, " "); + + // Target indices, length = U. + std::vector l; + + // Convert label from DistBelief + bool finished_sequence = false; + for (int i = 0; i < label.size(); ++i) { + if (i == 0 || !preprocess_collapse_repeated || label[i] != label[i - 1]) { + if (label[i] >= num_classes - 1) { + finished_sequence = true; + } else { + if (finished_sequence) { + // Saw an invalid sequence with non-null following null + // labels. + return errors::InvalidArgument( + "Saw a non-null label (index >= num_classes - 1) " + "following a ", + "null label, batch: ", b, " num_classes: ", num_classes, + " labels: ", str_util::Join(label, ","), + " labels seen so far: ", str_util::Join(l, ",")); + } + l.push_back(label[i]); + } + } + } + + for (int l_i : l) { + if (l_i < 0) { + return errors::InvalidArgument( + "All labels must be nonnegative integers, batch: ", b, + " labels: ", str_util::Join(l, ",")); + } else if (l_i >= num_classes) { + return errors::InvalidArgument( + "No label may be greater than num_classes. ", + "num_classes: ", num_classes, ", batch: ", b, + " labels: ", str_util::Join(l, ",")); + } + } + if (!ignore_longer_outputs_than_inputs) { + // Make sure there is enough time to output the target indices. + int time = seq_len(b) - output_delay_; + int required_time = label.size(); + if (required_time > time) { + return errors::InvalidArgument( + "Not enough time for target transition sequence (" + "required: ", + required_time, ", available: ", time, ")", b, + "You can turn this error into a warning by using the flag " + "ignore_longer_outputs_than_inputs"); + } + } + // Target indices with blanks before each index and a blank at the end. + // Length U' = 2U + 1. + // Convert l to l_prime + GetLPrimeIndices(l, &l_primes->at(b)); + *max_u_prime = std::max(*max_u_prime, l_primes->at(b).size()); + } + return OkStatus(); +} + +// Calculates the alpha(t, u) as described in (GravesTh) Section 7.3. +// Starting with t = 0 instead of t = 1 used in the text. +// Based on Kanishka's CTC. +template +void CTCLossCalculator::CalculateForwardVariables( + const std::vector& l_prime, const Matrix& y, bool ctc_merge_repeated, + Matrix* log_alpha) const { + using Eigen::numext::log; + + // Number of cols is the number of time steps = number of cols in target + // after the output delay. + log_alpha->setConstant(kLogZero()); + + int U = l_prime.size(); + int T = log_alpha->cols(); + + CHECK_EQ(U, log_alpha->rows()); + + // Initial alpha values in (GravesTh) Eq 7.5 and Eq 7.6. + log_alpha->coeffRef(0, 0) = log(y(blank_index_, output_delay_)); + // Below, l_prime[1] == labels[0] + auto label_0 = (l_prime.size() > 1) ? l_prime[1] : blank_index_; + log_alpha->coeffRef(1, 0) = log(y(label_0, output_delay_)); + + for (int t = 1; t < T; ++t) { + // If there is not enough time to output the remaining labels or + // some labels have been skipped, then let log_alpha(u, t) continue to + // be kLogZero. + for (int u = std::max(0, U - (2 * (T - t))); u < std::min(U, 2 * (t + 1)); + ++u) { + // Begin (GravesTh) Eq 7.9 + // Add in the u, t - 1 term. + auto sum_log_alpha = kLogZero(); + if (ctc_merge_repeated || l_prime[u] == blank_index_) { + sum_log_alpha = log_alpha->coeff(u, t - 1); + } + + // Add in the u - 1, t - 1 term. + if (u > 0) { + sum_log_alpha = + LogSumExp(sum_log_alpha, log_alpha->coeff(u - 1, t - 1)); + } + + // Add in the u - 2, t - 1 term if l_prime(u) != blank or l_prime(u-2). + if (u > 1) { + const bool matching_labels_merge = + ctc_merge_repeated && (l_prime[u] == l_prime[u - 2]); + if (l_prime[u] != blank_index_ && !matching_labels_merge) { + sum_log_alpha = + LogSumExp(sum_log_alpha, log_alpha->coeff(u - 2, t - 1)); + } + } + // Multiply the summed alphas with the activation log probability. + log_alpha->coeffRef(u, t) = + log(y(l_prime[u], output_delay_ + t)) + sum_log_alpha; + } // End (GravesTh) Eq 7.9. + } +} + +// Calculates the beta(t, u) as described in (GravesTh) Section 7.3. +template +void CTCLossCalculator::CalculateBackwardVariables( + const std::vector& l_prime, const Matrix& y, bool ctc_merge_repeated, + Matrix* log_beta) const { + // Number of cols is the number of time steps = number of cols in target. + // Matrix log_beta = + // Matrix::Constant(l_prime.size(), y.cols() - output_delay_, + // kLogZero); + using Eigen::numext::log; + + log_beta->setConstant(kLogZero()); + int T = log_beta->cols(); + int U = l_prime.size(); + CHECK_EQ(U, log_beta->rows()); + + // Initial beta values in (GravesTh) Eq 7.13: log of probability 1. + for (int u = U - 2; u < U; ++u) log_beta->coeffRef(u, T - 1) = 0; + + for (int t = T - 1 - 1; t >= 0; --t) { + // If there is not enough time to output the remaining labels or + // some labels have been skipped, then let log_beta(u, t) continue to + // be kLogZero. + for (int u = std::max(0, U - (2 * (T - t))); u < std::min(U, 2 * (t + 1)); + ++u) { + // Begin (GravesTh) Eq 7.15 + // Add in the u, t + 1 term. + if (ctc_merge_repeated || l_prime[u] == blank_index_) { + log_beta->coeffRef(u, t) = + LogSumExp(log_beta->coeff(u, t), + log_beta->coeff(u, t + 1) + + log(y(l_prime[u], output_delay_ + t + 1))); + } + + // Add in the u + 1, t + 1 term. + if (u + 1 < U) { + log_beta->coeffRef(u, t) = + LogSumExp(log_beta->coeff(u, t), + log_beta->coeff(u + 1, t + 1) + + log(y(l_prime[u + 1], output_delay_ + t + 1))); + } + + // Add in the u + 2, t + 1 term if l_prime(u) != blank or l_prime(u+2). + if (u + 2 < U) { + const bool matching_labels_merge = + ctc_merge_repeated && (l_prime[u] == l_prime[u + 2]); + if (l_prime[u] != blank_index_ && !matching_labels_merge) { + // Add in u + 2 term. + log_beta->coeffRef(u, t) = + LogSumExp(log_beta->coeff(u, t), + log_beta->coeff(u + 2, t + 1) + + log(y(l_prime[u + 2], output_delay_ + t + 1))); + } + } // End (GravesTh) Eq. 7.15 + } + } +} + +// Using (GravesTh) Eq 7.26 & 7.34. +template +void CTCLossCalculator::CalculateGradient(const std::vector& l_prime, + const Matrix& y, + const Matrix& log_alpha, + const Matrix& log_beta, + TT log_p_z_x, Matrix* dy) const { + // Only working with the leftmost part of dy for this batch element. + auto dy_b = dy->leftCols(y.cols()); + + // It is possible that no valid path is found if the activations for the + // targets are zero. + if (log_p_z_x == kLogZero()) { + LOG(WARNING) << "No valid path found."; + dy_b = y; + return; + } + + int L = y.rows(); + int T = y.cols(); + int U = l_prime.size(); + + for (int t = 0; t < T - output_delay_; ++t) { + Array prob_sum(L); + prob_sum.setConstant(kLogZero()); + + for (int u = 0; u < U; ++u) { + int l = l_prime[u]; + prob_sum[l] = LogSumExp(prob_sum[l], log_alpha(u, t) + log_beta(u, t)); + } + + for (int l = 0; l < L; ++l) { + // Negative term in (GravesTh) Eq 7.28. + auto negative_term = expf(prob_sum[l] - log_p_z_x); + + dy_b(l, output_delay_ + t) = y(l, output_delay_ + t) - negative_term; + } + } +} + +template +void CTCLossCalculator::GetLPrimeIndices(const std::vector& l, + std::vector* l_prime) const { + // Assumption is that l_prime is empty. + l_prime->reserve(2 * l.size() + 1); + + for (auto label : l) { + l_prime->push_back(blank_index_); + l_prime->push_back(label); + } + // Add final blank to l'. + l_prime->push_back(blank_index_); +} + +} // namespace ctc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_CALCULATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_loss_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_loss_util.h new file mode 100644 index 0000000000000000000000000000000000000000..e9fc99afac10e90d4a082933d7d045d00a23881d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/ctc/ctc_loss_util.h @@ -0,0 +1,55 @@ +/* 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. +==============================================================================*/ +// LINT.IfChange + +#ifndef TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_ +#define TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_ + +#include +#include + +namespace tensorflow { +namespace ctc { + +template +constexpr T kLogZero() { + return -std::numeric_limits::infinity(); // NOLINT +} + +// Add logarithmic probabilities using: +// ln(a + b) = ln(a) + ln(1 + exp(ln(b) - ln(a))) +// The two inputs are assumed to be log probabilities. +// (GravesTh) Eq. 7.18 +template +inline T LogSumExp(T log_prob_1, T log_prob_2) { + // const T kLogZero = -std::numeric_limits::infinity(); + // Always have 'b' be the smaller number to avoid the exponential from + // blowing up. + if (log_prob_1 == kLogZero()) { + return log_prob_2; + } else if (log_prob_2 == kLogZero()) { + return log_prob_1; + } else { + return (log_prob_1 > log_prob_2) + ? log_prob_1 + log1pf(expf(log_prob_2 - log_prob_1)) + : log_prob_2 + log1pf(expf(log_prob_1 - log_prob_2)); + } +} + +} // namespace ctc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_CTC_CTC_LOSS_UTIL_H_ +// LINT.ThenChange(//tensorflow/lite/kernels/ctc/ctc_loss_util.h) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/decode.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/decode.h new file mode 100644 index 0000000000000000000000000000000000000000..25b9620558c736e4d6219ba908f3855074907a43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/decode.h @@ -0,0 +1,711 @@ +/* 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. +==============================================================================*/ + +// Inline functions for parsing the protocol buffers wire format. +// +// These functions have been optimized at the expense of safety. +// They are broken out into a separate file for readability but are +// not intended for use by clients other than the decode_proto op. +// +// The calling code in the decode_proto op does some fairly +// complicated things to ensure that this code is called +// safely. Changes to this code should be thoroughly fuzz tested. + +#ifndef TENSORFLOW_CORE_UTIL_PROTO_DECODE_H_ +#define TENSORFLOW_CORE_UTIL_PROTO_DECODE_H_ + +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace internal { + +using tensorflow::protobuf::internal::WireFormatLite; +using tensorflow::protobuf::io::CodedInputStream; +using tensorflow::protobuf::io::CodedOutputStream; +using tensorflow::protobuf::io::StringOutputStream; + +// Converts an uint64 to an int64 without loss of information. +// Unsigned values greater than INT64_MAX are represented as +// negative numbers by wrapping (same as twos-complement bit equivalence). +inline int64_t WrapUnsignedAsSigned64(uint64 unsigned_value) { + // For a detailed explanation of why this works to wrap unsigned ints, see + // http://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior + // Both if tests should be optimized out. + if (unsigned_value <= INT64_MAX) { + return static_cast(unsigned_value); + } + // The C++ spec allows an architecture where this test is required. + if (unsigned_value >= INT64_MIN) { + return static_cast(unsigned_value - INT64_MIN) + INT64_MIN; + } + return 0; // This should never occur. +} + +// Converts an uint32 to an int32 without loss of information. +// Unsigned values greater than INT_MAX are represented as +// negative numbers by wrapping (same as twos-complement bit equivalence). +inline int32 WrapUnsignedAsSigned32(uint32 unsigned_value) { + // For a detailed explanation of why this works to wrap unsigned ints, see + // http://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior + // Both if tests should be optimized out. + if (unsigned_value <= INT_MAX) { + return static_cast(unsigned_value); + } + // The C++ spec allows an architecture where this test is required. + if (unsigned_value >= INT_MIN) { + return static_cast(unsigned_value - INT_MIN) + INT_MIN; + } + return 0; // This should never occur. +} + +// Reads a single varint32 from a byte array. +// It is the caller's responsibility to ensure that there is enough +// space in the buffer. +// The ok value will be set to false if the buffer does not contain +// a valid varint. +inline const uint8* ReadVarint64FromArray(const uint8* buffer, bool* ok, + uint64* value); + +// Reads a single varint32 from a byte array. +// It is the caller's responsibility to ensure that there is enough +// space in the buffer. +// The ok value will be set to false if the buffer does not contain +// a valid varint. +// This is slightly less efficient than the private version in +// coded_stream.cc but we duplicate less code by calling +// the 64 bit version instead of copying the code. +inline const uint8* ReadVarint32FromArray(const uint8* buffer, bool* ok, + uint32* value) { + uint64 tmp = 0; + const uint8* buf = ReadVarint64FromArray(buffer, ok, &tmp); + *value = tmp & 0xffffffff; + return buf; +} + +// Reads a single proto field value from a byte array into an array. +// The array is part of a Tensor that was allocated by the caller +// with type TensorType, while DeclaredType is the proto field type. +template +const uint8* ReadFromArray(const uint8* buf, TensorType* value); + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int64_t* value) { + uint32 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint32FromArray(buf, &unused_ok, &temp); + *value = static_cast(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int32* value) { + uint32 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint32FromArray(buf, &unused_ok, &temp); + *value = static_cast(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int64_t* value) { + uint64 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint64FromArray(buf, &unused_ok, &temp); + *value = WrapUnsignedAsSigned64(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, uint64* value) { + uint32 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint32FromArray(buf, &unused_ok, &temp); + *value = temp; + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, uint32* value) { + bool unused_ok; // The Counting pass would have failed if this were corrupt. + return ReadVarint32FromArray(buf, &unused_ok, value); +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, uint64* value) { + bool unused_ok; // The Counting pass would have failed if this were corrupt. + return ReadVarint64FromArray(buf, &unused_ok, value); +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int64_t* value) { + uint64 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint64FromArray(buf, &unused_ok, &temp); + *value = WireFormatLite::ZigZagDecode32(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int32* value) { + uint32 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint32FromArray(buf, &unused_ok, &temp); + *value = WireFormatLite::ZigZagDecode32(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int64_t* value) { + uint64 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint64FromArray(buf, &unused_ok, &temp); + *value = WireFormatLite::ZigZagDecode64(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, uint64* value) { + uint32 temp; + buf = WireFormatLite::ReadPrimitiveFromArray( + buf, &temp); + *value = temp; + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, uint32* value) { + uint32 temp; + buf = WireFormatLite::ReadPrimitiveFromArray( + buf, &temp); + *value = WrapUnsignedAsSigned32(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, uint64* value) { + protobuf_uint64 temp; + buf = WireFormatLite::ReadPrimitiveFromArray( + buf, &temp); + *value = WrapUnsignedAsSigned64(temp); + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int64_t* value) { + int32_t temp; + buf = WireFormatLite::ReadPrimitiveFromArray( + buf, &temp); + *value = temp; + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int32* value) { + return WireFormatLite::ReadPrimitiveFromArray( + buf, value); +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int64_t* value) { + protobuf_int64 temp; + buf = WireFormatLite::ReadPrimitiveFromArray( + buf, &temp); + *value = temp; + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, float* value) { + return WireFormatLite::ReadPrimitiveFromArray( + buf, value); +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, double* value) { + float temp; + buf = + WireFormatLite::ReadPrimitiveFromArray( + buf, &temp); + *value = temp; + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, double* value) { + return WireFormatLite::ReadPrimitiveFromArray( + buf, value); +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, bool* value) { + uint64 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint64FromArray(buf, &unused_ok, &temp); + *value = temp != 0; + return buf; +} + +template <> +inline const uint8* ReadFromArray( + const uint8* buf, int* value) { + uint32 temp = 0; + bool unused_ok; // The Counting pass would have failed if this were corrupt. + buf = ReadVarint32FromArray(buf, &unused_ok, &temp); + *value = static_cast(temp); + return buf; +} + +// Reads packed values from an array. +// Stride is set to 1 for repeated fields, and 0 for non-repeated fields +// (where any value overwrites previous values). +template +inline int ReadPackedPrimitives(const void* bufp, const size_t len, + const int index, const int stride, + void* datap) { + const uint8* buf = reinterpret_cast(bufp); + const uint8* bound = buf + len; + TensorType* data = reinterpret_cast(datap) + index; + int count; + + // This could overrun the bound by stride-1. This is defended + // against in the caller, where it ensures that the input buffer + // contains complete values. + for (count = 0; buf < bound; count += stride) { + buf = ReadFromArray(buf, data + count); + } + return count; +} + +// Reads a value of a primitive type field from a serialized proto. +// The value is parsed from the serialized format, then static_cast +// to the desired type for TensorFlow and stored. +template +inline Status ReadPrimitive(CodedInputStream* input, int index, void* data) { + ValueType v; + if (!WireFormatLite::ReadPrimitive(input, &v)) { + return errors::DataLoss("Failed reading primitive"); + } + + reinterpret_cast(data)[index] = v; + return OkStatus(); +} + +// Reads a string, submessage, or other variable-length field from a +// serialized proto. +// May read all or part of a repeated field. +inline Status ReadBytes(CodedInputStream* input, int index, void* datap) { + tstring* data = reinterpret_cast(datap) + index; + + uint32 length; + if (!input->ReadVarint32(&length)) { + return errors::DataLoss("Failed reading bytes"); + } + + data->resize_uninitialized(length); + + if (!input->ReadRaw(data->data(), length)) { + return errors::DataLoss("Failed reading bytes"); + } + return OkStatus(); +} + +// Reads a tag-delimited field (TYPE_GROUP) from a serialized proto, +// as a bytestring. +inline Status ReadGroupBytes(CodedInputStream* input, int field_number, + int index, void* datap) { + // WireFormatLite::SkipField has an option to emit the + // skipped bytes to an output stream. We could do better by implementing our + // own scanner but this is simpler for now. + // TODO(nix): there is a faster way to grab TYPE_GROUP bytes by relying + // on input->IsFlat() == true and using input->GetDirectBufferPointer() + // with input->CurrentPosition(). + tstring* data = reinterpret_cast(datap) + index; + // TODO(dero): To mitigate the string to tstring copy, we can implement our + // own scanner as described above. We would first need to obtain the length + // in an initial pass and resize/reserve the tstring. But, given that + // TYPE_GROUP is deprecated and currently no tests in + // tensorflow/python/kernel_tests/proto:decode_proto_op_test target a + // TYPE_GROUP tag, we use std::string as a read buffer. + string buf; + StringOutputStream string_stream(&buf); + { + CodedOutputStream out(&string_stream); + if (!WireFormatLite::SkipField( + input, + WireFormatLite::MakeTag(field_number, + WireFormatLite::WIRETYPE_START_GROUP), + &out)) { + return errors::DataLoss("Failed reading group"); + } + } + *data = buf; + return OkStatus(); +} + +// Reads a single field value from a CodedInputStream into a tensor. +inline Status ReadValue(CodedInputStream* input, + WireFormatLite::FieldType field_type, int field_number, + DataType dtype, int index, void* datap) { + // Dispatch to the appropriately typed field reader based on the schema type. + switch (field_type) { + case WireFormatLite::TYPE_DOUBLE: + return ReadPrimitive( + input, index, datap); + case WireFormatLite::TYPE_FLOAT: + switch (dtype) { + case DataType::DT_DOUBLE: + return ReadPrimitive( + input, index, datap); + case DataType::DT_FLOAT: + return ReadPrimitive( + input, index, datap); + default: + return errors::DataLoss("Failed reading TYPE_FLOAT for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_INT64: + return ReadPrimitive( + input, index, datap); + case WireFormatLite::TYPE_UINT64: + return ReadPrimitive(input, index, datap); + case WireFormatLite::TYPE_INT32: + switch (dtype) { + case DataType::DT_INT64: + return ReadPrimitive( + input, index, datap); + case DataType::DT_INT32: + return ReadPrimitive( + input, index, datap); + default: + return errors::DataLoss("Failed reading TYPE_INT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_FIXED64: + return ReadPrimitive(input, index, datap); + case WireFormatLite::TYPE_FIXED32: + switch (dtype) { + case DataType::DT_UINT64: + return ReadPrimitive( + input, index, datap); + case DataType::DT_UINT32: + return ReadPrimitive( + input, index, datap); + default: + return errors::DataLoss("Failed reading TYPE_FIXED32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_BOOL: + return ReadPrimitive(input, index, + datap); + case WireFormatLite::TYPE_STRING: + return ReadBytes(input, index, datap); + case WireFormatLite::TYPE_GROUP: + return ReadGroupBytes(input, field_number, index, datap); + case WireFormatLite::TYPE_MESSAGE: + return ReadBytes(input, index, datap); + case WireFormatLite::TYPE_BYTES: + return ReadBytes(input, index, datap); + case WireFormatLite::TYPE_UINT32: + switch (dtype) { + case DataType::DT_UINT64: + return ReadPrimitive( + input, index, datap); + case DataType::DT_UINT32: + return ReadPrimitive( + input, index, datap); + default: + return errors::DataLoss("Failed reading TYPE_UINT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_ENUM: + return ReadPrimitive( + input, index, datap); + case WireFormatLite::TYPE_SFIXED32: + switch (dtype) { + case DataType::DT_INT64: + return ReadPrimitive( + input, index, datap); + case DataType::DT_INT32: + return ReadPrimitive( + input, index, datap); + default: + return errors::DataLoss("Failed reading TYPE_SFIXED32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_SFIXED64: + return ReadPrimitive(input, index, datap); + case WireFormatLite::TYPE_SINT32: + switch (dtype) { + case DataType::DT_INT64: + return ReadPrimitive( + input, index, datap); + case DataType::DT_INT32: + return ReadPrimitive( + input, index, datap); + default: + return errors::DataLoss("Failed reading TYPE_SINT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_SINT64: + return ReadPrimitive(input, index, datap); + // default: intentionally omitted in order to enable static checking. + } + // Unreachable. + return errors::DataLoss("Failed reading unknown wire type"); +} + +// Reads and stores a length-delimited list of values. +inline Status ReadPackedFromArray(const void* buf, size_t buf_size, + const WireFormatLite::FieldType field_type, + const int field_number, const DataType dtype, + const int stride, int* index, void* data) { + // Dispatch to the appropriately typed field reader based on the schema type. + switch (field_type) { + case WireFormatLite::TYPE_DOUBLE: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case WireFormatLite::TYPE_FLOAT: + switch (dtype) { + case DataType::DT_DOUBLE: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case DataType::DT_FLOAT: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + default: + return errors::DataLoss("Failed reading TYPE_FLOAT for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_INT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case WireFormatLite::TYPE_UINT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case WireFormatLite::TYPE_INT32: + switch (dtype) { + case DataType::DT_INT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case DataType::DT_INT32: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + default: + return errors::DataLoss("Failed reading TYPE_INT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_FIXED64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case WireFormatLite::TYPE_FIXED32: + switch (dtype) { + case DataType::DT_UINT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case DataType::DT_UINT32: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + default: + return errors::DataLoss("Failed reading TYPE_FIXED32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_BOOL: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case WireFormatLite::TYPE_STRING: + case WireFormatLite::TYPE_GROUP: + case WireFormatLite::TYPE_MESSAGE: + case WireFormatLite::TYPE_BYTES: + return errors::DataLoss("Non-primitive type encountered as packed"); + case WireFormatLite::TYPE_UINT32: + switch (dtype) { + case DataType::DT_UINT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case DataType::DT_UINT32: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + default: + return errors::DataLoss("Failed reading TYPE_UINT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_ENUM: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case WireFormatLite::TYPE_SFIXED32: + switch (dtype) { + case DataType::DT_INT64: + *index += + ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case DataType::DT_INT32: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + default: + return errors::DataLoss("Failed reading TYPE_INT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_SFIXED64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + + case WireFormatLite::TYPE_SINT32: + switch (dtype) { + case DataType::DT_INT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + case DataType::DT_INT32: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + default: + return errors::DataLoss("Failed reading TYPE_SINT32 for ", + DataTypeString(dtype)); + } + case WireFormatLite::TYPE_SINT64: + *index += ReadPackedPrimitives( + buf, buf_size, *index, stride, data); + return OkStatus(); + // default: intentionally omitted in order to enable static checking. + } + // Unreachable. + return errors::DataLoss("Failed reading unknown wire type"); +} + +// Reads a varint from the given buffer, write it to *value, and return the +// new buffer pointer. +// This was copied from coded_stream.cc where it is private. +// Important: This routine may read as much as kMaxVarintBytes from +// the buffer. It is the caller's responsibility to make sure that there is +// enough space in the buffer. +inline const uint8* ReadVarint64FromArray(const uint8* buffer, bool* ok, + uint64* value) { + const uint8* ptr = buffer; + uint32 b; + + // Splitting into 32-bit pieces gives better performance on 32-bit + // processors. + uint32 part0 = 0, part1 = 0, part2 = 0; + + b = *(ptr++); + part0 = b; + if (!(b & 0x80)) goto done; + part0 -= 0x80; + b = *(ptr++); + part0 += b << 7; + if (!(b & 0x80)) goto done; + part0 -= 0x80 << 7; + b = *(ptr++); + part0 += b << 14; + if (!(b & 0x80)) goto done; + part0 -= 0x80 << 14; + b = *(ptr++); + part0 += b << 21; + if (!(b & 0x80)) goto done; + part0 -= 0x80 << 21; + b = *(ptr++); + part1 = b; + if (!(b & 0x80)) goto done; + part1 -= 0x80; + b = *(ptr++); + part1 += b << 7; + if (!(b & 0x80)) goto done; + part1 -= 0x80 << 7; + b = *(ptr++); + part1 += b << 14; + if (!(b & 0x80)) goto done; + part1 -= 0x80 << 14; + b = *(ptr++); + part1 += b << 21; + if (!(b & 0x80)) goto done; + part1 -= 0x80 << 21; + b = *(ptr++); + part2 = b; + if (!(b & 0x80)) goto done; + part2 -= 0x80; + b = *(ptr++); + part2 += b << 7; + if (!(b & 0x80)) goto done; + // "part2 -= 0x80 << 7" is irrelevant because (0x80 << 7) << 56 is 0. + + // We have overrun the maximum size of a varint (10 bytes). Assume + // the data is corrupt. + *ok = false; + return ptr; + +done: + *ok = true; + *value = (static_cast(part0)) | (static_cast(part1) << 28) | + (static_cast(part2) << 56); + return ptr; +} + +} // namespace internal +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_PROTO_DECODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/descriptor_pool_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/descriptor_pool_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..66c20e9e41337292bccf0c11c6c0b94a05e5df54 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/descriptor_pool_registry.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 TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTOR_POOL_REGISTRY_H_ +#define TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTOR_POOL_REGISTRY_H_ + +#include +#include +#include +#include +#include + +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/hash/hash.h" +#include "tensorflow/core/platform/protobuf.h" + +namespace tensorflow { + +class DescriptorPoolRegistry { + public: + typedef std::function* owned_desc_pool)> + DescriptorPoolFn; + + // Returns a pointer to a global DescriptorPoolRegistry object. + static DescriptorPoolRegistry* Global(); + + // Returns a pointer to a descriptor pool function for the given source. + DescriptorPoolFn* Get(const string& source); + + // Registers a descriptor pool factory. + void Register(const string& source, const DescriptorPoolFn& pool_fn); + + private: + std::map fns_; +}; + +namespace descriptor_pool_registration { + +class DescriptorPoolRegistration { + public: + DescriptorPoolRegistration( + const string& source, + const DescriptorPoolRegistry::DescriptorPoolFn& pool_fn) { + DescriptorPoolRegistry::Global()->Register(source, pool_fn); + } +}; + +} // namespace descriptor_pool_registration + +#define REGISTER_DESCRIPTOR_POOL(source, pool_fn) \ + REGISTER_DESCRIPTOR_POOL_UNIQ_HELPER(__COUNTER__, source, pool_fn) + +#define REGISTER_DESCRIPTOR_POOL_UNIQ_HELPER(ctr, source, pool_fn) \ + REGISTER_DESCRIPTOR_POOL_UNIQ(ctr, source, pool_fn) + +#define REGISTER_DESCRIPTOR_POOL_UNIQ(ctr, source, pool_fn) \ + static descriptor_pool_registration::DescriptorPoolRegistration \ + descriptor_pool_registration_fn_##ctr(source, pool_fn) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTOR_POOL_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/descriptors.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/descriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..36cf62f47e5c8418a7eb1e39cbae975268ca1e1e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/descriptors.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 TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTORS_H_ +#define TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTORS_H_ + +#include +#include + +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/status.h" + +namespace tsl { +class Env; +} // namespace tsl +namespace tensorflow { +using tsl::Env; + +// Gets a `DescriptorPool` object from the `descriptor_source`. This may be: +// +// 1) An empty string or "local://", in which case the local descriptor pool +// created for proto definitions linked to the binary is returned. +// +// 2) A file path, in which case the descriptor pool is created from the +// contents of the file, which is expected to contain a `FileDescriptorSet` +// serialized as a string. The descriptor pool ownership is transferred to the +// caller via `owned_desc_pool`. +// +// 3) A "bytes://", in which case the descriptor pool is created from +// ``, which is expected to be a `FileDescriptorSet` serialized as a +// string. The descriptor pool ownership is transferred to the caller via +// `owned_desc_pool`. +// +// Custom schemas can be supported by registering a handler with the +// `DescriptorPoolRegistry`. +Status GetDescriptorPool( + Env* env, string const& descriptor_source, + protobuf::DescriptorPool const** desc_pool, + std::unique_ptr* owned_desc_pool); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_PROTO_DESCRIPTORS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/proto_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/proto_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..43f8c918299c65ad1b3d2cf0b8b9385006b184c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/proto/proto_utils.h @@ -0,0 +1,70 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_PROTO_PROTO_UTILS_H_ +#define TENSORFLOW_CORE_UTIL_PROTO_PROTO_UTILS_H_ + +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tsl/util/proto/proto_utils.h" + +namespace tensorflow { +namespace proto_utils { + +using tensorflow::protobuf::FieldDescriptor; +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::proto_utils::FromDurationProto; +using tsl::proto_utils::ToDurationProto; +// NOLINTEND(misc-unused-using-decls) + +// Returns true if the proto field type can be converted to the tensor dtype. +bool IsCompatibleType(FieldDescriptor::Type field_type, DataType dtype); + +// Parses a text-formatted protobuf from a string into the given Message* output +// and returns status OK if valid, or INVALID_ARGUMENT with an accompanying +// parser error message if the text format is invalid. +Status ParseTextFormatFromString(absl::string_view input, + protobuf::Message* output); + +class StringErrorCollector : public protobuf::io::ErrorCollector { + public: + // String error_text is unowned and must remain valid during the use of + // StringErrorCollector. + explicit StringErrorCollector(string* error_text); + // If one_indexing is set to true, all line and column numbers will be + // increased by one for cases when provided indices are 0-indexed and + // 1-indexed error messages are desired + StringErrorCollector(string* error_text, bool one_indexing); + StringErrorCollector(const StringErrorCollector&) = delete; + StringErrorCollector& operator=(const StringErrorCollector&) = delete; + + // Implementation of protobuf::io::ErrorCollector::AddError. + void AddError(int line, int column, const string& message) override; + + // Implementation of protobuf::io::ErrorCollector::AddWarning. + void AddWarning(int line, int column, const string& message) override; + + private: + string* const error_text_; + const int index_offset_; +}; + + +} // namespace proto_utils +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_PROTO_PROTO_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..5ab8d02a0d248ee706ac8f6a42360ef227356ac0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.pb.h @@ -0,0 +1,618 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/util/quantization/uniform_quant_ops_attr.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_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_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_2eproto; +namespace tensorflow { +class UniformQuantizedConvolutionDimensionNumbersAttr; +struct UniformQuantizedConvolutionDimensionNumbersAttrDefaultTypeInternal; +extern UniformQuantizedConvolutionDimensionNumbersAttrDefaultTypeInternal _UniformQuantizedConvolutionDimensionNumbersAttr_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::UniformQuantizedConvolutionDimensionNumbersAttr* Arena::CreateMaybeMessage<::tensorflow::UniformQuantizedConvolutionDimensionNumbersAttr>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class UniformQuantizedConvolutionDimensionNumbersAttr final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr) */ { + public: + inline UniformQuantizedConvolutionDimensionNumbersAttr() : UniformQuantizedConvolutionDimensionNumbersAttr(nullptr) {} + ~UniformQuantizedConvolutionDimensionNumbersAttr() override; + explicit PROTOBUF_CONSTEXPR UniformQuantizedConvolutionDimensionNumbersAttr(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + UniformQuantizedConvolutionDimensionNumbersAttr(const UniformQuantizedConvolutionDimensionNumbersAttr& from); + UniformQuantizedConvolutionDimensionNumbersAttr(UniformQuantizedConvolutionDimensionNumbersAttr&& from) noexcept + : UniformQuantizedConvolutionDimensionNumbersAttr() { + *this = ::std::move(from); + } + + inline UniformQuantizedConvolutionDimensionNumbersAttr& operator=(const UniformQuantizedConvolutionDimensionNumbersAttr& from) { + CopyFrom(from); + return *this; + } + inline UniformQuantizedConvolutionDimensionNumbersAttr& operator=(UniformQuantizedConvolutionDimensionNumbersAttr&& 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 UniformQuantizedConvolutionDimensionNumbersAttr& default_instance() { + return *internal_default_instance(); + } + static inline const UniformQuantizedConvolutionDimensionNumbersAttr* internal_default_instance() { + return reinterpret_cast( + &_UniformQuantizedConvolutionDimensionNumbersAttr_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(UniformQuantizedConvolutionDimensionNumbersAttr& a, UniformQuantizedConvolutionDimensionNumbersAttr& b) { + a.Swap(&b); + } + inline void Swap(UniformQuantizedConvolutionDimensionNumbersAttr* 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(UniformQuantizedConvolutionDimensionNumbersAttr* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + UniformQuantizedConvolutionDimensionNumbersAttr* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const UniformQuantizedConvolutionDimensionNumbersAttr& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const UniformQuantizedConvolutionDimensionNumbersAttr& from) { + UniformQuantizedConvolutionDimensionNumbersAttr::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(UniformQuantizedConvolutionDimensionNumbersAttr* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr"; + } + protected: + explicit UniformQuantizedConvolutionDimensionNumbersAttr(::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 { + kInputSpatialDimensionsFieldNumber = 3, + kKernelSpatialDimensionsFieldNumber = 6, + kOutputSpatialDimensionsFieldNumber = 9, + kInputBatchDimensionFieldNumber = 1, + kInputFeatureDimensionFieldNumber = 2, + kKernelInputFeatureDimensionFieldNumber = 4, + kKernelOutputFeatureDimensionFieldNumber = 5, + kOutputBatchDimensionFieldNumber = 7, + kOutputFeatureDimensionFieldNumber = 8, + }; + // repeated int64 input_spatial_dimensions = 3; + int input_spatial_dimensions_size() const; + private: + int _internal_input_spatial_dimensions_size() const; + public: + void clear_input_spatial_dimensions(); + private: + int64_t _internal_input_spatial_dimensions(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_input_spatial_dimensions() const; + void _internal_add_input_spatial_dimensions(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_input_spatial_dimensions(); + public: + int64_t input_spatial_dimensions(int index) const; + void set_input_spatial_dimensions(int index, int64_t value); + void add_input_spatial_dimensions(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + input_spatial_dimensions() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_input_spatial_dimensions(); + + // repeated int64 kernel_spatial_dimensions = 6; + int kernel_spatial_dimensions_size() const; + private: + int _internal_kernel_spatial_dimensions_size() const; + public: + void clear_kernel_spatial_dimensions(); + private: + int64_t _internal_kernel_spatial_dimensions(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_kernel_spatial_dimensions() const; + void _internal_add_kernel_spatial_dimensions(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_kernel_spatial_dimensions(); + public: + int64_t kernel_spatial_dimensions(int index) const; + void set_kernel_spatial_dimensions(int index, int64_t value); + void add_kernel_spatial_dimensions(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + kernel_spatial_dimensions() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_kernel_spatial_dimensions(); + + // repeated int64 output_spatial_dimensions = 9; + int output_spatial_dimensions_size() const; + private: + int _internal_output_spatial_dimensions_size() const; + public: + void clear_output_spatial_dimensions(); + private: + int64_t _internal_output_spatial_dimensions(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_output_spatial_dimensions() const; + void _internal_add_output_spatial_dimensions(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_output_spatial_dimensions(); + public: + int64_t output_spatial_dimensions(int index) const; + void set_output_spatial_dimensions(int index, int64_t value); + void add_output_spatial_dimensions(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + output_spatial_dimensions() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_output_spatial_dimensions(); + + // int64 input_batch_dimension = 1; + void clear_input_batch_dimension(); + int64_t input_batch_dimension() const; + void set_input_batch_dimension(int64_t value); + private: + int64_t _internal_input_batch_dimension() const; + void _internal_set_input_batch_dimension(int64_t value); + public: + + // int64 input_feature_dimension = 2; + void clear_input_feature_dimension(); + int64_t input_feature_dimension() const; + void set_input_feature_dimension(int64_t value); + private: + int64_t _internal_input_feature_dimension() const; + void _internal_set_input_feature_dimension(int64_t value); + public: + + // int64 kernel_input_feature_dimension = 4; + void clear_kernel_input_feature_dimension(); + int64_t kernel_input_feature_dimension() const; + void set_kernel_input_feature_dimension(int64_t value); + private: + int64_t _internal_kernel_input_feature_dimension() const; + void _internal_set_kernel_input_feature_dimension(int64_t value); + public: + + // int64 kernel_output_feature_dimension = 5; + void clear_kernel_output_feature_dimension(); + int64_t kernel_output_feature_dimension() const; + void set_kernel_output_feature_dimension(int64_t value); + private: + int64_t _internal_kernel_output_feature_dimension() const; + void _internal_set_kernel_output_feature_dimension(int64_t value); + public: + + // int64 output_batch_dimension = 7; + void clear_output_batch_dimension(); + int64_t output_batch_dimension() const; + void set_output_batch_dimension(int64_t value); + private: + int64_t _internal_output_batch_dimension() const; + void _internal_set_output_batch_dimension(int64_t value); + public: + + // int64 output_feature_dimension = 8; + void clear_output_feature_dimension(); + int64_t output_feature_dimension() const; + void set_output_feature_dimension(int64_t value); + private: + int64_t _internal_output_feature_dimension() const; + void _internal_set_output_feature_dimension(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr) + 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 > input_spatial_dimensions_; + mutable std::atomic _input_spatial_dimensions_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > kernel_spatial_dimensions_; + mutable std::atomic _kernel_spatial_dimensions_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > output_spatial_dimensions_; + mutable std::atomic _output_spatial_dimensions_cached_byte_size_; + int64_t input_batch_dimension_; + int64_t input_feature_dimension_; + int64_t kernel_input_feature_dimension_; + int64_t kernel_output_feature_dimension_; + int64_t output_batch_dimension_; + int64_t output_feature_dimension_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// UniformQuantizedConvolutionDimensionNumbersAttr + +// int64 input_batch_dimension = 1; +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_input_batch_dimension() { + _impl_.input_batch_dimension_ = int64_t{0}; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_input_batch_dimension() const { + return _impl_.input_batch_dimension_; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::input_batch_dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_batch_dimension) + return _internal_input_batch_dimension(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_set_input_batch_dimension(int64_t value) { + + _impl_.input_batch_dimension_ = value; +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_input_batch_dimension(int64_t value) { + _internal_set_input_batch_dimension(value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_batch_dimension) +} + +// int64 input_feature_dimension = 2; +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_input_feature_dimension() { + _impl_.input_feature_dimension_ = int64_t{0}; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_input_feature_dimension() const { + return _impl_.input_feature_dimension_; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::input_feature_dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_feature_dimension) + return _internal_input_feature_dimension(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_set_input_feature_dimension(int64_t value) { + + _impl_.input_feature_dimension_ = value; +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_input_feature_dimension(int64_t value) { + _internal_set_input_feature_dimension(value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_feature_dimension) +} + +// repeated int64 input_spatial_dimensions = 3; +inline int UniformQuantizedConvolutionDimensionNumbersAttr::_internal_input_spatial_dimensions_size() const { + return _impl_.input_spatial_dimensions_.size(); +} +inline int UniformQuantizedConvolutionDimensionNumbersAttr::input_spatial_dimensions_size() const { + return _internal_input_spatial_dimensions_size(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_input_spatial_dimensions() { + _impl_.input_spatial_dimensions_.Clear(); +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_input_spatial_dimensions(int index) const { + return _impl_.input_spatial_dimensions_.Get(index); +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::input_spatial_dimensions(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_spatial_dimensions) + return _internal_input_spatial_dimensions(index); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_input_spatial_dimensions(int index, int64_t value) { + _impl_.input_spatial_dimensions_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_spatial_dimensions) +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_add_input_spatial_dimensions(int64_t value) { + _impl_.input_spatial_dimensions_.Add(value); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::add_input_spatial_dimensions(int64_t value) { + _internal_add_input_spatial_dimensions(value); + // @@protoc_insertion_point(field_add:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_spatial_dimensions) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +UniformQuantizedConvolutionDimensionNumbersAttr::_internal_input_spatial_dimensions() const { + return _impl_.input_spatial_dimensions_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +UniformQuantizedConvolutionDimensionNumbersAttr::input_spatial_dimensions() const { + // @@protoc_insertion_point(field_list:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_spatial_dimensions) + return _internal_input_spatial_dimensions(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +UniformQuantizedConvolutionDimensionNumbersAttr::_internal_mutable_input_spatial_dimensions() { + return &_impl_.input_spatial_dimensions_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +UniformQuantizedConvolutionDimensionNumbersAttr::mutable_input_spatial_dimensions() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.input_spatial_dimensions) + return _internal_mutable_input_spatial_dimensions(); +} + +// int64 kernel_input_feature_dimension = 4; +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_kernel_input_feature_dimension() { + _impl_.kernel_input_feature_dimension_ = int64_t{0}; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_kernel_input_feature_dimension() const { + return _impl_.kernel_input_feature_dimension_; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::kernel_input_feature_dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_input_feature_dimension) + return _internal_kernel_input_feature_dimension(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_set_kernel_input_feature_dimension(int64_t value) { + + _impl_.kernel_input_feature_dimension_ = value; +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_kernel_input_feature_dimension(int64_t value) { + _internal_set_kernel_input_feature_dimension(value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_input_feature_dimension) +} + +// int64 kernel_output_feature_dimension = 5; +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_kernel_output_feature_dimension() { + _impl_.kernel_output_feature_dimension_ = int64_t{0}; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_kernel_output_feature_dimension() const { + return _impl_.kernel_output_feature_dimension_; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::kernel_output_feature_dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_output_feature_dimension) + return _internal_kernel_output_feature_dimension(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_set_kernel_output_feature_dimension(int64_t value) { + + _impl_.kernel_output_feature_dimension_ = value; +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_kernel_output_feature_dimension(int64_t value) { + _internal_set_kernel_output_feature_dimension(value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_output_feature_dimension) +} + +// repeated int64 kernel_spatial_dimensions = 6; +inline int UniformQuantizedConvolutionDimensionNumbersAttr::_internal_kernel_spatial_dimensions_size() const { + return _impl_.kernel_spatial_dimensions_.size(); +} +inline int UniformQuantizedConvolutionDimensionNumbersAttr::kernel_spatial_dimensions_size() const { + return _internal_kernel_spatial_dimensions_size(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_kernel_spatial_dimensions() { + _impl_.kernel_spatial_dimensions_.Clear(); +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_kernel_spatial_dimensions(int index) const { + return _impl_.kernel_spatial_dimensions_.Get(index); +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::kernel_spatial_dimensions(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_spatial_dimensions) + return _internal_kernel_spatial_dimensions(index); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_kernel_spatial_dimensions(int index, int64_t value) { + _impl_.kernel_spatial_dimensions_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_spatial_dimensions) +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_add_kernel_spatial_dimensions(int64_t value) { + _impl_.kernel_spatial_dimensions_.Add(value); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::add_kernel_spatial_dimensions(int64_t value) { + _internal_add_kernel_spatial_dimensions(value); + // @@protoc_insertion_point(field_add:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_spatial_dimensions) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +UniformQuantizedConvolutionDimensionNumbersAttr::_internal_kernel_spatial_dimensions() const { + return _impl_.kernel_spatial_dimensions_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +UniformQuantizedConvolutionDimensionNumbersAttr::kernel_spatial_dimensions() const { + // @@protoc_insertion_point(field_list:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_spatial_dimensions) + return _internal_kernel_spatial_dimensions(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +UniformQuantizedConvolutionDimensionNumbersAttr::_internal_mutable_kernel_spatial_dimensions() { + return &_impl_.kernel_spatial_dimensions_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +UniformQuantizedConvolutionDimensionNumbersAttr::mutable_kernel_spatial_dimensions() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.kernel_spatial_dimensions) + return _internal_mutable_kernel_spatial_dimensions(); +} + +// int64 output_batch_dimension = 7; +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_output_batch_dimension() { + _impl_.output_batch_dimension_ = int64_t{0}; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_output_batch_dimension() const { + return _impl_.output_batch_dimension_; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::output_batch_dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_batch_dimension) + return _internal_output_batch_dimension(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_set_output_batch_dimension(int64_t value) { + + _impl_.output_batch_dimension_ = value; +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_output_batch_dimension(int64_t value) { + _internal_set_output_batch_dimension(value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_batch_dimension) +} + +// int64 output_feature_dimension = 8; +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_output_feature_dimension() { + _impl_.output_feature_dimension_ = int64_t{0}; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_output_feature_dimension() const { + return _impl_.output_feature_dimension_; +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::output_feature_dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_feature_dimension) + return _internal_output_feature_dimension(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_set_output_feature_dimension(int64_t value) { + + _impl_.output_feature_dimension_ = value; +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_output_feature_dimension(int64_t value) { + _internal_set_output_feature_dimension(value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_feature_dimension) +} + +// repeated int64 output_spatial_dimensions = 9; +inline int UniformQuantizedConvolutionDimensionNumbersAttr::_internal_output_spatial_dimensions_size() const { + return _impl_.output_spatial_dimensions_.size(); +} +inline int UniformQuantizedConvolutionDimensionNumbersAttr::output_spatial_dimensions_size() const { + return _internal_output_spatial_dimensions_size(); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::clear_output_spatial_dimensions() { + _impl_.output_spatial_dimensions_.Clear(); +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::_internal_output_spatial_dimensions(int index) const { + return _impl_.output_spatial_dimensions_.Get(index); +} +inline int64_t UniformQuantizedConvolutionDimensionNumbersAttr::output_spatial_dimensions(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_spatial_dimensions) + return _internal_output_spatial_dimensions(index); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::set_output_spatial_dimensions(int index, int64_t value) { + _impl_.output_spatial_dimensions_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_spatial_dimensions) +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::_internal_add_output_spatial_dimensions(int64_t value) { + _impl_.output_spatial_dimensions_.Add(value); +} +inline void UniformQuantizedConvolutionDimensionNumbersAttr::add_output_spatial_dimensions(int64_t value) { + _internal_add_output_spatial_dimensions(value); + // @@protoc_insertion_point(field_add:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_spatial_dimensions) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +UniformQuantizedConvolutionDimensionNumbersAttr::_internal_output_spatial_dimensions() const { + return _impl_.output_spatial_dimensions_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +UniformQuantizedConvolutionDimensionNumbersAttr::output_spatial_dimensions() const { + // @@protoc_insertion_point(field_list:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_spatial_dimensions) + return _internal_output_spatial_dimensions(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +UniformQuantizedConvolutionDimensionNumbersAttr::_internal_mutable_output_spatial_dimensions() { + return &_impl_.output_spatial_dimensions_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +UniformQuantizedConvolutionDimensionNumbersAttr::mutable_output_spatial_dimensions() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.UniformQuantizedConvolutionDimensionNumbersAttr.output_spatial_dimensions) + return _internal_mutable_output_spatial_dimensions(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2fquantization_2funiform_5fquant_5fops_5fattr_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.proto new file mode 100644 index 0000000000000000000000000000000000000000..4066ac507523e823baddbd951831846522ae8969 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_attr.proto @@ -0,0 +1,48 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +syntax = "proto3"; + +package tensorflow; + +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/protobuf/for_core_protos_go_proto"; + +// Describes the dimension numbers for Convolution op. Corresponds to +// ::mlir::mhlo::ConvDimensionNumbersAttr. +message UniformQuantizedConvolutionDimensionNumbersAttr { + // The dimension that represents batch in the input. + int64 input_batch_dimension = 1; + // The dimension that represents features in the input. + int64 input_feature_dimension = 2; + // The dimensions that represents spatial dimensions in the input. Length must + // be rank-2 for the tensor rank for Convolution op. + repeated int64 input_spatial_dimensions = 3; + + // The dimension that represents input features in the kernel (rhs). + int64 kernel_input_feature_dimension = 4; + // The dimension that represents output features in the kernel (rhs). + int64 kernel_output_feature_dimension = 5; + // The dimensions that represents spatial dimensions in the kernel (rhs). + // Length must be rank-2 for the tensor rank for Convolution op. + repeated int64 kernel_spatial_dimensions = 6; + + // The dimension that represents batch in the output. + int64 output_batch_dimension = 7; + // The dimension that represents features in the output. + int64 output_feature_dimension = 8; + // The dimensions that represents spatial dimensions in the output. Length + // must be rank-2 for the tensor rank for Convolution op. + repeated int64 output_spatial_dimensions = 9; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_params.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_params.h new file mode 100644 index 0000000000000000000000000000000000000000..8c970245a1cbea2a426901456d6c38455a4e4cf9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/quantization/uniform_quant_ops_params.h @@ -0,0 +1,121 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_UTIL_QUANTIZATION_UNIFORM_QUANT_OPS_PARAMS_H_ +#define TENSORFLOW_CORE_UTIL_QUANTIZATION_UNIFORM_QUANT_OPS_PARAMS_H_ + +#include +#include + +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/util/quantization/uniform_quant_ops_attr.pb.h" + +namespace tensorflow { + +// Utility class to load and retrieve params for +// UniformQuantizedConvolution{Hybrid} Op kernels. +// +// NOTE: This class instance is fully loaded and valid, only after (1) One of +// LoadFromAttrs() is called (2) ValidateOrFillParamsAndValidateShape is called. +// Member retrieve and CalculateOutputShape() can be used only after both are +// called. +class UniformQuantizedConvolutionParams { + public: + UniformQuantizedConvolutionParams() = default; + // Only for unit tests. + UniformQuantizedConvolutionParams( + const std::vector& window_strides, + const std::vector& lhs_dilation, + const std::vector& rhs_dilation, + const UniformQuantizedConvolutionDimensionNumbersAttr& dimension_numbers, + int feature_group_count, int batch_group_count, + const std::string& padding, const std::vector& padding_list = {}) + : window_strides_(window_strides), + lhs_dilation_(lhs_dilation), + rhs_dilation_(rhs_dilation), + dimension_numbers_(dimension_numbers), + feature_group_count_(feature_group_count), + batch_group_count_(batch_group_count), + padding_(padding), + padding_list_(padding_list) {} + + const std::vector& window_strides() const { return window_strides_; } + const std::vector& lhs_dilation() const { return lhs_dilation_; } + const std::vector& rhs_dilation() const { return rhs_dilation_; } + const UniformQuantizedConvolutionDimensionNumbersAttr& dimension_numbers() + const { + return dimension_numbers_; + } + int batch_group_count() const { return batch_group_count_; } + + const std::vector& padding_list() const { return padding_list_; } + int feature_group_count() const { return feature_group_count_; } + + // Load UniformQuantizedConvolutionParams members by reading op attrs. + Status LoadFromAttrs(const OpKernelConstruction& context); + Status LoadFromAttrs(const shape_inference::InferenceContext& context); + + // Check if UniformQuantizedConvolutionParams members loaded from Attr are + // valid regarding the lhs_shape and rhs_shape, and fill param values if + // required. (Set default of empty optional Attrs, and fill padding_list_ if + // required.) + // Then, validate given lhs_shape and rhs_shape. + // + // NOTE: This method should be called only after calling one of + // LoadFromAttrs(). + Status ValidateOrFillParamsAndValidateShape(const TensorShape& lhs_shape, + const TensorShape& rhs_shape); + + // Calculate output shape using lhs_shape, rhs_shape, and the params. + // + // NOTE: this method can be used only after calling both LoadFromAttrs() and + // ValidateOrFillParamsAndValidateShape(). + // Reference: + // https://github.com/google/jax/blob/0584c6a1c405b23317deb1596c2c161eb5709c84/jax/_src/lax/convolution.py#L349 + StatusOr CalculateOutputShape( + const TensorShape& lhs_shape, const TensorShape& rhs_shape) const; + + // Given the original size of a dimension and a dilation, calculate the + // resulting size after dilation is applied. + inline static int64_t DilatedSize(int64_t size, int dilation) { + return size == 0 ? 0 : size + (dilation - 1) * (size - 1); + } + + private: + template + Status LoadFromAttrsInternal(const ContextT& context); + Status ValidateShape(const TensorShape& lhs_shape, + const TensorShape& rhs_shape); + Status ValidateOrFillPaddingList(const TensorShape& lhs_shape, + const TensorShape& rhs_shape); + + // Params from Attrs. + std::vector window_strides_; + std::vector lhs_dilation_; + std::vector rhs_dilation_; + UniformQuantizedConvolutionDimensionNumbersAttr dimension_numbers_; + int feature_group_count_; + int batch_group_count_; + std::string padding_; + + // Params derived from Attrs and Inputs. + std::vector padding_list_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_QUANTIZATION_UNIFORM_QUANT_OPS_PARAMS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/dim_comparator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/dim_comparator.h new file mode 100644 index 0000000000000000000000000000000000000000..76d50c67811f3ba168caeafadf846e94dfccf1e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/dim_comparator.h @@ -0,0 +1,121 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_SPARSE_DIM_COMPARATOR_H_ +#define TENSORFLOW_CORE_UTIL_SPARSE_DIM_COMPARATOR_H_ + +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace sparse { + +///////////////// +// DimComparator +///////////////// +// +// Helper class, mainly used by the IndexSortOrder. This comparator +// can be passed to e.g. std::sort, or any other sorter, to sort two +// rows of an index matrix according to the dimension(s) of interest. +// The dimensions to sort by are passed to the constructor as "order". +// +// Example: if given index matrix IX, two rows ai and bi, and order = {2,1}. +// operator() compares +// IX(ai,2) < IX(bi,2). +// If IX(ai,2) == IX(bi,2), it compares +// IX(ai,1) < IX(bi,1). +// +// This can be used to sort a vector of row indices into IX according to +// the values in IX in particular columns (dimensions) of interest. +class DimComparator { + public: + typedef typename gtl::ArraySlice VarDimArray; + + DimComparator(const TTypes::Matrix& ix, const VarDimArray& order, + const VarDimArray& shape) + : ix_(ix), order_(order), dims_(shape.size()) { + DCHECK_GT(order.size(), size_t{0}) << "Must order using at least one index"; + DCHECK_LE(order.size(), shape.size()) << "Can only sort up to dims"; + for (size_t d = 0; d < order.size(); ++d) { + DCHECK_GE(order[d], 0); + DCHECK_LT(order[d], shape.size()); + } + } + + inline bool operator()(const int64_t i, const int64_t j) const { + for (int di = 0; di < dims_; ++di) { + const int64_t d = order_[di]; + if (ix_(i, d) < ix_(j, d)) return true; + if (ix_(i, d) > ix_(j, d)) return false; + } + return false; + } + + // Compares two indices taken from corresponding index matrices, using the + // standard, row-major (or lexicographic) order. Useful for cases that need + // to distinguish between all three orderings (<, ==, >). + inline static int cmp(const TTypes::ConstMatrix& a_idx, + const TTypes::ConstMatrix& b_idx, + const int64_t a_row, const int64_t b_row, + const int dims) { + for (int d = 0; d < dims; ++d) { + const int64_t a = a_idx(a_row, d); + const int64_t b = b_idx(b_row, d); + if (a < b) { + return -1; + } else if (a > b) { + return 1; + } + } + return 0; + } + + protected: + const TTypes::Matrix ix_; + const VarDimArray order_; + const int dims_; + const std::vector* ix_order_; +}; + +template +class FixedDimComparator : DimComparator { + public: + FixedDimComparator(const TTypes::Matrix& ix, + const VarDimArray& order, const VarDimArray& shape) + : DimComparator(ix, order, shape) { + DCHECK_EQ(order.size(), ORDER_DIM); + } + inline bool operator()(const int64_t i, const int64_t j) const { + bool value = false; + for (int di = 0; di < ORDER_DIM; ++di) { + const int64_t d = order_[di]; + if (ix_(i, d) < ix_(j, d)) { + value = true; + break; + } + if (ix_(i, d) > ix_(j, d)) break; + } + return value; + } +}; + +} // namespace sparse +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_SPARSE_DIM_COMPARATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/group_iterator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/group_iterator.h new file mode 100644 index 0000000000000000000000000000000000000000..f1d16ce6d2ae4a644a3b11161049b633b8918463 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/group_iterator.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. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_SPARSE_GROUP_ITERATOR_H_ +#define TENSORFLOW_CORE_UTIL_SPARSE_GROUP_ITERATOR_H_ + +#include +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace sparse { + +class GroupIterable; // Predeclare GroupIterable for Group. + +// This class is returned when dereferencing a GroupIterable iterator. +// It provides the methods group(), indices(), and values(), which +// provide access into the underlying SparseTensor. +class Group { + public: + Group(GroupIterable* iter, int64_t loc, int64_t next_loc) + : iter_(iter), loc_(loc), next_loc_(next_loc) {} + + std::vector group() const; + int64_t group_at(size_t index) const; + TTypes::UnalignedConstMatrix indices() const; + template + typename TTypes::UnalignedVec values() const; + + private: + GroupIterable* iter_; + int64_t loc_; + int64_t next_loc_; +}; + +///////////////// +// GroupIterable +///////////////// +// +// Returned when calling sparse_tensor.group({dim0, dim1, ...}). +// +// Please note: the sparse_tensor should already be ordered according +// to {dim0, dim1, ...}. Otherwise this iteration will return invalid groups. +// +// Allows grouping and iteration of the SparseTensor according to the +// subset of dimensions provided to the group call. +// +// The actual grouping dimensions are stored in the +// internal vector group_dims_. Iterators inside the iterable provide +// the three methods: +// +// * group(): returns a vector with the current group dimension values. +// * indices(): a map of index, providing the indices in +// this group. +// * values(): a map of values, providing the values in +// this group. +// +// To iterate across GroupIterable, see examples in README.md. +// + +// Forward declaration of SparseTensor +class GroupIterable { + public: + typedef gtl::ArraySlice VarDimArray; + + GroupIterable(Tensor ix, Tensor vals, int dims, const VarDimArray& group_dims) + : ix_(ix), + ix_matrix_(ix_.matrix()), + vals_(vals), + dims_(dims), + group_dims_(group_dims.begin(), group_dims.end()) {} + + class IteratorStep; + + IteratorStep begin() { return IteratorStep(this, 0); } + IteratorStep at(int64_t loc) { + CHECK(loc >= 0 && loc <= ix_.dim_size(0)) + << "loc provided must lie between 0 and " << ix_.dim_size(0); + return IteratorStep(this, loc); + } + IteratorStep end() { return IteratorStep(this, ix_.dim_size(0)); } + + template + inline bool GroupMatches(const TIX& ix, int64_t loc_a, int64_t loc_b) const { + for (int d : group_dims_) { + if (ix(loc_a, d) != ix(loc_b, d)) { + return false; + } + } + return true; + } + + class IteratorStep { + public: + IteratorStep(GroupIterable* iter, int64_t loc) + : iter_(iter), loc_(loc), next_loc_(loc_) { + UpdateEndOfGroup(); + } + + void UpdateEndOfGroup(); + bool operator!=(const IteratorStep& rhs) const; + bool operator==(const IteratorStep& rhs) const; + IteratorStep& operator++(); // prefix ++ + IteratorStep operator++(int); // postfix ++ + Group operator*() const { return Group(iter_, loc_, next_loc_); } + int64_t loc() const { return loc_; } + + private: + GroupIterable* iter_; + int64_t loc_; + int64_t next_loc_; + }; + + private: + friend class Group; + const Tensor ix_; + const TTypes::ConstMatrix ix_matrix_; + Tensor vals_; + const int dims_; + const gtl::InlinedVector group_dims_; +}; + +inline int64_t Group::group_at(size_t index) const { + const auto& ix_t = iter_->ix_matrix_; + return ix_t(loc_, index); +} + +// Implementation of Group::values() +template +typename TTypes::UnalignedVec Group::values() const { + return typename TTypes::UnalignedVec(&(iter_->vals_.vec()(loc_)), + next_loc_ - loc_); +} + +} // namespace sparse +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_SPARSE_GROUP_ITERATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/sparse_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/sparse_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..8ed99084b41725e0089b11d607ac8a831a667c45 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/sparse/sparse_tensor.h @@ -0,0 +1,672 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_SPARSE_SPARSE_TENSOR_H_ +#define TENSORFLOW_CORE_UTIL_SPARSE_SPARSE_TENSOR_H_ + +#include +#include +#include + +#include "absl/base/macros.h" +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/sparse/dim_comparator.h" +#include "tensorflow/core/util/sparse/group_iterator.h" + +namespace tensorflow { +namespace sparse { + +class SparseTensor { + public: + typedef typename gtl::ArraySlice VarDimArray; + typedef typename gtl::InlinedVector ShapeArray; + + static Status Create(Tensor ix, Tensor vals, const VarDimArray shape, + const VarDimArray order, SparseTensor* result); + + static Status Create(Tensor ix, Tensor vals, const TensorShape& shape, + SparseTensor* result); + + static Status Create(Tensor ix, Tensor vals, const VarDimArray shape, + SparseTensor* result); + + static Status Create(Tensor ix, Tensor vals, const TensorShape& shape, + const VarDimArray order, SparseTensor* result); + + SparseTensor() : dims_(0) {} + + ABSL_DEPRECATED("Use Create() functions instead of constructors directly.") + SparseTensor(Tensor ix, Tensor vals, const TensorShape& shape) + : SparseTensor(std::move(ix), std::move(vals), TensorShapeToVector(shape), + UndefinedOrder(TensorShapeToVector(shape))) {} + + ABSL_DEPRECATED("Use Create() functions instead of constructors directly.") + SparseTensor(Tensor ix, Tensor vals, const VarDimArray shape) + : SparseTensor(std::move(ix), std::move(vals), shape, + UndefinedOrder(shape)) {} + + ABSL_DEPRECATED("use Create() functions instead of constructors directly.") + SparseTensor(Tensor ix, Tensor vals, const TensorShape& shape, + const VarDimArray order) + : SparseTensor(std::move(ix), std::move(vals), TensorShapeToVector(shape), + order) {} + + ABSL_DEPRECATED("Use Create() functions instead of constructors directly.") + SparseTensor(Tensor ix, Tensor vals, const VarDimArray shape, + const VarDimArray order); + + SparseTensor(const SparseTensor& other) + : SparseTensor(other.ix_, other.vals_, other.shape_, other.order_) {} + + SparseTensor(SparseTensor&& other) + : SparseTensor(std::move(other.ix_), std::move(other.vals_), + std::move(other.shape_), std::move(other.order_)) {} + + SparseTensor& operator=(const SparseTensor& other) { + ix_ = other.ix_; + vals_ = other.vals_; + shape_ = other.shape_; + order_ = other.order_; + dims_ = other.dims_; + return *this; + } + + SparseTensor& operator=(SparseTensor&& other) { + ix_ = std::move(other.ix_); + vals_ = std::move(other.vals_); + shape_ = std::move(other.shape_); + order_ = std::move(other.order_); + dims_ = std::move(other.dims_); + return *this; + } + + std::size_t num_entries() const { return ix_.dim_size(0); } + + int dims() const { return shape_.size(); } + + const Tensor& indices() const { return ix_; } + + const Tensor& values() const { return vals_; } + + DataType dtype() const { return vals_.dtype(); } + + Status IndicesValid() const; + + VarDimArray shape() const { return shape_; } + + VarDimArray order() const { return order_; } + + // Resorts the indices and values according to the dimensions in order. + template + void Reorder(const VarDimArray& order); + + // Returns a group iterable that can be used for clumping indices + // and values according to the group indices of interest. + // + // Precondition: order()[0..group_ix.size()] == group_ix. + // + // See the README.md in this directory for more usage information. + GroupIterable group(const VarDimArray& group_ix) const { + DCHECK_LE(group_ix.size(), dims_); + for (std::size_t di = 0; di < group_ix.size(); ++di) { + DCHECK_GE(group_ix[di], 0) << "Group dimension out of range"; + DCHECK_LT(group_ix[di], dims_) << "Group dimension out of range"; + DCHECK_EQ(group_ix[di], order_[di]) + << "Group dimension does not match sorted order"; + } + return GroupIterable(ix_, vals_, dims_, group_ix); + } + + // Stores the sparse indices into the dense tensor out. + // Preconditions: + // out->shape().dims() == shape().dims() + // out->shape().dim_size(d) >= shape(d) for all d + // + // Returns true on success. False on failure (mismatched dimensions + // or out-of-bounds indices). + // + // If initialize==True, ToDense first overwrites all coefficients in out to 0. + // + template + bool ToDense(Tensor* out, bool initialize = true); + + // Concat() will concatenate all the tensors according to their first order + // dimension. All tensors must have identical shape except for + // the first order dimension. All tensors orders' first dimension + // must match. + // + // If all of the tensors have identical ordering, then the output + // will have this ordering. Otherwise the output is set as not + // having any order and a Reorder() should be called on it before + // performing any subsequent operations. + template + static SparseTensor Concat(const gtl::ArraySlice& tensors); + + // Split() will split the input SparseTensor into a list of num_split + // SparseTensor given a splitting dimension. If the input dimension range + // isn't an integer multiple of split_dim, we add one extra dimension for + // each slice. + template + static Status Split(const SparseTensor& tensor, const int split_dim, + const int num_split, std::vector* result); + + // Slice() will slice the input SparseTensor into a SparseTensor based on + // specified start and size. Both start and size are 1-D array with each + // element of the array representing one dimension. The start is the start + // index at each dimension and the size is the size at each dimension. + template + static StatusOr Slice(const SparseTensor& tensor, + const gtl::ArraySlice start, + const gtl::ArraySlice size); + + // Picks out the dimensions according to `dim_indices`. + std::vector PickDims(gtl::ArraySlice dim_indices) const { + std::vector res(dim_indices.size()); + for (size_t i = 0; i < dim_indices.size(); ++i) { + res[i] = shape_[dim_indices[i]]; + } + return res; + } + + private: + static inline ShapeArray UndefinedOrder(const VarDimArray shape) { + return ShapeArray(shape.size(), -1); + } + + static inline ShapeArray TensorShapeToVector(const TensorShape& shape) { + ShapeArray vec(shape.dims()); + for (int i = 0; i < shape.dims(); ++i) vec[i] = shape.dim_size(i); + return vec; + } + + // Optimized implementation of `IndicesValid` for 1-D sparse tensors. + // REQUIRES: `shape_.size() == 1`. + bool IndicesValidVectorFastPath() const; + + // Optimized implementation of `IndicesValid` for 2-D sparse tensors whose + // indices fit within the range of an `int32`. + // REQUIRES: `shape_.size() == 2`. + bool IndicesValidMatrix32BitFastPath() const; + + template + Status IndicesValidHelper() const; + + // Helper for ToDense() + template + bool ValidateAndInitializeToDense(Tensor* out, bool initialize); + + // Helper for Split() that returns the slice index. + static inline int GetSliceIndex(const int dim, const int split_size, + const int residual) { + DCHECK_GT(split_size, 0); + DCHECK_GE(dim, 0); + if (residual == 0) return dim / split_size; + const int offset = residual * (split_size + 1); + if (dim < offset) { + return dim / (split_size + 1); + } else { + return residual + ((dim - offset) / split_size); + } + } + + // Helper for Split() that returns the dimension in the slice. + static inline int GetDimensionInSlice(const int dim, const int split_size, + const int residual) { + DCHECK_GT(split_size, 0); + DCHECK_GE(dim, 0); + if (residual == 0) return dim % split_size; + const int offset = residual * (split_size + 1); + if (dim < offset) { + return dim % (split_size + 1); + } else { + return (dim - offset) % split_size; + } + } + + // Helper for Split() that returns the shape given a slice index. + static inline int GetSliceShape(const int slice_index, const int split_size, + const int residual) { + DCHECK_GT(split_size, 0); + DCHECK_GE(slice_index, 0); + if (residual == 0) return split_size; + if (slice_index < residual) { + return split_size + 1; + } else { + return split_size; + } + } + + Tensor ix_; + Tensor vals_; + ShapeArray shape_; + ShapeArray order_; + int dims_; +}; + +// This operation updates the indices and values Tensor rows, so it is +// an in-place algorithm. It requires O(N log N) time and O(N) +// temporary space. +template +inline void SparseTensor::Reorder(const VarDimArray& order) { + DCHECK_EQ(DataTypeToEnum::v(), dtype()) + << "Reorder requested with the wrong datatype"; + DCHECK_EQ(order.size(), dims_) << "Order length must be SparseTensor rank"; + auto ix_t = ix_.matrix(); + auto vals_t = vals_.vec(); + + std::vector reorder(num_entries()); + std::iota(reorder.begin(), reorder.end(), 0); + + // Sort to get order of indices + switch (order.size()) { +#define CASE_SORT(ORDER_SIZE) \ + case ORDER_SIZE: { \ + FixedDimComparator sorter(ix_t, order, shape()); \ + std::sort(reorder.begin(), reorder.end(), sorter); \ + break; \ + } + CASE_SORT(0); + CASE_SORT(1); + CASE_SORT(2); + CASE_SORT(3); + CASE_SORT(4); + CASE_SORT(5); +#undef CASE_SORT + default: { + DimComparator sorter(ix_t, order, shape()); + std::sort(reorder.begin(), reorder.end(), sorter); + } + } + + // We have a forward reordering, but what we'll need is a + // permutation (the inverse). This can be calculated with O(1) + // additional + // and O(n) time (INVPERM) but we just do the simple thing here. + std::vector permutation(reorder.size()); + for (std::size_t n = 0; n < reorder.size(); ++n) { + permutation[reorder[n]] = n; + } + + // Update indices & values by converting the permutations to + // a product of transpositions. Iterate over the cycles in the + // permutation, and convert each of those into a product of + // transpositions (swaps): + // https://en.wikipedia.org/wiki/Cyclic_permutation + // This is N swaps, 2*N comparisons. + for (std::size_t n = 0; n + 1 < permutation.size(); ++n) { + while (n != permutation[n]) { + std::size_t r = permutation[n]; + std::swap_ranges(&(ix_t(n, 0)), &(ix_t(n + 1, 0)), &(ix_t(r, 0))); + std::swap(vals_t(n), vals_t(r)); + std::swap(permutation[n], permutation[r]); + } + } + + order_ = ShapeArray(order.begin(), order.end()); +} + +template +inline bool SparseTensor::ValidateAndInitializeToDense(Tensor* out, + bool initialize) { + DCHECK_EQ(DataTypeToEnum::v(), dtype()) + << "ToDense requested with the wrong datatype"; + + DCHECK_EQ(out->shape().dims(), dims_) + << "Incompatible dimensions between SparseTensor and output"; + + DCHECK_EQ(out->dtype(), DataTypeToEnum::v()) + << "Output must be type: " << DataTypeToEnum::v() + << " but got: " << out->dtype(); + + // Make sure the dense output is the same rank and has room + // to hold the SparseTensor. + const auto& out_shape = out->shape(); + if (shape_.size() != out_shape.dims()) return false; + for (int d = 0; d < shape_.size(); ++d) { + if (shape_[d] > out_shape.dim_size(d)) return false; + } + + if (initialize) { + auto out_t = out->flat(); + out_t.setConstant(T()); + } + + return true; +} + +template +inline bool SparseTensor::ToDense(Tensor* out, bool initialize) { + if (!ValidateAndInitializeToDense(out, initialize)) return false; + + auto out_t = out->flat(); + auto vals_t = vals_.vec(); + auto ix_t = ix_.matrix(); + const int64_t* const ix_ptr = ix_t.data(); + + if (dims_ == 1) { + // Fast path for sparse vectors. + const int64_t out_length = out->shape().dim_size(0); + for (int n = 0; n < vals_t.dimension(0); ++n) { + const int64_t index = internal::SubtleMustCopy(ix_ptr[n]); + if (!FastBoundsCheck(index, out_length)) return false; + out_t(index) = vals_t(n); + } + return true; + } else if (dims_ == 2) { + // Fast path for sparse matrices. + const auto& out_shape = out->shape(); + const int64_t out_rows = out_shape.dim_size(0); + const int64_t out_cols = out_shape.dim_size(1); + for (int n = 0; n < vals_t.dimension(0); ++n) { + const int64_t row_index = internal::SubtleMustCopy(ix_ptr[n * 2]); + const int64_t col_index = internal::SubtleMustCopy(ix_ptr[n * 2 + 1]); + if (!(FastBoundsCheck(row_index, out_rows) && + FastBoundsCheck(col_index, out_cols))) { + return false; + } + out_t(row_index * out_cols + col_index) = vals_t(n); + } + return true; + } else { + // General path for N-dimensional sparse tensors. + gtl::InlinedVector strides(dims_); + const auto& out_shape = out->shape().dim_sizes(); + if (dims_ > 0) { + strides[dims_ - 1] = 1; + } + for (int d = dims_ - 2; d >= 0; --d) { + strides[d] = strides[d + 1] * out_shape[d + 1]; + } + + for (int n = 0; n < vals_t.dimension(0); ++n) { + bool invalid_dims = false; + int64_t ix = 0; + for (int d = 0; d < dims_; ++d) { + const int64_t ix_n_d = internal::SubtleMustCopy(ix_ptr[n * dims_ + d]); + if (!FastBoundsCheck(ix_n_d, out_shape[d])) { + invalid_dims = true; + } + ix += strides[d] * ix_n_d; + } + if (invalid_dims) return false; + out_t(ix) = vals_t(n); + } + return true; + } +} + +template +inline SparseTensor SparseTensor::Concat( + const gtl::ArraySlice& tensors) { + DCHECK_GE(tensors.size(), size_t{1}) << "Cannot concat 0 SparseTensors"; + const int dims = tensors[0].dims_; + DCHECK_GE(dims, 1) << "Cannot concat 0-dimensional SparseTensors"; + auto order_0 = tensors[0].order(); + const int primary_dim = order_0[0]; + ShapeArray final_order(order_0.begin(), order_0.end()); + ShapeArray final_shape(tensors[0].shape().begin(), tensors[0].shape().end()); + final_shape[primary_dim] = 0; // We'll build this up as we go along. + int num_entries = 0; + + bool fully_ordered = true; + for (const SparseTensor& st : tensors) { + DCHECK_EQ(st.dims_, dims) << "All SparseTensors must have the same rank."; + DCHECK_EQ(DataTypeToEnum::v(), st.dtype()) + << "Concat requested with the wrong data type"; + DCHECK_GE(st.order()[0], 0) << "SparseTensor must be ordered"; + DCHECK_EQ(st.order()[0], primary_dim) + << "All SparseTensors' order[0] must match. This is the concat dim."; + if (st.order() != final_order) fully_ordered = false; + const VarDimArray& st_shape = st.shape(); + for (int d = 0; d < dims - 1; ++d) { + const int cdim = (d < primary_dim) ? d : d + 1; + DCHECK_EQ(final_shape[cdim], st_shape[cdim]) + << "All SparseTensors' shapes must match except on the concat dim. " + << "Concat dim: " << primary_dim + << ", mismatched shape at dim: " << cdim + << ". Expecting shape like: [" << str_util::Join(final_shape, ",") + << "] but saw shape: [" << str_util::Join(st_shape, ",") << "]"; + } + + // Update dimension of final shape + final_shape[primary_dim] = + (final_shape[primary_dim] + st_shape[primary_dim]); + + num_entries += st.num_entries(); // Update number of entries + } + + // If nonconsistent ordering among inputs, set final order to -1s. + if (!fully_ordered) { + final_order = UndefinedOrder(final_shape); + } + + Tensor output_ix(DT_INT64, TensorShape({num_entries, dims})); + Tensor output_vals(DataTypeToEnum::v(), TensorShape({num_entries})); + + TTypes::Matrix ix_t = output_ix.matrix(); + typename TTypes::Vec vals_t = output_vals.vec(); + + Eigen::DenseIndex offset = 0; + int64_t shape_offset = 0; + for (const SparseTensor& st : tensors) { + const int st_num_entries = st.num_entries(); + + // Fill in indices & values. + if (st_num_entries > 0) { + std::copy_n(&st.vals_.vec()(0), st_num_entries, &vals_t(offset)); + + const auto* st_ix = &st.ix_.matrix()(0, 0); + auto* ix_out = &ix_t(offset, 0); + for (std::size_t i = 0; i < st_num_entries * dims; ++i) { + *ix_out++ = *st_ix++ + ((i % dims == primary_dim) ? shape_offset : 0); + } + } + + offset += st_num_entries; + shape_offset += st.shape()[primary_dim]; + } + + return SparseTensor(output_ix, output_vals, final_shape, final_order); +} + +template +inline Status SparseTensor::Split(const SparseTensor& input_tensor, + const int split_dim, const int num_split, + std::vector* result) { + std::vector output_indices; + std::vector output_values; + std::vector output_shapes; + output_indices.reserve(num_split); + output_values.reserve(num_split); + output_shapes.reserve(num_split); + + std::vector::Matrix> output_indices_t; + std::vector::Vec> output_values_t; + output_indices_t.reserve(num_split); + output_values_t.reserve(num_split); + auto input_values_t = input_tensor.values().vec(); + auto input_indices_t = input_tensor.indices().matrix(); + + std::vector num_values(num_split, 0); + const int num_dim = input_tensor.shape().size(); + const int split_dim_size = input_tensor.shape()[split_dim]; + const int split_size = split_dim_size / num_split; + + if (!(num_split > 0 && num_split <= split_dim_size)) { + return errors::InvalidArgument("num_split must be in the interval (0, ", + split_dim_size, "]"); + } + if (!(split_dim >= 0 && split_dim < num_dim)) { + return errors::InvalidArgument("num_dim must be in the interval [0, ", + num_dim, ")"); + } + + const int residual = split_dim_size % num_split; + for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) { + const int dim = input_tensor.indices().matrix()(i, split_dim); + int slice_index = GetSliceIndex(dim, split_size, residual); + if (slice_index >= num_values.size()) { + return errors::InvalidArgument("Slice index ", slice_index, + " is larger than num_split."); + } + num_values[slice_index]++; + } + + for (int i = 0; i < num_split; ++i) { + // TODO(ataei): Pass an allocator to avoid allocating large memory buffer. + output_indices.emplace_back(DT_INT64, + TensorShape({num_values[i], num_dim})); + output_values.emplace_back(DataTypeToEnum::v(), + TensorShape({num_values[i]})); + output_shapes.emplace_back(input_tensor.shape()); + output_indices_t.emplace_back(output_indices[i].matrix()); + output_values_t.emplace_back(output_values[i].vec()); + const int size = GetSliceShape(i, split_size, residual); + output_shapes[i].set_dim(split_dim, size); + } + + std::vector values_inserted_in_slice(num_split, 0); + for (int i = 0; i < input_tensor.indices().dim_size(0); ++i) { + const int dim = input_indices_t(i, split_dim); + const int slice_index = GetSliceIndex(dim, split_size, residual); + const int slice_dim = values_inserted_in_slice[slice_index]++; + output_values_t[slice_index](slice_dim) = input_values_t(i); + for (int j = 0; j < num_dim; ++j) { + const int64_t original_dim = input_indices_t(i, j); + output_indices_t[slice_index](slice_dim, j) = + (j == split_dim) + ? GetDimensionInSlice(original_dim, split_size, residual) + : original_dim; + } + } + + result->clear(); + result->reserve(num_split); + for (int i = 0; i < num_split; ++i) { + SparseTensor tensor; + Status create_status = + Create(output_indices[i], output_values[i], output_shapes[i], &tensor); + if (!create_status.ok()) { + return create_status; + } + result->push_back(std::move(tensor)); + } + return OkStatus(); +} + +template +inline StatusOr SparseTensor::Slice( + const SparseTensor& input_tensor, const gtl::ArraySlice start, + const gtl::ArraySlice size) { + TensorShape output_shape(input_tensor.shape()); + + const int dims = input_tensor.dims(); + for (int dim = 0; dim < dims; dim++) { + // Determine the size of the result; if the selected slice goes beyond the + // input boundary, the result will correspond to the size of the overlap + // between the input and the selected slice. + const int64_t input_size = output_shape.dim_size(dim); + const int64_t start_index = start[dim]; + const int64_t slice_size = size[dim]; + + if (start_index < input_size - slice_size) { + // The entire selection is within input boundaries. + TF_RETURN_IF_ERROR(output_shape.SetDimWithStatus(dim, slice_size)); + } else if (start_index < input_size) { + // The selection starts within input boundaries, but goes beyond them. + TF_RETURN_IF_ERROR( + output_shape.SetDimWithStatus(dim, input_size - start_index)); + } else { + // The selection is entirely out of input boundaries. + TF_RETURN_IF_ERROR(output_shape.SetDimWithStatus(dim, 0)); + } + } + + auto input_indices_t = input_tensor.indices().matrix(); + auto input_values_t = input_tensor.values().vec(); + + // Find the number of indices that fall inside start and size. + int count = 0; + for (int i = 0; i < input_tensor.indices().dim_size(0); i++) { + // The following will check to see if an input is within the + // range specified by start and size. + // The for loop below iterates through all dimensions. In case + // the index falls outside of the start and size at any dimension, + // it will be considered as a "no hit" (hit = false). In this + // case, it will not be counted as the index that fall inside + // the range specified by start and size. + bool hit = true; + for (int dim = 0; dim < dims; dim++) { + if (!(start[dim] <= input_indices_t(i, dim) && + input_indices_t(i, dim) < start[dim] + size[dim])) { + hit = false; + break; + } + } + if (!hit) { + continue; + } + count++; + } + + Tensor output_values(DataTypeToEnum::v(), TensorShape({count})); + Tensor output_indices(DT_INT64, TensorShape({count, dims})); + + auto output_values_t = output_values.vec(); + auto output_indices_t = output_indices.matrix(); + + // Obtain the output indices that fall inside start and size. + int index = 0; + for (int i = 0; i < input_tensor.indices().dim_size(0) && index < count; + i++) { + // The logic here is similar as the above except that the above + // only count the number of indices while here we actually generate + // the output. + bool hit = true; + for (int dim = 0; dim < dims; dim++) { + if (!(start[dim] <= input_indices_t(i, dim) && + input_indices_t(i, dim) < start[dim] + size[dim])) { + hit = false; + break; + } + } + if (!hit) { + continue; + } + output_values_t(index) = input_values_t(i); + for (int dim = 0; dim < dims; dim++) { + output_indices_t(index, dim) = input_indices_t(i, dim) - start[dim]; + } + index++; + } + + return SparseTensor(output_indices, output_values, output_shape); +} + +} // namespace sparse +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_SPARSE_SPARSE_TENSOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_array.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_array.h new file mode 100644 index 0000000000000000000000000000000000000000..ed3b6e1445eabbf3d47065e48eaf98b5062fa1e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_array.h @@ -0,0 +1,30 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_BYTE_SWAP_ARRAY_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_BYTE_SWAP_ARRAY_H_ + +#include "tensorflow/core/platform/byte_order.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tsl/util/byte_swap_array.h" + +namespace tensorflow { + +using tsl::ByteSwapArray; // NOLINT(misc-unused-using-decls) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_BYTE_SWAP_ARRAY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..dbfd63e355c18d71ef9ab4e15fc06537b7d7e724 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/byte_swap_tensor.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 TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_BYTE_SWAP_TENSOR_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_BYTE_SWAP_TENSOR_H_ + +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/byte_order.h" +#include "tensorflow/core/protobuf/meta_graph.pb.h" +#include "tensorflow/core/util/tensor_bundle/byte_swap_array.h" + +namespace tensorflow { + +// Check if a data type is byte swappable. +bool IsByteSwappable(DataType dtype); + +// Byte-swap a tensor's backing buffer in place. +// +// Args: +// t: Tensor to be modified IN PLACE. Any tensors that share a backing +// buffer with this one will also end up byte-swapped. +// Returns: OkStatus() on success, -1 otherwise +// TODO(frreiss): Should this be a member of the Tensor class? +Status ByteSwapTensor(Tensor *t); + +// Swap tensor_content field of Const Op Tensors in the named functions +// in NodeDef +Status ByteSwapTensorContentInNode(NodeDef& node); + +// Swap tensor_content field of Const Op Tensors in the named functions +// in MetaGraphDef +Status ByteSwapTensorContentInMetaGraphDef(MetaGraphDef* meta_graph_def); + +// Swap tensor_content field of Const Op Tensors in the named functions +// in GraphDef +Status ByteSwapTensorContentInGraphDef(GraphDef* graph_def); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_BYTE_SWAP_TENSOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/naming.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/naming.h new file mode 100644 index 0000000000000000000000000000000000000000..3e851392cafbfff4744c8ef8ab091c097530b903 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/naming.h @@ -0,0 +1,47 @@ +/* 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. +==============================================================================*/ + +// A minimal library exposing the naming logic used in tensor_bundle. +// +// A tensor bundle contains a metadata file and sharded data files, which all +// share a common pathname prefix. +// +// Given the prefix, the actual pathnames of the files can be queried via: +// +// MetaFilename(prefix): pathname of the metadata file. +// DataFilename(prefix, shard_id, num_shards): pathname of a data file. +// +// Typical usage includes forming a filepattern to match files on disk: +// +// // To find the unique metadata file. +// const string metadata_file = MetaFilename("/fs/train/ckpt-step"); +// Env::Default()->GetMatchingFiles(metadata_file, &path); +// +// Regexp can also be used: e.g. R".data-\d{5}-of-\d{5}" for data files. + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_NAMING_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_NAMING_H_ + +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +string MetaFilename(StringPiece prefix); +string DataFilename(StringPiece prefix, int32_t shard_id, int32_t num_shards); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_NAMING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/tensor_bundle.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/tensor_bundle.h new file mode 100644 index 0000000000000000000000000000000000000000..1c9a8a3e6b1c007a2d69dc0b93c2c30a71d32c64 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_bundle/tensor_bundle.h @@ -0,0 +1,379 @@ +/* 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. +==============================================================================*/ + +// A tensor bundle is a set of immutable persistent files storing a set of named +// tensors. It is designed for checkpointing TensorFlow tensors. +// +// The paths of the managed files share a common prefix; e.g., with the prefix: +// /fs/model/train/ckpt-step/ckpt +// +// the bundle may contain a metadata file, and sharded data files: +// /fs/model/train/ckpt-step/ +// ckpt.index +// ckpt.data-00000-of-00020 +// ckpt.data-00001-of-00020 +// ... +// ckpt.data-00019-of-00020 +// +// The ".index" file is a string-string immutable table +// (tensorflow::table::Table). Each key is a name of a tensor and its value is +// a serialized BundleEntryProto. Each BundleEntryProto describes the metadata +// of a tensor: which of the "data" files contains the content of a tensor, the +// offset into that file, checksum, some auxiliary data, etc. +// +// A tensor bundle can be accessed randomly using a BundleReader. Usage: +// +// BundleReader reader(env, "/fs/model/train/ckpt-step/ckpt"); +// reader.Lookup("name", &tensor); +// +// A tensor bundle can be built using BundleWriter. Each BundleWriter builds a +// single data file bundle. Multiple bundles can then be merged by +// MergeBundles() without reading and writing large chunk of data: it reads the +// metadata files and outputs a single merged metadata. Typical usage: +// +// worker 0: +// BundleWriter writer(env, "/fs/model/train/ckpt-step/tmp/worker0-step"); +// writer.Add(...); // Adds the tensors on this worker. +// writer.Finish(); // Flushes. +// worker 1: +// BundleWriter writer(env, "/fs/model/train/ckpt-step/tmp/worker1-step"); +// writer.Add(...); +// writer.Finish(); +// worker 2: +// MergeBundles(env, +// {"/fs/model/train/ckpt-step/tmp/worker0-step", +// "/fs/model/train/ckpt-step/tmp/worker1-step"}, +// "/fs/model/train/ckpt-step/ckpt" /* merged prefix */); +// + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_TENSOR_BUNDLE_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_TENSOR_BUNDLE_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_map.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/lib/io/cache.h" +#include "tensorflow/core/lib/io/inputbuffer.h" +#include "tensorflow/core/lib/io/iterator.h" +#include "tensorflow/core/lib/io/table.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/file_system.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/tstring.h" +#include "tensorflow/core/protobuf/tensor_bundle.pb.h" +#include "tensorflow/core/util/tensor_slice_set.h" +#include "tsl/lib/io/buffered_file.h" +#include "tsl/platform/errors.h" + +namespace tensorflow { + +// Versioning of the tensor bundle format. +// Follows the same rules as 3p/tf/core/public/version.h. +// +// History: +// 0. Any tensor bundles produced before this field was added. +// 1. Added this field (2016-09-14). +extern const int kTensorBundleMinProducer; +extern const int kTensorBundleMinConsumer; +extern const int kTensorBundleVersion; + +// The empty string, hence always the first key in the metadata table. Its +// corresponding value is a BundleHeaderProto. +extern const char* const kHeaderEntryKey; + +// Builds a string-string table of tensor names to BundleEntryProto (metadata). +// +// On construction, attempts to create a directory given by the dirname of +// "prefix", so "status()" must be checked before calling any member functions. +// +// All threads accessing the same BundleWriter must synchronize. +class BundleWriter { + public: + struct Options { + Options() {} + // Alignment, in bytes, for tensor data. + // Must be >= 1. The default size of 1 densely packs tensors. + int data_alignment{1}; + }; + BundleWriter(Env* env, absl::string_view prefix, + const Options& options = Options()); + + // Adds the tensor "val" under key "key". + // Across calls "key" must be unique but can be added in any order. + Status Add(absl::string_view key, const Tensor& val); + + // Partitioned variables support. + // A slice of a full tensor is stored in two entries in the metadata table: + // + // full_tensor_key -> BundleEntryProto, describing all stored slices + // of this full tensor. Does not append to the data + // file. + // encoded slice key -> BundleEntryProto, describing one particular slice. + // Appends values of this slice to the data file. + // + // Slices of a full tensor can be added in any order. + // + // If a full tensor has slices placed on N devices and N BundleWriter's are + // concurrently used, the caller must use MergeBundles() to ensure that a + // consistent entry for "full_tensor_key" is produced. + // + // Returns an error if the same slice is added the second time. + Status AddSlice(absl::string_view full_tensor_key, + const TensorShape& full_tensor_shape, + const TensorSlice& slice_spec, const Tensor& slice_tensor); + + // Finishes the writer and flushes. + Status Finish() TF_MUST_USE_RESULT; + + Status status() const { return status_; } + + private: + Env* const env_; // Not owned. + const Options options_; + const std::string prefix_; + std::string metadata_path_; + std::string data_path_; + bool use_temp_file_; + std::unique_ptr out_; + int64_t size_; // Number of bytes written into out_. + std::map entries_; + Status status_; + + BundleWriter(const BundleWriter&) = delete; + void operator=(const BundleWriter&) = delete; +}; + +// Merges a set of bundles (given their prefixes) into a single bundle with the +// given "merged_prefix". The merged metadata is guaranteed to be consistent. +// +// If there are N bundles in "prefixes", during the merge the data files will be +// renamed to contain a proper sharded file spec, with num_shards set to the sum +// of num_shards across the N input bundles. +// +// The caller should only rely on the metadata file of the merged bundle to +// query information about a tensor. In particular, this function does not +// guarantee not to re-order the input data files. +// +// Once merged, makes a best effort to delete the old metadata files. +// Returns OK iff all bundles are successfully merged. +// +// "allow_missing_files": If set to true, merges "prefixes" as long as +// at least one file exists. (Defaults to false.) +// +// Returns an InvalidArgumentError when "allow_missing_files" is set to true +// and all data files named in "prefixes" do not exist. +// +// Returns a NotFoundError when "allow_missing_files" is set to false and +// any data file named in "prefixes" does not exist. +Status MergeBundles(Env* env, gtl::ArraySlice prefixes, + absl::string_view merged_prefix, + bool allow_missing_files = false); + +// On construction, silently attempts to read the metadata associated with +// "prefix". If caller intends to call any function afterwards, "status()" +// must be checked. +// All threads accessing the same BundleReader must synchronize. +class BundleReader { + public: + BundleReader(Env* const env, absl::string_view prefix, + bool enable_multi_threading_for_testing = false); + ~BundleReader(); + + // Is ok() iff the reader construction is successful (completed the read of + // the metadata). + Status status() const { return status_; } + + // Queries whether the bundle contains an entry keyed by "key". Calls Seek() + // internally, so this call invalidates the reader's current position. + // REQUIRES: status().ok() + bool Contains(absl::string_view key); + + // Sorts a `container` of tensors to read such that when `Seek(key)` is called + // on the elements of the sorted container, the underlying file access is + // sequential. Sorting can greatly improve overall read speed. + // + // `get_key` should be a function that when passed an element in `container`, + // returns the `key` of the tensor. + // + // REQUIRES: status().ok() + template + Status SortForSequentialAccess( + std::vector& container, + absl::FunctionRef get_key); + + // Looks up the dtype and the shape of the tensor keyed by "key". + // REQUIRES: status().ok() + Status LookupDtypeAndShape(absl::string_view key, DataType* dtype, + TensorShape* shape) TF_MUST_USE_RESULT; + + // Looks up the shape of the tensor keyed by "key". + // Clears "shape" if not found. + // REQUIRES: status().ok() + Status LookupTensorShape(absl::string_view key, + TensorShape* shape) TF_MUST_USE_RESULT; + + // Looks up the tensor keyed by "key". If "key" refers to a partitioned + // tensor, attempts to look up the full contents using all stored slices. + // + // Caller must make sure "val" has the same shape and dtype as the + // corresponding contents, so that its buffer can be filled without needing + // extra allocation. These can be queried via "LookupDtypeAndShape()". + // + // On error, "val" may contain nonsense data. Returns a NotFound error if + // tensor keyed by "key" does not exist in this bundle. + // + // Validates the stored crc32c checksum against the restored bytes. + // REQUIRES: status().ok() + Status Lookup(absl::string_view key, Tensor* val) TF_MUST_USE_RESULT; + + // Looks up the tensor pointed to by the internal iterator. + // + // On error, "val" may contain nonsense data. + // + // Validates the stored crc32c checksum against the restored bytes. + // REQUIRES: status().ok() && Valid() + Status ReadCurrent(Tensor* val) TF_MUST_USE_RESULT; + + // Looks up the slices of the tensor keyed by "key". On OK, "slices" + // is non-empty if and only if the tensor is a partitioned tensor. + // + // Warning - there is no guaranteed ordering for the returned slices, so + // a slice with a larger start index in some dimension could come before + // another slice with a smaller start index in the same dimension. + // REQUIRES: status().ok() + Status LookupTensorSlices(absl::string_view key, + std::vector* slices) + TF_MUST_USE_RESULT; + + // Looks up a specific slice of a partitioned tensor. + // It is only required that the stored slices cover the requested slice, + // namely "slice_spec" is a subset of the union of the stored slices. + // REQUIRES: status().ok() + Status LookupSlice(absl::string_view full_tensor_key, + const TensorSlice& slice_spec, + Tensor* val) TF_MUST_USE_RESULT; + + // Seeks to the first position in the bundle whose key is no less than "key". + // REQUIRES: status().ok() + void Seek(absl::string_view key) { return iter_->Seek(key); } + // Moves to the next position in the bundle. + // REQUIRES: status().ok() + void Next() const { iter_->Next(); } + // Returns true iff the reader is positioned to a key/val pair. + // REQUIRES: status().ok() + bool Valid() const { return iter_->Valid(); } + + // Returns the key at the current position. + // REQUIRES: status().ok() && Valid() + absl::string_view key() const { return iter_->key(); } + // Returns the raw value at the current position. + // REQUIRES: status().ok() && Valid() + absl::string_view value() const { return iter_->value(); } + + std::string DebugString(); + + private: + // Seeks for "key" and reads the metadata proto. + // On non-OK return, clears "entry" for the caller. + // REQUIRES: status().ok() + Status GetBundleEntryProto(absl::string_view key, + BundleEntryProto* entry) TF_MUST_USE_RESULT; + + // Reads the tensor value described by the metadata proto "entry". + // Usage for "val" follows the comment of "Lookup()". + Status GetValue(const BundleEntryProto& entry, + Tensor* val) TF_MUST_USE_RESULT; + + // Reads the slice described by "slice_spec". The corresponding full tensor + // has key "ful_tensor_key" and metadata proto "full_tensor_entry". + // REQUIRES: full_tensor_entry.slices_size() > 0 + Status GetSliceValue(absl::string_view full_tensor_key, + const BundleEntryProto& full_tensor_entry, + const TensorSlice& slice_spec, + Tensor* val) TF_MUST_USE_RESULT; + + Env* env_; // Not owned. + const std::string prefix_; + + Status status_; + RandomAccessFile* metadata_; // Owned. + table::Table* table_; + table::Cache* index_cache_; + table::Iterator* iter_; + // Owned the InputBuffer objects and their underlying RandomAccessFile's. + std::unordered_map data_; + + // Maps each partitioned tensor's key to its stored slices (represented in a + // TensorSliceSet). Populated on-demand. + std::unordered_map tensor_slices_; + + // Expected number of data file shards in the bundle. Extracted by reading + // the header entry in the metadata table. + int num_shards_; + + // Flag that this class sets to true when the endianness of the target bundle + // differs from that of the current system's processor architecture. + bool need_to_swap_bytes_; + + friend class TensorBundleAlignmentTest; // For testing data alignment. + + bool enable_multi_threading_for_testing_ = false; + + BundleReader(const BundleReader&) = delete; + void operator=(const BundleReader&) = delete; +}; + +template +Status BundleReader::SortForSequentialAccess( + std::vector& container, + absl::FunctionRef get_key) { + struct FileOffset { + int32_t shard_id; + int64_t offset; + }; + absl::flat_hash_map file_offsets; + for (const T& element : container) { + BundleEntryProto entry; + TF_RETURN_IF_ERROR(GetBundleEntryProto(get_key(element), &entry)); + file_offsets[get_key(element)] = {entry.shard_id(), entry.offset()}; + } + absl::c_sort(container, [&get_key, &file_offsets](const T& a, const T& b) { + const FileOffset& file_offset_a = file_offsets[get_key(a)]; + const FileOffset& file_offset_b = file_offsets[get_key(b)]; + if (file_offset_a.shard_id == file_offset_b.shard_id) { + return file_offset_a.offset < file_offset_b.offset; + } else { + return file_offset_a.shard_id < file_offset_b.shard_id; + } + }); + return OkStatus(); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_BUNDLE_TENSOR_BUNDLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_format.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_format.h new file mode 100644 index 0000000000000000000000000000000000000000..887ee5a778658e540676dd54adeb52e0d5797923 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_format.h @@ -0,0 +1,678 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_FORMAT_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_FORMAT_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// Tensor format for input/output activations used in convolution operations. +// The mnemonics specify the meaning of each tensor dimension sorted from +// largest to smallest memory stride. +// N = Batch, H = Image Height, W = Image Width, C = Number of Channels. +// TODO(pauldonnelly): It would probably be better to switch to a registration +// process for tensor formats, so specialized formats could be defined more +// locally to where they are used. +enum TensorFormat { + // FORMAT_NHWC is the default format in TensorFlow. + FORMAT_NHWC = 0, + + // FORMAT_NCHW often improves performance on GPUs. + FORMAT_NCHW = 1, + + // NCHW_VECT_C is the most performant tensor format for cudnn6's quantized + // int8 convolution and fused convolution. It is laid out in the same order + // as NCHW, except that the size of the Channels dimension is divided by 4, + // and a new dimension of size 4 is appended, which packs 4 adjacent channel + // activations for the same pixel into an int32. Thus an NCHW format tensor + // with dimensions [N, C, H, W] would have dimensions [N, C/4, H, W, 4] in + // NCHW_VECT_C format. + // A pre-condition of this format is that C must be a multiple of 4. + FORMAT_NCHW_VECT_C = 2, + + // Similar to NHWC, but the size of the W dimension is divided by 4, and a + // new dimension of size 4 is appended, which packs 4 adjacent activations + // in the width dimension. + FORMAT_NHWC_VECT_W = 3, + + // Note: although the current code in this file assumes VECT_C and VECT_W + // enums imply int8x4 vectors, this should not be relied upon. + // In the future we may change the meaning of these enums to include vectors + // of other types such as int16x2, with op implementations automatically + // determining which format is implied based on the datatype. + + // FORMAT_HWNC is for TPUs. + FORMAT_HWNC = 4, + + // FORMAT_HWCN is for TPUs. + FORMAT_HWCN = 5, +}; + +// Tensor format for convolutional filters. +// The mnemonics specify the meaning of each tensor dimension sorted +// from largest to smallest memory stride. +// H = Kernel Height, W = Kernel Width, I = Input Channels, O = Output Channels. +// Note: In cudnnGetFilter4dDescriptor(), 'O' is called 'K', 'I' is called 'C'. +enum FilterTensorFormat { + // FORMAT_HWIO is the default filter format in TensorFlow. + // Ops that do not have a 'filter_format' attribute will assume this format. + FORMAT_HWIO = 0, + + // FORMAT_OIHW often improves performance on GPUs. + FORMAT_OIHW = 1, + + // FORMAT_OHWI used by cuDNN for NHWC convolutions. + FORMAT_OHWI = 2, + + // OIHW_VECT_I is the most performant tensor format for cudnn6's quantized + // int8 convolution and fused convolution. It is analogous to the NCHW_VECT_C + // data format. It is laid out in the same order as OIHW, except that the size + // of the Input Channels dimension is divided by 4, and a new dimension of + // size 4 is appended, which packs 4 adjacent input channel weights into an + // int32. Thus an OIHW format filter with dimensions [O, I, H, W] would have + // dimensions [O, I/4, H, W, 4] in OIHW_VECT_I format. + // A pre-condition of this format is that I must be a multiple of 4. + FORMAT_OIHW_VECT_I = 3, +}; + +// Parse tensor format from the given string. +// Return true if the parsing succeeds, and false if it fails. +bool FormatFromString(absl::string_view format_str, TensorFormat* format); + +// Parse tensor format from the given string. +// Return true if the parsing succeeds, and false if it fails. +bool FilterFormatFromString(absl::string_view format_str, + FilterTensorFormat* format); + +// Convert a tensor format into string. +std::string ToString(TensorFormat format); + +// Convert a filter tensor format into string. +std::string ToString(FilterTensorFormat format); + +// Returns the number of spatial dims of a tensor of rank 'num_dims' and tensor +// format 'format'. +inline int GetTensorSpatialDims(int num_dims, TensorFormat format) { + switch (format) { + case FORMAT_NHWC: + case FORMAT_NCHW: + case FORMAT_HWNC: + case FORMAT_HWCN: + return num_dims - 2; // Exclude N,C. + case FORMAT_NCHW_VECT_C: + case FORMAT_NHWC_VECT_W: + // Note: the VECT_W is not counted as an independent spatial dim here, + // since it just a component of the width dimension. + return num_dims - 3; // Exclude N,C,VectDim. + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +inline int GetFilterTensorSpatialDims(int num_dims, FilterTensorFormat format) { + if (format == FORMAT_OIHW_VECT_I) { + return num_dims - 3; // Exclude O,I,InnerI. + } else { + return num_dims - 2; // Exclude O,I. + } +} + +// Returns the rank of a tensor with 'num_spatial_dims' spatial dimensions and +// tensor format 'format'. This is the inverse of GetTensorSpatialDims. +inline int GetTensorDimsFromSpatialDims(int num_spatial_dims, + TensorFormat format) { + switch (format) { + case FORMAT_NHWC: + case FORMAT_NCHW: + case FORMAT_HWNC: + case FORMAT_HWCN: + return num_spatial_dims + 2; // Include N,C. + case FORMAT_NCHW_VECT_C: + case FORMAT_NHWC_VECT_W: + return num_spatial_dims + 3; // Include N,C,VectDim. + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +// Returns the rank of a tensor with 'num_spatial_dims' spatial dimensions and +// filter tensor format 'format'. +inline int GetFilterTensorDimsFromSpatialDims(int num_spatial_dims, + FilterTensorFormat format) { + if (format == FORMAT_OIHW_VECT_I) { + return num_spatial_dims + 3; // Include O,I,InnerI. + } else { + return num_spatial_dims + 2; // Include O,I. + } +} + +// Returns the index of the batch dimension. +inline int GetTensorBatchDimIndex(int num_dims, TensorFormat format) { + switch (format) { + case FORMAT_NHWC: + case FORMAT_NCHW: + case FORMAT_NCHW_VECT_C: + case FORMAT_NHWC_VECT_W: + return 0; + case FORMAT_HWNC: + return num_dims - 2; + case FORMAT_HWCN: + return num_dims - 1; + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +// Returns the index of the feature dimension. If format is NCHW_VECT_C, returns +// the index of the outer feature dimension (i.e. dimension 1, whose size would +// be num_features / 4 in this case). +inline int GetTensorFeatureDimIndex(int num_dims, TensorFormat format) { + switch (format) { + case FORMAT_NHWC: + case FORMAT_HWNC: + return num_dims - 1; + case FORMAT_NHWC_VECT_W: + case FORMAT_HWCN: + return num_dims - 2; + case FORMAT_NCHW: + case FORMAT_NCHW_VECT_C: + return 1; + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +// Returns the index of the inner feature dimension. +inline int GetTensorInnerFeatureDimIndex(int num_dims, TensorFormat format) { + DCHECK_EQ(format, FORMAT_NCHW_VECT_C); + return num_dims - 1; +} + +// Returns the index of the inner width dimension. +inline int GetTensorInnerWidthDimIndex(int num_dims, TensorFormat format) { + DCHECK_EQ(format, FORMAT_NHWC_VECT_W); + return num_dims - 1; +} + +// Returns the dimension index of the specified 'spatial_dim' within an +// activation tensor. If format is NHWC_VECT_W and spatial_dim is 1, returns +// the index of the outer width dimension (i.e. dimension 2, whose size would +// be width / 4 in this case). +inline int GetTensorSpatialDimIndex(int num_dims, TensorFormat format, + int spatial_dim) { + CHECK(spatial_dim >= 0 && + spatial_dim < GetTensorSpatialDims(num_dims, format)) + << spatial_dim << " " << num_dims << " " << ToString(format); + switch (format) { + case FORMAT_NHWC: + case FORMAT_NHWC_VECT_W: + return spatial_dim + 1; + case FORMAT_NCHW: + case FORMAT_NCHW_VECT_C: + return spatial_dim + 2; + case FORMAT_HWNC: + case FORMAT_HWCN: + return spatial_dim; + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +inline int GetFilterTensorSpatialDimIndex(int num_dims, + FilterTensorFormat format, int dim) { + CHECK(dim >= 0 && dim < GetFilterTensorSpatialDims(num_dims, format)) + << dim << " " << num_dims << " " << ToString(format); + switch (format) { + case FORMAT_HWIO: + return dim; + case FORMAT_OIHW: + case FORMAT_OIHW_VECT_I: + return dim + 2; + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +// Returns the index of the inner input channels dimension. +inline int GetFilterTensorInnerInputChannelsDimIndex( + int num_dims, FilterTensorFormat format) { + DCHECK_EQ(format, FORMAT_OIHW_VECT_I); + return num_dims - 1; +} + +// Returns the index of the input channels dimension. +// If 'format' is FORMAT_OIHW_VECT_I, returns the dimension index of the +// outer input channel (i.e. 1), which holds num_input_channels / 4. +inline int GetFilterTensorInputChannelsDimIndex(int num_dims, + FilterTensorFormat format) { + switch (format) { + case FORMAT_HWIO: + return num_dims - 2; + case FORMAT_OIHW: + case FORMAT_OIHW_VECT_I: + return 1; + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +// Returns the index of the output channels dimension. +inline int GetFilterTensorOutputChannelsDimIndex(int num_dims, + FilterTensorFormat format) { + switch (format) { + case FORMAT_HWIO: + return num_dims - 1; + case FORMAT_OIHW: + case FORMAT_OIHW_VECT_I: + return 0; + default: + LOG(FATAL) << "Unknown format " << format; + return -1; // Avoid compiler warning about missing return value + } +} + +// TODO(pauldonnelly): Replace these tensor dimension index functions with +// constant structs to improve performance and reduce code size in Compute() +// functions. + +// Return the dimension index for the specified 'dimension' of the specified +// data 'tensor_format'. 'dimension' is a char that can be 'N' (batch size), +// 'C' (channels), 'H' (height), 'W' (width), or a numbered spatial dimension: +// '0', .. (NUM_SPATIAL_DIMS-1).. +// If 'format' is NCHW_VECT_C and 'dimension' is 'C', returns the index of +// the outer channel dimension (i.e. 1). +template +inline int32 GetTensorDimIndex(TensorFormat format, char dimension) { + if (format == FORMAT_NHWC || format == FORMAT_NHWC_VECT_W) { + // clang-format off + switch (dimension) { + case 'N': return 0; + case '0': return 1; + case '1': return 2; + case '2': return 3; + case 'H': return NUM_SPATIAL_DIMS - 1; + case 'W': return NUM_SPATIAL_DIMS; + case 'C': return NUM_SPATIAL_DIMS + 1; + default: + LOG(FATAL) << "Invalid dimension: " << dimension; + return -1; // Avoid compiler warning about missing return value + } + } else if (format == FORMAT_NCHW || format == FORMAT_NCHW_VECT_C) { + switch (dimension) { + case 'N': return 0; + case 'C': return 1; + case '0': return 2; + case '1': return 3; + case '2': return 4; + case 'H': return NUM_SPATIAL_DIMS; + case 'W': return NUM_SPATIAL_DIMS + 1; + default: + LOG(FATAL) << "Invalid dimension: " << dimension; + return -1; // Avoid compiler warning about missing return value + } + } else if (format == FORMAT_HWNC) { + switch (dimension) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case 'H': return NUM_SPATIAL_DIMS - 2; + case 'W': return NUM_SPATIAL_DIMS - 1; + case 'N': return NUM_SPATIAL_DIMS; + case 'C': return NUM_SPATIAL_DIMS + 1; + default: + LOG(FATAL) << "Invalid dimension: " << dimension; + return -1; // Avoid compiler warning about missing return value + } + } else if (format == FORMAT_HWCN) { + switch (dimension) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case 'H': return NUM_SPATIAL_DIMS - 2; + case 'W': return NUM_SPATIAL_DIMS - 1; + case 'C': return NUM_SPATIAL_DIMS; + case 'N': return NUM_SPATIAL_DIMS + 1; + default: + LOG(FATAL) << "Invalid dimension: " << dimension; + return -1; // Avoid compiler warning about missing return value + } + } else { + LOG(FATAL) << "Invalid format: " << static_cast(format); + return -1; // Avoid compiler warning about missing return value + } + // clang-format on +} + +// Return the dimension index for the specified 'dimension' of the specified +// 'filter_tensor_format'. 'dimension' is a char that can be 'O' (num output +// channels), 'I' (num input channels), 'H' (height), 'W' (width), or a +// numbered spatial dimension: '0', .. (NUM_SPATIAL_DIMS-1). +// If 'format' is OIHW_VECT_I and 'dimension' is 'I', returns the index of the +// outer input channels dimension (i.e. 1). +template +inline int GetFilterDimIndex(FilterTensorFormat filter_tensor_format, + char dimension) { + // clang-format off + if (filter_tensor_format == FORMAT_HWIO) { + switch (dimension) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case 'H': return NUM_SPATIAL_DIMS - 2; + case 'W': return NUM_SPATIAL_DIMS - 1; + case 'I': return NUM_SPATIAL_DIMS; + case 'O': return NUM_SPATIAL_DIMS + 1; + default: + LOG(FATAL) << "Invalid dimension: " << dimension; + return -1; // Avoid compiler warning about missing return value + } + } else if (filter_tensor_format == FORMAT_OIHW || + filter_tensor_format == FORMAT_OIHW_VECT_I) { + switch (dimension) { + case 'O': return 0; + case 'I': return 1; + case '0': return 2; + case '1': return 3; + case '2': return 4; + case 'H': return NUM_SPATIAL_DIMS; + case 'W': return NUM_SPATIAL_DIMS + 1; + default: + LOG(FATAL) << "Invalid dimension: " << dimension; + return -1; // Avoid compiler warning about missing return value + } + } else { + LOG(FATAL) << "Invalid format: " << static_cast(filter_tensor_format); + return -1; // Avoid compiler warning about missing return value + } + // clang-format on +} + +inline int32 GetTensorDimIndex(TensorFormat format, char dimension) { + return GetTensorDimIndex<2>(format, dimension); +} + +inline int32 GetTensorDimIndex(TensorFormat format, char dimension, + int num_total_dims) { + int32_t index = (GetTensorSpatialDims(num_total_dims, format) == 3) + ? GetTensorDimIndex<3>(format, dimension) + : GetTensorDimIndex<2>(format, dimension); + CHECK(index >= 0 && index < num_total_dims) // Crash OK. + << "Invalid index from the dimension: " << index << ", " << format << ", " + << dimension; + return index; +} + +// Return the element from 'dimension_attributes' that corresponds to the +// specified 'dimension' according to 'tensor_format'. +template +T GetTensorDim(gtl::ArraySlice dimension_attributes, + TensorFormat tensor_format, char dimension) { + int index = + GetTensorDimIndex(tensor_format, dimension, dimension_attributes.size()); + return dimension_attributes[index]; +} + +// Return the element from 'dimension_attribute' that corresponds to the +// specified 'dimension' according to 'filter_tensor_format'. +template +T GetFilterDim(gtl::ArraySlice dimension_attribute, + FilterTensorFormat filter_tensor_format, char dimension) { + int index = (GetFilterTensorSpatialDims(dimension_attribute.size(), + filter_tensor_format) == 3) + ? GetFilterDimIndex<3>(filter_tensor_format, dimension) + : GetFilterDimIndex<2>(filter_tensor_format, dimension); + using size_type = typename gtl::ArraySlice::size_type; + CHECK(index >= 0 && + static_cast(index) < dimension_attribute.size()) + << "Invalid index from the dimension: " << index << ", " + << filter_tensor_format << ", " << dimension; + return dimension_attribute[index]; +} + +template +T GetTensorDim(const std::vector& attributes, TensorFormat format, + char dimension) { + return GetTensorDim(gtl::ArraySlice(attributes), format, dimension); +} + +// Return the size of the specified 'dimension' within 'tensor_shape' +// according to 'tensor_format'. +inline int64_t GetTensorDim(const TensorShape& tensor_shape, + TensorFormat tensor_format, char dimension) { + return GetTensorDim(gtl::ArraySlice(tensor_shape.dim_sizes()), + tensor_format, dimension); +} + +// Return the size of the specified 'dimension' within 'tensor_shape' +// according to 'tensor_filter_format'. +inline int64_t GetFilterDim(const TensorShape& tensor_shape, + FilterTensorFormat tensor_filter_format, + char dimension) { + return GetFilterDim(gtl::ArraySlice(tensor_shape.dim_sizes()), + tensor_filter_format, dimension); +} + +// Return the size of the specified 'dimension' of 'tensor' according to +// 'tensor_format'. +inline int64_t GetTensorDim(const Tensor& tensor, TensorFormat tensor_format, + char dimension) { + return GetTensorDim(tensor.shape(), tensor_format, dimension); +} + +// Return the size of the specified 'dimension' of 'tensor' according to +// 'filter_tensor_format'. +inline int64_t GetFilterDim(const Tensor& tensor, + FilterTensorFormat filter_tensor_format, + char dimension) { + return GetFilterDim(tensor.shape(), filter_tensor_format, dimension); +} + +inline void GetExplicitPaddingForDim( + const std::vector& explicit_paddings, TensorFormat tensor_format, + char dimension, int64_t* padding_before, int64_t* padding_after) { + int index = + GetTensorDimIndex(tensor_format, dimension, explicit_paddings.size() / 2); + *padding_before = explicit_paddings[2 * index]; + *padding_after = explicit_paddings[2 * index + 1]; +} + +// Return the string that specifies the data format for convnet operations. +std::string GetConvnetDataFormatAttrString(); +std::string GetConvnet3dDataFormatAttrString(); + +// Return the string that specifies the filter format for convnet operations. +std::string GetConvnetFilterFormatAttrString(); +std::string GetConvnet3dFilterFormatAttrString(); +std::string GetConvnetDataFormat2D3DAttrString(); + +// Returns a tensor shape for the specified format and dimension sizes. +// Works for both 2D and 3D operations. The output shapes are as follows: +// FORMAT_NHWC: (N, spatial, C); rank = spatial.size() + 2 +// FORMAT_NCHW: (N, C, spatial); rank = spatial.size() + 2 +// FORMAT_NCHW_VECT_C: (N, C, spatial, InnerC); rank = spatial.size() + 3 +// FORMAT_NHWC_VECT_W: (N, spatial, C, InnerW); rank = spatial.size() + 3 +inline Status ShapeFromFormatWithStatus(TensorFormat format, int64_t N, + gtl::ArraySlice spatial, + int64_t C, TensorShape* shape) { + const int dims = GetTensorDimsFromSpatialDims(spatial.size(), format); + gtl::InlinedVector dim_sizes(dims); + dim_sizes[GetTensorBatchDimIndex(dims, format)] = N; + for (int dim = 0; static_cast(dim) < spatial.size(); dim++) { + auto dim_size = spatial[dim]; + if (format == FORMAT_NHWC_VECT_W && + static_cast(dim) == spatial.size() - 1) { + CHECK_EQ(0, dim_size % 4) + << "FORMAT_NHWC_VECT_W requires W to be a multiple of 4, but W=" + << dim_size; + dim_sizes[GetTensorInnerWidthDimIndex(dims, format)] = 4; + dim_size /= 4; + } + dim_sizes[GetTensorSpatialDimIndex(dims, format, dim)] = dim_size; + } + + int feature_index = GetTensorFeatureDimIndex(dims, format); + if (format == FORMAT_NCHW_VECT_C) { + CHECK_EQ(0, C % 4) << "NCHW_VECT_C requires C to be a multiple of 4, but C=" + << C; + C /= 4; + dim_sizes[GetTensorInnerFeatureDimIndex(dims, format)] = 4; + } + dim_sizes[feature_index] = C; + return TensorShapeUtils::MakeShape(dim_sizes, shape); +} + +inline TensorShape ShapeFromFormat(TensorFormat format, int64_t N, + gtl::ArraySlice spatial, + int64_t C) { + TensorShape shape; + TF_CHECK_OK(ShapeFromFormatWithStatus(format, N, spatial, C, &shape)); + return shape; +} + +// Return a tensor shape of the specified 'format', and dimensions. +// Works for both 2D and 3D operations. If 'format' is OIHW_VECT_I, +// the output TensorShape has spatial.size() + 3 dimensions, otherwise +// it has spatial.size() + 2 dimensions. +inline TensorShape ShapeFromFilterTensorFormat(FilterTensorFormat format, + gtl::ArraySlice spatial, + int64_t I, int64_t O) { + const int dims = GetFilterTensorDimsFromSpatialDims(spatial.size(), format); + gtl::InlinedVector dim_sizes(dims); + dim_sizes[GetFilterTensorOutputChannelsDimIndex(dims, format)] = O; + for (int dim = 0; static_cast(dim) < spatial.size(); dim++) { + dim_sizes[GetFilterTensorSpatialDimIndex(dims, format, dim)] = spatial[dim]; + } + + if (format == FORMAT_OIHW_VECT_I) { + CHECK_EQ(0, I % 4) << "OIHW_VECT_I requires I to be a multiple of 4, but I=" + << I; + I /= 4; + dim_sizes[GetFilterTensorInnerInputChannelsDimIndex(dims, format)] = 4; + } + dim_sizes[GetFilterTensorInputChannelsDimIndex(dims, format)] = I; + return TensorShape(dim_sizes); +} + +// Return a tensor shape of the specified 'format', and dimensions. +inline Status ShapeFromFormatWithStatus(TensorFormat format, int64_t N, + int64_t H, int64_t W, int64_t C, + TensorShape* shape) { + return ShapeFromFormatWithStatus(format, N, {H, W}, C, shape); +} + +// Return a tensor shape of the specified 'format', and dimensions. +inline TensorShape ShapeFromFormat(TensorFormat format, int64_t N, int64_t H, + int64_t W, int64_t C) { + TensorShape shape; + TF_CHECK_OK(ShapeFromFormatWithStatus(format, N, {H, W}, C, &shape)); + return shape; +} + +// Return a filter tensor shape of the specified 'format', and dimensions. +inline TensorShape ShapeFromFilterTensorFormat(FilterTensorFormat format, + int64_t H, int64_t W, int64_t I, + int64_t O) { + return ShapeFromFilterTensorFormat(format, {H, W}, I, O); +} + +// Returns a copy of the specified tensor 'src_shape' converted from +// 'src_format' to 'dst_format'. +inline Status ShapeFromFormatWithStatus(TensorFormat dst_format, + const TensorShape& src_shape, + TensorFormat src_format, + TensorShape* shape) { + if (src_format == dst_format) { + *shape = src_shape; + return OkStatus(); + } + + const int64_t batch = GetTensorDim(src_shape, src_format, 'N'); + const int64_t channels = GetTensorDim(src_shape, src_format, 'C') * + (src_format == FORMAT_NCHW_VECT_C ? 4 : 1); + const int num_src_spatial_dims = + GetTensorSpatialDims(src_shape.dims(), src_format); + std::vector spatial_dims(num_src_spatial_dims); + for (int spatial_dim = 0; spatial_dim < num_src_spatial_dims; ++spatial_dim) { + spatial_dims[spatial_dim] = gtl::ArraySlice( + src_shape.dim_sizes())[GetTensorSpatialDimIndex( + src_shape.dims(), src_format, spatial_dim)]; + } + if (src_format == FORMAT_NHWC_VECT_W) { + spatial_dims[num_src_spatial_dims - 1] *= 4; + } + return ShapeFromFormatWithStatus(dst_format, batch, {spatial_dims}, channels, + shape); +} + +inline TensorShape ShapeFromFormat(TensorFormat dst_format, + const TensorShape& src_shape, + TensorFormat src_format) { + TensorShape shape; + TF_CHECK_OK( + ShapeFromFormatWithStatus(dst_format, src_shape, src_format, &shape)); + return shape; +} + +// Returns a copy of the specified filter tensor 'src_shape' converted from +// 'src_filter_format' to 'dst_filter_format'. +inline TensorShape ShapeFromFilterFormat(FilterTensorFormat dst_filter_format, + const TensorShape& src_shape, + FilterTensorFormat src_filter_format) { + if (src_filter_format == dst_filter_format) { + return src_shape; + } + + const int64_t output_channels = + GetFilterDim(src_shape, src_filter_format, 'O'); + const int64_t input_channels = + GetFilterDim(src_shape, src_filter_format, 'I') * + (src_filter_format == FORMAT_OIHW_VECT_I ? 4 : 1); + + if (GetFilterTensorSpatialDims(src_shape.dims(), src_filter_format) == 3) { + return ShapeFromFilterTensorFormat( + dst_filter_format, + {{GetFilterDim(src_shape, src_filter_format, '0'), + GetFilterDim(src_shape, src_filter_format, '1'), + GetFilterDim(src_shape, src_filter_format, '2')}}, + input_channels, output_channels); + } + + return ShapeFromFilterTensorFormat( + dst_filter_format, + {{GetFilterDim(src_shape, src_filter_format, 'H'), + GetFilterDim(src_shape, src_filter_format, 'W')}}, + input_channels, output_channels); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_FORMAT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_ops_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_ops_util.h new file mode 100644 index 0000000000000000000000000000000000000000..4dd6588e58a2a059a0a02235340690f31c26aa8b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_ops_util.h @@ -0,0 +1,128 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_OPS_UTIL_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_OPS_UTIL_H_ + +#define EIGEN_USE_THREADS + +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/variant_op_registry.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +typedef Eigen::ThreadPoolDevice CPUDevice; +typedef Eigen::GpuDevice GPUDevice; + +template +Status ZerosLikeTensor(OpKernelContext* ctx, const Tensor& x, Tensor* out) { + AllocatorAttributes attr; + if (x.dtype() == DT_VARIANT) { + attr.set_on_host(true); + } + TF_RETURN_IF_ERROR(ctx->allocate_temp(x.dtype(), x.shape(), out, attr)); + + switch (out->dtype()) { +#define DTYPE_CASE(dtype) \ + case DataTypeToEnum::value: \ + /* TODO(skyewm): use SetZeroFunctor like in ZerosLikeOp? */ \ + out->flat().device(ctx->eigen_device()) = \ + out->flat().constant(dtype(0)); \ + break; + + TF_CALL_POD_TYPES(DTYPE_CASE) +#undef DTYPE_CASE + + case DT_INVALID: { + *out = Tensor(DT_INVALID); + break; + } + case DataTypeToEnum::value: { + Variant* out_variant = out->scalar().data(); + TF_RETURN_IF_ERROR( + UnaryOpVariant(ctx, ZEROS_LIKE_VARIANT_UNARY_OP, + x.scalar()(), out_variant)); + break; + } + default: + return errors::InvalidArgument( + "Trying to compute zeros_like for unsupported dtype ", + DataTypeString(out->dtype())); + } + return OkStatus(); +} + +template +Status BinaryAddTensors(OpKernelContext* ctx, const Tensor& a, const Tensor& b, + Tensor* out) { + if (a.dtype() == DT_INVALID) { + *out = b; + return OkStatus(); + } + if (b.dtype() == DT_INVALID) { + *out = a; + return OkStatus(); + } + if (a.dtype() != b.dtype()) { + return errors::InvalidArgument( + "Trying to add two tensors with incompatible element types. ", + "One is ", DataTypeString(a.dtype()), " and the other is ", + DataTypeString(b.dtype())); + } + if (a.shape() != b.shape()) { + // TODO(apassos) support broadcasting additions here? + return errors::InvalidArgument( + "Trying to add two tensors with incompatible element shapes. ", + "One is ", a.shape().DebugString(), " and the other is ", + b.shape().DebugString()); + } + + AllocatorAttributes attr; + if (a.dtype() == DT_VARIANT) { + attr.set_on_host(true); + } + TF_RETURN_IF_ERROR(ctx->allocate_temp(a.dtype(), a.shape(), out, attr)); + + switch (out->dtype()) { +#define DTYPE_CASE(dtype) \ + case DataTypeToEnum::value: \ + out->flat().device(ctx->eigen_device()) = \ + a.flat() + b.flat(); \ + break; + + TF_CALL_NUMBER_TYPES(DTYPE_CASE) +#undef DTYPE_CASE + + case DataTypeToEnum::value: { + Variant* out_variant = out->scalar().data(); + TF_RETURN_IF_ERROR(BinaryOpVariants( + ctx, ADD_VARIANT_BINARY_OP, a.scalar()(), + b.scalar()(), out_variant)); + break; + } + default: + return errors::InvalidArgument("Trying to add unsupported dtype ", + out->dtype()); + } + return OkStatus(); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_OPS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_reader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_reader.h new file mode 100644 index 0000000000000000000000000000000000000000..91ee7cd7d76ab94f670bd63cfbbc7ea42c347a19 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_reader.h @@ -0,0 +1,215 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The utility to read checkpoints for google brain tensor ops and v3 +// checkpoints for dist_belief. + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_H_ + +#include +#include +#include +#include +#include + +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/lib/gtl/map_util.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/saved_tensor_slice.pb.h" +#include "tensorflow/core/util/saved_tensor_slice_util.h" +#include "tensorflow/core/util/tensor_slice_set.h" +#include "tensorflow/core/util/tensor_slice_util.h" + +namespace tensorflow { + +namespace checkpoint { + +// The reader reads in all the meta data about all the tensor slices. Then it +// will try to read the relevant data on-demand to produce the data for the +// slices needed. +// NOTE(yangke): another way to do this is to first load a list of the tensor +// slices needed and then just selectively read some of the meta data. That +// might optimize the loading but makes the logic a bit more complicated. We +// might want to revisit that. +// TODO(yangke): consider moving to TensorProto. +class TensorSliceReader { + public: + // Abstract interface for reading data out of a tensor slice checkpoint file + class Table { + public: + virtual ~Table(); + virtual bool Get(const string& key, string* value) = 0; + }; + typedef std::function OpenTableFunction; + + static constexpr int kLoadAllShards = -1; + TensorSliceReader(const string& filepattern); + TensorSliceReader(const string& filepattern, OpenTableFunction open_function); + TensorSliceReader(const string& filepattern, OpenTableFunction open_function, + int preferred_shard); + virtual ~TensorSliceReader(); + + // Get the filename this reader is attached to. + const string& filepattern() const { return filepattern_; } + + // Get the number of files matched. + int num_files() const { return sss_.size(); } + + // Get the status of the reader. + Status status() const { return status_; } + + // Checks if the reader contains any slice of a tensor. In case the reader + // does contain the tensor, if "shape" is not nullptr, fill "shape" with the + // shape of the tensor; if "type" is not nullptr, fill "type" with the type + // of the tensor. + bool HasTensor(const string& name, TensorShape* shape, DataType* type) const; + + // Checks if the reader contains all the data about a tensor slice, and if + // yes, copies the data of the slice to "data". The caller needs to make sure + // that "data" points to a buffer that holds enough data. + // This is a slow function since it needs to read sstables. + template + bool CopySliceData(const string& name, const TensorSlice& slice, + T* data) const; + + // Get the tensors. + const std::unordered_map& Tensors() const { + return tensors_; + } + + // Returns value for one tensor. Only single slice checkpoints are supported + // at the moment. + Status GetTensor(const string& name, + std::unique_ptr* out_tensor) const; + + typedef std::unordered_map VarToShapeMap; + typedef std::unordered_map VarToDataTypeMap; + + // Returns a map from tensor name to shape. + VarToShapeMap GetVariableToShapeMap() const; + + // Returns a map from tensor name to data type. + VarToDataTypeMap GetVariableToDataTypeMap() const; + + // Returns a string containing names and shapes of all the tensors. + const string DebugString() const; + + private: + friend class TensorSliceWriteTestHelper; + + void LoadShard(int shard) const; + void LoadAllShards() const; + + const TensorSliceSet* FindTensorSlice( + const string& name, const TensorSlice& slice, + std::vector>* details) const; + + const string filepattern_; + const OpenTableFunction open_function_; + std::vector fnames_; + std::unordered_map fname_to_index_; + + // Guards the attributes below. + mutable mutex mu_; + mutable bool all_shards_loaded_ = false; + mutable std::vector> sss_; + mutable std::unordered_map tensors_; + mutable Status status_; + + TensorSliceReader(const TensorSliceReader&) = delete; + void operator=(const TensorSliceReader&) = delete; +}; + +Status OpenTableTensorSliceReader(const string& fname, + TensorSliceReader::Table** result); + +template +bool TensorSliceReader::CopySliceData(const string& name, + const TensorSlice& slice, T* data) const { + std::vector> details; + const TensorSliceSet* tss; + { + mutex_lock l(mu_); + tss = FindTensorSlice(name, slice, &details); + if (!tss && !all_shards_loaded_) { + VLOG(1) << "Did not find slice in preferred shard, loading all shards." + << name << ": " << slice.DebugString(); + LoadAllShards(); + tss = FindTensorSlice(name, slice, &details); + } + if (!tss) { + // No such tensor + return false; + } + } + // We have the data -- copy it over. + string value; + for (const auto& x : details) { + const TensorSlice& slice_s = x.first; + const string& fname = x.second; + int idx = gtl::FindWithDefault(fname_to_index_, fname, -1); + CHECK_GE(idx, 0) << "Failed to find the index for filename " << fname; + // We read a record in the corresponding sstable + const string key = EncodeTensorNameSlice(name, slice_s); + if (!sss_[idx]->Get(key, &value)) { + VLOG(1) << "Failed to seek to the record for tensor " << name + << ", slice " << slice_s.DebugString() + << ": computed key = " << key; + return false; + } + SavedTensorSlices sts; + if (!ParseProtoUnlimited(&sts, value)) { + VLOG(1) << "Failed to parse the record for tensor " << name << ", slice " + << slice_s.DebugString() << ": computed key = " << key; + return false; + } + // Ensure the TensorSlice contains the expected amount of data. + TensorShape shp_s; + Status s = slice_s.SliceTensorShape(tss->shape(), &shp_s); + if (!s.ok()) { + VLOG(1) << "Failed to slice tensor " << name << ", slice " + << slice_s.DebugString() << ": " << s; + return false; + } + if (checkpoint::TensorProtoDataSize(sts.data().data()) != + shp_s.num_elements()) { + VLOG(1) << "Tensor " << name << ", slice " << slice_s.DebugString() + << " had an unexpected amount of data: expected = " + << shp_s.num_elements() << ", got = " + << checkpoint::TensorProtoDataSize(sts.data().data()); + return false; + } + CopyDataFromTensorSliceToTensorSlice( + tss->shape(), slice_s, slice, + checkpoint::TensorProtoData(sts.data().data()), data); + } + return true; +} + +} // namespace checkpoint + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_reader_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_reader_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..59426f97de19d7464daffd0a58c73852147cd2c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_reader_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. +==============================================================================*/ + +// The utility to read checkpoints for google brain tensor ops and v3 +// checkpoints for dist_belief. + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_CACHE_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_CACHE_H_ + +#include +#include +#include + +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/tensor_slice_reader.h" + +namespace tensorflow { + +namespace checkpoint { + +class TensorSliceReaderCache; + +// Wrapper to a lazily allocated TensorSliceReaderCache. +class TensorSliceReaderCacheWrapper { + public: + TensorSliceReaderCacheWrapper(); + ~TensorSliceReaderCacheWrapper(); + + // Same as TensorSliceReaderCache::GetReader(). + const TensorSliceReader* GetReader( + const string& filepattern, + TensorSliceReader::OpenTableFunction open_function, + int preferred_shard) const; + + private: + mutable mutex mu_; + mutable TensorSliceReaderCache* cache_ = nullptr; +}; + +// A cache of TensorSliceReaders. +class TensorSliceReaderCache { + public: + TensorSliceReaderCache(); + ~TensorSliceReaderCache(); + + // Returns the TensorSliceReader corresponding to 'filepattern' and the + // open_function. May return nullptr if we can not create a new + // TensorSliceReader for the filepattern/open_function combination. + const TensorSliceReader* GetReader( + const string& filepattern, + TensorSliceReader::OpenTableFunction open_function, int preferred_shard); + + private: + // Need to use a regular function type in the key map as std::function does + // not support ==. + typedef Status (*OpenFuncType)(const string&, TensorSliceReader::Table**); + + // Protects attributes below. + mutex mu_; + + // Maps of opened readers. + std::unordered_map> + readers_; + + // Set of keys that a previous GetReader() call is still trying to populate. + std::set still_opening_; + + // Condition variable to notify when a reader has been created. + condition_variable cv_; +}; + +} // namespace checkpoint + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_READER_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_set.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_set.h new file mode 100644 index 0000000000000000000000000000000000000000..4887321de959f6008a6a76ce7589bcf1f0f8d833 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_set.h @@ -0,0 +1,94 @@ +/* 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. +==============================================================================*/ + +// A class to manage slices of a tensor. You can "register" set of slices for a +// tensor and then "query" if we have data for a given slice. + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_SET_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_SET_H_ + +#include // for string +#include +#include +#include + +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" // for Status +#include "tensorflow/core/lib/core/stringpiece.h" // for StringPiece +#include "tensorflow/core/platform/types.h" // for int64 + +namespace tensorflow { + +namespace checkpoint { + +class TensorSliceSet { + public: + TensorSliceSet(const TensorShape& shape, DataType type); + virtual ~TensorSliceSet(); + + const TensorShape& shape() const { return shape_; } + DataType type() const { return type_; } + + // Register a new slice for the tensor. The "tag" is an arbitrary string + // associated with the slice (in one application it denotes the name of the + // file that contains the slice); the "data" points to the data of the tensor + // slice (it can be a nullptr). + Status Register(const TensorSlice& slice, const string& tag); + + // Alternative way of querying about a new slice: instead of copying the + // data, it returns a list of meta data about the stored slices that will + // supply data for the slice. + bool QueryMeta( + const TensorSlice& slice, + std::vector>* results) const; + + struct SliceInfo { + TensorSlice slice; + const string tag; + int64_t num_floats; + }; + + // Returns the map from slice string to SliceInfo. + const std::unordered_map& Slices() const { + return slices_; + } + + private: + const TensorShape shape_; + const DataType type_; + // We maintain a mapping from the slice string to the slice information. + std::unordered_map slices_; + + // Minimal slice which contains all presented slices. Used for speeding up + // overlap check when slices are being added consequently. + TensorSlice slices_hull_; +}; + +// Registers "slice" in the TensorSliceSet stored in "tensor_slices", under key +// "name". Other arguments are used for validations. Does not modify the map +// or its values on non-OK. +// REQUIRES: tensor_slices != nullptr +Status RegisterTensorSlice( + const string& name, const TensorShape& shape, DataType type, + const string& tag, const TensorSlice& slice, + std::unordered_map* tensor_slices); + +} // namespace checkpoint + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_SET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7507d5ae6135ca4181cbfb937f9ced478778a052 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_util.h @@ -0,0 +1,191 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_UTIL_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_UTIL_H_ + +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/platform/logging.h" + +namespace tensorflow { + +namespace { + +// Some hackery to invoke eigen tensor to copy over tensor slices with variable +// dimension tensors. +// TODO(yangke): get rid of that once the variable dimension tensor support is +// in. +static const int kTensorSliceMaxRank = 8; + +// Create a tensor map with the given shape: we support up to 8 dimensions. If +// the shape has less than 8 dimensions, we pad the remaining dimension with 1. +template +Eigen::TensorMap> +GetEigenTensorMapFromTensorShape(const TensorShape& shape, T* data) { + Eigen::DSizes dsizes = + shape.AsEigenDSizesWithPadding(); + Eigen::TensorMap> eig( + data, dsizes); + return eig; +} + +// For everything except string, a standard Eigen cast and assignment works +template +struct CopyThatWorksWithStringPointer { + template + static void Copy(const SrcTensor& s, Shape s_start, Shape len, DstTensor& d, + Shape d_start) { + d.slice(d_start, len) = s.slice(s_start, len).template cast(); + } +}; + +// Eigen makes it extremely difficult to dereference a tensor of string* into +// string, so we roll our own loop instead. +template <> +struct CopyThatWorksWithStringPointer { + template + static void Copy(const SrcTensor& s, Shape s_start, Shape len, DstTensor& d, + Shape d_start) { + typedef typename SrcTensor::Index Index; + static_assert(kTensorSliceMaxRank == 8, + "If kTensorSliceMaxRank changes, modify the loop below."); + for (Index i0 = 0; i0 < len[0]; i0++) { + for (Index i1 = 0; i1 < len[1]; i1++) { + for (Index i2 = 0; i2 < len[2]; i2++) { + for (Index i3 = 0; i3 < len[3]; i3++) { + for (Index i4 = 0; i4 < len[4]; i4++) { + for (Index i5 = 0; i5 < len[5]; i5++) { + for (Index i6 = 0; i6 < len[6]; i6++) { + for (Index i7 = 0; i7 < len[7]; i7++) { + d(d_start[0] + i0, d_start[1] + i1, d_start[2] + i2, + d_start[3] + i3, d_start[4] + i4, d_start[5] + i5, + d_start[6] + i6, d_start[7] + i7) = + *s(s_start[0] + i0, s_start[1] + i1, s_start[2] + i2, + s_start[3] + i3, s_start[4] + i4, s_start[5] + i5, + s_start[6] + i6, s_start[7] + i7); + } + } + } + } + } + } + } + } + } +}; + +// Checkpointing of half is done by storing the raw 16 bits as a signed 32bit +// integer. To restore the checkpoint we need to do the reverse operation by +// reinterpreting the integer as a 16 bit float. This prevents us from using +// the default cast operation. +template <> +struct CopyThatWorksWithStringPointer { + template + static void Copy(const SrcTensor& s, Shape s_start, Shape len, DstTensor& d, + Shape d_start) { + typedef typename SrcTensor::Index Index; + static_assert(kTensorSliceMaxRank == 8, + "If kTensorSliceMaxRank changes, modify the loop below."); + for (Index i0 = 0; i0 < len[0]; i0++) { + for (Index i1 = 0; i1 < len[1]; i1++) { + for (Index i2 = 0; i2 < len[2]; i2++) { + for (Index i3 = 0; i3 < len[3]; i3++) { + for (Index i4 = 0; i4 < len[4]; i4++) { + for (Index i5 = 0; i5 < len[5]; i5++) { + for (Index i6 = 0; i6 < len[6]; i6++) { + for (Index i7 = 0; i7 < len[7]; i7++) { + d(d_start[0] + i0, d_start[1] + i1, d_start[2] + i2, + d_start[3] + i3, d_start[4] + i4, d_start[5] + i5, + d_start[6] + i6, d_start[7] + i7) = + Eigen::numext::bit_cast( + s(s_start[0] + i0, s_start[1] + i1, s_start[2] + i2, + s_start[3] + i3, s_start[4] + i4, s_start[5] + i5, + s_start[6] + i6, s_start[7] + i7)); + } + } + } + } + } + } + } + } + } +}; + +// Given a tensor described by "shape", two slices "slice_s" and "slice_d", +// and two pointers "ptr_s" and "ptr_d", where "ptr_s" points to a chunk of +// memory that stores the data for "slice_s" and "ptr_d" points to a chunk of +// memory that stores the data for "slice_d". This function copies the data +// that belongs to the intersection of the two slices from slice_s to +// slice_d. Uses Tensor cast() to convert from SrcT to DstT. Returns true +// iff the two slices share any intersection (and thus some data is copied). +// TODO(yangke): figure out if we can make it private. +template +static bool CopyDataFromTensorSliceToTensorSlice(const TensorShape& shape, + const TensorSlice& slice_s, + const TensorSlice& slice_d, + const SrcT* ptr_s, + DstT* ptr_d) { + CHECK_LE(shape.dims(), kTensorSliceMaxRank) + << "Only tensors of size up to " << kTensorSliceMaxRank + << " are supported"; + // We need to compute the intersection of the two slices. + TensorSlice inter; + if (!slice_s.Intersect(slice_d, &inter)) { + // There is no intersection: returns false. + return false; + } else { + // We need to compute the applied shapes after applying slice_s and + // slice_d. + TensorShape shp_s, shp_d; + Status s; + s = slice_s.SliceTensorShape(shape, &shp_s); + if (!s.ok()) { + LOG(WARNING) << s; + return false; + } + s = slice_d.SliceTensorShape(shape, &shp_d); + if (!s.ok()) { + LOG(WARNING) << s; + return false; + } + + // We need to compute the relative slice of "inter" w.r.t. both slice_s and + // slice_d. + TensorSlice rel_s, rel_d; + slice_s.ComputeRelative(inter, &rel_s); + slice_d.ComputeRelative(inter, &rel_d); + + // Get the eigen tensor maps to the data. + auto t_s = GetEigenTensorMapFromTensorShape(shp_s, ptr_s); + auto t_d = GetEigenTensorMapFromTensorShape(shp_d, ptr_d); + + Eigen::DSizes s_start, s_len, + d_start, d_len; + + rel_s.FillIndicesAndSizes(shp_s, &s_start, &s_len); + rel_d.FillIndicesAndSizes(shp_d, &d_start, &d_len); + CopyThatWorksWithStringPointer::Copy(t_s, s_start, s_len, t_d, + d_start); + return true; + } +} + +} // namespace + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_writer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..1bd7b1c91202dcb32b8d2bfeabdfbe23e8db4fef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/tensor_slice_writer.h @@ -0,0 +1,206 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The utility to write checkpoints for google brain tensor ops and v3 +// checkpoints for dist_belief. + +#ifndef TENSORFLOW_CORE_UTIL_TENSOR_SLICE_WRITER_H_ +#define TENSORFLOW_CORE_UTIL_TENSOR_SLICE_WRITER_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/lib/gtl/map_util.h" +#include "tensorflow/core/lib/strings/stringprintf.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/saved_tensor_slice.pb.h" +#include "tensorflow/core/util/saved_tensor_slice_util.h" + +namespace tensorflow { + +namespace checkpoint { + +class TensorSliceWriter { + public: + // Abstract interface that TensorSliceWriter uses for building + class Builder { + public: + virtual ~Builder() = default; + virtual void Add(StringPiece key, StringPiece value) = 0; + virtual Status Finish(int64_t* file_size) = 0; + }; + typedef std::function CreateBuilderFunction; + + TensorSliceWriter(const string& filename, + CreateBuilderFunction create_builder); + virtual ~TensorSliceWriter() = default; + // Adds a slice. We support float and int32 for now. + // TODO(yangke): add more supports + template + Status Add(const string& name, const TensorShape& shape, + const TensorSlice& slice, const T* data); + Status Finish(); + + // Allocate "num_elements" elements in "ss" and save the data in "data" + // there. + template + static Status SaveData(const T* data, int64_t num_elements, SavedSlice* ss); + + static size_t MaxBytesPerElement(DataType dt); + + private: + static size_t MaxBytesPerElementOrZero(DataType dt); + + static constexpr size_t kMaxMessageBytes = 1LL << 31; + // Filling in the TensorProto in a SavedSlice will add the following + // header bytes, in addition to the data: + // - 1 byte: TensorProto tag and wire format + // - <= 5 bytes: TensorProto length + // - 1 byte: Repeated *_val tag and wire format + // - <= 5 bytes: *_val length + // However, we add 1KB of slack, to be conservative and guard + // against other additions to the TensorProto. + static constexpr size_t kTensorProtoHeaderBytes = 1 << 10; + + const string filename_; + const CreateBuilderFunction create_builder_; + const string tmpname_; + + // A mapping from the tensor names to their index in meta_.saved_slice_meta() + std::unordered_map name_to_index_; + // The metadata that holds all the saved tensor slices. + SavedTensorSlices sts_; + // The data to be written to the builder + std::map data_; + // Total number of slices written + int slices_; + TensorSliceWriter(const TensorSliceWriter&) = delete; + void operator=(const TensorSliceWriter&) = delete; +}; + +template +Status TensorSliceWriter::Add(const string& name, const TensorShape& shape, + const TensorSlice& slice, const T* data) { + // The tensor and the slice have to be compatible + if (shape.dims() != slice.dims()) { + return errors::Internal("Incompatible tensor shape and slice: ", "shape = ", + shape.DebugString(), + ", slice = ", slice.DebugString()); + } + DataType dt = DataTypeToEnum::value; + // We need to add an entry for "name" if there isn't an entry already. + int index = gtl::FindWithDefault(name_to_index_, name, -1); + if (index >= 0) { + // The same tensor has been registered -- we verify that the shapes and the + // type agree. + const SavedSliceMeta& ssm = sts_.meta().tensor(index); + CHECK_EQ(name, ssm.name()) << ssm.ShortDebugString(); + TensorShape ssm_shape(ssm.shape()); + if (!shape.IsSameSize(ssm_shape)) { + return errors::Internal( + "Mismatching shapes: existing tensor = ", ssm_shape.DebugString(), + ", trying to add name ", name, ", shape = ", shape.DebugString()); + } + if (dt != ssm.type()) { + return errors::Internal( + "Mismatching types: existing type = ", DataTypeString(ssm.type()), + ", trying to add name ", name, ", type = ", DataTypeString(dt)); + } + } else { + // Insert the new tensor name with the shape information + index = sts_.meta().tensor_size(); + name_to_index_.insert(std::make_pair(name, index)); + SavedSliceMeta* ssm = sts_.mutable_meta()->add_tensor(); + ssm->set_name(name); + shape.AsProto(ssm->mutable_shape()); + ssm->set_type(dt); + } + // Now we need to add the slice info the list of slices. + SavedSliceMeta* ssm = sts_.mutable_meta()->mutable_tensor(index); + slice.AsProto(ssm->add_slice()); + + // Now we need to add the real data. + { + SavedTensorSlices sts; + SavedSlice* ss = sts.mutable_data(); + ss->set_name(name); + slice.AsProto(ss->mutable_slice()); + TensorShape saved_shape(ssm->shape()); + TensorShape sliced_shape; + TF_RETURN_IF_ERROR(slice.SliceTensorShape(saved_shape, &sliced_shape)); + TF_RETURN_IF_ERROR(SaveData(data, sliced_shape.num_elements(), ss)); + string key = EncodeTensorNameSlice(name, slice); + // TODO(yangke): consider doing a two-pass thing where the first pass just + // list the tensor slices we want to save and then another pass to actually + // set the data. Need to figure out if the interface works well. + std::pair key_value(key, ""); + if (!sts.AppendToString(&key_value.second)) { + return errors::Internal("Error writing Tensor. Possible size overflow."); + } + data_.insert(key_value); + } + ++slices_; + return OkStatus(); +} + +template +Status TensorSliceWriter::SaveData(const T* data, int64_t num_elements, + SavedSlice* ss) { + size_t max_bytes_per_element = + MaxBytesPerElementOrZero(DataTypeToEnum::value); + if (max_bytes_per_element == 0) { + return errors::InvalidArgument( + "Tensor slice serialization not implemented for dtype ", + DataTypeToEnum::value); + } + size_t size_bound = ss->ByteSize() + kTensorProtoHeaderBytes + + (max_bytes_per_element * num_elements); + if (size_bound > kMaxMessageBytes) { + return errors::InvalidArgument( + "Tensor slice is too large to serialize (conservative estimate: ", + size_bound, " bytes)"); + } + Fill(data, num_elements, ss->mutable_data()); + DCHECK_GE(ss->ByteSize(), 0); + DCHECK_LE(ss->ByteSize(), size_bound); + return OkStatus(); +} + +template <> +Status TensorSliceWriter::SaveData(const tstring* data, int64_t num_elements, + SavedSlice* ss); + +// Create a table builder that will write to "filename" in +// tensorflow::io::Table format. If successful, return OK +// and set "*builder" to the allocated builder. Otherwise, return a +// non-OK status. +Status CreateTableTensorSliceBuilder(const string& filename, + TensorSliceWriter::Builder** builder); + +} // namespace checkpoint + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TENSOR_SLICE_WRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/test_log.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/test_log.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..5577f200265c724a11c173857f1ae47f34f52572 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/test_log.pb.h @@ -0,0 +1,75 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/util/test_log.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2ftest_5flog_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2ftest_5flog_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include "tsl/protobuf/test_log.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2futil_2ftest_5flog_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_tensorflow_2fcore_2futil_2ftest_5flog_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2futil_2ftest_5flog_2eproto; +PROTOBUF_NAMESPACE_OPEN +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { +namespace dummy { + +// =================================================================== + + +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace dummy +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2futil_2ftest_5flog_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/test_log.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/test_log.proto new file mode 100644 index 0000000000000000000000000000000000000000..92d9d1ac637a7244f0ae964854df03b23723e1ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/test_log.proto @@ -0,0 +1,6 @@ +// Protocol messages for describing the results of benchmarks and unit tests. +syntax = "proto3"; + +package tensorflow.dummy; + +import public "tsl/protobuf/test_log.proto"; diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/transform_output_iterator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/transform_output_iterator.h new file mode 100644 index 0000000000000000000000000000000000000000..2dd201cdf9d29589992079f17367f87e9e69c787 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/transform_output_iterator.h @@ -0,0 +1,149 @@ +/* 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 TENSORFLOW_CORE_UTIL_TRANSFORM_OUTPUT_ITERATOR_H_ +#define TENSORFLOW_CORE_UTIL_TRANSFORM_OUTPUT_ITERATOR_H_ + +#include +#include + +namespace tensorflow { + +template +class TransformOutputIterator { + protected: + // Proxy object + struct Reference { + StoreType* ptr; + ConversionOp conversion_op; + + /// Constructor + __host__ __device__ __forceinline__ Reference(StoreType* ptr, + ConversionOp conversion_op) + : ptr(ptr), conversion_op(conversion_op) {} + + /// Assignment + __host__ __device__ __forceinline__ InputType operator=(InputType val) { + *ptr = conversion_op(val); + return val; + } + }; + + public: + // Required iterator traits + typedef TransformOutputIterator self_type; ///< My own type + typedef OffsetT difference_type; ///< Type to express the result of + ///< subtracting one iterator from another + typedef void + value_type; ///< The type of the element the iterator can point to + typedef void pointer; ///< The type of a pointer to an element the iterator + ///< can point to + typedef Reference reference; ///< The type of a reference to an element the + ///< iterator can point to + + typedef std::random_access_iterator_tag + iterator_category; ///< The iterator category + + /*private:*/ + + StoreType* ptr; + ConversionOp conversion_op; + + public: + /// Constructor + template + __host__ __device__ __forceinline__ TransformOutputIterator( + QualifiedStoreType* ptr, + ConversionOp conversionOp) ///< Native pointer to wrap + : ptr(ptr), conversion_op(conversionOp) {} + + /// Postfix increment + __host__ __device__ __forceinline__ self_type operator++(int) { + self_type retval = *this; + ptr++; + return retval; + } + + /// Prefix increment + __host__ __device__ __forceinline__ self_type operator++() { + ptr++; + return *this; + } + + /// Indirection + __host__ __device__ __forceinline__ reference operator*() const { + return Reference(ptr, conversion_op); + } + + /// Addition + template + __host__ __device__ __forceinline__ self_type operator+(Distance n) const { + self_type retval(ptr + n, conversion_op); + return retval; + } + + /// Addition assignment + template + __host__ __device__ __forceinline__ self_type& operator+=(Distance n) { + ptr += n; + return *this; + } + + /// Subtraction + template + __host__ __device__ __forceinline__ self_type operator-(Distance n) const { + self_type retval(ptr - n, conversion_op); + return retval; + } + + /// Subtraction assignment + template + __host__ __device__ __forceinline__ self_type& operator-=(Distance n) { + ptr -= n; + return *this; + } + + /// Distance + __host__ __device__ __forceinline__ difference_type + operator-(self_type other) const { + return ptr - other.ptr; + } + + /// Array subscript + template + __host__ __device__ __forceinline__ reference operator[](Distance n) const { + return Reference(ptr + n, conversion_op); + } + + /// Equal to + __host__ __device__ __forceinline__ bool operator==(const self_type& rhs) { + return (ptr == rhs.ptr); + } + + /// Not equal to + __host__ __device__ __forceinline__ bool operator!=(const self_type& rhs) { + return (ptr != rhs.ptr); + } + + /// ostream operator + friend std::ostream& operator<<(std::ostream& os, const self_type& itr) { + return os; + } +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_TRANSFORM_OUTPUT_ITERATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/use_cudnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/use_cudnn.h new file mode 100644 index 0000000000000000000000000000000000000000..ac9f918b494b305e2e0c88e02d1c5f9f26e50f25 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/use_cudnn.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. +==============================================================================*/ + +// The utility to check Cudnn dependency and set Cudnn-related flags. + +#ifndef TENSORFLOW_CORE_UTIL_USE_CUDNN_H_ +#define TENSORFLOW_CORE_UTIL_USE_CUDNN_H_ + +#include + +#include "tsl/util/use_cudnn.h" + +namespace tensorflow { + +using tsl::CudnnDisableConv1x1Optimization; +using tsl::CudnnRnnUseAutotune; +using tsl::CudnnUseAutotune; +using tsl::CudnnUseFrontend; +using tsl::CudnnUseRuntimeFusion; +using tsl::DebugCudnnRnn; +using tsl::DebugCudnnRnnAlgo; +using tsl::DebugCudnnRnnUseTensorOps; +using tsl::ShouldCudnnGroupedConvolutionBeUsed; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_USE_CUDNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/util.h new file mode 100644 index 0000000000000000000000000000000000000000..8c388aea3edb66f21cfb83413239817605c0d1d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/util.h @@ -0,0 +1,70 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_UTIL_H_ +#define TENSORFLOW_CORE_UTIL_UTIL_H_ + +#include + +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/platform/cpu_info.h" + +namespace tensorflow { + +// If op_name has '/' in it, then return everything before the first '/'. +// Otherwise return empty string. +StringPiece NodeNamePrefix(const StringPiece& op_name); + +// If op_name has '/' in it, then return everything before the last '/'. +// Otherwise return empty string. +StringPiece NodeNameFullPrefix(const StringPiece& op_name); + +class MovingAverage { + public: + explicit MovingAverage(int window); + ~MovingAverage(); + + void Clear(); + + double GetAverage() const; + void AddValue(double v); + + private: + const int window_; // Max size of interval + double sum_; // Sum over interval + double* data_; // Actual data values + int head_; // Offset of the newest statistic in data_ + int count_; // # of valid data elements in window +}; + +// Returns a string printing bytes in ptr[0..n). The output looks +// like "00 01 ef cd cd ef". +std::string PrintMemory(const char* ptr, size_t n); + +// Given a flattened index into a tensor, computes a string s so that +// StrAppend("tensor", s) is a Python indexing expression. E.g., +// "tensor", "tensor[i]", "tensor[i, j]", etc. +std::string SliceDebugString(const TensorShape& shape, int64_t flat); + +// Check if MKL is enabled in runtime +bool IsMKLEnabled(); + +// Check if BF16 is supported +bool IsBF16SupportedByOneDNNOnThisCPU(); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/work_sharder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/work_sharder.h new file mode 100644 index 0000000000000000000000000000000000000000..c414f70693110c91d4ef357095fcdce998862974 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/work_sharder.h @@ -0,0 +1,103 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_UTIL_WORK_SHARDER_H_ +#define TENSORFLOW_CORE_UTIL_WORK_SHARDER_H_ + +#include + +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// DEPRECATED: Prefer threadpool->ParallelFor with SchedulingStrategy, which +// allows you to specify the strategy for choosing shard sizes, including using +// a fixed shard size. Use this function only if you want to manually cap +// parallelism. +// +// Shards the "total" unit of work assuming each unit of work having +// roughly "cost_per_unit". Each unit of work is indexed 0, 1, ..., +// total - 1. Each shard contains 1 or more units of work and the +// total cost of each shard is roughly the same. The calling thread and the +// "workers" are used to compute each shard (calling work(start, +// limit). A common configuration is that "workers" is a thread pool +// with at least "max_parallelism" threads. +// +// "cost_per_unit" is an estimate of the number of CPU cycles (or nanoseconds +// if not CPU-bound) to complete a unit of work. Overestimating creates too +// many shards and CPU time will be dominated by per-shard overhead, such as +// Context creation. Underestimating may not fully make use of the specified +// parallelism. +// +// "work" should be a callable taking (int64, int64) arguments. +// work(start, limit) computes the work units from [start, +// limit), i.e., [start, limit) is a shard. +// +// Too much parallelism can also cause excessive thread switches, +// therefore, Shard() often limits the maximum parallelism. Each +// caller can provide the 1st argument max_parallelism. A thread can +// call SetMaxParallelism() so that all Shard() calls later limits the +// thread parallelism. +// +// REQUIRES: max_parallelism >= 0 +// REQUIRES: workers != nullptr +// REQUIRES: total >= 0 +// REQUIRES: cost_per_unit >= 0 +void Shard(int max_parallelism, thread::ThreadPool* workers, int64_t total, + int64_t cost_per_unit, std::function work); + +// Each thread has an associated option to express the desired maximum +// parallelism. Its default is a very large quantity. +// +// Within TF runtime, per-thread max parallelism affects Shard() and +// intra-op parallelism. E.g., if SetPerThreadMaxParallelism(1) is +// arranged to be called by a tf_compute thread, Shard() calls and +// eigen device assignment happens in that thread afterwards becomes +// single-threaded. +void SetPerThreadMaxParallelism(int max_parallelism); +int GetPerThreadMaxParallelism(); + +// Helper to set and unset per-thread max parallelism. +class ScopedPerThreadMaxParallelism { + public: + ScopedPerThreadMaxParallelism(int max_parallelism) + : previous_(GetPerThreadMaxParallelism()) { + SetPerThreadMaxParallelism(max_parallelism); + } + + ~ScopedPerThreadMaxParallelism() { SetPerThreadMaxParallelism(previous_); } + + private: + int previous_ = -1; +}; + +// Implementation details for Shard(). +class Sharder { + public: + typedef std::function Closure; + typedef std::function Runner; + typedef std::function Work; + + // Refers to Shard()'s comment for the meaning of total, + // cost_per_unit, work, max_parallelism. runner is an interface to + // schedule a closure. Shard() uses thread::ThreadPool instead. + static void Do(int64_t total, int64_t cost_per_unit, const Work& work, + const Runner& runner, int max_parallelism); +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_WORK_SHARDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/xla_config_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/xla_config_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..dbfc0d90f97d19667242201350cb06574849cd75 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/xla_config_registry.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 TENSORFLOW_CORE_UTIL_XLA_CONFIG_REGISTRY_H_ +#define TENSORFLOW_CORE_UTIL_XLA_CONFIG_REGISTRY_H_ + +#include + +#include "tensorflow/core/framework/logging.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +namespace xla_config_registry { + +// XlaGlobalJitLevel is used by XLA to expose its JIT level for processing +// single gpu and general (multi-gpu) graphs. +struct XlaGlobalJitLevel { + OptimizerOptions::GlobalJitLevel single_gpu; + OptimizerOptions::GlobalJitLevel general; +}; + +// Input is the jit_level in session config, and return value is the jit_level +// from XLA, reflecting the effect of the environment variable flags. +typedef std::function + GlobalJitLevelGetterTy; + +void RegisterGlobalJitLevelGetter(GlobalJitLevelGetterTy getter); + +XlaGlobalJitLevel GetGlobalJitLevel( + OptimizerOptions::GlobalJitLevel jit_level_in_session_opts); + +#define REGISTER_XLA_CONFIG_GETTER(getter) \ + REGISTER_XLA_CONFIG_GETTER_UNIQ_HELPER(__COUNTER__, getter) + +#define REGISTER_XLA_CONFIG_GETTER_UNIQ_HELPER(ctr, getter) \ + REGISTER_XLA_CONFIG_GETTER_UNIQ(ctr, getter) + +#define REGISTER_XLA_CONFIG_GETTER_UNIQ(ctr, getter) \ + static bool xla_config_registry_registration_##ctr = \ + (::tensorflow::xla_config_registry::RegisterGlobalJitLevelGetter( \ + getter), \ + true) + +} // namespace xla_config_registry + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_UTIL_XLA_CONFIG_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/zen_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/zen_util.h new file mode 100644 index 0000000000000000000000000000000000000000..079026ccdb94e6b3fc70ab786bd41b3e4302990b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/util/zen_util.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 TENSORFLOW_CORE_UTIL_ZEN_UTIL_H_ +#define TENSORFLOW_CORE_UTIL_ZEN_UTIL_H_ + +#ifdef AMD_ZENDNN + +#include "absl/base/call_once.h" +#include "tensorflow/core/util/env_var.h" + +namespace tensorflow { + +inline int64_t GetMempool() { + static absl::once_flag once; + static int64_t mempool = 1; + absl::call_once(once, [&] { + TF_CHECK_OK( + ReadInt64FromEnvVar("ZENDNN_ENABLE_MEMPOOL", mempool, &mempool)); + return mempool; + }); + return mempool; +} + +inline bool IsBlockedFormatEnabled() { + static absl::once_flag once; + static bool blocked_format = false; + static int64_t conv_algo = 1; + absl::call_once(once, [&] { + TF_CHECK_OK(ReadInt64FromEnvVar("ZENDNN_CONV_ALGO", conv_algo, &conv_algo)); + blocked_format = (conv_algo == 3); + return blocked_format; + }); + return blocked_format; +} + +} // namespace tensorflow + +#endif // AMD_ZENDNN +#endif // TENSORFLOW_CORE_UTIL_ZEN_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/float8/ml_dtypes/include/float8.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/float8/ml_dtypes/include/float8.h new file mode 100644 index 0000000000000000000000000000000000000000..f3f557b7d41a975cdd47296293e6bbe92a607339 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/float8/ml_dtypes/include/float8.h @@ -0,0 +1,1401 @@ +/* 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 ML_DTYPES_FLOAT8_H_ +#define ML_DTYPES_FLOAT8_H_ + +// 8-bit Floating Point Interchange Format, as described by +// https://arxiv.org/abs/2209.05433 + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __has_include +# if __has_include() +# include +# endif +#endif + +#if (defined(__cpp_lib_bitops) && __cpp_lib_bitops >= 201907L) +#include +#endif + +#include "Eigen/Core" + +namespace ml_dtypes { +namespace float8_internal { + +// Forward-declarations of classes. +class float8_e4m3fn; +class float8_e4m3fnuz; +class float8_e4m3b11fnuz; +class float8_e5m2; +class float8_e5m2fnuz; + +template +class float8_base { + protected: + // Constructor tag to allow constexpr construction from bit representation. + struct ConstructFromRepTag {}; + constexpr float8_base(uint8_t rep, ConstructFromRepTag) : rep_{rep} {} + + public: + constexpr float8_base() : rep_(0) {} + + template >> + explicit EIGEN_DEVICE_FUNC float8_base(T f) + : float8_base(ConvertFrom(static_cast(f)).rep(), + ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(double f64) + : float8_base(ConvertFrom(f64).rep(), ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(float f32) + : float8_base(ConvertFrom(f32).rep(), ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(Eigen::bfloat16 bf16) + : float8_base(ConvertFrom(bf16).rep(), ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(Eigen::half f16) + : float8_base(ConvertFrom(f16).rep(), ConstructFromRepTag{}) {} + + constexpr uint8_t rep() const { return rep_; } + + template >> + explicit EIGEN_DEVICE_FUNC operator T() const { + return static_cast(static_cast(derived())); + } + explicit EIGEN_DEVICE_FUNC operator double() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator float() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator Eigen::bfloat16() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator Eigen::half() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator bool() const { + return (rep() & 0x7F) != 0; + } + + constexpr Derived operator-() const { + return Derived(static_cast(rep() ^ 0x80), ConstructFromRepTag{}); + } + + constexpr const Derived& derived() const { + return *static_cast(this); + } + + constexpr Derived& derived() { return *static_cast(this); } + + static constexpr Derived FromRep(uint8_t rep) { + return Derived(rep, ConstructFromRepTag{}); + } + + // Conversions allowing saturation and truncation. + template + static inline EIGEN_DEVICE_FUNC Derived ConvertFrom(const From& from); + + template + static inline EIGEN_DEVICE_FUNC To ConvertTo(const Derived& from); + + // Operators via float32. + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator+(const Derived& other) const { + return Derived{float{derived()} + float{other}}; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator-(const Derived& other) const { + return Derived{float{derived()} - float{other}}; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator*(const Derived& other) const { + return Derived{float{derived()} * float{other}}; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator/(const Derived& other) const { + return Derived{float{derived()} / float{other}}; + } + + constexpr bool operator==(const Derived& other) const { + return Compare(derived(), other) == Ordering::kEquivalent; + } + + constexpr bool operator!=(const Derived& other) const { + return Compare(derived(), other) != Ordering::kEquivalent; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator<( + const Derived& other) const { + return Compare(derived(), other) == Ordering::kLess; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator<=( + const Derived& other) const { + return Compare(derived(), other) <= Ordering::kEquivalent; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator>( + const Derived& other) const { + return Compare(derived(), other) == Ordering::kGreater; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator>=( + const Derived& other) const { + Ordering ordering = Compare(derived(), other); + return ordering == Ordering::kGreater || ordering == Ordering::kEquivalent; + } + + // Compound assignment. + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator+=( + const Derived& other) { + derived() = derived() + other; + return derived(); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator-=( + const Derived& other) { + derived() = derived() - other; + return derived(); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator*=( + const Derived& other) { + derived() = derived() * other; + return derived(); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator/=( + const Derived& other) { + derived() = derived() / other; + return derived(); + } + + private: + static EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC std::pair + SignAndMagnitude(Derived x) { + const uint8_t x_abs_bits = + Eigen::numext::bit_cast(Eigen::numext::abs(x)); + const uint8_t x_bits = Eigen::numext::bit_cast(x); + const uint8_t x_sign = x_bits ^ x_abs_bits; + return {x_sign, x_abs_bits}; + } + static EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC int8_t + SignAndMagnitudeToTwosComplement(uint8_t sign, uint8_t magnitude) { + return magnitude ^ (static_cast(sign) < 0 ? -1 : 0); + } + + enum Ordering : int8_t { + kLess = -1, + kEquivalent = 0, + kGreater = 1, + kUnordered = 2, + }; + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC friend Ordering Compare( + const Derived& lhs, const Derived& rhs) { + if (Eigen::numext::isnan(lhs) || Eigen::numext::isnan(rhs)) { + return Ordering::kUnordered; + } + auto [lhs_sign, lhs_mag] = SignAndMagnitude(lhs); + auto [rhs_sign, rhs_mag] = SignAndMagnitude(rhs); + if (lhs_mag == 0 && rhs_mag == 0) { + return Ordering::kEquivalent; + } + int8_t lhs_twos_complement = + SignAndMagnitudeToTwosComplement(lhs_sign, lhs_mag); + int8_t rhs_twos_complement = + SignAndMagnitudeToTwosComplement(rhs_sign, rhs_mag); + if (lhs_twos_complement < rhs_twos_complement) { + return Ordering::kLess; + } + if (lhs_twos_complement > rhs_twos_complement) { + return Ordering::kGreater; + } + return Ordering::kEquivalent; + } + + uint8_t rep_; +}; + +class float8_e4m3fn : public float8_base { + // Exponent: 4, Mantissa: 3, bias: 7. + // Extended range: no inf, NaN represented by 0bS111'1111. + // The "fn" suffix is for consistency with the corresponding LLVM/MLIR type, + // signaling this type is not consistent with IEEE-754. The "f" indicates + // it is finite values only. The "n" indicates it includes NaNs, but only + // at the outer range. + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e4m3fn(const float8_e5m2& f8) + : float8_e4m3fn(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fn(const float8_e4m3b11fnuz& f8) + : float8_e4m3fn(ConvertFrom(f8)) {} +}; + +class float8_e4m3b11fnuz : public float8_base { + // Exponent: 4, Mantissa: 3, bias: 11. + // Extended range: no inf, NaN represented by 0b1000'0000. + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e5m2& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e5m2fnuz& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e4m3fn& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e4m3fnuz& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + + constexpr float8_e4m3b11fnuz operator-() const { + if ((rep() & 0x7f) == 0x00) { + return *this; + } + return Base::operator-(); + } + + float8_e4m3b11fnuz operator-(const float8_e4m3b11fnuz& other) const { + return Base::operator-(other); + } + + explicit EIGEN_DEVICE_FUNC operator bool() const { return rep() != 0; } +}; + +// Legacy name used in XLA (TODO(jewillco): remove). +using float8_e4m3b11 = float8_e4m3b11fnuz; + +class float8_e4m3fnuz : public float8_base { + // 8-bit floating point with 3 bit mantissa. + // + // An 8-bit floating point type with 1 sign bit, 4 bits exponent and 3 bits + // mantissa. The suffix "fnuz" is consistent with LLVM/MLIR naming and is + // derived from the differences to IEEE floating point conventions. `F` is + // for "finite" (no infinities), `N` for with special NaN encoding, `UZ` for + // unsigned zero. + // + // This type has the following characteristics: + // * bit encoding: S1E4M3 - `0bSEEEEMMM` + // * exponent bias: 8 + // * infinities: Not supported + // * NaNs: Supported with sign bit set to 1, exponent bits and mantissa bits + // set to all 0s - `0b10000000` + // * denormals when exponent is 0 + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e5m2& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e5m2fnuz& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e4m3b11fnuz& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e4m3fn& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + + constexpr float8_e4m3fnuz operator-() const { + if ((rep() & 0x7f) == 0x00) { + return *this; + } + return Base::operator-(); + } + + float8_e4m3fnuz operator-(const float8_e4m3fnuz& other) const { + return Base::operator-(other); + } + + explicit EIGEN_DEVICE_FUNC operator bool() const { return rep() != 0; } +}; + +class float8_e5m2 : public float8_base { + // Exponent: 5, Mantissa: 2, bias: 15. + // IEEE 754. + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e4m3fn f8) + : float8_e5m2(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e4m3fnuz f8) + : float8_e5m2(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e4m3b11fnuz f8) + : float8_e5m2(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e5m2fnuz& f8) + : float8_e5m2(ConvertFrom(f8)) {} +}; + +class float8_e5m2fnuz : public float8_base { + // 8-bit floating point with 2 bit mantissa. + // + // An 8-bit floating point type with 1 sign bit, 5 bits exponent and 2 bits + // mantissa. The suffix "fnuz" is consistent with LLVM/MLIR naming and is + // derived from the differences to IEEE floating point conventions. `F` is + // for "finite" (no infinities), `N` for with special NaN encoding, `UZ` for + // unsigned zero. + // + // This type has the following characteristics: + // * bit encoding: S1E5M2 - `0bSEEEEEMM` + // * exponent bias: 16 + // * infinities: Not supported + // * NaNs: Supported with sign bit set to 1, exponent bits and mantissa bits + // set to all 0s - `0b10000000` + // * denormals when exponent is 0 + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e5m2& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e4m3b11fnuz& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e4m3fn& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e4m3fnuz& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + + constexpr float8_e5m2fnuz operator-() const { + if ((rep() & 0x7f) == 0x00) { + return *this; + } + return Base::operator-(); + } + + float8_e5m2fnuz operator-(const float8_e5m2fnuz& other) const { + return Base::operator-(other); + } + + explicit EIGEN_DEVICE_FUNC operator bool() const { return rep() != 0; } +}; + +constexpr double ConstexprAbs(double x) { return x < 0.0 ? -x : x; } + +constexpr double ConstexprCeil(double x) { + constexpr double kIntegerThreshold = + uint64_t{1} << (std::numeric_limits::digits - 1); + // Too big or NaN inputs get returned unchanged. + if (!(ConstexprAbs(x) < kIntegerThreshold)) { + return x; + } + const double x_trunc = static_cast(static_cast(x)); + return x_trunc < x ? x_trunc + 1.0 : x_trunc; +} + +constexpr double ConstexprFloor(double x) { return -ConstexprCeil(-x); } + +constexpr double kLog10Of2 = 0.3010299956639812; +// C17 5.2.4.2.2p11: +// "number of decimal digits, q, such that any floating-point number with q +// decimal digits can be rounded into a floating-point number with p radix b +// digits and back again without change to the q decimal digits" +// floor((p - 1) * log10(2)); +constexpr int Digits10FromDigits(int digits) { + return static_cast(ConstexprFloor((digits - 1) * kLog10Of2)); +} + +// C17 5.2.4.2.2p11: +// "number of decimal digits, n, such that any floating-point number with p +// radix b digits can be rounded to a floating-point number with n decimal +// digits and back again without change to the value" +// ceil(1 + p * log10(2)); +constexpr int MaxDigits10FromDigits(int digits) { + return static_cast(ConstexprCeil(1.0 + (digits * kLog10Of2))); +} + +// C17 5.2.4.2.2p11: +// "minimum negative integer such that 10 raised to that power is in the range +// of normalized floating-point numbers" +// ceil(log10(2**(emin - 1))) == ceil((emin - 1) * log10(2)); +constexpr int MinExponent10FromMinExponent(int min_exponent) { + return static_cast(ConstexprCeil((min_exponent - 1) * kLog10Of2)); +} + +// C17 5.2.4.2.2p11: +// "maximum integer such that 10 raised to that power is in the range of +// representable finite floating-point numbers" +// floor(log10((1 - 2**-p) * 2**emax)) == floor(log10(1 - 2**-p) + +// emax * log10(2)) +constexpr int MaxExponent10FromMaxExponentAndDigits(int max_exponent, + int digits) { + // We only support digits in {3,4}. This table would grow if we wanted to + // handle more values. + constexpr double kLog10OfOnePredecessor[] = { + // log10(1 - 2**-3) + -0.057991946977686754, + // log10(1 - 2**-4) + -0.028028723600243537, + }; + return static_cast(ConstexprFloor(kLog10OfOnePredecessor[digits - 3] + + max_exponent * kLog10Of2)); +} + +// Structures for use in specializing std::numeric_limits. +struct numeric_limits_float8_base { + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const bool is_specialized = true; + static inline constexpr const bool is_signed = true; + static inline constexpr const bool is_integer = false; + static inline constexpr const bool is_exact = false; + static inline constexpr const bool has_quiet_NaN = true; + static inline constexpr const std::float_denorm_style has_denorm = + std::denorm_present; + static inline constexpr const bool has_denorm_loss = false; + static inline constexpr const std::float_round_style round_style = + std::round_to_nearest; + static inline constexpr const bool is_bounded = true; + static inline constexpr const bool is_modulo = false; + static inline constexpr const int radix = std::numeric_limits::radix; + static inline constexpr const bool traps = std::numeric_limits::traps; + static inline constexpr const bool tinyness_before = + std::numeric_limits::tinyness_before; + // NOLINTEND +}; + +struct numeric_limits_float8_e4m3fn : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 7; + static inline constexpr const int kMantissaBits = 3; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b1111 - 7) + 1; // Extended format. + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + // 1.0 * 2^(0b0001 - 7) = 1.0 * 2^-6 = 0.015625 + static constexpr float8_e4m3fn min() { + return float8_e4m3fn::FromRep(0b0'0001 << kMantissaBits); + } + // -(1 + 0b110 * 2^-3) * 2^(0b1111 - 7) = -1.75 * 2^8 = 448 + static constexpr float8_e4m3fn lowest() { + return float8_e4m3fn::FromRep(0b1'1111'110); + } + // (1 + 0b110 * 2^-3) * 2**(0b1111 - 7) = 1.75 * 2^8 = 448 + static constexpr float8_e4m3fn max() { + return float8_e4m3fn::FromRep(0b0'1111'110); + } + // 1.0 * 2^-3 = 0.125 + static constexpr float8_e4m3fn epsilon() { + return float8_e4m3fn::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + // 1.0 * 2^-1 = 0.5 + static constexpr float8_e4m3fn round_error() { + return float8_e4m3fn::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e4m3fn infinity() { + return float8_e4m3fn::FromRep(0b0'1111'111); + } + // NaN. + static constexpr float8_e4m3fn quiet_NaN() { + return float8_e4m3fn::FromRep(0b0'1111'111); + } + static constexpr float8_e4m3fn signaling_NaN() { + return float8_e4m3fn::FromRep(0b0'1111'111); + } + // 1.0 * 2^(-7 - 3 + 1) = 1.0 * 2^-9 = 0.001953125 + static constexpr float8_e4m3fn denorm_min() { + return float8_e4m3fn::FromRep(0b0'0000'001); + } +}; + +struct numeric_limits_float8_e4m3b11fnuz : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 11; + static inline constexpr const int kMantissaBits = 3; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b1111 - kExponentBias) + 1; // Extended format. + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + // 1.0 * 2^(0b0001 - 11) = 1.0 * 2^-10 = 0.0009765625 + static constexpr float8_e4m3b11fnuz min() { + return float8_e4m3b11fnuz::FromRep(1 << kMantissaBits); + } + // -(1 + 0b111 * 2^-3) * 2^(0b1111 - 11) = -1.875 * 2^4 = -30 + static constexpr float8_e4m3b11fnuz lowest() { + return float8_e4m3b11fnuz::FromRep(0b1'1111'111); + } + // (1 + 0b111 * 2^-3) * 2^(0b1111 - 11) = 1.875 * 2^4 = 30 + static constexpr float8_e4m3b11fnuz max() { + return float8_e4m3b11fnuz::FromRep(0b0'1111'111); + } + // 1.0 * 2^-3 = 0.125 + static constexpr float8_e4m3b11fnuz epsilon() { + return float8_e4m3b11fnuz::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + // 1.0 * 2^-1 = 0.5 + static constexpr float8_e4m3b11fnuz round_error() { + return float8_e4m3b11fnuz::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e4m3b11fnuz infinity() { + return float8_e4m3b11fnuz::FromRep(0b1'0000'000); + } + // NaN. + static constexpr float8_e4m3b11fnuz quiet_NaN() { + return float8_e4m3b11fnuz::FromRep(0b1'0000'000); + } + static constexpr float8_e4m3b11fnuz signaling_NaN() { + return float8_e4m3b11fnuz::FromRep(0b1'0000'000); + } + // 1.0 * 2^(-11 - 3 + 1) = 1.0 * 2^-13 = 0.0001220703125 + static constexpr float8_e4m3b11fnuz denorm_min() { + return float8_e4m3b11fnuz::FromRep(0b0'0000'001); + } +}; + +struct numeric_limits_float8_e4m3fnuz : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 8; + static inline constexpr const int kMantissaBits = 3; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b1111 - kExponentBias) + 1; // Extended format. + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + static constexpr float8_e4m3fnuz min() { + return float8_e4m3fnuz::FromRep(0x08); + } + static constexpr float8_e4m3fnuz lowest() { + return float8_e4m3fnuz::FromRep(0xFF); + } + static constexpr float8_e4m3fnuz max() { + return float8_e4m3fnuz::FromRep(0x7F); + } + static constexpr float8_e4m3fnuz epsilon() { + return float8_e4m3fnuz::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + static constexpr float8_e4m3fnuz round_error() { + return float8_e4m3fnuz::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e4m3fnuz infinity() { + return float8_e4m3fnuz::FromRep(0x80); + } // NaN. + static constexpr float8_e4m3fnuz quiet_NaN() { + return float8_e4m3fnuz::FromRep(0x80); + } + static constexpr float8_e4m3fnuz signaling_NaN() { + return float8_e4m3fnuz::FromRep(0x80); + } + static constexpr float8_e4m3fnuz denorm_min() { + return float8_e4m3fnuz::FromRep(0x01); + } +}; + +struct numeric_limits_float8_e5m2 : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 15; + static inline constexpr const int kMantissaBits = 2; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = 0b11111 - kExponentBias; + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = true; + static inline constexpr const bool has_infinity = true; + static inline constexpr const bool has_signaling_NaN = true; + // NOLINTEND + + // 1.0 * 2^(0b00001 - 15) = 1.0 * 2^-14 = 0.00006103515625 + static constexpr float8_e5m2 min() { + return float8_e5m2::FromRep(1 << kMantissaBits); + } + // -(1 + 0b11 * 2^-2) * 2^(0b11110 - 15) = -1.75 * 2^15 = -57344 + static constexpr float8_e5m2 lowest() { + return float8_e5m2::FromRep(0b1'11110'11); + } + // (1 + 0b11 * 2^-2) * 2^(0b11110 - 15) = 1.75 * 2^15 = 57344 + static constexpr float8_e5m2 max() { + return float8_e5m2::FromRep(0b0'11110'11); + } + // 1.0 * 2^-2 = 0.25 + static constexpr float8_e5m2 epsilon() { + return float8_e5m2::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + // 1.0 * 2^-1 = 0.5 + static constexpr float8_e5m2 round_error() { + return float8_e5m2::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e5m2 infinity() { + return float8_e5m2::FromRep(0b0'11111'00); + } + static constexpr float8_e5m2 quiet_NaN() { + // IEEE 754-2019 6.2.1: "All binary NaN bit strings have the sign bit S set + // to 0 or 1 and all the bits of the biased exponent field E set to 1 + // (see 3.4). A quiet NaN bit string should be encoded with the first bit + // (d1) of the trailing significand field T being 1." + return float8_e5m2::FromRep(0b0'11111'10); + } + static constexpr float8_e5m2 signaling_NaN() { + // IEEE 754-2019 6.2.1: "A signaling NaN bit string should be encoded with + // the first bit of the trailing significand field being 0." + return float8_e5m2::FromRep(0b0'11111'01); + } + // 1.0 * 2^(-15 - 2 + 1) = 1.0 * 2^-16 = 0.0000152587890625 + static constexpr float8_e5m2 denorm_min() { + return float8_e5m2::FromRep(0b0'00000'01); + } +}; + +struct numeric_limits_float8_e5m2fnuz : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 16; + static inline constexpr const int kMantissaBits = 2; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b11111 - kExponentBias) + 1; + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + static constexpr float8_e5m2fnuz min() { + return float8_e5m2fnuz::FromRep(0x04); + } + static constexpr float8_e5m2fnuz lowest() { + return float8_e5m2fnuz::FromRep(0xFF); + } + static constexpr float8_e5m2fnuz max() { + return float8_e5m2fnuz::FromRep(0x7F); + } + static constexpr float8_e5m2fnuz epsilon() { + return float8_e5m2fnuz::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + static constexpr float8_e5m2fnuz round_error() { + return float8_e5m2fnuz::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e5m2fnuz infinity() { + return float8_e5m2fnuz::FromRep(0x80); + } // NaN. + static constexpr float8_e5m2fnuz quiet_NaN() { + return float8_e5m2fnuz::FromRep(0x80); + } + static constexpr float8_e5m2fnuz signaling_NaN() { + return float8_e5m2fnuz::FromRep(0x80); + } + static constexpr float8_e5m2fnuz denorm_min() { + return float8_e5m2fnuz::FromRep(0x01); + } +}; + +} // namespace float8_internal +} // namespace ml_dtypes + +namespace std { +// Standard-library overrides. Note that these are picked up by Eigen as well. +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e4m3fn {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e4m3b11fnuz {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e4m3fnuz {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e5m2 {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e5m2fnuz {}; +} // namespace std + +namespace ml_dtypes { +namespace float8_internal { + +// Free-functions for use with ADL and in Eigen. +constexpr inline float8_e4m3fn abs(const float8_e4m3fn& a) { + return float8_e4m3fn::FromRep(a.rep() & 0b0'1111'111); +} + +constexpr inline bool(isnan)(const float8_e4m3fn& a) { + return abs(a).rep() == std::numeric_limits::quiet_NaN().rep(); +} + +constexpr inline float8_e4m3b11fnuz abs(const float8_e4m3b11fnuz& a) { + return (a.rep() & 0b0'1111'111) == 0 + ? float8_e4m3b11fnuz::FromRep(a.rep()) + : float8_e4m3b11fnuz::FromRep(a.rep() & 0b0'1111'111); +} + +constexpr inline bool(isnan)(const float8_e4m3b11fnuz& a) { + return a.rep() == std::numeric_limits::quiet_NaN().rep(); +} + +constexpr inline float8_e4m3fnuz abs(const float8_e4m3fnuz& a) { + return (a.rep() & 0x7F) == 0 ? float8_e4m3fnuz::FromRep(a.rep()) + : float8_e4m3fnuz::FromRep(a.rep() & 0x7F); +} + +constexpr inline bool(isnan)(const float8_e4m3fnuz& a) { + return abs(a).rep() == + std::numeric_limits::quiet_NaN().rep(); +} + +constexpr inline float8_e5m2 abs(const float8_e5m2& a) { + return float8_e5m2::FromRep(a.rep() & 0b0'11111'11); +} + +constexpr inline bool(isnan)(const float8_e5m2& a) { + return abs(a).rep() > std::numeric_limits::infinity().rep(); +} + +constexpr inline float8_e5m2fnuz abs(const float8_e5m2fnuz& a) { + return (a.rep() & 0x7F) == 0 ? float8_e5m2fnuz::FromRep(a.rep()) + : float8_e5m2fnuz::FromRep(a.rep() & 0x7F); +} + +constexpr inline bool isnan(const float8_e5m2fnuz& a) { + return a.rep() == 0x80; +} + +template +constexpr inline bool(isinf)(const float8_base& a) { + return std::numeric_limits::has_infinity + ? abs(a.derived()).rep() == + std::numeric_limits::infinity().rep() + : false; // No inf representation. +} + +template +constexpr inline bool(isfinite)(const float8_base& a) { + return !isnan(a.derived()) && !isinf(a.derived()); +} + +template +std::ostream& operator<<(std::ostream& os, const float8_base& f8) { + os << static_cast(f8.derived()); + return os; +} + +//============================================================================== +// Inline conversion routines between float8 and other types. +//============================================================================== + +// Helper for getting a bit representation provided a byte size. +template +using GetUnsignedInteger = + typename Eigen::numext::get_integer_by_size::unsigned_type; + +// Converts between two floating-point types. +template +struct ConvertImpl; + +// Convert to same type. We need explicit specializations for all combinations +// of template parameters to avoid ambiguities. +template +struct IdentityConversion { + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& from) { + return from; + } +}; + +template +struct ConvertImpl : public IdentityConversion {}; +template +struct ConvertImpl : public IdentityConversion {}; +template +struct ConvertImpl : public IdentityConversion {}; +template +struct ConvertImpl : public IdentityConversion {}; + +template +struct TraitsBase { + using BitsType = GetUnsignedInteger; + static constexpr int kBits = sizeof(Float) * CHAR_BIT; + static constexpr int kMantissaBits = Eigen::NumTraits::digits() - 1; + static constexpr int kExponentBits = kBits - kMantissaBits - 1; + static constexpr BitsType kExponentMask = ((BitsType{1} << kExponentBits) - 1) + << kMantissaBits; + static constexpr BitsType kMantissaMask = (BitsType{1} << kMantissaBits) - 1; + static constexpr int kExponentBias = (1 << (kExponentBits - 1)) - 1; +}; + +template +struct Traits : public TraitsBase {}; + +template <> +struct Traits : public TraitsBase { + static constexpr int kExponentBias = 11; +}; + +template <> +struct Traits : public TraitsBase { + using Base = TraitsBase; + static constexpr int kExponentBias = Base::kExponentBias + 1; +}; + +template <> +struct Traits : public TraitsBase { + using Base = TraitsBase; + static constexpr int kExponentBias = Base::kExponentBias + 1; +}; + +template +constexpr inline Bits RoundBitsToNearestEven(Bits bits, int roundoff) { + // Round to nearest even by adding a bias term. + // Consider a bit pattern + // FFF...FLRTT...T, + // where bits RTT...T need to be rounded-off. We add a bias term to the + // bit pattern s.t. a carry is introduced to round up only if + // - L is 1, R is 1, OR + // - L is 0, R is 1, any T is one. + // We do this by adding L to a bit pattern consisting of all T = 1. + Bits bias = roundoff == 0 + ? 0 + : ((bits >> roundoff) & 1) + (Bits{1} << (roundoff - 1)) - 1; + return bits + bias; +} + +#if (defined(__cpp_lib_bitops) && __cpp_lib_bitops >= 201907L) +using std::countl_zero; +#else +static constexpr inline int countl_zero(uint64_t x) { + int zeroes = 60; + if (x >> 32) { + zeroes -= 32; + x >>= 32; + } + if (x >> 16) { + zeroes -= 16; + x >>= 16; + } + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +static constexpr inline int countl_zero(uint32_t x) { + int zeroes = 28; + if (x >> 16) { + zeroes -= 16; + x >>= 16; + } + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +static constexpr inline int countl_zero(uint16_t x) { + int zeroes = 12; + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +static constexpr inline int countl_zero(uint8_t x) { + int zeroes = 4; + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +#endif + +template +struct ConvertImpl>> { + using FromTraits = Traits; + using FromBits = typename FromTraits::BitsType; + static constexpr int kFromBits = FromTraits::kBits; + static constexpr int kFromMantissaBits = FromTraits::kMantissaBits; + static constexpr int kFromExponentBits = FromTraits::kExponentBits; + static constexpr int kFromExponentBias = FromTraits::kExponentBias; + static constexpr FromBits kFromExponentMask = FromTraits::kExponentMask; + + using ToTraits = Traits; + using ToBits = typename ToTraits::BitsType; + static constexpr int kToBits = ToTraits::kBits; + static constexpr int kToMantissaBits = ToTraits::kMantissaBits; + static constexpr int kToExponentBits = ToTraits::kExponentBits; + static constexpr int kToExponentBias = ToTraits::kExponentBias; + static constexpr ToBits kToExponentMask = ToTraits::kExponentMask; + + // `WideBits` is wide enough to accommodate the largest exponent and mantissa + // in either `From` or `To`. + static constexpr int kWideBits = + (std::max(kToMantissaBits, kFromMantissaBits)) + // Max significand. + (std::max(kToExponentBits, kFromExponentBits)); // Max exponent. + static constexpr int kWideBytes = (kWideBits + (CHAR_BIT - 1)) / CHAR_BIT; + using WideBits = GetUnsignedInteger; + static constexpr int kExponentOffset = kToExponentBias - kFromExponentBias; + static constexpr int kDigitShift = kToMantissaBits - kFromMantissaBits; + + static EIGEN_DEVICE_FUNC inline To run(const From& from) { + // Shift bits to destination type, without sign bit. + const bool from_sign_bit = + Eigen::numext::bit_cast(from) >> (kFromBits - 1); + const FromBits from_bits = + Eigen::numext::bit_cast(Eigen::numext::abs(from)); + + // Special values, preserving sign. + if (Eigen::numext::isinf(from)) { + return from_sign_bit ? -Eigen::NumTraits::infinity() + : Eigen::NumTraits::infinity(); + } + if (Eigen::numext::isnan(from)) { + return from_sign_bit ? -Eigen::NumTraits::quiet_NaN() + : Eigen::NumTraits::quiet_NaN(); + } + if (from_bits == 0) { + return from_sign_bit ? -To{} : To{}; + } + + const int biased_from_exponent = from_bits >> kFromMantissaBits; + + // `To` supports more exponents near zero which means that some subnormal + // values in `From` may become normal. + if constexpr (std::numeric_limits::min_exponent < + std::numeric_limits::min_exponent) { + if (biased_from_exponent == 0) { + // Subnormals. + WideBits bits = from_bits; + + // Determine exponent in target type. + const int normalization_factor = + countl_zero(from_bits) - (kFromBits - kFromMantissaBits) + 1; + const int biased_exponent = kExponentOffset - normalization_factor + 1; + if (biased_exponent <= 0) { + // Result is subnormal. Adjust the subnormal bits to account for + // the difference in exponent bias. + if constexpr (kExponentOffset < sizeof(WideBits) * CHAR_BIT) { + bits <<= kExponentOffset; + } + } else { + // Result is normal. Shift the mantissa to account for the number of + // leading zero digits, and clear the hidden bit. + bits <<= normalization_factor; + bits &= ~(WideBits{1} << kFromMantissaBits); + // Insert the exponent bits. + bits |= static_cast(biased_exponent) << kFromMantissaBits; + } + + // Truncate/round mantissa if necessary. + if constexpr (kDigitShift > 0) { + bits <<= kDigitShift; + } else { + if constexpr (!kTruncate) { + bits = RoundBitsToNearestEven(bits, -kDigitShift); + } + bits >>= -kDigitShift; + } + To to = Eigen::numext::bit_cast(static_cast(bits)); + return from_sign_bit ? -to : to; + } + } + // `To` supports fewer exponents near zero which means that some values in + // `From` may become subnormal. + if constexpr (std::numeric_limits::min_exponent > + std::numeric_limits::min_exponent) { + const int unbiased_exponent = biased_from_exponent - kFromExponentBias; + const int biased_to_exponent = unbiased_exponent + kToExponentBias; + // Subnormals and zero. + if (biased_to_exponent <= 0) { + // Round and shift mantissa down. + FromBits from_has_leading_one = (biased_from_exponent > 0 ? 1 : 0); + int exponent_shift = + -kDigitShift - biased_to_exponent + from_has_leading_one; + // Insert the implicit leading 1 bit on the mantissa for normalized + // inputs. + FromBits rounded_from_bits = + (from_bits & FromTraits::kMantissaMask) | + (from_has_leading_one << kFromMantissaBits); + ToBits bits = 0; + // To avoid UB, limit rounding and shifting to the full mantissa plus + // leading 1. + if (exponent_shift <= kFromMantissaBits + 1) { + if constexpr (!kTruncate) { + // NOTE: we need to round again from the original from_bits, + // otherwise the lower precision bits may already be lost. There is + // an edge-case where rounding to a normalized value would normally + // round down, but for a subnormal, we need to round up. + rounded_from_bits = + RoundBitsToNearestEven(rounded_from_bits, exponent_shift); + } + bits = (rounded_from_bits >> exponent_shift); + } + // Insert sign and return. + To to = Eigen::numext::bit_cast(bits); + return from_sign_bit ? -to : to; + } + } + + // Round the mantissa if it is shrinking. + WideBits rounded_from_bits = from_bits; + if constexpr (kDigitShift < 0) { + if constexpr (!kTruncate) { + rounded_from_bits = RoundBitsToNearestEven(from_bits, -kDigitShift); + } + // Zero-out tail bits. + rounded_from_bits &= ~((WideBits{1} << (-kDigitShift)) - 1); + } + + // Re-bias the exponent. + rounded_from_bits += static_cast(kExponentOffset) + << kFromMantissaBits; + + ToBits bits; + // Check for overflows by aligning the significands. We always align the + // narrower significand to the wider significand. + const WideBits kToHighestRep = + Eigen::numext::bit_cast(Eigen::NumTraits::highest()); + WideBits aligned_highest{kToHighestRep}; + if constexpr (kDigitShift < 0) { + aligned_highest <<= -kDigitShift; + // Shift down, all dropped bits should already be zero. + bits = static_cast(rounded_from_bits >> -kDigitShift); + } else if constexpr (kDigitShift >= 0) { + // Shift up, inserting zeros in the newly created digits. + rounded_from_bits <<= kDigitShift; + bits = ToBits{rounded_from_bits}; + } + + To to = Eigen::numext::bit_cast(bits); + // `From` supports larger values than `To`, we may overflow. + if constexpr (std::make_pair(std::numeric_limits::max_exponent, + std::numeric_limits::digits) < + std::make_pair(std::numeric_limits::max_exponent, + std::numeric_limits::digits)) { + if (rounded_from_bits > aligned_highest) { + // Overflowed values map to highest or infinity depending on kSaturate. + to = kSaturate ? Eigen::NumTraits::highest() + : Eigen::NumTraits::infinity(); + } + } + // Insert sign bit. + return from_sign_bit ? -to : to; + } +}; + +// Saturation has no impact when casting e4m3 to e5m2. +template +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline float8_e5m2 run(const float8_e4m3fn& from) { + return ConvertImpl::run(from); + } +}; + +template +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline float8_e5m2 run(const Eigen::half& from) { + uint16_t from_bits = Eigen::numext::bit_cast(from); + + // Special values (Inf or NaN). + uint16_t abs_bits = from_bits & 0x7FFF; + if (abs_bits == 0x7C00) { + return float8_e5m2::FromRep(from_bits >> 8); + } else if (abs_bits > 0x7C00) { + // IEEE 754-2019 6.2.1: "A quiet NaN bit string should be encoded with the + // first bit (d1) of the trailing significand field T being 1." + // IEEE 754-2019 6.2.3: "Conversion of a quiet NaN to a floating-point + // format of the same or a different radix that does not allow the payload + // to be preserved, shall return a quiet NaN [...]" + return float8_e5m2::FromRep((from_bits >> 8) | 0b0'00000'10); + } + + if constexpr (!kTruncate) { + from_bits = RoundBitsToNearestEven(from_bits, 8); + // Rounding can cause an overflow to infinity. Clamp to the largest finite + // value if saturation is requested. + if constexpr (kSaturate) { + const float8_e5m2 kHighest = Eigen::NumTraits::highest(); + if ((from_bits & 0x7F00) > static_cast(kHighest.rep()) << 8) { + const bool from_sign_bit = from_bits >> 15; + return from_sign_bit ? -kHighest : kHighest; + } + } + } + return float8_e5m2::FromRep(from_bits >> 8); + } +}; + +template <> +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline Eigen::half run(const float8_e5m2& from) { + return Eigen::numext::bit_cast( + static_cast(static_cast(from.rep()) << 8)); + } +}; + +// Direct casts of e5m2 to Eigen::half simply shifts bits over. +template +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline Eigen::half run(const float8_e5m2& from) { + return Eigen::numext::bit_cast( + static_cast(static_cast(from.rep()) << 8)); + } +}; + +template +template +EIGEN_DEVICE_FUNC Derived float8_base::ConvertFrom(const From& from) { + return ConvertImpl::run(from); +} + +template +template +EIGEN_DEVICE_FUNC To float8_base::ConvertTo(const Derived& from) { + return ConvertImpl::run(from); +} + +} // namespace float8_internal + +// Exported types. +using float8_e4m3fn = float8_internal::float8_e4m3fn; +using float8_e4m3fnuz = float8_internal::float8_e4m3fnuz; +using float8_e4m3b11fnuz = float8_internal::float8_e4m3b11fnuz; +using float8_e5m2 = float8_internal::float8_e5m2; +using float8_e5m2fnuz = float8_internal::float8_e5m2fnuz; + +} // namespace ml_dtypes + +// Eigen-specific overrides. +namespace Eigen { +namespace numext { + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC ml_dtypes::float8_e4m3fn +bit_cast(const uint8_t& src) { + return ml_dtypes::float8_e4m3fn::FromRep(src); +} + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC uint8_t +bit_cast( + const ml_dtypes::float8_e4m3fn& src) { + return src.rep(); +} + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC ml_dtypes::float8_e5m2 +bit_cast(const uint8_t& src) { + return ml_dtypes::float8_e5m2::FromRep(src); +} + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC uint8_t +bit_cast(const ml_dtypes::float8_e5m2& src) { + return src.rep(); +} + +} // namespace numext + +// Work-around for isinf/isnan/isfinite issue on aarch64. +namespace internal { +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e4m3fn& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e4m3b11fnuz& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e4m3fnuz& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e5m2& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e5m2fnuz& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e4m3fn& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e4m3b11fnuz& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e4m3fnuz& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e5m2& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e5m2fnuz& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e4m3fn& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e4m3b11fnuz& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e4m3fnuz& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e5m2& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e5m2fnuz& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +} // namespace internal +} // namespace Eigen + +#endif // ML_DTYPES_FLOAT8_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/int4/ml_dtypes/include/int4.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/int4/ml_dtypes/include/int4.h new file mode 100644 index 0000000000000000000000000000000000000000..419cc9f3fc71920d3932ab99b01c92b32fce923f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/_virtual_includes/int4/ml_dtypes/include/int4.h @@ -0,0 +1,262 @@ +/* Copyright 2023 The ml_dtypes 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 ML_DTYPES_INT4_H_ +#define ML_DTYPES_INT4_H_ + +#include +#include +#include +#include +#include +#include + +namespace ml_dtypes { + +template +struct i4 { + private: + UnderlyingTy v : 4; + + public: + constexpr i4() : v(0) {} + constexpr i4(const i4& other) = default; + constexpr i4(i4&& other) = default; + constexpr i4& operator=(const i4& other) = default; + constexpr i4& operator=(i4&&) = default; + + explicit constexpr i4(UnderlyingTy val) : v(val & 0x0F) {} + template + explicit constexpr i4(T t) : i4(static_cast(t)) {} + + static constexpr i4 lowest() { + return std::is_signed::value ? i4(-8) : i4(0); + } + static constexpr i4 highest() { + return std::is_signed::value ? i4(7) : i4(15); + } + + template + explicit constexpr operator T() const { + return static_cast(v); + } + // NOLINTNEXTLINE(google-explicit-constructor) + constexpr operator std::optional() const { + return static_cast(v); + } + + constexpr i4 operator-() const { return i4(-v); } + constexpr i4 operator+(const i4& other) const { return i4((v + other.v)); } + constexpr i4 operator-(const i4& other) const { return i4((v - other.v)); } + constexpr i4 operator*(const i4& other) const { return i4((v * other.v)); } + constexpr i4 operator/(const i4& other) const { return i4((v / other.v)); } + constexpr i4 operator%(const i4& other) const { return i4((v % other.v)); } + + constexpr i4 operator&(const i4& other) const { return i4((v & other.v)); } + constexpr i4 operator|(const i4& other) const { return i4((v | other.v)); } + constexpr i4 operator^(const i4& other) const { return i4((v ^ other.v)); } + constexpr i4 operator~() const { return i4(~v); } + constexpr i4 operator>>(int amount) const { return i4((v >> amount)); } + constexpr i4 operator<<(int amount) const { return i4((v << amount)); } + + constexpr bool operator==(const i4& other) const { return v == other.v; } + constexpr bool operator!=(const i4& other) const { return v != other.v; } + constexpr bool operator<(const i4& other) const { return v < other.v; } + constexpr bool operator>(const i4& other) const { return v > other.v; } + constexpr bool operator<=(const i4& other) const { return v <= other.v; } + constexpr bool operator>=(const i4& other) const { return v >= other.v; } + + constexpr bool operator==(int64_t other) const { return v == other; } + constexpr bool operator!=(int64_t other) const { return v != other; } + constexpr bool operator<(int64_t other) const { return v < other; } + constexpr bool operator>(int64_t other) const { return v > other; } + constexpr bool operator<=(int64_t other) const { return v <= other; } + constexpr bool operator>=(int64_t other) const { return v >= other; } + + friend constexpr bool operator==(int64_t a, const i4& b) { return a == b.v; } + friend constexpr bool operator!=(int64_t a, const i4& b) { return a != b.v; } + friend constexpr bool operator<(int64_t a, const i4& b) { return a < b.v; } + friend constexpr bool operator>(int64_t a, const i4& b) { return a > b.v; } + friend constexpr bool operator<=(int64_t a, const i4& b) { return a <= b.v; } + friend constexpr bool operator>=(int64_t a, const i4& b) { return a >= b.v; } + + constexpr i4& operator++() { + v = (v + 1) & 0x0F; + return *this; + } + + constexpr i4 operator++(int) { + i4 orig = *this; + this->operator++(); + return orig; + } + + constexpr i4& operator--() { + v = (v - 1) & 0x0F; + return *this; + } + + constexpr i4 operator--(int) { + i4 orig = *this; + this->operator--(); + return orig; + } + + constexpr i4& operator+=(const i4& other) { + *this = *this + other; + return *this; + } + constexpr i4& operator-=(const i4& other) { + *this = *this - other; + return *this; + } + constexpr i4& operator*=(const i4& other) { + *this = *this * other; + return *this; + } + constexpr i4& operator/=(const i4& other) { + *this = *this / other; + return *this; + } + constexpr i4& operator%=(const i4& other) { + *this = *this % other; + return *this; + } + constexpr i4& operator&=(const i4& other) { + *this = *this & other; + return *this; + } + constexpr i4& operator|=(const i4& other) { + *this = *this | other; + return *this; + } + constexpr i4& operator^=(const i4& other) { + *this = *this ^ other; + return *this; + } + constexpr i4& operator>>=(int amount) { + *this = *this >> amount; + return *this; + } + constexpr i4& operator<<=(int amount) { + *this = *this << amount; + return *this; + } + + friend ::std::ostream& operator<<(::std::ostream& os, const i4& num) { + os << static_cast(num.v); + return os; + } + + std::string ToString() const { + std::ostringstream os; + os << static_cast(v); + return os.str(); + } +}; + +using int4 = i4; +using uint4 = i4; + +namespace internal { + +struct int4_numeric_limits_base { + static inline constexpr const bool is_specialized = true; + static inline constexpr const bool is_integer = true; + static inline constexpr const bool is_exact = true; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_quiet_NaN = false; + static inline constexpr const bool has_signaling_NaN = false; + static inline constexpr const std::float_denorm_style has_denorm = + std::denorm_absent; + static inline constexpr const bool has_denorm_loss = false; + static inline constexpr const std::float_round_style round_style = + std::round_toward_zero; + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool is_bounded = true; + static inline constexpr const int max_digits10 = 0; // Not used for integers. + static inline constexpr const int radix = 2; + static inline constexpr const int min_exponent = 0; + static inline constexpr const int min_exponent10 = 0; + static inline constexpr const int max_exponent = 0; + static inline constexpr const int max_exponent10 = 0; + static inline constexpr const bool traps = true; + static inline constexpr const bool tinyness_before = false; + + static constexpr ml_dtypes::int4 epsilon() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 round_error() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 infinity() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 quiet_NaN() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 signaling_NaN() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 denorm_min() noexcept { + return ml_dtypes::int4(0); + } +}; + +} // namespace internal + +} // namespace ml_dtypes + +namespace std { + +template <> +struct numeric_limits + : public ml_dtypes::internal::int4_numeric_limits_base { + static inline constexpr const bool is_signed = true; + static inline constexpr const bool is_modulo = false; + static inline constexpr const int digits = 3; + static inline constexpr const int digits10 = 0; // floor(3 * log10(2)) + static constexpr ml_dtypes::int4 min() noexcept { + return ml_dtypes::int4::lowest(); + } + static constexpr ml_dtypes::int4 lowest() noexcept { + return ml_dtypes::int4::lowest(); + } + static constexpr ml_dtypes::int4 max() noexcept { + return ml_dtypes::int4::highest(); + } +}; + +template <> +struct numeric_limits + : public ml_dtypes::internal::int4_numeric_limits_base { + static inline constexpr const bool is_signed = false; + static inline constexpr const bool is_modulo = true; + static inline constexpr const int digits = 4; + static inline constexpr const int digits10 = 1; // floor(4 * log10(2)) + static constexpr ml_dtypes::uint4 min() noexcept { + return ml_dtypes::uint4::lowest(); + } + static constexpr ml_dtypes::uint4 lowest() noexcept { + return ml_dtypes::uint4::lowest(); + } + static constexpr ml_dtypes::uint4 max() noexcept { + return ml_dtypes::uint4::highest(); + } +}; + +} // namespace std + +#endif // ML_DTYPES_INT4_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/include/float8.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/include/float8.h new file mode 100644 index 0000000000000000000000000000000000000000..f3f557b7d41a975cdd47296293e6bbe92a607339 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/include/float8.h @@ -0,0 +1,1401 @@ +/* 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 ML_DTYPES_FLOAT8_H_ +#define ML_DTYPES_FLOAT8_H_ + +// 8-bit Floating Point Interchange Format, as described by +// https://arxiv.org/abs/2209.05433 + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __has_include +# if __has_include() +# include +# endif +#endif + +#if (defined(__cpp_lib_bitops) && __cpp_lib_bitops >= 201907L) +#include +#endif + +#include "Eigen/Core" + +namespace ml_dtypes { +namespace float8_internal { + +// Forward-declarations of classes. +class float8_e4m3fn; +class float8_e4m3fnuz; +class float8_e4m3b11fnuz; +class float8_e5m2; +class float8_e5m2fnuz; + +template +class float8_base { + protected: + // Constructor tag to allow constexpr construction from bit representation. + struct ConstructFromRepTag {}; + constexpr float8_base(uint8_t rep, ConstructFromRepTag) : rep_{rep} {} + + public: + constexpr float8_base() : rep_(0) {} + + template >> + explicit EIGEN_DEVICE_FUNC float8_base(T f) + : float8_base(ConvertFrom(static_cast(f)).rep(), + ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(double f64) + : float8_base(ConvertFrom(f64).rep(), ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(float f32) + : float8_base(ConvertFrom(f32).rep(), ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(Eigen::bfloat16 bf16) + : float8_base(ConvertFrom(bf16).rep(), ConstructFromRepTag{}) {} + explicit EIGEN_DEVICE_FUNC float8_base(Eigen::half f16) + : float8_base(ConvertFrom(f16).rep(), ConstructFromRepTag{}) {} + + constexpr uint8_t rep() const { return rep_; } + + template >> + explicit EIGEN_DEVICE_FUNC operator T() const { + return static_cast(static_cast(derived())); + } + explicit EIGEN_DEVICE_FUNC operator double() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator float() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator Eigen::bfloat16() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator Eigen::half() const { + return ConvertTo(derived()); + } + explicit EIGEN_DEVICE_FUNC operator bool() const { + return (rep() & 0x7F) != 0; + } + + constexpr Derived operator-() const { + return Derived(static_cast(rep() ^ 0x80), ConstructFromRepTag{}); + } + + constexpr const Derived& derived() const { + return *static_cast(this); + } + + constexpr Derived& derived() { return *static_cast(this); } + + static constexpr Derived FromRep(uint8_t rep) { + return Derived(rep, ConstructFromRepTag{}); + } + + // Conversions allowing saturation and truncation. + template + static inline EIGEN_DEVICE_FUNC Derived ConvertFrom(const From& from); + + template + static inline EIGEN_DEVICE_FUNC To ConvertTo(const Derived& from); + + // Operators via float32. + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator+(const Derived& other) const { + return Derived{float{derived()} + float{other}}; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator-(const Derived& other) const { + return Derived{float{derived()} - float{other}}; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator*(const Derived& other) const { + return Derived{float{derived()} * float{other}}; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived + operator/(const Derived& other) const { + return Derived{float{derived()} / float{other}}; + } + + constexpr bool operator==(const Derived& other) const { + return Compare(derived(), other) == Ordering::kEquivalent; + } + + constexpr bool operator!=(const Derived& other) const { + return Compare(derived(), other) != Ordering::kEquivalent; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator<( + const Derived& other) const { + return Compare(derived(), other) == Ordering::kLess; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator<=( + const Derived& other) const { + return Compare(derived(), other) <= Ordering::kEquivalent; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator>( + const Derived& other) const { + return Compare(derived(), other) == Ordering::kGreater; + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bool operator>=( + const Derived& other) const { + Ordering ordering = Compare(derived(), other); + return ordering == Ordering::kGreater || ordering == Ordering::kEquivalent; + } + + // Compound assignment. + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator+=( + const Derived& other) { + derived() = derived() + other; + return derived(); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator-=( + const Derived& other) { + derived() = derived() - other; + return derived(); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator*=( + const Derived& other) { + derived() = derived() * other; + return derived(); + } + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC Derived& operator/=( + const Derived& other) { + derived() = derived() / other; + return derived(); + } + + private: + static EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC std::pair + SignAndMagnitude(Derived x) { + const uint8_t x_abs_bits = + Eigen::numext::bit_cast(Eigen::numext::abs(x)); + const uint8_t x_bits = Eigen::numext::bit_cast(x); + const uint8_t x_sign = x_bits ^ x_abs_bits; + return {x_sign, x_abs_bits}; + } + static EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC int8_t + SignAndMagnitudeToTwosComplement(uint8_t sign, uint8_t magnitude) { + return magnitude ^ (static_cast(sign) < 0 ? -1 : 0); + } + + enum Ordering : int8_t { + kLess = -1, + kEquivalent = 0, + kGreater = 1, + kUnordered = 2, + }; + + EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC friend Ordering Compare( + const Derived& lhs, const Derived& rhs) { + if (Eigen::numext::isnan(lhs) || Eigen::numext::isnan(rhs)) { + return Ordering::kUnordered; + } + auto [lhs_sign, lhs_mag] = SignAndMagnitude(lhs); + auto [rhs_sign, rhs_mag] = SignAndMagnitude(rhs); + if (lhs_mag == 0 && rhs_mag == 0) { + return Ordering::kEquivalent; + } + int8_t lhs_twos_complement = + SignAndMagnitudeToTwosComplement(lhs_sign, lhs_mag); + int8_t rhs_twos_complement = + SignAndMagnitudeToTwosComplement(rhs_sign, rhs_mag); + if (lhs_twos_complement < rhs_twos_complement) { + return Ordering::kLess; + } + if (lhs_twos_complement > rhs_twos_complement) { + return Ordering::kGreater; + } + return Ordering::kEquivalent; + } + + uint8_t rep_; +}; + +class float8_e4m3fn : public float8_base { + // Exponent: 4, Mantissa: 3, bias: 7. + // Extended range: no inf, NaN represented by 0bS111'1111. + // The "fn" suffix is for consistency with the corresponding LLVM/MLIR type, + // signaling this type is not consistent with IEEE-754. The "f" indicates + // it is finite values only. The "n" indicates it includes NaNs, but only + // at the outer range. + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e4m3fn(const float8_e5m2& f8) + : float8_e4m3fn(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fn(const float8_e4m3b11fnuz& f8) + : float8_e4m3fn(ConvertFrom(f8)) {} +}; + +class float8_e4m3b11fnuz : public float8_base { + // Exponent: 4, Mantissa: 3, bias: 11. + // Extended range: no inf, NaN represented by 0b1000'0000. + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e5m2& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e5m2fnuz& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e4m3fn& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3b11fnuz(const float8_e4m3fnuz& f8) + : float8_e4m3b11fnuz(ConvertFrom(f8)) {} + + constexpr float8_e4m3b11fnuz operator-() const { + if ((rep() & 0x7f) == 0x00) { + return *this; + } + return Base::operator-(); + } + + float8_e4m3b11fnuz operator-(const float8_e4m3b11fnuz& other) const { + return Base::operator-(other); + } + + explicit EIGEN_DEVICE_FUNC operator bool() const { return rep() != 0; } +}; + +// Legacy name used in XLA (TODO(jewillco): remove). +using float8_e4m3b11 = float8_e4m3b11fnuz; + +class float8_e4m3fnuz : public float8_base { + // 8-bit floating point with 3 bit mantissa. + // + // An 8-bit floating point type with 1 sign bit, 4 bits exponent and 3 bits + // mantissa. The suffix "fnuz" is consistent with LLVM/MLIR naming and is + // derived from the differences to IEEE floating point conventions. `F` is + // for "finite" (no infinities), `N` for with special NaN encoding, `UZ` for + // unsigned zero. + // + // This type has the following characteristics: + // * bit encoding: S1E4M3 - `0bSEEEEMMM` + // * exponent bias: 8 + // * infinities: Not supported + // * NaNs: Supported with sign bit set to 1, exponent bits and mantissa bits + // set to all 0s - `0b10000000` + // * denormals when exponent is 0 + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e5m2& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e5m2fnuz& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e4m3b11fnuz& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e4m3fnuz(const float8_e4m3fn& f8) + : float8_e4m3fnuz(ConvertFrom(f8)) {} + + constexpr float8_e4m3fnuz operator-() const { + if ((rep() & 0x7f) == 0x00) { + return *this; + } + return Base::operator-(); + } + + float8_e4m3fnuz operator-(const float8_e4m3fnuz& other) const { + return Base::operator-(other); + } + + explicit EIGEN_DEVICE_FUNC operator bool() const { return rep() != 0; } +}; + +class float8_e5m2 : public float8_base { + // Exponent: 5, Mantissa: 2, bias: 15. + // IEEE 754. + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e4m3fn f8) + : float8_e5m2(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e4m3fnuz f8) + : float8_e5m2(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e4m3b11fnuz f8) + : float8_e5m2(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2(float8_e5m2fnuz& f8) + : float8_e5m2(ConvertFrom(f8)) {} +}; + +class float8_e5m2fnuz : public float8_base { + // 8-bit floating point with 2 bit mantissa. + // + // An 8-bit floating point type with 1 sign bit, 5 bits exponent and 2 bits + // mantissa. The suffix "fnuz" is consistent with LLVM/MLIR naming and is + // derived from the differences to IEEE floating point conventions. `F` is + // for "finite" (no infinities), `N` for with special NaN encoding, `UZ` for + // unsigned zero. + // + // This type has the following characteristics: + // * bit encoding: S1E5M2 - `0bSEEEEEMM` + // * exponent bias: 16 + // * infinities: Not supported + // * NaNs: Supported with sign bit set to 1, exponent bits and mantissa bits + // set to all 0s - `0b10000000` + // * denormals when exponent is 0 + private: + using Base = float8_base; + friend class float8_base; + using Base::Base; + + public: + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e5m2& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e4m3b11fnuz& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e4m3fn& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + explicit EIGEN_DEVICE_FUNC float8_e5m2fnuz(const float8_e4m3fnuz& f8) + : float8_e5m2fnuz(ConvertFrom(f8)) {} + + constexpr float8_e5m2fnuz operator-() const { + if ((rep() & 0x7f) == 0x00) { + return *this; + } + return Base::operator-(); + } + + float8_e5m2fnuz operator-(const float8_e5m2fnuz& other) const { + return Base::operator-(other); + } + + explicit EIGEN_DEVICE_FUNC operator bool() const { return rep() != 0; } +}; + +constexpr double ConstexprAbs(double x) { return x < 0.0 ? -x : x; } + +constexpr double ConstexprCeil(double x) { + constexpr double kIntegerThreshold = + uint64_t{1} << (std::numeric_limits::digits - 1); + // Too big or NaN inputs get returned unchanged. + if (!(ConstexprAbs(x) < kIntegerThreshold)) { + return x; + } + const double x_trunc = static_cast(static_cast(x)); + return x_trunc < x ? x_trunc + 1.0 : x_trunc; +} + +constexpr double ConstexprFloor(double x) { return -ConstexprCeil(-x); } + +constexpr double kLog10Of2 = 0.3010299956639812; +// C17 5.2.4.2.2p11: +// "number of decimal digits, q, such that any floating-point number with q +// decimal digits can be rounded into a floating-point number with p radix b +// digits and back again without change to the q decimal digits" +// floor((p - 1) * log10(2)); +constexpr int Digits10FromDigits(int digits) { + return static_cast(ConstexprFloor((digits - 1) * kLog10Of2)); +} + +// C17 5.2.4.2.2p11: +// "number of decimal digits, n, such that any floating-point number with p +// radix b digits can be rounded to a floating-point number with n decimal +// digits and back again without change to the value" +// ceil(1 + p * log10(2)); +constexpr int MaxDigits10FromDigits(int digits) { + return static_cast(ConstexprCeil(1.0 + (digits * kLog10Of2))); +} + +// C17 5.2.4.2.2p11: +// "minimum negative integer such that 10 raised to that power is in the range +// of normalized floating-point numbers" +// ceil(log10(2**(emin - 1))) == ceil((emin - 1) * log10(2)); +constexpr int MinExponent10FromMinExponent(int min_exponent) { + return static_cast(ConstexprCeil((min_exponent - 1) * kLog10Of2)); +} + +// C17 5.2.4.2.2p11: +// "maximum integer such that 10 raised to that power is in the range of +// representable finite floating-point numbers" +// floor(log10((1 - 2**-p) * 2**emax)) == floor(log10(1 - 2**-p) + +// emax * log10(2)) +constexpr int MaxExponent10FromMaxExponentAndDigits(int max_exponent, + int digits) { + // We only support digits in {3,4}. This table would grow if we wanted to + // handle more values. + constexpr double kLog10OfOnePredecessor[] = { + // log10(1 - 2**-3) + -0.057991946977686754, + // log10(1 - 2**-4) + -0.028028723600243537, + }; + return static_cast(ConstexprFloor(kLog10OfOnePredecessor[digits - 3] + + max_exponent * kLog10Of2)); +} + +// Structures for use in specializing std::numeric_limits. +struct numeric_limits_float8_base { + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const bool is_specialized = true; + static inline constexpr const bool is_signed = true; + static inline constexpr const bool is_integer = false; + static inline constexpr const bool is_exact = false; + static inline constexpr const bool has_quiet_NaN = true; + static inline constexpr const std::float_denorm_style has_denorm = + std::denorm_present; + static inline constexpr const bool has_denorm_loss = false; + static inline constexpr const std::float_round_style round_style = + std::round_to_nearest; + static inline constexpr const bool is_bounded = true; + static inline constexpr const bool is_modulo = false; + static inline constexpr const int radix = std::numeric_limits::radix; + static inline constexpr const bool traps = std::numeric_limits::traps; + static inline constexpr const bool tinyness_before = + std::numeric_limits::tinyness_before; + // NOLINTEND +}; + +struct numeric_limits_float8_e4m3fn : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 7; + static inline constexpr const int kMantissaBits = 3; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b1111 - 7) + 1; // Extended format. + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + // 1.0 * 2^(0b0001 - 7) = 1.0 * 2^-6 = 0.015625 + static constexpr float8_e4m3fn min() { + return float8_e4m3fn::FromRep(0b0'0001 << kMantissaBits); + } + // -(1 + 0b110 * 2^-3) * 2^(0b1111 - 7) = -1.75 * 2^8 = 448 + static constexpr float8_e4m3fn lowest() { + return float8_e4m3fn::FromRep(0b1'1111'110); + } + // (1 + 0b110 * 2^-3) * 2**(0b1111 - 7) = 1.75 * 2^8 = 448 + static constexpr float8_e4m3fn max() { + return float8_e4m3fn::FromRep(0b0'1111'110); + } + // 1.0 * 2^-3 = 0.125 + static constexpr float8_e4m3fn epsilon() { + return float8_e4m3fn::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + // 1.0 * 2^-1 = 0.5 + static constexpr float8_e4m3fn round_error() { + return float8_e4m3fn::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e4m3fn infinity() { + return float8_e4m3fn::FromRep(0b0'1111'111); + } + // NaN. + static constexpr float8_e4m3fn quiet_NaN() { + return float8_e4m3fn::FromRep(0b0'1111'111); + } + static constexpr float8_e4m3fn signaling_NaN() { + return float8_e4m3fn::FromRep(0b0'1111'111); + } + // 1.0 * 2^(-7 - 3 + 1) = 1.0 * 2^-9 = 0.001953125 + static constexpr float8_e4m3fn denorm_min() { + return float8_e4m3fn::FromRep(0b0'0000'001); + } +}; + +struct numeric_limits_float8_e4m3b11fnuz : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 11; + static inline constexpr const int kMantissaBits = 3; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b1111 - kExponentBias) + 1; // Extended format. + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + // 1.0 * 2^(0b0001 - 11) = 1.0 * 2^-10 = 0.0009765625 + static constexpr float8_e4m3b11fnuz min() { + return float8_e4m3b11fnuz::FromRep(1 << kMantissaBits); + } + // -(1 + 0b111 * 2^-3) * 2^(0b1111 - 11) = -1.875 * 2^4 = -30 + static constexpr float8_e4m3b11fnuz lowest() { + return float8_e4m3b11fnuz::FromRep(0b1'1111'111); + } + // (1 + 0b111 * 2^-3) * 2^(0b1111 - 11) = 1.875 * 2^4 = 30 + static constexpr float8_e4m3b11fnuz max() { + return float8_e4m3b11fnuz::FromRep(0b0'1111'111); + } + // 1.0 * 2^-3 = 0.125 + static constexpr float8_e4m3b11fnuz epsilon() { + return float8_e4m3b11fnuz::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + // 1.0 * 2^-1 = 0.5 + static constexpr float8_e4m3b11fnuz round_error() { + return float8_e4m3b11fnuz::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e4m3b11fnuz infinity() { + return float8_e4m3b11fnuz::FromRep(0b1'0000'000); + } + // NaN. + static constexpr float8_e4m3b11fnuz quiet_NaN() { + return float8_e4m3b11fnuz::FromRep(0b1'0000'000); + } + static constexpr float8_e4m3b11fnuz signaling_NaN() { + return float8_e4m3b11fnuz::FromRep(0b1'0000'000); + } + // 1.0 * 2^(-11 - 3 + 1) = 1.0 * 2^-13 = 0.0001220703125 + static constexpr float8_e4m3b11fnuz denorm_min() { + return float8_e4m3b11fnuz::FromRep(0b0'0000'001); + } +}; + +struct numeric_limits_float8_e4m3fnuz : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 8; + static inline constexpr const int kMantissaBits = 3; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b1111 - kExponentBias) + 1; // Extended format. + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + static constexpr float8_e4m3fnuz min() { + return float8_e4m3fnuz::FromRep(0x08); + } + static constexpr float8_e4m3fnuz lowest() { + return float8_e4m3fnuz::FromRep(0xFF); + } + static constexpr float8_e4m3fnuz max() { + return float8_e4m3fnuz::FromRep(0x7F); + } + static constexpr float8_e4m3fnuz epsilon() { + return float8_e4m3fnuz::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + static constexpr float8_e4m3fnuz round_error() { + return float8_e4m3fnuz::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e4m3fnuz infinity() { + return float8_e4m3fnuz::FromRep(0x80); + } // NaN. + static constexpr float8_e4m3fnuz quiet_NaN() { + return float8_e4m3fnuz::FromRep(0x80); + } + static constexpr float8_e4m3fnuz signaling_NaN() { + return float8_e4m3fnuz::FromRep(0x80); + } + static constexpr float8_e4m3fnuz denorm_min() { + return float8_e4m3fnuz::FromRep(0x01); + } +}; + +struct numeric_limits_float8_e5m2 : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 15; + static inline constexpr const int kMantissaBits = 2; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = 0b11111 - kExponentBias; + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = true; + static inline constexpr const bool has_infinity = true; + static inline constexpr const bool has_signaling_NaN = true; + // NOLINTEND + + // 1.0 * 2^(0b00001 - 15) = 1.0 * 2^-14 = 0.00006103515625 + static constexpr float8_e5m2 min() { + return float8_e5m2::FromRep(1 << kMantissaBits); + } + // -(1 + 0b11 * 2^-2) * 2^(0b11110 - 15) = -1.75 * 2^15 = -57344 + static constexpr float8_e5m2 lowest() { + return float8_e5m2::FromRep(0b1'11110'11); + } + // (1 + 0b11 * 2^-2) * 2^(0b11110 - 15) = 1.75 * 2^15 = 57344 + static constexpr float8_e5m2 max() { + return float8_e5m2::FromRep(0b0'11110'11); + } + // 1.0 * 2^-2 = 0.25 + static constexpr float8_e5m2 epsilon() { + return float8_e5m2::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + // 1.0 * 2^-1 = 0.5 + static constexpr float8_e5m2 round_error() { + return float8_e5m2::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e5m2 infinity() { + return float8_e5m2::FromRep(0b0'11111'00); + } + static constexpr float8_e5m2 quiet_NaN() { + // IEEE 754-2019 6.2.1: "All binary NaN bit strings have the sign bit S set + // to 0 or 1 and all the bits of the biased exponent field E set to 1 + // (see 3.4). A quiet NaN bit string should be encoded with the first bit + // (d1) of the trailing significand field T being 1." + return float8_e5m2::FromRep(0b0'11111'10); + } + static constexpr float8_e5m2 signaling_NaN() { + // IEEE 754-2019 6.2.1: "A signaling NaN bit string should be encoded with + // the first bit of the trailing significand field being 0." + return float8_e5m2::FromRep(0b0'11111'01); + } + // 1.0 * 2^(-15 - 2 + 1) = 1.0 * 2^-16 = 0.0000152587890625 + static constexpr float8_e5m2 denorm_min() { + return float8_e5m2::FromRep(0b0'00000'01); + } +}; + +struct numeric_limits_float8_e5m2fnuz : public numeric_limits_float8_base { + private: + static inline constexpr const int kExponentBias = 16; + static inline constexpr const int kMantissaBits = 2; + + public: + // NOLINTBEGIN: these names must match std::numeric_limits. + static inline constexpr const int digits = kMantissaBits + 1; + static inline constexpr const int digits10 = Digits10FromDigits(digits); + static inline constexpr const int max_digits10 = + MaxDigits10FromDigits(digits); + static inline constexpr const int min_exponent = (1 - kExponentBias) + 1; + static inline constexpr const int min_exponent10 = + MinExponent10FromMinExponent(min_exponent); + static inline constexpr const int max_exponent = + (0b11111 - kExponentBias) + 1; + static inline constexpr const int max_exponent10 = + MaxExponent10FromMaxExponentAndDigits(max_exponent, digits); + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_signaling_NaN = false; + // NOLINTEND + + static constexpr float8_e5m2fnuz min() { + return float8_e5m2fnuz::FromRep(0x04); + } + static constexpr float8_e5m2fnuz lowest() { + return float8_e5m2fnuz::FromRep(0xFF); + } + static constexpr float8_e5m2fnuz max() { + return float8_e5m2fnuz::FromRep(0x7F); + } + static constexpr float8_e5m2fnuz epsilon() { + return float8_e5m2fnuz::FromRep((-kMantissaBits + kExponentBias) + << kMantissaBits); + } + static constexpr float8_e5m2fnuz round_error() { + return float8_e5m2fnuz::FromRep((-1 + kExponentBias) << kMantissaBits); + } + static constexpr float8_e5m2fnuz infinity() { + return float8_e5m2fnuz::FromRep(0x80); + } // NaN. + static constexpr float8_e5m2fnuz quiet_NaN() { + return float8_e5m2fnuz::FromRep(0x80); + } + static constexpr float8_e5m2fnuz signaling_NaN() { + return float8_e5m2fnuz::FromRep(0x80); + } + static constexpr float8_e5m2fnuz denorm_min() { + return float8_e5m2fnuz::FromRep(0x01); + } +}; + +} // namespace float8_internal +} // namespace ml_dtypes + +namespace std { +// Standard-library overrides. Note that these are picked up by Eigen as well. +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e4m3fn {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e4m3b11fnuz {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e4m3fnuz {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e5m2 {}; + +template <> +struct numeric_limits + : public ml_dtypes::float8_internal::numeric_limits_float8_e5m2fnuz {}; +} // namespace std + +namespace ml_dtypes { +namespace float8_internal { + +// Free-functions for use with ADL and in Eigen. +constexpr inline float8_e4m3fn abs(const float8_e4m3fn& a) { + return float8_e4m3fn::FromRep(a.rep() & 0b0'1111'111); +} + +constexpr inline bool(isnan)(const float8_e4m3fn& a) { + return abs(a).rep() == std::numeric_limits::quiet_NaN().rep(); +} + +constexpr inline float8_e4m3b11fnuz abs(const float8_e4m3b11fnuz& a) { + return (a.rep() & 0b0'1111'111) == 0 + ? float8_e4m3b11fnuz::FromRep(a.rep()) + : float8_e4m3b11fnuz::FromRep(a.rep() & 0b0'1111'111); +} + +constexpr inline bool(isnan)(const float8_e4m3b11fnuz& a) { + return a.rep() == std::numeric_limits::quiet_NaN().rep(); +} + +constexpr inline float8_e4m3fnuz abs(const float8_e4m3fnuz& a) { + return (a.rep() & 0x7F) == 0 ? float8_e4m3fnuz::FromRep(a.rep()) + : float8_e4m3fnuz::FromRep(a.rep() & 0x7F); +} + +constexpr inline bool(isnan)(const float8_e4m3fnuz& a) { + return abs(a).rep() == + std::numeric_limits::quiet_NaN().rep(); +} + +constexpr inline float8_e5m2 abs(const float8_e5m2& a) { + return float8_e5m2::FromRep(a.rep() & 0b0'11111'11); +} + +constexpr inline bool(isnan)(const float8_e5m2& a) { + return abs(a).rep() > std::numeric_limits::infinity().rep(); +} + +constexpr inline float8_e5m2fnuz abs(const float8_e5m2fnuz& a) { + return (a.rep() & 0x7F) == 0 ? float8_e5m2fnuz::FromRep(a.rep()) + : float8_e5m2fnuz::FromRep(a.rep() & 0x7F); +} + +constexpr inline bool isnan(const float8_e5m2fnuz& a) { + return a.rep() == 0x80; +} + +template +constexpr inline bool(isinf)(const float8_base& a) { + return std::numeric_limits::has_infinity + ? abs(a.derived()).rep() == + std::numeric_limits::infinity().rep() + : false; // No inf representation. +} + +template +constexpr inline bool(isfinite)(const float8_base& a) { + return !isnan(a.derived()) && !isinf(a.derived()); +} + +template +std::ostream& operator<<(std::ostream& os, const float8_base& f8) { + os << static_cast(f8.derived()); + return os; +} + +//============================================================================== +// Inline conversion routines between float8 and other types. +//============================================================================== + +// Helper for getting a bit representation provided a byte size. +template +using GetUnsignedInteger = + typename Eigen::numext::get_integer_by_size::unsigned_type; + +// Converts between two floating-point types. +template +struct ConvertImpl; + +// Convert to same type. We need explicit specializations for all combinations +// of template parameters to avoid ambiguities. +template +struct IdentityConversion { + static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& from) { + return from; + } +}; + +template +struct ConvertImpl : public IdentityConversion {}; +template +struct ConvertImpl : public IdentityConversion {}; +template +struct ConvertImpl : public IdentityConversion {}; +template +struct ConvertImpl : public IdentityConversion {}; + +template +struct TraitsBase { + using BitsType = GetUnsignedInteger; + static constexpr int kBits = sizeof(Float) * CHAR_BIT; + static constexpr int kMantissaBits = Eigen::NumTraits::digits() - 1; + static constexpr int kExponentBits = kBits - kMantissaBits - 1; + static constexpr BitsType kExponentMask = ((BitsType{1} << kExponentBits) - 1) + << kMantissaBits; + static constexpr BitsType kMantissaMask = (BitsType{1} << kMantissaBits) - 1; + static constexpr int kExponentBias = (1 << (kExponentBits - 1)) - 1; +}; + +template +struct Traits : public TraitsBase {}; + +template <> +struct Traits : public TraitsBase { + static constexpr int kExponentBias = 11; +}; + +template <> +struct Traits : public TraitsBase { + using Base = TraitsBase; + static constexpr int kExponentBias = Base::kExponentBias + 1; +}; + +template <> +struct Traits : public TraitsBase { + using Base = TraitsBase; + static constexpr int kExponentBias = Base::kExponentBias + 1; +}; + +template +constexpr inline Bits RoundBitsToNearestEven(Bits bits, int roundoff) { + // Round to nearest even by adding a bias term. + // Consider a bit pattern + // FFF...FLRTT...T, + // where bits RTT...T need to be rounded-off. We add a bias term to the + // bit pattern s.t. a carry is introduced to round up only if + // - L is 1, R is 1, OR + // - L is 0, R is 1, any T is one. + // We do this by adding L to a bit pattern consisting of all T = 1. + Bits bias = roundoff == 0 + ? 0 + : ((bits >> roundoff) & 1) + (Bits{1} << (roundoff - 1)) - 1; + return bits + bias; +} + +#if (defined(__cpp_lib_bitops) && __cpp_lib_bitops >= 201907L) +using std::countl_zero; +#else +static constexpr inline int countl_zero(uint64_t x) { + int zeroes = 60; + if (x >> 32) { + zeroes -= 32; + x >>= 32; + } + if (x >> 16) { + zeroes -= 16; + x >>= 16; + } + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +static constexpr inline int countl_zero(uint32_t x) { + int zeroes = 28; + if (x >> 16) { + zeroes -= 16; + x >>= 16; + } + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +static constexpr inline int countl_zero(uint16_t x) { + int zeroes = 12; + if (x >> 8) { + zeroes -= 8; + x >>= 8; + } + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +static constexpr inline int countl_zero(uint8_t x) { + int zeroes = 4; + if (x >> 4) { + zeroes -= 4; + x >>= 4; + } + return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[x] + zeroes; +} +#endif + +template +struct ConvertImpl>> { + using FromTraits = Traits; + using FromBits = typename FromTraits::BitsType; + static constexpr int kFromBits = FromTraits::kBits; + static constexpr int kFromMantissaBits = FromTraits::kMantissaBits; + static constexpr int kFromExponentBits = FromTraits::kExponentBits; + static constexpr int kFromExponentBias = FromTraits::kExponentBias; + static constexpr FromBits kFromExponentMask = FromTraits::kExponentMask; + + using ToTraits = Traits; + using ToBits = typename ToTraits::BitsType; + static constexpr int kToBits = ToTraits::kBits; + static constexpr int kToMantissaBits = ToTraits::kMantissaBits; + static constexpr int kToExponentBits = ToTraits::kExponentBits; + static constexpr int kToExponentBias = ToTraits::kExponentBias; + static constexpr ToBits kToExponentMask = ToTraits::kExponentMask; + + // `WideBits` is wide enough to accommodate the largest exponent and mantissa + // in either `From` or `To`. + static constexpr int kWideBits = + (std::max(kToMantissaBits, kFromMantissaBits)) + // Max significand. + (std::max(kToExponentBits, kFromExponentBits)); // Max exponent. + static constexpr int kWideBytes = (kWideBits + (CHAR_BIT - 1)) / CHAR_BIT; + using WideBits = GetUnsignedInteger; + static constexpr int kExponentOffset = kToExponentBias - kFromExponentBias; + static constexpr int kDigitShift = kToMantissaBits - kFromMantissaBits; + + static EIGEN_DEVICE_FUNC inline To run(const From& from) { + // Shift bits to destination type, without sign bit. + const bool from_sign_bit = + Eigen::numext::bit_cast(from) >> (kFromBits - 1); + const FromBits from_bits = + Eigen::numext::bit_cast(Eigen::numext::abs(from)); + + // Special values, preserving sign. + if (Eigen::numext::isinf(from)) { + return from_sign_bit ? -Eigen::NumTraits::infinity() + : Eigen::NumTraits::infinity(); + } + if (Eigen::numext::isnan(from)) { + return from_sign_bit ? -Eigen::NumTraits::quiet_NaN() + : Eigen::NumTraits::quiet_NaN(); + } + if (from_bits == 0) { + return from_sign_bit ? -To{} : To{}; + } + + const int biased_from_exponent = from_bits >> kFromMantissaBits; + + // `To` supports more exponents near zero which means that some subnormal + // values in `From` may become normal. + if constexpr (std::numeric_limits::min_exponent < + std::numeric_limits::min_exponent) { + if (biased_from_exponent == 0) { + // Subnormals. + WideBits bits = from_bits; + + // Determine exponent in target type. + const int normalization_factor = + countl_zero(from_bits) - (kFromBits - kFromMantissaBits) + 1; + const int biased_exponent = kExponentOffset - normalization_factor + 1; + if (biased_exponent <= 0) { + // Result is subnormal. Adjust the subnormal bits to account for + // the difference in exponent bias. + if constexpr (kExponentOffset < sizeof(WideBits) * CHAR_BIT) { + bits <<= kExponentOffset; + } + } else { + // Result is normal. Shift the mantissa to account for the number of + // leading zero digits, and clear the hidden bit. + bits <<= normalization_factor; + bits &= ~(WideBits{1} << kFromMantissaBits); + // Insert the exponent bits. + bits |= static_cast(biased_exponent) << kFromMantissaBits; + } + + // Truncate/round mantissa if necessary. + if constexpr (kDigitShift > 0) { + bits <<= kDigitShift; + } else { + if constexpr (!kTruncate) { + bits = RoundBitsToNearestEven(bits, -kDigitShift); + } + bits >>= -kDigitShift; + } + To to = Eigen::numext::bit_cast(static_cast(bits)); + return from_sign_bit ? -to : to; + } + } + // `To` supports fewer exponents near zero which means that some values in + // `From` may become subnormal. + if constexpr (std::numeric_limits::min_exponent > + std::numeric_limits::min_exponent) { + const int unbiased_exponent = biased_from_exponent - kFromExponentBias; + const int biased_to_exponent = unbiased_exponent + kToExponentBias; + // Subnormals and zero. + if (biased_to_exponent <= 0) { + // Round and shift mantissa down. + FromBits from_has_leading_one = (biased_from_exponent > 0 ? 1 : 0); + int exponent_shift = + -kDigitShift - biased_to_exponent + from_has_leading_one; + // Insert the implicit leading 1 bit on the mantissa for normalized + // inputs. + FromBits rounded_from_bits = + (from_bits & FromTraits::kMantissaMask) | + (from_has_leading_one << kFromMantissaBits); + ToBits bits = 0; + // To avoid UB, limit rounding and shifting to the full mantissa plus + // leading 1. + if (exponent_shift <= kFromMantissaBits + 1) { + if constexpr (!kTruncate) { + // NOTE: we need to round again from the original from_bits, + // otherwise the lower precision bits may already be lost. There is + // an edge-case where rounding to a normalized value would normally + // round down, but for a subnormal, we need to round up. + rounded_from_bits = + RoundBitsToNearestEven(rounded_from_bits, exponent_shift); + } + bits = (rounded_from_bits >> exponent_shift); + } + // Insert sign and return. + To to = Eigen::numext::bit_cast(bits); + return from_sign_bit ? -to : to; + } + } + + // Round the mantissa if it is shrinking. + WideBits rounded_from_bits = from_bits; + if constexpr (kDigitShift < 0) { + if constexpr (!kTruncate) { + rounded_from_bits = RoundBitsToNearestEven(from_bits, -kDigitShift); + } + // Zero-out tail bits. + rounded_from_bits &= ~((WideBits{1} << (-kDigitShift)) - 1); + } + + // Re-bias the exponent. + rounded_from_bits += static_cast(kExponentOffset) + << kFromMantissaBits; + + ToBits bits; + // Check for overflows by aligning the significands. We always align the + // narrower significand to the wider significand. + const WideBits kToHighestRep = + Eigen::numext::bit_cast(Eigen::NumTraits::highest()); + WideBits aligned_highest{kToHighestRep}; + if constexpr (kDigitShift < 0) { + aligned_highest <<= -kDigitShift; + // Shift down, all dropped bits should already be zero. + bits = static_cast(rounded_from_bits >> -kDigitShift); + } else if constexpr (kDigitShift >= 0) { + // Shift up, inserting zeros in the newly created digits. + rounded_from_bits <<= kDigitShift; + bits = ToBits{rounded_from_bits}; + } + + To to = Eigen::numext::bit_cast(bits); + // `From` supports larger values than `To`, we may overflow. + if constexpr (std::make_pair(std::numeric_limits::max_exponent, + std::numeric_limits::digits) < + std::make_pair(std::numeric_limits::max_exponent, + std::numeric_limits::digits)) { + if (rounded_from_bits > aligned_highest) { + // Overflowed values map to highest or infinity depending on kSaturate. + to = kSaturate ? Eigen::NumTraits::highest() + : Eigen::NumTraits::infinity(); + } + } + // Insert sign bit. + return from_sign_bit ? -to : to; + } +}; + +// Saturation has no impact when casting e4m3 to e5m2. +template +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline float8_e5m2 run(const float8_e4m3fn& from) { + return ConvertImpl::run(from); + } +}; + +template +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline float8_e5m2 run(const Eigen::half& from) { + uint16_t from_bits = Eigen::numext::bit_cast(from); + + // Special values (Inf or NaN). + uint16_t abs_bits = from_bits & 0x7FFF; + if (abs_bits == 0x7C00) { + return float8_e5m2::FromRep(from_bits >> 8); + } else if (abs_bits > 0x7C00) { + // IEEE 754-2019 6.2.1: "A quiet NaN bit string should be encoded with the + // first bit (d1) of the trailing significand field T being 1." + // IEEE 754-2019 6.2.3: "Conversion of a quiet NaN to a floating-point + // format of the same or a different radix that does not allow the payload + // to be preserved, shall return a quiet NaN [...]" + return float8_e5m2::FromRep((from_bits >> 8) | 0b0'00000'10); + } + + if constexpr (!kTruncate) { + from_bits = RoundBitsToNearestEven(from_bits, 8); + // Rounding can cause an overflow to infinity. Clamp to the largest finite + // value if saturation is requested. + if constexpr (kSaturate) { + const float8_e5m2 kHighest = Eigen::NumTraits::highest(); + if ((from_bits & 0x7F00) > static_cast(kHighest.rep()) << 8) { + const bool from_sign_bit = from_bits >> 15; + return from_sign_bit ? -kHighest : kHighest; + } + } + } + return float8_e5m2::FromRep(from_bits >> 8); + } +}; + +template <> +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline Eigen::half run(const float8_e5m2& from) { + return Eigen::numext::bit_cast( + static_cast(static_cast(from.rep()) << 8)); + } +}; + +// Direct casts of e5m2 to Eigen::half simply shifts bits over. +template +struct ConvertImpl { + static EIGEN_DEVICE_FUNC inline Eigen::half run(const float8_e5m2& from) { + return Eigen::numext::bit_cast( + static_cast(static_cast(from.rep()) << 8)); + } +}; + +template +template +EIGEN_DEVICE_FUNC Derived float8_base::ConvertFrom(const From& from) { + return ConvertImpl::run(from); +} + +template +template +EIGEN_DEVICE_FUNC To float8_base::ConvertTo(const Derived& from) { + return ConvertImpl::run(from); +} + +} // namespace float8_internal + +// Exported types. +using float8_e4m3fn = float8_internal::float8_e4m3fn; +using float8_e4m3fnuz = float8_internal::float8_e4m3fnuz; +using float8_e4m3b11fnuz = float8_internal::float8_e4m3b11fnuz; +using float8_e5m2 = float8_internal::float8_e5m2; +using float8_e5m2fnuz = float8_internal::float8_e5m2fnuz; + +} // namespace ml_dtypes + +// Eigen-specific overrides. +namespace Eigen { +namespace numext { + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC ml_dtypes::float8_e4m3fn +bit_cast(const uint8_t& src) { + return ml_dtypes::float8_e4m3fn::FromRep(src); +} + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC uint8_t +bit_cast( + const ml_dtypes::float8_e4m3fn& src) { + return src.rep(); +} + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC ml_dtypes::float8_e5m2 +bit_cast(const uint8_t& src) { + return ml_dtypes::float8_e5m2::FromRep(src); +} + +template <> +EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC uint8_t +bit_cast(const ml_dtypes::float8_e5m2& src) { + return src.rep(); +} + +} // namespace numext + +// Work-around for isinf/isnan/isfinite issue on aarch64. +namespace internal { +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e4m3fn& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e4m3b11fnuz& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e4m3fnuz& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e5m2& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isinf_impl( + const ml_dtypes::float8_e5m2fnuz& x) { + return ml_dtypes::float8_internal::isinf(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e4m3fn& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e4m3b11fnuz& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e4m3fnuz& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e5m2& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isnan_impl( + const ml_dtypes::float8_e5m2fnuz& x) { + return ml_dtypes::float8_internal::isnan(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e4m3fn& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e4m3b11fnuz& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e4m3fnuz& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e5m2& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +template <> +EIGEN_DEVICE_FUNC inline bool isfinite_impl( + const ml_dtypes::float8_e5m2fnuz& x) { + return ml_dtypes::float8_internal::isfinite(x); +} + +} // namespace internal +} // namespace Eigen + +#endif // ML_DTYPES_FLOAT8_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/include/int4.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/include/int4.h new file mode 100644 index 0000000000000000000000000000000000000000..419cc9f3fc71920d3932ab99b01c92b32fce923f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/include/external/ml_dtypes/include/int4.h @@ -0,0 +1,262 @@ +/* Copyright 2023 The ml_dtypes 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 ML_DTYPES_INT4_H_ +#define ML_DTYPES_INT4_H_ + +#include +#include +#include +#include +#include +#include + +namespace ml_dtypes { + +template +struct i4 { + private: + UnderlyingTy v : 4; + + public: + constexpr i4() : v(0) {} + constexpr i4(const i4& other) = default; + constexpr i4(i4&& other) = default; + constexpr i4& operator=(const i4& other) = default; + constexpr i4& operator=(i4&&) = default; + + explicit constexpr i4(UnderlyingTy val) : v(val & 0x0F) {} + template + explicit constexpr i4(T t) : i4(static_cast(t)) {} + + static constexpr i4 lowest() { + return std::is_signed::value ? i4(-8) : i4(0); + } + static constexpr i4 highest() { + return std::is_signed::value ? i4(7) : i4(15); + } + + template + explicit constexpr operator T() const { + return static_cast(v); + } + // NOLINTNEXTLINE(google-explicit-constructor) + constexpr operator std::optional() const { + return static_cast(v); + } + + constexpr i4 operator-() const { return i4(-v); } + constexpr i4 operator+(const i4& other) const { return i4((v + other.v)); } + constexpr i4 operator-(const i4& other) const { return i4((v - other.v)); } + constexpr i4 operator*(const i4& other) const { return i4((v * other.v)); } + constexpr i4 operator/(const i4& other) const { return i4((v / other.v)); } + constexpr i4 operator%(const i4& other) const { return i4((v % other.v)); } + + constexpr i4 operator&(const i4& other) const { return i4((v & other.v)); } + constexpr i4 operator|(const i4& other) const { return i4((v | other.v)); } + constexpr i4 operator^(const i4& other) const { return i4((v ^ other.v)); } + constexpr i4 operator~() const { return i4(~v); } + constexpr i4 operator>>(int amount) const { return i4((v >> amount)); } + constexpr i4 operator<<(int amount) const { return i4((v << amount)); } + + constexpr bool operator==(const i4& other) const { return v == other.v; } + constexpr bool operator!=(const i4& other) const { return v != other.v; } + constexpr bool operator<(const i4& other) const { return v < other.v; } + constexpr bool operator>(const i4& other) const { return v > other.v; } + constexpr bool operator<=(const i4& other) const { return v <= other.v; } + constexpr bool operator>=(const i4& other) const { return v >= other.v; } + + constexpr bool operator==(int64_t other) const { return v == other; } + constexpr bool operator!=(int64_t other) const { return v != other; } + constexpr bool operator<(int64_t other) const { return v < other; } + constexpr bool operator>(int64_t other) const { return v > other; } + constexpr bool operator<=(int64_t other) const { return v <= other; } + constexpr bool operator>=(int64_t other) const { return v >= other; } + + friend constexpr bool operator==(int64_t a, const i4& b) { return a == b.v; } + friend constexpr bool operator!=(int64_t a, const i4& b) { return a != b.v; } + friend constexpr bool operator<(int64_t a, const i4& b) { return a < b.v; } + friend constexpr bool operator>(int64_t a, const i4& b) { return a > b.v; } + friend constexpr bool operator<=(int64_t a, const i4& b) { return a <= b.v; } + friend constexpr bool operator>=(int64_t a, const i4& b) { return a >= b.v; } + + constexpr i4& operator++() { + v = (v + 1) & 0x0F; + return *this; + } + + constexpr i4 operator++(int) { + i4 orig = *this; + this->operator++(); + return orig; + } + + constexpr i4& operator--() { + v = (v - 1) & 0x0F; + return *this; + } + + constexpr i4 operator--(int) { + i4 orig = *this; + this->operator--(); + return orig; + } + + constexpr i4& operator+=(const i4& other) { + *this = *this + other; + return *this; + } + constexpr i4& operator-=(const i4& other) { + *this = *this - other; + return *this; + } + constexpr i4& operator*=(const i4& other) { + *this = *this * other; + return *this; + } + constexpr i4& operator/=(const i4& other) { + *this = *this / other; + return *this; + } + constexpr i4& operator%=(const i4& other) { + *this = *this % other; + return *this; + } + constexpr i4& operator&=(const i4& other) { + *this = *this & other; + return *this; + } + constexpr i4& operator|=(const i4& other) { + *this = *this | other; + return *this; + } + constexpr i4& operator^=(const i4& other) { + *this = *this ^ other; + return *this; + } + constexpr i4& operator>>=(int amount) { + *this = *this >> amount; + return *this; + } + constexpr i4& operator<<=(int amount) { + *this = *this << amount; + return *this; + } + + friend ::std::ostream& operator<<(::std::ostream& os, const i4& num) { + os << static_cast(num.v); + return os; + } + + std::string ToString() const { + std::ostringstream os; + os << static_cast(v); + return os.str(); + } +}; + +using int4 = i4; +using uint4 = i4; + +namespace internal { + +struct int4_numeric_limits_base { + static inline constexpr const bool is_specialized = true; + static inline constexpr const bool is_integer = true; + static inline constexpr const bool is_exact = true; + static inline constexpr const bool has_infinity = false; + static inline constexpr const bool has_quiet_NaN = false; + static inline constexpr const bool has_signaling_NaN = false; + static inline constexpr const std::float_denorm_style has_denorm = + std::denorm_absent; + static inline constexpr const bool has_denorm_loss = false; + static inline constexpr const std::float_round_style round_style = + std::round_toward_zero; + static inline constexpr const bool is_iec559 = false; + static inline constexpr const bool is_bounded = true; + static inline constexpr const int max_digits10 = 0; // Not used for integers. + static inline constexpr const int radix = 2; + static inline constexpr const int min_exponent = 0; + static inline constexpr const int min_exponent10 = 0; + static inline constexpr const int max_exponent = 0; + static inline constexpr const int max_exponent10 = 0; + static inline constexpr const bool traps = true; + static inline constexpr const bool tinyness_before = false; + + static constexpr ml_dtypes::int4 epsilon() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 round_error() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 infinity() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 quiet_NaN() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 signaling_NaN() noexcept { + return ml_dtypes::int4(0); + } + static constexpr ml_dtypes::int4 denorm_min() noexcept { + return ml_dtypes::int4(0); + } +}; + +} // namespace internal + +} // namespace ml_dtypes + +namespace std { + +template <> +struct numeric_limits + : public ml_dtypes::internal::int4_numeric_limits_base { + static inline constexpr const bool is_signed = true; + static inline constexpr const bool is_modulo = false; + static inline constexpr const int digits = 3; + static inline constexpr const int digits10 = 0; // floor(3 * log10(2)) + static constexpr ml_dtypes::int4 min() noexcept { + return ml_dtypes::int4::lowest(); + } + static constexpr ml_dtypes::int4 lowest() noexcept { + return ml_dtypes::int4::lowest(); + } + static constexpr ml_dtypes::int4 max() noexcept { + return ml_dtypes::int4::highest(); + } +}; + +template <> +struct numeric_limits + : public ml_dtypes::internal::int4_numeric_limits_base { + static inline constexpr const bool is_signed = false; + static inline constexpr const bool is_modulo = true; + static inline constexpr const int digits = 4; + static inline constexpr const int digits10 = 1; // floor(4 * log10(2)) + static constexpr ml_dtypes::uint4 min() noexcept { + return ml_dtypes::uint4::lowest(); + } + static constexpr ml_dtypes::uint4 lowest() noexcept { + return ml_dtypes::uint4::lowest(); + } + static constexpr ml_dtypes::uint4 max() noexcept { + return ml_dtypes::uint4::highest(); + } +}; + +} // namespace std + +#endif // ML_DTYPES_INT4_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/lite/kernels/shim/op_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/lite/kernels/shim/op_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..84ff3c2c851a2c795348061a8a7b86a31158598b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/lite/kernels/shim/op_kernel.h @@ -0,0 +1,277 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_LITE_KERNELS_SHIM_OP_KERNEL_H_ +#define TENSORFLOW_LITE_KERNELS_SHIM_OP_KERNEL_H_ + +// This file defines a shim layer on top of TF and TFLite custom op APIs. +// The goal is for a custom op to be written once and used for both runtimes +// +// It consists of two pieces: +// * A set of *context* interfaces: +// ** InvokeContext, InitContext, ShapeInferenceContext +// These are passed on to the custom op implementation to read/write +// tensors, etc. +// +// * An OpKernelShim interface: +// This is what a custom op needs to implement. By using that interface the +// custom op can then be easily converted to both a TF op kernel and a +// TFLite op kernel. + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "absl/types/variant.h" +#include "tensorflow/lite/kernels/shim/shape.h" +#include "tensorflow/lite/kernels/shim/status_macros.h" +#include "tensorflow/lite/kernels/shim/tensor_view.h" + +namespace tflite { +namespace shim { + +// List of the TF custom op APIs this shim library is abstracting away. +// +// This enum is used as the template parameter in various places in +// order to pick the correct set of types (eg. TfInvokeContext vs. +// TfLiteInvokeContext) in the op implementation. +enum class Runtime { kTf, kTfLite }; + +// TensorView or error +using TensorViewOr = absl::StatusOr>; +using ConstTensorViewOr = absl::StatusOr>; + +// Below are the interfaces for various "Context" objects to abstract away the +// TF and TFLite differences. +// +// The interfaces are static and use the CRTP pattern instead of virtual +// methods. + +// The attribute dictionary passed to the op +using AttrValue = absl::variant; + +// The interface for available methods during an op kernel initialization +template +class InitContext { + public: + // Read the given attribute and populate the given value. + template + absl::Status GetAttr(const std::string& attr_name, AttrType* value) const; + + protected: + // Read a given attribute or return error + absl::StatusOr GetAttr(const std::string& attr_name) const { + return static_cast(*this).GetAttr(attr_name); + } +}; + +// The interface for available methods during an op kernel invocation +template +class InvokeContext { + public: + // Read an input tensor + ConstTensorViewOr GetInput(const int idx) const { + return static_cast(*this).GetInput(idx); + } + // Get a mutable output tensor + TensorViewOr GetOutput(const int idx, const Shape& shape) const { + return static_cast(*this).GetOutput(idx, shape); + } + // Number of input tensors + int NumInputs() const { + return static_cast(*this).NumInputs(); + } + // Number of output tensors + int NumOutputs() const { + return static_cast(*this).NumOutputs(); + } +}; + +// The interface for available methods during shape inference +template +class ShapeInferenceContext { + public: + // Read an input tensor shape + ShapeOr GetInputShape(const int idx) const { + return static_cast(*this).GetInputShape(idx); + } + // Set an output tensor shape + absl::Status SetOutputShape(const int idx, const Shape& shape) { + return static_cast(*this).SetOutputShape(idx, shape); + } + // Read an input tensor during shape inference + ConstTensorViewOr GetInputTensor(const int idx) const { + return static_cast(*this).GetInputTensor(idx); + } + // Number of input tensors + int NumInputs() const { + return static_cast(*this).NumInputs(); + } + // Number of output tensors + int NumOutputs() const { + return static_cast(*this).NumOutputs(); + } + // Read the given attribute and populate the given value. + template + absl::Status GetAttr(const std::string& attr_name, AttrType* value) const; + + protected: + // Read a given attribute or return error + absl::StatusOr GetAttr(const std::string& attr_name) const { + return static_cast(*this).GetAttr(attr_name); + } +}; + +// Maps the Runtime to the correct context types. +// eg. ContextTypeForRuntime --> +// { TfInitContext, TfInvokeContext, TfShapreInferenceContext } +template +struct ContextTypeForRuntime { + // * Init + // * Invoke + // * ShapeInference +}; + +// A Tensorflow operation interface which is then adapted to both TF and TFLite +// runtimes. +// +// Example usage: +// +// template +// class MyOp : public OpKernelShim { +// +// // Attributes declaration +// // (syntax: https://www.tensorflow.org/guide/create_op) +// static std::vector Attrs(); +// +// // Input tensors declaration +// // (syntax: https://www.tensorflow.org/guide/create_op) +// static std::vector Inputs(); +// +// // Output tensors declaration +// // (syntax: https://www.tensorflow.org/guide/create_op) +// static std::vector Outputs(); +// +// // Initializes the op +// absl::Status Init(InitContext* ctx); +// +// // Runs the operation +// absl::Status Invoke(InvokeContext* ctx); +// +// // Shape inference +// static absl::Status ShapeInference(ShapeInferenceContext* ctx); +// +// }; +// +// WARNING: Experimental interface, subject to change +template