diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/buffer_sharing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/buffer_sharing.h new file mode 100644 index 0000000000000000000000000000000000000000..5867dd8d03193a5b95adf9ea45e3de1b61007527 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/buffer_sharing.h @@ -0,0 +1,36 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_BUFFER_SHARING_H_ +#define XLA_SERVICE_GPU_BUFFER_SHARING_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/shape_util.h" + +namespace xla { +namespace gpu { +std::optional FusionCanShareBufferHint(const HloInstruction* user, + const HloInstruction* operand, + const ShapeIndex& user_index); + +std::optional CanShareBufferHint(const HloInstruction* user, + const HloInstruction* operand, + const ShapeIndex& user_index); +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_BUFFER_SHARING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/compile_module_to_llvm_ir.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/compile_module_to_llvm_ir.h new file mode 100644 index 0000000000000000000000000000000000000000..64d73b81700f96b394368b39dd7f1610bd3deaed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/compile_module_to_llvm_ir.h @@ -0,0 +1,81 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_COMPILE_MODULE_TO_LLVM_IR_H_ +#define XLA_SERVICE_GPU_COMPILE_MODULE_TO_LLVM_IR_H_ + +#include +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/buffer_value.h" +#include "xla/service/gpu/executable.pb.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +struct CompileModuleResults { + std::unique_ptr llvm_module; + std::unique_ptr buffer_assignment; + std::vector allocations; + std::variant + executable; + EntryFunctionAttributes entry_func_attrs; + std::vector constants; + absl::flat_hash_map output_info; + Shape output_shape; + std::string module_name; +}; + +// Removes all globals from the given module that are both uninitialized and +// have no uses within that module. +void RemoveUnusedAndUninitializedGlobals( + llvm::Module* llvm_module, + const std::vector& constants); + +// Compile `hlo_module` using XLA GPU and return the LLVM module thus generated. +// The GpuExecutable (and the Thunks that are part of it) are not returned. +StatusOr> CompileModuleToLlvmIr( + HloModule* hlo_module, llvm::LLVMContext* llvm_context, + const std::string& target_triple, const std::string& data_layout, + const std::string& platform_name, se::Platform::Id platform_id, + const se::DeviceDescription& gpu_device_info, + const BufferValue::SizeFunction& buffer_size_bytes_function); + +Status CompileModuleToLlvmIrImpl( + HloModule* hlo_module, llvm::LLVMContext* llvm_context, + const std::string& target_triple, const std::string& data_layout, + const std::string& platform_name, se::Platform::Id platform_id, + const se::DeviceDescription& gpu_device_info, + const HloDataflowAnalysis::CanShareBuffer& can_share_buffer_function, + const BufferValue::SizeFunction& buffer_size_bytes_function, + CompileModuleResults* results, se::StreamExecutor* stream_exec = nullptr); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_COMPILE_MODULE_TO_LLVM_IR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conditional_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conditional_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..044275b4b88848d1cf4cfaa3e2dab7a54d88fae9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conditional_thunk.h @@ -0,0 +1,72 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CONDITIONAL_THUNK_H_ +#define XLA_SERVICE_GPU_CONDITIONAL_THUNK_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/sequential_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +struct ConditionalThunkConfig { + bool branch_index_is_bool; + int64_t branch_count; + std::vector> branch_thunks; +}; + +// ConditionalThunk implements the conditional instruction on GPU by reading the +// predicate of the conditional and executing the true or the false computation +// depending on the value of the predicate. +// +// ConditionalThunk assumes that the buffers of the conditional result and the +// result of the true and false computations share the same allocation. Also, +// the buffers of the true operand of the conditional and that of the parameter +// instruction of the true computation share the same allocation. Similarly, the +// buffers of the false operand and that of the parameter instruction of the +// false computation share the same allocation. +class ConditionalThunk : public Thunk { + public: + ConditionalThunk(ThunkInfo thunk_info, ConditionalThunkConfig config, + const BufferAllocation::Slice& branch_index_buffer_index); + + ConditionalThunk(const ConditionalThunk&) = delete; + ConditionalThunk& operator=(const ConditionalThunk&) = delete; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + absl::Span> branch_thunks() { + return config_.branch_thunks; + } + + private: + const ConditionalThunkConfig config_; + BufferAllocation::Slice branch_index_buffer_index_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CONDITIONAL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_algorithm_picker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_algorithm_picker.h new file mode 100644 index 0000000000000000000000000000000000000000..2850c0609e70a7eeeef3444d1c577875a4cae712 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_algorithm_picker.h @@ -0,0 +1,164 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CONV_ALGORITHM_PICKER_H_ +#define XLA_SERVICE_GPU_CONV_ALGORITHM_PICKER_H_ + +#include +#include +#include +#include + +#include "xla/autotune_results.pb.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/gpu/gpu_conv_runner.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) +#include "xla/stream_executor/gpu/redzone_allocator.h" +#endif + +namespace xla { +namespace gpu { + +// Choose the fastest algorithm for each conv. +// Modifies CustomCalls to cudnn convolutions, choosing the best algorithm for +// each and adding explicit scratch space to the CustomCalls. +// +// We pick the algorithm before fusion so that we can generate better HLO. After +// GpuConvRewriter, our convolutions are CustomCalls which return a +// tuple (conv_result, scratch_memory), and the each conv uses 0 bytes of +// scratch: +// +// customcall = (f32[...], f32[0]) +// return gte(customcall, 0) +// +// The algorithm picker then chooses the best algorithm, and potentially +// increases the scratch space. It replaces customcall with new_tuple, +// giving us the following: +// +// new_customcall = (f32[...], f32[N]) +// new_tuple = tuple(gte(new_customcall, 0), constant f32[0]) +// return gte(new_tuple, 0) +// +// The new tuple and gte instructions can be simplified away, because +// nobody is expected to use the scratch value. +// +// However, if we were to run GpuConvAlgorithmPicker after fusion +// the gte(customcall, 0) would probably already be into a fusion node. We +// can't simplify across HloComputation boundaries, so in this case we +// wouldn't be able to simplify away the new_tuple bits. +// +// It supports two modes: device and deviceless. +// In device mode, we run autotuning on the device and store autotune results. +// +// In deviceless mode, we pass in some information related to the device and +// use stored autotune results to rewrite convolutions. If the required autotune +// result is not stored, then the performance of convolution will be suboptimal. +class GpuConvAlgorithmPicker : public HloModulePass { + public: + explicit GpuConvAlgorithmPicker(AutotuneConfig config) : config_(config) {} + + absl::string_view name() const override { + return "gpu-conv-algorithm-picker"; + } + + static bool IsEnabled(const HloModule* module) { + return module->config().debug_options().xla_gpu_autotune_level() != 0; + } + + static bool IsCandidate(const HloInstruction* instr) { + return IsCustomCallToDnnConvolution(*instr); + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Run autotuning on allocated buffers and pick the best algorithm. + StatusOr PickBestAlgorithmWithAllocatedBuffer( + const AutotuneConfig& config, GpuConvConfig conv_config, + const ServiceExecutableRunOptions* run_options, + const DebugOptions& debug_options, + std::vector buffers, + std::vector result_buffers); + + private: + StatusOr RunOnComputation(HloComputation* computation); + StatusOr RunOnInstruction(HloInstruction* instr); + + StatusOr PickBestAlgorithm( + const HloCustomCallInstruction* instr); + StatusOr PickBestAlgorithmNoCache( + const HloCustomCallInstruction* instr); + +#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) + // Simple bundle of an algorithm and its output, for comparing results across + // autotuned algorithms. + struct ReferenceResult { + stream_executor::dnn::AlgorithmDesc algorithm; + std::vector buffers; + }; + + // Execution environment for autotuning. Runtime autotuning requires runtime + // information such as input/output buffers in order to run. It can be + // constructed from the autotuned instruction by FromInstruction. + struct AutotuneRuntimeArguments { + const Shape result_shape; + const HloModuleConfig hlo_module_config; + std::vector operand_buffers; + std::vector result_buffers; + se::RedzoneAllocator* input_output_allocator; + const GpuConvConfig gpu_conv_config; + std::optional canonical_hlo; + + static StatusOr FromInstruction( + const HloCustomCallInstruction* instr, + se::DeviceMemoryAllocator* allocator, se::StreamExecutor* stream, + se::RedzoneAllocator* input_output_allocator); + }; + + StatusOr AutotuneOneConvRunner( + se::Stream* stream, GenericConvRunner* runner, + std::optional* reference_result, + absl::Span disabled_algos, + std::optional instruction_info, + const AutotuneRuntimeArguments& runtime_arguments); + + // Pick the best algorithm for CUDA platform. + StatusOr PickBestAlgorithmNoCacheCuda( + const HloCustomCallInstruction* instr, se::Stream* stream, + std::optional instruction_info, + const AutotuneRuntimeArguments& runtime_arguments); +#endif + + StatusOr PickBestAlgorithmNoCacheRocm( + const HloCustomCallInstruction* instr, + se::DeviceMemoryAllocator* allocator, se::Stream* stream); + + private: + AutotuneConfig config_; +}; + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_CONV_ALGORITHM_PICKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_layout_normalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_layout_normalization.h new file mode 100644 index 0000000000000000000000000000000000000000..52fd26c1fbf95b60e73f14f0646eecd03f2b726d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/conv_layout_normalization.h @@ -0,0 +1,37 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CONV_LAYOUT_NORMALIZATION_H_ +#define XLA_SERVICE_GPU_CONV_LAYOUT_NORMALIZATION_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +StatusOr> NormalizeLayoutForGpuCustomCalls( + HloCustomCallInstruction*); + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_CONV_LAYOUT_NORMALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/convolution_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/convolution_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..d7f731302c1a949314725a837910618c109b4ff5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/convolution_thunk.h @@ -0,0 +1,95 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CONVOLUTION_THUNK_H_ +#define XLA_SERVICE_GPU_CONVOLUTION_THUNK_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/gpu_conv_runner.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a DNN +// convolution. It is generated by IrEmitter. +// +// This is thread-compatible. +class ConvolutionThunk : public Thunk { + public: + // Constructs a thunk for launching a DNN convolution. + // + // operand_slices should be in the same order as cudnn_call->operands(). + ConvolutionThunk(ThunkInfo thunk_info, GpuConvConfig config, + std::vector operand_slices, + std::vector result_slices, + BufferAllocation::Slice scratch_slice); + + ConvolutionThunk(const ConvolutionThunk&) = delete; + ConvolutionThunk& operator=(const ConvolutionThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + std::vector operand_buffers_; + std::vector result_buffers_; + BufferAllocation::Slice scratch_buffer_; + GenericConvRunner& GetOrCreateRunner(const stream_executor::Stream* stream); + + // Convolution config + const GpuConvConfig config_; + absl::Mutex mu_; + absl::flat_hash_map> + runner_cache_ ABSL_GUARDED_BY(mu_); +}; + +// Launches the kernel that reorders input data for int8x32 convolutions. +class ConvolutionReorderThunk : public Thunk { + public: + ConvolutionReorderThunk(ThunkInfo thunk_info, absl::Span filter_nchw, + std::vector operand_slices, + std::vector result_slices); + + ConvolutionReorderThunk(const ConvolutionReorderThunk&) = delete; + ConvolutionReorderThunk& operator=(const ConvolutionReorderThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + static se::dnn::FilterDescriptor CreateFilterDescriptor( + absl::Span filter_nchw); + + const se::dnn::FilterDescriptor filter_descriptor_; + std::vector operand_buffers_; + std::vector result_buffers_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CONVOLUTION_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..fa9306ce7e3fde7bc1485161e2036a6766a62b46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_fusion.h @@ -0,0 +1,46 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_COPY_FUSION_H_ +#define XLA_SERVICE_GPU_COPY_FUSION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// CopyFusion checks if a fusion is followed by multiple copies and if so, adds +// those copies to the fusion, replacing the copies with get_tuple_elements. +class CopyFusion : public HloModulePass { + public: + CopyFusion() = default; + + absl::string_view name() const override { return "copy_fusion"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr DoCopyFusion(HloComputation* computation); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_COPY_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..7576c81ca98ec652ed8d4c18828eadd7ee30d45b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/copy_thunk.h @@ -0,0 +1,70 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_COPY_THUNK_H_ +#define XLA_SERVICE_GPU_COPY_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that copies data from a device buffer to another device buffer. +class DeviceToDeviceCopyThunk : public Thunk { + public: + // Constructs a CopyThunk that copies host data from `source_buffer` to the + // device buffer `destination_buffer`. `mem_size` is the size of the data in + // bytes. + DeviceToDeviceCopyThunk(ThunkInfo thunk_info, + const BufferAllocation::Slice& source_buffer, + const BufferAllocation::Slice& destination_buffer, + uint64_t mem_size, mlir::Value source_value, + mlir::Value destination_value); + + DeviceToDeviceCopyThunk(const DeviceToDeviceCopyThunk&) = delete; + DeviceToDeviceCopyThunk& operator=(const DeviceToDeviceCopyThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + source_value_ = nullptr; + destination_value_ = nullptr; + } + + const BufferAllocation::Slice& source() const { return source_buffer_; } + const BufferAllocation::Slice& destination() const { + return destination_buffer_; + } + uint64_t size_bytes() const { return mem_size_; } + mlir::Value source_value() const { return source_value_; } + mlir::Value destination_value() const { return destination_value_; } + + private: + const BufferAllocation::Slice source_buffer_; + const BufferAllocation::Slice destination_buffer_; + const uint64_t mem_size_; + mlir::Value source_value_; + mlir::Value destination_value_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_COPY_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_cudnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_cudnn.h new file mode 100644 index 0000000000000000000000000000000000000000..4feaf28bb1f51c467b413912b9b51a8ff332e02f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_cudnn.h @@ -0,0 +1,205 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUBLAS_CUDNN_H_ +#define XLA_SERVICE_GPU_CUBLAS_CUDNN_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "tsl/platform/statusor.h" + +namespace xla { +namespace gpu { + +// Different types of convolutions supported by cudnn. +// +// A way to think about these is that a convolution is defined by three arrays +// -- the "input", the "filter", and the "output" -- and given any two of these, +// we can compute the third. For example, a backward-input convolution takes as +// input a filter and an "output" and produces an "input" such that if one were +// to do a forward convolution of "input" using filter, the result would be +// something with the same shape as "output". +// +// This way of thinking is not correct if you look at the values produced. For +// example, a backward-input convolution is not actually the mathematical +// inverse of a forward convolution. But it's right as far as the shapes and +// "connectivity" (i.e. which elements of the input affect which elements of +// the output) are concerned. +enum class CudnnConvKind { + kForward, // input + filter => output + kBackwardInput, // filter + output => input + kBackwardFilter, // input + output => filter + kForwardActivation, // activation(conv(input, filter) + broadcast(bias) + + // (optionally) side_input) => output + kForwardGraph, // pointwise(...pointwise(conv(input, filter))...) + // => output +}; + +enum class CudnnfMHAKind { + kBmmBmm, + kScaleBiasMaskSoftmax, + kScaleBiasMaskSoftmaxDropout, + kScaleMaskSoftmax, + kScaleMaskSoftmaxDropout, + kSoftmaxDropout, + kSoftmax, + kScaleBiasSoftmax, + kScaleBiasSoftmaxDropout, + kBackwardBmmBmm, + kBackwardScaleBiasMaskSoftmax, + kBackwardScaleBiasMaskSoftmaxDropout, + kBackwardScaleMaskSoftmax, + kBackwardScaleMaskSoftmaxDropout, + kBackwardSoftmaxDropout, + kBackwardSoftmax, + kBackwardScaleBiasSoftmax, + kBackwardScaleBiasSoftmaxDropout, +}; + +StatusOr GetCudnnConvKind(const HloCustomCallInstruction* instr); + +// Converts a CudnnConvKind value to a string. +std::string CudnnConvKindToString(CudnnConvKind kind); + +// Matrix multiplication rewritten into a GEMM custom call. +// All matrix multiplications should be rewritten as such custom calls +// after a GemmRewriter lowering pass. +bool IsCublasGemm(const HloInstruction& hlo); + +// Matrix multiplication that calls into legacy cublas. +bool IsLegacyCublasMatmul(const HloInstruction& hlo); + +// Matrix multiplication that calls into cublasLt. +bool IsCublasLtMatmul(const HloInstruction& hlo); + +// Scaled matrix multiplication in FP8. Calls into cublasLt. +bool IsCublasLtMatmulF8(const HloInstruction& hlo); + +// A call to cuBLAS general matrix multiplication API. +extern const absl::string_view kGemmCallTarget; + +// A call to cuBLAS Lt API matrix multiplication. +extern const absl::string_view kCublasLtMatmulCallTarget; + +// A call to cuBLASLt for scaled matrix multiplication in FP8. +extern const absl::string_view kCublasLtMatmulF8CallTarget; + +// A call to cuBLAS for a triangular solve. +// +// Like cudnn convolutions, this op returns a tuple (result, scratch_memory). +extern const absl::string_view kTriangularSolveCallTarget; + +// A call to cuDNN for convolution (forward, backward filter, or backward input) +// is represented as a CustomCall HLO with a call target equal to one of these +// strings. +// +// These CustomCalls have window() and convolution_dimension_numbers() set like +// regular convolution ops. They have the same LHS and RHS operands, plus two +// additional constant operands: an int64_t operand for the cudnn algorithm and +// a bool operand for whether tensor_ops is enabled. A value of -1 for the cudnn +// algorithm means that the implementation is free to choose the best algorithm +// it can. +// +// These calls output a tuple (conv_result, scratch_memory), where conv_result +// is the actual result of the convolution, and scratch_memory is temporary +// memory used by cudnn. Callers shouldn't inspect scratch_memory, as its value +// is not well-defined. +// +// GpuConvRewriter lowers kConvolution HLOs to these custom calls. +// When it does so, it chooses algorithm -1 and 0 bytes of scratch space. Later +// on in the pipeline, CudnnConvAlgorithmChooser chooses an explicit +// algorithm for each conv and sets the amount of scratch space needed. +// +// (Representing the scratch memory as an output may seem strange at first, but +// it's quite sensible, from a certain point of view. The scratch buffer is a +// location in memory that the conv can write into, but which it can't legally +// read from, at least until it's written something first. But that's exactly +// the definition of an output buffer.) +extern const absl::string_view kCudnnConvForwardCallTarget; +extern const absl::string_view kCudnnConvBackwardInputCallTarget; +extern const absl::string_view kCudnnConvBackwardFilterCallTarget; +extern const absl::string_view kCudnnConvBiasActivationForwardCallTarget; +extern const absl::string_view kCudnnConvForwardGraphCallTarget; + +// cuDNN specific convolution helper (emitted together with a int8x32 +// convolution, if reordering is required). +extern const absl::string_view kCudnnConvReorderFilterCallTarget; +extern const absl::string_view kCudnnConvReorderFilterAndBiasCallTarget; + +// Returns true if `hlo` will be implemented as a call to a cuDNN convolution +// routine. +// +// This returns true if `hlo` is a CustomCall HLO with a call target equal to +// one of the kCudnnConvFoo constants above, but returns *false* for HLOs with a +// kConvolution opcode. +bool IsCustomCallToDnnConvolution(const HloInstruction& hlo); + +// Returns true if `hlo` will be implemented as a call to cuDNN convolution +// reordering helper (required for int8x32 convolutions). +bool IsCudnnConvolutionReorder(const HloInstruction& hlo); + +// The fused_mha_rewriter phase where each of the MHA signatures are pattern +// matched and rewritten into a custom-call with specific custom-call target. +// The custom-call target specifies the MHA signature. For example, BMM1 - Bias +// - Scale - Mask - Softmax - BMM2 pattern can have the target as +// cudnn$fmhaBiasScaleMaskSoftmax. +// The fMHA signatures currently supported by cudnn are: +// 1.BMM1 - BMM2 +// 2. BMM1 - Scale - Bias - Mask - Softmax - BMM2 +// 3. BMM1 - Scale - Bias - Mask - Softmax - Dropout - BMM2 +// 4. BMM1 - Scale - Mask - Softmax - BMM2 +// 5. BMM1 - Scale - Mask - Softmax - Dropout - BMM2 +// 6. BMM1 - Softmax - Dropout - BMM2 +// 7. BMM1 - Softmax - BMM2 +// 8. BMM1 - scale - Bias - Softmax - BMM2 +// Forward calls +extern const absl::string_view kCudnnfMHABmmBmmCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasMaskSoftmaxCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasMaskSoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHAScaleMaskSoftmaxCallTarget; +extern const absl::string_view kCudnnfMHAScaleMaskSoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasSoftmaxDropoutCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasSoftmaxCallTarget; +// Backward calls +extern const absl::string_view kCudnnfMHABmmBmmBackwardCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxBackwardCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasMaskSoftmaxBackwardCallTarget; +extern const absl::string_view + kCudnnfMHAScaleBiasMaskSoftmaxDropoutBackwardCallTarget; +extern const absl::string_view kCudnnfMHAScaleMaskSoftmaxBackwardCallTarget; +extern const absl::string_view + kCudnnfMHAScaleMaskSoftmaxDropoutBackwardCallTarget; +extern const absl::string_view kCudnnfMHASoftmaxDropoutBackwardCallTarget; +extern const absl::string_view + kCudnnfMHAScaleBiasSoftmaxDropoutBackwardCallTarget; +extern const absl::string_view kCudnnfMHAScaleBiasSoftmaxBackwardCallTarget; + +bool IsFwdCustomCallTofMHA(const HloInstruction& hlo); +bool IsBwdCustomCallTofMHA(const HloInstruction& hlo); +bool IsCustomCallTofMHA(const HloInstruction& hlo); + +StatusOr GetCudnnfMHAKind(const HloCustomCallInstruction* instr); + +std::string CudnnfMHAKindToString(CudnnfMHAKind kind); +Status SetFMHAInstructionName(HloModule* module, HloInstruction* fmha); + +bool MHACallHasDropout(absl::string_view fmha_call_name); +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_CUDNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_lt_matmul_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_lt_matmul_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..3098d18687d35aec6590366480a3a3dd7d3bc27e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_lt_matmul_thunk.h @@ -0,0 +1,85 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUBLAS_LT_MATMUL_THUNK_H_ +#define XLA_SERVICE_GPU_CUBLAS_LT_MATMUL_THUNK_H_ + +#include +#include +#include + +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/matmul_utils.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "tsl/platform/statusor.h" +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#else +#include "rocm/rocm_config.h" +#include "xla/stream_executor/rocm/hip_blas_lt.h" +#endif // GOOGLE_CUDA + +namespace xla { +namespace gpu { + +class CublasLtMatmulThunk : public Thunk { + public: + CublasLtMatmulThunk(ThunkInfo thunk_info, GemmConfig gemm_config, + se::gpu::BlasLt::Epilogue epilogue, int64_t algorithm_idx, + BufferAllocation::Slice a_buffer, + BufferAllocation::Slice b_buffer, + BufferAllocation::Slice c_buffer, + BufferAllocation::Slice d_buffer, + BufferAllocation::Slice bias_buffer /* may be null */, + BufferAllocation::Slice aux_buffer /* may be null */, + BufferAllocation::Slice a_scale_buffer /* may be null */, + BufferAllocation::Slice b_scale_buffer /* may be null */, + BufferAllocation::Slice c_scale_buffer /* may be null */, + BufferAllocation::Slice d_scale_buffer /* may be null */, + BufferAllocation::Slice d_amax_buffer /* may be null */); + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + StatusOr GetMatmulPlan( + const stream_executor::Stream* stream); + + absl::Mutex matmul_plans_cache_mutex_; + absl::flat_hash_map> + matmul_plans_cache_ ABSL_GUARDED_BY(matmul_plans_cache_mutex_); + + GemmConfig gemm_config_; + se::gpu::BlasLt::Epilogue epilogue_; + int64_t algorithm_idx_; + BufferAllocation::Slice a_buffer_; + BufferAllocation::Slice b_buffer_; + BufferAllocation::Slice c_buffer_; + BufferAllocation::Slice d_buffer_; + BufferAllocation::Slice bias_buffer_; + BufferAllocation::Slice aux_buffer_; + BufferAllocation::Slice a_scale_buffer_; + BufferAllocation::Slice b_scale_buffer_; + BufferAllocation::Slice c_scale_buffer_; + BufferAllocation::Slice d_scale_buffer_; + BufferAllocation::Slice d_amax_buffer_; + std::optional algorithm_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_LT_MATMUL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_pad_for_gemms.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_pad_for_gemms.h new file mode 100644 index 0000000000000000000000000000000000000000..758949c91eb9fb0bb37398bf34ee47db92b97c35 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_pad_for_gemms.h @@ -0,0 +1,56 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUBLAS_PAD_FOR_GEMMS_H_ +#define XLA_SERVICE_GPU_CUBLAS_PAD_FOR_GEMMS_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Adds padding to dot operations to make them run faster on GPUs. +// +// +// This can be used to pad f16 dots on tensor cores, or s8 dots to multiples of +// four. +// +// This pass depends on xla::DotDecomposer pass, +// so it should go strictly later. +class CublasPadForGemms : public HloModulePass { + public: + CublasPadForGemms(const se::CudaComputeCapability cuda_compute_capability, + PrimitiveType datatype, int32_t pad_to_multiple_of) + : cuda_compute_capability_(cuda_compute_capability), + datatype_(datatype), + pad_to_multiple_of_(pad_to_multiple_of) {} + + absl::string_view name() const override { return "cublas-pad-for-gemms"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability cuda_compute_capability_; + PrimitiveType datatype_; + int32_t pad_to_multiple_of_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_PAD_FOR_GEMMS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_padding_requirements.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_padding_requirements.h new file mode 100644 index 0000000000000000000000000000000000000000..b0b44e61b57bbe68c29834d295a6ca5f4ddbc3c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cublas_padding_requirements.h @@ -0,0 +1,47 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUBLAS_PADDING_REQUIREMENTS_H_ +#define XLA_SERVICE_GPU_CUBLAS_PADDING_REQUIREMENTS_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +struct CublasPaddingRequirement { + int min_compute_capability; + PrimitiveType data_type; + int multiple_of; +}; + +// List of padding requirements per compute capability and data type. +constexpr std::array CublasPaddingRequirements{ + {{se::CudaComputeCapability::VOLTA, S8, 4}, + {se::CudaComputeCapability::VOLTA, F16, 8}, + {se::CudaComputeCapability::AMPERE, BF16, 8}}}; + +// Tell if either of the operands of the dot requires padding. +bool CublasRequiresPadding(const HloDotInstruction& dot, + se::CudaComputeCapability cc); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUBLAS_PADDING_REQUIREMENTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_conv_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_conv_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..67c40792df08ad4527f8687afe4bace7d8fd1f23 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_conv_rewriter.h @@ -0,0 +1,116 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_FUSED_CONV_REWRITER_H_ +#define XLA_SERVICE_GPU_CUDNN_FUSED_CONV_REWRITER_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Rewrites custom-calls targeting cudnnConvolutionForward to +// cudnnConvolutionBiasActivationForward by fusing operations following forward +// convolution. This transform must run after cudnn_conv_rewriter. +// +// Semantics of underlying cudnn ops: +// +// https://docs.nvidia.com/deeplearning/cudnn/api/index.html#cudnnConvolutionBiasActivationForward +// https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#scaling-parameters +// +// ## Floating-point convs +// +// A "complete" fused floating-point conv has the form +// +// max(0, alpha1 * conv(x, w) + alpha2 * side_input + broadcast(bias)), +// +// which we fuse to +// +// cudnnConvolutionBiasActivationForward(x, w, bias, side_input). +// +// You can leave out side_input, bias, alpha1, alpha2, and max(x, 0) and still +// get a fused convolution. alpha1/2 must be broadcasts of scalar constants. +// +// f16 convs accumulate in f32. We represent this in HLO as an f32 convolution +// whose inputs can be converted to f16 without loss of precision and whose +// output is immediately converted to f16. A fused f16 conv must follow one of +// the following idioms. +// +// 1. convert_f16(conv_f32(x_f32, w_f32)) + +// side_input_f16 + broadcast(bias_f16) +// +// 2. convert_f16(conv_f32(x_f32, w_f32) + +// side_input_f32 + broadcast(bias_f32)) +// +// (These are not strictly mathematically equivalent, but cudnn doesn't tell us +// which one it does, and we deem them "close enough".) +// +// The foo_f32 HLOs must all be losslessly-convertible to f16. Some valid +// examples: +// +// - foo_f32 = convert_f32(foo_f16) +// - foo_f32 = an f32 constant whose values all fit within f16 +// - foo_f32 = broadcast/transpose/reshape(one of the above) +// +// If you have a relu, it can appear before or after the convert_f16. +// +// Note that here `bias` must be losslessly-convertible to f16; this is +// different than for s8 convolutions, where bias is f32. +// +// ## Integer convs +// +// In pure HLO, a "complete" integer conv is spelled as one of the following +// `result`s. +// +// base = alpha1_f32 * convert_f32(conv_s32(input_s32, filter_s32)) + +// alpha2_f32 * side_input + +// bias_f32 +// +// result_f32 = max(result_f32, 0) +// result_s8_option1 = max(convert_s8(clamp(-128, base, 127)), 0) +// result_s8_option2 = convert_s8(clamp(-128, max(base, 0), 127)) +// +// The foo_s32 HLOs must be losslessly-convertible to s8. If the `result_s8` +// case, side_input should be an f32 HLO that's losslessly-convertible to s8; +// otherwise, it should be losslessly-convertible to f32. +// +// In the `result_s8` case where there's no bias, side-input, or alpha1, you can +// skip the convert_f32 on conv. +// +// If you have an integer convolution that doesn't fit one of these idioms, this +// pass returns an error -- cudnn will not be able to run it. +class CudnnFusedConvRewriter : public HloModulePass { + public: + explicit CudnnFusedConvRewriter(se::CudaComputeCapability cc) + : compute_capability_(cc) {} + + absl::string_view name() const override { + return "cudnn-fused-convolution-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_FUSED_CONV_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..76704ff06ae1c4dd215dba8e6e0634df250fe654 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_rewriter.h @@ -0,0 +1,54 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_FUSED_MHA_REWRITER_H_ +#define XLA_SERVICE_GPU_CUDNN_FUSED_MHA_REWRITER_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/dnn.h" + +namespace xla { +namespace gpu { + +class CudnnFusedMHARewriter : public HloModulePass { + public: + explicit CudnnFusedMHARewriter(se::CudaComputeCapability cc, + se::StreamExecutor* stream_executor) + : compute_capability_(cc), stream_executor_(stream_executor) {} + + explicit CudnnFusedMHARewriter(se::CudaComputeCapability cc, + se::dnn::VersionInfo cudnn_version) + : compute_capability_(cc), cudnn_version_(cudnn_version) {} + + absl::string_view name() const override { + return "cudnn-fused-multi-headed-attention-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; + se::StreamExecutor* stream_executor_ = nullptr; + const se::dnn::VersionInfo cudnn_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_FUSED_MHA_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..2cbdc041e82a68419d7581a950f6d7d135ccfe73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_fused_mha_transpose_fusion.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_FUSED_MHA_TRANSPOSE_FUSION_H_ +#define XLA_SERVICE_GPU_CUDNN_FUSED_MHA_TRANSPOSE_FUSION_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +class CudnnFusedMHATransposeFusion : public HloModulePass { + public: + CudnnFusedMHATransposeFusion() = default; + + absl::string_view name() const override { + return "cudnn-fused-multi-headed-attention-transpose-fusion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_FUSED_MHA_TRANSPOSE_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_pad_for_convolutions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_pad_for_convolutions.h new file mode 100644 index 0000000000000000000000000000000000000000..dc403112632eec742e9dd1fdd36928c1d30c4961 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_pad_for_convolutions.h @@ -0,0 +1,53 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_PAD_FOR_CONVOLUTIONS_H_ +#define XLA_SERVICE_GPU_CUDNN_PAD_FOR_CONVOLUTIONS_H_ + +#include "xla/hlo/ir/hlo_casting_utils.h" +#include "xla/literal_util.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/util.h" +#include "xla/window_util.h" + +namespace xla { +namespace gpu { + +// Two zero-paddings for CuDNN thunking are done in this transform: padding for +// tensor cores and padding for integer convolutions. This transform also +// add slice instruction to remove unnecessary output features. +class CudnnPadForConvolutions : public HloModulePass { + public: + explicit CudnnPadForConvolutions(se::CudaComputeCapability compute_capability) + : compute_capability_(compute_capability) {} + + absl::string_view name() const override { + return "cudnn_pad_for_convolutions"; + } + // Run PadForConvolutions on the given module and return if any change is made + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_PAD_FOR_CONVOLUTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_simplify_padding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_simplify_padding.h new file mode 100644 index 0000000000000000000000000000000000000000..67b5d37316ec72ece02622f1275dc74cd75feb0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_simplify_padding.h @@ -0,0 +1,64 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_SIMPLIFY_PADDING_H_ +#define XLA_SERVICE_GPU_CUDNN_SIMPLIFY_PADDING_H_ + +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla::gpu { + +// Simplifies or eliminates padding introduced by CudnnPadForConvolutions and +// CudnnVectorizeConvolutions. +// +// CudnnVectorizeConvolutions will generate code that does the following. +// - pad input and output features to a multiple of 32 (or 4), +// - reshape input from [N,C,H,W] to [N,C/32,H,W,32] and reshape kernel from +// [I,O,H,W] to [I/32,32,O,H,W], +// - run the conv, +// - reshape output from [N,C/32,H,W,32] to [N,C,H,W], and finally +// - slice off the padding on the C channel. +// +// But if this is followed by another convolution (very common), then the slice +// is immediately followed by another pad. This may be redundant; we know that +// the trailing channels sliced off from the first conv are 0. +// +// Ideally we can eliminate the whole reshape+slice+pad+reshape sequence between +// the two convolutions. +// +// Specifically, this pass tries to merge the slice at the end of the sequence +// above into the pad from the next convolution (when we can prove that the +// sliced-off elements are all 0). We then rely on algsimp to remove the pad if +// it's a nop and then to merge and eliminate the remaining reshapes. +// +// This pass should run after CudnnVectorizeConvolutions and there should be no +// simplification passes in between that modify the reshape-transpose-reshape +// introduced by int8x32 convolution filter reordering. +class CudnnSimplifyPadding : public HloModulePass { + public: + CudnnSimplifyPadding() = default; + + absl::string_view name() const override { return "cudnn_simplify_padding"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_CUDNN_SIMPLIFY_PADDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_support_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_support_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0ed4a88bdd21fc17ceeb5ef1966e61e81e19cab9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_support_utils.h @@ -0,0 +1,74 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_SUPPORT_UTILS_H_ +#define XLA_SERVICE_GPU_CUDNN_SUPPORT_UTILS_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/shape.h" +#include "xla/stream_executor/device_description.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// Indicates whether the `compute_capability` supports an optimized integer +// implementation of the given `conv` operation vectorized to `vector_size`. +// +// This function does not guarantee that a convolution will be padded and/or +// vectorized. It only checks that it is a valid candiate for such optimization. +StatusOr CudnnSupportsOptimizedIntegerConvolution( + const se::CudaComputeCapability& compute_capability, + HloCustomCallInstruction& conv, int vector_size); + +// Represents configuration for the reshape-transpose-reshape operations that +// are equivalent to `cudnnReorderFilterAndBias`. This is used by int8x32 +// vectorized convolutions. +// +// For filter reordering the equivalent HLO is: +// %reshape = s8[$S] reshape(%input) +// %transpose = s8[I/32,H,W,O/8,2,8,4,4] transpose(%reshape), dimensions={$D} +// %result = s8[O,I/32,H,W,32] reshape(%transpose) +// +// For bias reordering the HLO is similar, but the op shapes are s8[O/32,4,2,4] +// for %transpose, and s8[O/32,2,4,4] for %result. +// +// The helper functions below calculate the shape $S (transpose_shape) and +// dimensions $D (permutation) from the convolution dimensions numbers config. +// The result_shape is fixed and is present for the convenience. +struct CudnnReorderTransposeConfig { + Shape transpose_shape; + Shape result_shape; + std::vector permutation; +}; + +// Create a transposition for an int8x32 convolution filter that effectively +// does the same thing as cudnnReorderFilterAndBias, but could also be constant +// folded or fused. +StatusOr CudnnInferTransposeForFilterReordering( + const Shape& shape, const ConvolutionDimensionNumbers& dimension_numbers); + +// Create a transposition for an int8x32 convolution bias that effectively +// does the same thing as cudnnReorderFilterAndBias, but could also be constant +// folded or fused. +StatusOr CudnnInferTransposeForBiasReordering( + const Shape& shape); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_SUPPORT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_vectorize_convolutions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_vectorize_convolutions.h new file mode 100644 index 0000000000000000000000000000000000000000..9721125cf23751c25eb5946a5e9a1466aed92bd4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cudnn_vectorize_convolutions.h @@ -0,0 +1,71 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_ +#define XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_ + +#include + +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" + +namespace xla { +namespace gpu { + +// Changes the shape of cudnn convolutions to allow faster "vectorized" +// algorithms. +// +// On sm61+ will convert int8_t convolutions from +// +// - [N, C, H, W] to [N, C/4, H, W, 4], +// +// assuming C is divisible by 4. +// +// On sm75+ will convert int8_t convolutions from +// +// - [N, C, H, W] to [N, C/32, H, W, 32], +// - [N, C/4, H, W, 4] to [N, C/32, H, W, 32], and +// - [N, C, H, W] to [N, C/4, H, W, 4] (same as sm61+), +// +// assuming C is divisible by 4 or 32. +// +// This pass will not pad the channel dim to a multiple of 4 or 32, so you +// should run CudnnPadForConvolutions before this. +class CudnnVectorizeConvolutions : public HloModulePass { + public: + explicit CudnnVectorizeConvolutions( + se::CudaComputeCapability compute_capability, + se::dnn::VersionInfo cudnn_version) + : compute_capability_(compute_capability), + cudnn_version_(cudnn_version) {} + + absl::string_view name() const override { + return "cudnn_vectorize_convolutions"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const se::CudaComputeCapability compute_capability_; + const se::dnn::VersionInfo cudnn_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_context.h new file mode 100644 index 0000000000000000000000000000000000000000..63138f5fd601585f2bf116af811f8e219682b6f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_context.h @@ -0,0 +1,110 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUSOLVER_CONTEXT_H_ +#define XLA_SERVICE_GPU_CUSOLVER_CONTEXT_H_ + +#include +#include + +#define TENSORFLOW_USE_HIPSOLVER \ + (TENSORFLOW_USE_ROCM && (TF_ROCM_VERSION >= 40500)) +#define TENSORFLOW_USE_ROCSOLVER \ + (TENSORFLOW_USE_ROCM && (TF_ROCM_VERSION < 40500)) +#define TENSORFLOW_USE_CUSOLVER_OR_HIPSOLVER \ + (!TENSORFLOW_USE_ROCM || TENSORFLOW_USE_HIPSOLVER) + +#if !TENSORFLOW_USE_ROCM +#include "third_party/gpus/cuda/include/cusolverDn.h" +using gpusolverHandle_t = cusolverDnHandle_t; +#else +#include "rocm/rocm_config.h" +// Macros to ease the transition from rocsolver to hipsolver. +#if TENSORFLOW_USE_HIPSOLVER +#include "xla/stream_executor/rocm/hipsolver_wrapper.h" +using gpusolverHandle_t = hipsolverHandle_t; +#else // TENSORFLOW_USE_ROCSOLVER +#include "xla/stream_executor/rocm/rocblas_wrapper.h" +#include "xla/stream_executor/rocm/rocsolver_wrapper.h" +using gpusolverHandle_t = rocblas_handle; +#endif // TF_ROCM_VERSION >= 40500 +#endif // TENSORFLOW_USE_ROCM + +#include "xla/statusor.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +namespace se = ::stream_executor; + +class GpuSolverContext { + public: + static StatusOr Create(); + + Status SetStream(se::Stream* stream); + + // Computes the Cholesky factorization of multiple matrices. See + // https://docs.nvidia.com/cuda/cusolver/index.html#cuSolverDN-lt-t-gt-batchpotrf + // + // `as` is a list of pointers to the batch_size individual n x n matricies + // that make up the input array. + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory as, int lda, + se::DeviceMemory lapack_info, int batch_size); + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory as, int lda, + se::DeviceMemory lapack_info, int batch_size); + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory*> as, int lda, + se::DeviceMemory lapack_info, int batch_size); + Status PotrfBatched(se::blas::UpperLower uplo, int n, + se::DeviceMemory*> as, int lda, + se::DeviceMemory lapack_info, int batch_size); + + // Returns the max size of the `workspace` required by Potrf and PotrfBatched, + // in number of elements of `type`. + // + // (cusolver's PotrfBatched doesn't require a workspace per se -- it uses the + // input array as scratch. But we do need to materialize the `as` input, and + // we do this in the workspace.) + // + // This is a bit of a hack; we could instead split it up into two functions. + // But at the moment, it's an implementation detail of CholeskyThunk whether + // it calls Potrf or PotrfBatched, so we need to allocate enough scratch space + // for either. + // + // In practice, this does not result in a notable increase in scratch space + // needed, because both cases require a relatively small amount of scratch. + StatusOr PotrfBufferSize(PrimitiveType type, + se::blas::UpperLower uplo, int n, int lda, + int batch_size); + + private: + explicit GpuSolverContext(gpusolverHandle_t handle); + + struct Deleter { + void operator()(gpusolverHandle_t handle); + }; + + std::unique_ptr, Deleter> handle_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUSOLVER_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..9d68cfa15bae1424f6903cfbdd7e9206d2700290 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/cusolver_rewriter.h @@ -0,0 +1,47 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUSOLVER_REWRITER_H_ +#define XLA_SERVICE_GPU_CUSOLVER_REWRITER_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/cusolver_context.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Rewrites Cholesky calls into CustomCall HLOs that call into cuSolver. +class GpusolverRewriter : public HloModulePass { + public: + GpusolverRewriter(); + absl::string_view name() const override { return "gpusolver-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation* computation); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUSOLVER_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/custom_call_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/custom_call_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..329dbf02dfa8f09e341f75e4c7524a6a8cff4632 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/custom_call_thunk.h @@ -0,0 +1,70 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ +#define XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ + +#include "xla/service/custom_call_status_internal.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "xla/stream_executor/gpu/gpu_types.h" +#endif + +namespace xla { +namespace gpu { + +// Thunk to run a GPU custom call. +// +// This thunk's `ExecuteOnStream` implementation executes a host function +// `call_target` which is expected to enqueue operations onto the GPU. +// +// Note that not all kCustomCall HLOs in XLA:GPU end up being run by this thunk. +// XLA itself creates kCustomCall instructions when lowering kConvolution HLOs +// into calls to cudnn. These internally-created custom-calls are run using +// ConvolutionThunk, not CustomCallThunk. There's no ambiguity because they +// have special call target names (e.g. "__cudnn$convForward") that only the +// compiler is allowed to create. +class CustomCallThunk : public Thunk { + public: + using OptionalSlice = ::std::optional; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + using Stream = stream_executor::gpu::GpuStreamHandle; +#else // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + using Stream = void*; +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + + using CustomCallTarget = std::function; + CustomCallThunk(ThunkInfo thunk_info, CustomCallTarget call_target, + std::vector operands, + std::vector results, + const std::string& opaque); + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const CustomCallTarget call_target_; + const std::vector operands_; + const std::vector results_; + const std::string opaque_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_CUSTOM_CALL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/dot_dimension_sorter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/dot_dimension_sorter.h new file mode 100644 index 0000000000000000000000000000000000000000..0a2e19542f0b7429bff4a8fa2e52216a9c468db8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/dot_dimension_sorter.h @@ -0,0 +1,49 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_DOT_DIMENSION_SORTER_H_ +#define XLA_SERVICE_GPU_DOT_DIMENSION_SORTER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Sorts contracting dimensions of dot() operands when this reduces the +// number of transposes. Example: +// dot(p0, p1), lhs_contracting_dims={3,2}, rhs_contracting_dims={2,1} -> +// dot(p0, p1), lhs_contracting_dims={2,3}, rhs_contracting_dims={1,2} +// The first case gets transposes inserted by dot_decomposer, the second one +// does not and thus is generally more efficient. + +// TODO(b/265688934): do the same for batch dimensions? + +class DotDimensionSorter : public HloModulePass { + public: + absl::string_view name() const override { return "dot_dimension_sorter"; } + + // Run the pass on computations in 'module'. + // Returns whether the 'module' was changed. + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_DOT_DIMENSION_SORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..f97861ba2e7afc1e0064452a29726ac4c3409685 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h @@ -0,0 +1,137 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_ELEMENTAL_IR_EMITTER_H_ +#define XLA_SERVICE_GPU_ELEMENTAL_IR_EMITTER_H_ + +#include + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/gpu/target_util.h" +#include "xla/service/hlo_module_config.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +class GpuElementalIrEmitter : public ElementalIrEmitter { + public: + GpuElementalIrEmitter(IrEmitterContext& ir_emitter_context, + llvm::IRBuilder<>* b); + + protected: + llvm_ir::IrArray::Index GetSourceIndexOfBitcast( + const llvm_ir::IrArray::Index& index, const HloInstruction* hlo) override; + + StatusOr EmitFloatBinaryOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value) override; + + StatusOr EmitLog(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitLog1p(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitSin(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitCos(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitTan(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitExp(PrimitiveType prim_type, llvm::Value* value, + absl::string_view name) override; + + StatusOr EmitExpm1(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitSqrt(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitRsqrt(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitPow(PrimitiveType prim_type, llvm::Value* lhs, + llvm::Value* rhs, + absl::string_view name) override; + + StatusOr EmitAtan2(PrimitiveType prim_type, llvm::Value* lhs, + llvm::Value* rhs, + absl::string_view name) override; + + StatusOr EmitTanh(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitComplexAbs(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr EmitCbrt(PrimitiveType prim_type, + llvm::Value* value) override; + + StatusOr> EmitThreadLocalCall( + const HloComputation& callee, absl::Span parameters, + absl::string_view, bool /*is_reducer*/) override; + + llvm::Value* EmitThreadId() override; + + bool fast_min_max() override { + return ir_emitter_context_.debug_options().xla_gpu_enable_fast_min_max(); + } + + private: + // Emits IR for op, which must have opcode kPower. + StatusOr EmitPowerOp(const HloInstruction* op, + llvm::Value* lhs_value, + llvm::Value* rhs_value); + + // Emits IR to call an LLVM intrinsic of type [T] -> T. Adjusts + // callee_name according to T. Returns the IR value that represents the + // return value of the function. + StatusOr EmitLlvmIntrinsicMathCall( + const std::string& callee_name, absl::Span operands, + absl::Span input_types, PrimitiveType output_type); + + // Emits IR to call a device function of type [T] -> T. Adjusts + // callee_name according to T. Returns the IR value that represents the + // return value of the function. + StatusOr EmitDeviceMathCall( + TargetDeviceFunctionID funcid, absl::Span operands, + absl::Span input_types, PrimitiveType output_type, + absl::string_view name = ""); + + // Emits IR to call a function of type [T] -> T. Does not munge callee_name. + // Returns the IR value that represents the return value of the function. + StatusOr EmitMathCall( + const std::string& callee_name, absl::Span operands, + absl::Span input_types, PrimitiveType output_type, + absl::string_view name = ""); + + IrEmitterContext& ir_emitter_context_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_ELEMENTAL_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/executable.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/executable.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..6840eaebe1d68afcf732afac015a58c161b6330e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/executable.pb.h @@ -0,0 +1,935 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/executable.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fexecutable_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fexecutable_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include "xla/service/hlo.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fexecutable_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fexecutable_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fexecutable_2eproto; +namespace xla { +namespace gpu { +class XlaRuntimeGpuExecutableProto; +struct XlaRuntimeGpuExecutableProtoDefaultTypeInternal; +extern XlaRuntimeGpuExecutableProtoDefaultTypeInternal _XlaRuntimeGpuExecutableProto_default_instance_; +class XlaRuntimeGpuExecutableProto_ConstantInfoProto; +struct XlaRuntimeGpuExecutableProto_ConstantInfoProtoDefaultTypeInternal; +extern XlaRuntimeGpuExecutableProto_ConstantInfoProtoDefaultTypeInternal _XlaRuntimeGpuExecutableProto_ConstantInfoProto_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::XlaRuntimeGpuExecutableProto* Arena::CreateMaybeMessage<::xla::gpu::XlaRuntimeGpuExecutableProto>(Arena*); +template<> ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* Arena::CreateMaybeMessage<::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +// =================================================================== + +class XlaRuntimeGpuExecutableProto_ConstantInfoProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto) */ { + public: + inline XlaRuntimeGpuExecutableProto_ConstantInfoProto() : XlaRuntimeGpuExecutableProto_ConstantInfoProto(nullptr) {} + ~XlaRuntimeGpuExecutableProto_ConstantInfoProto() override; + explicit PROTOBUF_CONSTEXPR XlaRuntimeGpuExecutableProto_ConstantInfoProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaRuntimeGpuExecutableProto_ConstantInfoProto(const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from); + XlaRuntimeGpuExecutableProto_ConstantInfoProto(XlaRuntimeGpuExecutableProto_ConstantInfoProto&& from) noexcept + : XlaRuntimeGpuExecutableProto_ConstantInfoProto() { + *this = ::std::move(from); + } + + inline XlaRuntimeGpuExecutableProto_ConstantInfoProto& operator=(const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from) { + CopyFrom(from); + return *this; + } + inline XlaRuntimeGpuExecutableProto_ConstantInfoProto& operator=(XlaRuntimeGpuExecutableProto_ConstantInfoProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const XlaRuntimeGpuExecutableProto_ConstantInfoProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaRuntimeGpuExecutableProto_ConstantInfoProto* internal_default_instance() { + return reinterpret_cast( + &_XlaRuntimeGpuExecutableProto_ConstantInfoProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(XlaRuntimeGpuExecutableProto_ConstantInfoProto& a, XlaRuntimeGpuExecutableProto_ConstantInfoProto& b) { + a.Swap(&b); + } + inline void Swap(XlaRuntimeGpuExecutableProto_ConstantInfoProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(XlaRuntimeGpuExecutableProto_ConstantInfoProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaRuntimeGpuExecutableProto_ConstantInfoProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaRuntimeGpuExecutableProto_ConstantInfoProto& from) { + XlaRuntimeGpuExecutableProto_ConstantInfoProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(XlaRuntimeGpuExecutableProto_ConstantInfoProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto"; + } + protected: + explicit XlaRuntimeGpuExecutableProto_ConstantInfoProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kSymbolNameFieldNumber = 1, + kContentFieldNumber = 2, + kAllocationIndexFieldNumber = 3, + }; + // string symbol_name = 1; + void clear_symbol_name(); + const std::string& symbol_name() const; + template + void set_symbol_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_symbol_name(); + PROTOBUF_NODISCARD std::string* release_symbol_name(); + void set_allocated_symbol_name(std::string* symbol_name); + private: + const std::string& _internal_symbol_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_symbol_name(const std::string& value); + std::string* _internal_mutable_symbol_name(); + public: + + // bytes content = 2; + void clear_content(); + const std::string& content() const; + template + void set_content(ArgT0&& arg0, ArgT... args); + std::string* mutable_content(); + PROTOBUF_NODISCARD std::string* release_content(); + void set_allocated_content(std::string* content); + private: + const std::string& _internal_content() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_content(const std::string& value); + std::string* _internal_mutable_content(); + public: + + // int32 allocation_index = 3; + void clear_allocation_index(); + int32_t allocation_index() const; + void set_allocation_index(int32_t value); + private: + int32_t _internal_allocation_index() const; + void _internal_set_allocation_index(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr symbol_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_; + int32_t allocation_index_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fexecutable_2eproto; +}; +// ------------------------------------------------------------------- + +class XlaRuntimeGpuExecutableProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.XlaRuntimeGpuExecutableProto) */ { + public: + inline XlaRuntimeGpuExecutableProto() : XlaRuntimeGpuExecutableProto(nullptr) {} + ~XlaRuntimeGpuExecutableProto() override; + explicit PROTOBUF_CONSTEXPR XlaRuntimeGpuExecutableProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + XlaRuntimeGpuExecutableProto(const XlaRuntimeGpuExecutableProto& from); + XlaRuntimeGpuExecutableProto(XlaRuntimeGpuExecutableProto&& from) noexcept + : XlaRuntimeGpuExecutableProto() { + *this = ::std::move(from); + } + + inline XlaRuntimeGpuExecutableProto& operator=(const XlaRuntimeGpuExecutableProto& from) { + CopyFrom(from); + return *this; + } + inline XlaRuntimeGpuExecutableProto& operator=(XlaRuntimeGpuExecutableProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const XlaRuntimeGpuExecutableProto& default_instance() { + return *internal_default_instance(); + } + static inline const XlaRuntimeGpuExecutableProto* internal_default_instance() { + return reinterpret_cast( + &_XlaRuntimeGpuExecutableProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(XlaRuntimeGpuExecutableProto& a, XlaRuntimeGpuExecutableProto& b) { + a.Swap(&b); + } + inline void Swap(XlaRuntimeGpuExecutableProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(XlaRuntimeGpuExecutableProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + XlaRuntimeGpuExecutableProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const XlaRuntimeGpuExecutableProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const XlaRuntimeGpuExecutableProto& from) { + XlaRuntimeGpuExecutableProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(XlaRuntimeGpuExecutableProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.XlaRuntimeGpuExecutableProto"; + } + protected: + explicit XlaRuntimeGpuExecutableProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + typedef XlaRuntimeGpuExecutableProto_ConstantInfoProto ConstantInfoProto; + + // accessors ------------------------------------------------------- + + enum : int { + kConstantsFieldNumber = 5, + kGpuAsmTextFieldNumber = 3, + kGpuBinaryFieldNumber = 4, + kXlaRuntimeExecutableFieldNumber = 1, + kEntryFuncAttrsFieldNumber = 2, + }; + // repeated .xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto constants = 5; + int constants_size() const; + private: + int _internal_constants_size() const; + public: + void clear_constants(); + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* mutable_constants(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >* + mutable_constants(); + private: + const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& _internal_constants(int index) const; + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* _internal_add_constants(); + public: + const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& constants(int index) const; + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* add_constants(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >& + constants() const; + + // string gpu_asm_text = 3; + void clear_gpu_asm_text(); + const std::string& gpu_asm_text() const; + template + void set_gpu_asm_text(ArgT0&& arg0, ArgT... args); + std::string* mutable_gpu_asm_text(); + PROTOBUF_NODISCARD std::string* release_gpu_asm_text(); + void set_allocated_gpu_asm_text(std::string* gpu_asm_text); + private: + const std::string& _internal_gpu_asm_text() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_gpu_asm_text(const std::string& value); + std::string* _internal_mutable_gpu_asm_text(); + public: + + // bytes gpu_binary = 4; + void clear_gpu_binary(); + const std::string& gpu_binary() const; + template + void set_gpu_binary(ArgT0&& arg0, ArgT... args); + std::string* mutable_gpu_binary(); + PROTOBUF_NODISCARD std::string* release_gpu_binary(); + void set_allocated_gpu_binary(std::string* gpu_binary); + private: + const std::string& _internal_gpu_binary() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_gpu_binary(const std::string& value); + std::string* _internal_mutable_gpu_binary(); + public: + + // .xla.XlaRuntimeExecutableProto xla_runtime_executable = 1; + bool has_xla_runtime_executable() const; + private: + bool _internal_has_xla_runtime_executable() const; + public: + void clear_xla_runtime_executable(); + const ::xla::XlaRuntimeExecutableProto& xla_runtime_executable() const; + PROTOBUF_NODISCARD ::xla::XlaRuntimeExecutableProto* release_xla_runtime_executable(); + ::xla::XlaRuntimeExecutableProto* mutable_xla_runtime_executable(); + void set_allocated_xla_runtime_executable(::xla::XlaRuntimeExecutableProto* xla_runtime_executable); + private: + const ::xla::XlaRuntimeExecutableProto& _internal_xla_runtime_executable() const; + ::xla::XlaRuntimeExecutableProto* _internal_mutable_xla_runtime_executable(); + public: + void unsafe_arena_set_allocated_xla_runtime_executable( + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable); + ::xla::XlaRuntimeExecutableProto* unsafe_arena_release_xla_runtime_executable(); + + // .xla.EntryFunctionAttributes entry_func_attrs = 2; + bool has_entry_func_attrs() const; + private: + bool _internal_has_entry_func_attrs() const; + public: + void clear_entry_func_attrs(); + const ::xla::EntryFunctionAttributes& entry_func_attrs() const; + PROTOBUF_NODISCARD ::xla::EntryFunctionAttributes* release_entry_func_attrs(); + ::xla::EntryFunctionAttributes* mutable_entry_func_attrs(); + void set_allocated_entry_func_attrs(::xla::EntryFunctionAttributes* entry_func_attrs); + private: + const ::xla::EntryFunctionAttributes& _internal_entry_func_attrs() const; + ::xla::EntryFunctionAttributes* _internal_mutable_entry_func_attrs(); + public: + void unsafe_arena_set_allocated_entry_func_attrs( + ::xla::EntryFunctionAttributes* entry_func_attrs); + ::xla::EntryFunctionAttributes* unsafe_arena_release_entry_func_attrs(); + + // @@protoc_insertion_point(class_scope:xla.gpu.XlaRuntimeGpuExecutableProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto > constants_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr gpu_asm_text_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr gpu_binary_; + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable_; + ::xla::EntryFunctionAttributes* entry_func_attrs_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fexecutable_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// XlaRuntimeGpuExecutableProto_ConstantInfoProto + +// string symbol_name = 1; +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::clear_symbol_name() { + _impl_.symbol_name_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::symbol_name() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) + return _internal_symbol_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_symbol_name(ArgT0&& arg0, ArgT... args) { + + _impl_.symbol_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::mutable_symbol_name() { + std::string* _s = _internal_mutable_symbol_name(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_symbol_name() const { + return _impl_.symbol_name_.Get(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_set_symbol_name(const std::string& value) { + + _impl_.symbol_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_mutable_symbol_name() { + + return _impl_.symbol_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::release_symbol_name() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) + return _impl_.symbol_name_.Release(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_allocated_symbol_name(std::string* symbol_name) { + if (symbol_name != nullptr) { + + } else { + + } + _impl_.symbol_name_.SetAllocated(symbol_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.symbol_name_.IsDefault()) { + _impl_.symbol_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.symbol_name) +} + +// bytes content = 2; +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::clear_content() { + _impl_.content_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::content() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) + return _internal_content(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_content(ArgT0&& arg0, ArgT... args) { + + _impl_.content_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::mutable_content() { + std::string* _s = _internal_mutable_content(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_content() const { + return _impl_.content_.Get(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_set_content(const std::string& value) { + + _impl_.content_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_mutable_content() { + + return _impl_.content_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto_ConstantInfoProto::release_content() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) + return _impl_.content_.Release(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_allocated_content(std::string* content) { + if (content != nullptr) { + + } else { + + } + _impl_.content_.SetAllocated(content, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.content_.IsDefault()) { + _impl_.content_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.content) +} + +// int32 allocation_index = 3; +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::clear_allocation_index() { + _impl_.allocation_index_ = 0; +} +inline int32_t XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_allocation_index() const { + return _impl_.allocation_index_; +} +inline int32_t XlaRuntimeGpuExecutableProto_ConstantInfoProto::allocation_index() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.allocation_index) + return _internal_allocation_index(); +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::_internal_set_allocation_index(int32_t value) { + + _impl_.allocation_index_ = value; +} +inline void XlaRuntimeGpuExecutableProto_ConstantInfoProto::set_allocation_index(int32_t value) { + _internal_set_allocation_index(value); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto.allocation_index) +} + +// ------------------------------------------------------------------- + +// XlaRuntimeGpuExecutableProto + +// .xla.XlaRuntimeExecutableProto xla_runtime_executable = 1; +inline bool XlaRuntimeGpuExecutableProto::_internal_has_xla_runtime_executable() const { + return this != internal_default_instance() && _impl_.xla_runtime_executable_ != nullptr; +} +inline bool XlaRuntimeGpuExecutableProto::has_xla_runtime_executable() const { + return _internal_has_xla_runtime_executable(); +} +inline const ::xla::XlaRuntimeExecutableProto& XlaRuntimeGpuExecutableProto::_internal_xla_runtime_executable() const { + const ::xla::XlaRuntimeExecutableProto* p = _impl_.xla_runtime_executable_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_XlaRuntimeExecutableProto_default_instance_); +} +inline const ::xla::XlaRuntimeExecutableProto& XlaRuntimeGpuExecutableProto::xla_runtime_executable() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) + return _internal_xla_runtime_executable(); +} +inline void XlaRuntimeGpuExecutableProto::unsafe_arena_set_allocated_xla_runtime_executable( + ::xla::XlaRuntimeExecutableProto* xla_runtime_executable) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_runtime_executable_); + } + _impl_.xla_runtime_executable_ = xla_runtime_executable; + if (xla_runtime_executable) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::release_xla_runtime_executable() { + + ::xla::XlaRuntimeExecutableProto* temp = _impl_.xla_runtime_executable_; + _impl_.xla_runtime_executable_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::unsafe_arena_release_xla_runtime_executable() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) + + ::xla::XlaRuntimeExecutableProto* temp = _impl_.xla_runtime_executable_; + _impl_.xla_runtime_executable_ = nullptr; + return temp; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::_internal_mutable_xla_runtime_executable() { + + if (_impl_.xla_runtime_executable_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::XlaRuntimeExecutableProto>(GetArenaForAllocation()); + _impl_.xla_runtime_executable_ = p; + } + return _impl_.xla_runtime_executable_; +} +inline ::xla::XlaRuntimeExecutableProto* XlaRuntimeGpuExecutableProto::mutable_xla_runtime_executable() { + ::xla::XlaRuntimeExecutableProto* _msg = _internal_mutable_xla_runtime_executable(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) + return _msg; +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_xla_runtime_executable(::xla::XlaRuntimeExecutableProto* xla_runtime_executable) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.xla_runtime_executable_); + } + if (xla_runtime_executable) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(xla_runtime_executable)); + if (message_arena != submessage_arena) { + xla_runtime_executable = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, xla_runtime_executable, submessage_arena); + } + + } else { + + } + _impl_.xla_runtime_executable_ = xla_runtime_executable; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.xla_runtime_executable) +} + +// .xla.EntryFunctionAttributes entry_func_attrs = 2; +inline bool XlaRuntimeGpuExecutableProto::_internal_has_entry_func_attrs() const { + return this != internal_default_instance() && _impl_.entry_func_attrs_ != nullptr; +} +inline bool XlaRuntimeGpuExecutableProto::has_entry_func_attrs() const { + return _internal_has_entry_func_attrs(); +} +inline const ::xla::EntryFunctionAttributes& XlaRuntimeGpuExecutableProto::_internal_entry_func_attrs() const { + const ::xla::EntryFunctionAttributes* p = _impl_.entry_func_attrs_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_EntryFunctionAttributes_default_instance_); +} +inline const ::xla::EntryFunctionAttributes& XlaRuntimeGpuExecutableProto::entry_func_attrs() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) + return _internal_entry_func_attrs(); +} +inline void XlaRuntimeGpuExecutableProto::unsafe_arena_set_allocated_entry_func_attrs( + ::xla::EntryFunctionAttributes* entry_func_attrs) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.entry_func_attrs_); + } + _impl_.entry_func_attrs_ = entry_func_attrs; + if (entry_func_attrs) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::release_entry_func_attrs() { + + ::xla::EntryFunctionAttributes* temp = _impl_.entry_func_attrs_; + _impl_.entry_func_attrs_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::unsafe_arena_release_entry_func_attrs() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) + + ::xla::EntryFunctionAttributes* temp = _impl_.entry_func_attrs_; + _impl_.entry_func_attrs_ = nullptr; + return temp; +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::_internal_mutable_entry_func_attrs() { + + if (_impl_.entry_func_attrs_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::EntryFunctionAttributes>(GetArenaForAllocation()); + _impl_.entry_func_attrs_ = p; + } + return _impl_.entry_func_attrs_; +} +inline ::xla::EntryFunctionAttributes* XlaRuntimeGpuExecutableProto::mutable_entry_func_attrs() { + ::xla::EntryFunctionAttributes* _msg = _internal_mutable_entry_func_attrs(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) + return _msg; +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_entry_func_attrs(::xla::EntryFunctionAttributes* entry_func_attrs) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.entry_func_attrs_); + } + if (entry_func_attrs) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(entry_func_attrs)); + if (message_arena != submessage_arena) { + entry_func_attrs = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, entry_func_attrs, submessage_arena); + } + + } else { + + } + _impl_.entry_func_attrs_ = entry_func_attrs; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.entry_func_attrs) +} + +// string gpu_asm_text = 3; +inline void XlaRuntimeGpuExecutableProto::clear_gpu_asm_text() { + _impl_.gpu_asm_text_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto::gpu_asm_text() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) + return _internal_gpu_asm_text(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto::set_gpu_asm_text(ArgT0&& arg0, ArgT... args) { + + _impl_.gpu_asm_text_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) +} +inline std::string* XlaRuntimeGpuExecutableProto::mutable_gpu_asm_text() { + std::string* _s = _internal_mutable_gpu_asm_text(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto::_internal_gpu_asm_text() const { + return _impl_.gpu_asm_text_.Get(); +} +inline void XlaRuntimeGpuExecutableProto::_internal_set_gpu_asm_text(const std::string& value) { + + _impl_.gpu_asm_text_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::_internal_mutable_gpu_asm_text() { + + return _impl_.gpu_asm_text_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::release_gpu_asm_text() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) + return _impl_.gpu_asm_text_.Release(); +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_gpu_asm_text(std::string* gpu_asm_text) { + if (gpu_asm_text != nullptr) { + + } else { + + } + _impl_.gpu_asm_text_.SetAllocated(gpu_asm_text, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.gpu_asm_text_.IsDefault()) { + _impl_.gpu_asm_text_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_asm_text) +} + +// bytes gpu_binary = 4; +inline void XlaRuntimeGpuExecutableProto::clear_gpu_binary() { + _impl_.gpu_binary_.ClearToEmpty(); +} +inline const std::string& XlaRuntimeGpuExecutableProto::gpu_binary() const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) + return _internal_gpu_binary(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void XlaRuntimeGpuExecutableProto::set_gpu_binary(ArgT0&& arg0, ArgT... args) { + + _impl_.gpu_binary_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) +} +inline std::string* XlaRuntimeGpuExecutableProto::mutable_gpu_binary() { + std::string* _s = _internal_mutable_gpu_binary(); + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) + return _s; +} +inline const std::string& XlaRuntimeGpuExecutableProto::_internal_gpu_binary() const { + return _impl_.gpu_binary_.Get(); +} +inline void XlaRuntimeGpuExecutableProto::_internal_set_gpu_binary(const std::string& value) { + + _impl_.gpu_binary_.Set(value, GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::_internal_mutable_gpu_binary() { + + return _impl_.gpu_binary_.Mutable(GetArenaForAllocation()); +} +inline std::string* XlaRuntimeGpuExecutableProto::release_gpu_binary() { + // @@protoc_insertion_point(field_release:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) + return _impl_.gpu_binary_.Release(); +} +inline void XlaRuntimeGpuExecutableProto::set_allocated_gpu_binary(std::string* gpu_binary) { + if (gpu_binary != nullptr) { + + } else { + + } + _impl_.gpu_binary_.SetAllocated(gpu_binary, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.gpu_binary_.IsDefault()) { + _impl_.gpu_binary_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.XlaRuntimeGpuExecutableProto.gpu_binary) +} + +// repeated .xla.gpu.XlaRuntimeGpuExecutableProto.ConstantInfoProto constants = 5; +inline int XlaRuntimeGpuExecutableProto::_internal_constants_size() const { + return _impl_.constants_.size(); +} +inline int XlaRuntimeGpuExecutableProto::constants_size() const { + return _internal_constants_size(); +} +inline void XlaRuntimeGpuExecutableProto::clear_constants() { + _impl_.constants_.Clear(); +} +inline ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* XlaRuntimeGpuExecutableProto::mutable_constants(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _impl_.constants_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >* +XlaRuntimeGpuExecutableProto::mutable_constants() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return &_impl_.constants_; +} +inline const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& XlaRuntimeGpuExecutableProto::_internal_constants(int index) const { + return _impl_.constants_.Get(index); +} +inline const ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto& XlaRuntimeGpuExecutableProto::constants(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _internal_constants(index); +} +inline ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* XlaRuntimeGpuExecutableProto::_internal_add_constants() { + return _impl_.constants_.Add(); +} +inline ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* XlaRuntimeGpuExecutableProto::add_constants() { + ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto* _add = _internal_add_constants(); + // @@protoc_insertion_point(field_add:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::XlaRuntimeGpuExecutableProto_ConstantInfoProto >& +XlaRuntimeGpuExecutableProto::constants() const { + // @@protoc_insertion_point(field_list:xla.gpu.XlaRuntimeGpuExecutableProto.constants) + return _impl_.constants_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fexecutable_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fft_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fft_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..6b2224a7b13f01070c36d2ee8bb32896096491dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fft_thunk.h @@ -0,0 +1,100 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_FFT_THUNK_H_ +#define XLA_SERVICE_GPU_FFT_THUNK_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +struct FftPlan { + // CuFFT thread-safety requires that separate host threads not share plans; + // protect each plan with a mutex. + absl::Mutex mu; + std::unique_ptr plan ABSL_GUARDED_BY(mu); + float scale_factor ABSL_GUARDED_BY(mu); +}; + +class FftPlanCache { + public: + // Returnes Fft plan cached for the given device ordinal or creates a new one. + FftPlan* GetOrCreate(int device_ordinal) { + absl::MutexLock lock(&mu_); + std::unique_ptr& plan = fft_plans_[device_ordinal]; + if (!plan) plan = std::make_unique(); + return plan.get(); + } + + private: + absl::Mutex mu_; + absl::flat_hash_map> fft_plans_ + ABSL_GUARDED_BY(mu_); +}; + +// This class stores everything that StreamExecutor needs to launch an FFT. +// It is generated by IrEmitter. +// +// This is thread-compatible. +class FftThunk : public Thunk { + public: + // Constructs a thunk for launching an FFT on a stream. + // Semantics of null hlo_instruction argument are as in Thunk. + FftThunk(ThunkInfo thunk_info, FftType fft_type, + absl::Span fft_length, + const BufferAllocation::Slice& input_buffer, + const BufferAllocation::Slice& output_buffer, + const Shape& input_shape, const Shape& output_shape); + + FftThunk(const FftThunk&) = delete; // Cannot share fft_plan_ + FftThunk& operator=(const FftThunk&) = delete; // Cannot share fft_plan_ + + // Does the FFT for the thunk on "stream". + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const se::fft::Type fft_type_; + const std::vector fft_length_; + + FftPlanCache fft_plan_cache_; + + const BufferAllocation::Slice input_buffer_; + const BufferAllocation::Slice output_buffer_; + + const Shape input_shape_; + const Shape output_shape_; +}; + +Status RunFft(se::DeviceMemoryBase input, const Shape& input_shape, + se::DeviceMemoryBase output, const Shape& output_shape, + se::fft::Type fft_type, absl::Span fft_length, + int device_ordinal, FftPlanCache* fft_plan_cache, + se::Stream* stream, se::DeviceMemoryAllocator* memory_allocator); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FFT_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/for_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/for_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..13e44ede16fa128e958ffacc5801d0ba6e1528c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/for_thunk.h @@ -0,0 +1,52 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_FOR_THUNK_H_ +#define XLA_SERVICE_GPU_FOR_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/sequential_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// ForThunk executes 'loop_limit' invocations of 'body_thunk_sequence'. +class ForThunk : public Thunk { + public: + ForThunk(ThunkInfo thunk_info, int64_t loop_limit, + std::unique_ptr body_thunk_sequence); + ForThunk(const ForThunk&) = delete; + ForThunk& operator=(const ForThunk&) = delete; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + SequentialThunk* body_thunk_sequence() { return body_thunk_sequence_.get(); } + + private: + const int64_t loop_limit_; + std::unique_ptr body_thunk_sequence_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FOR_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fused_mha_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fused_mha_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..a1db1d23e16c9e2c6d01508d6f4f864e785b2aee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fused_mha_thunk.h @@ -0,0 +1,129 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_FUSED_MHA_THUNK_H_ +#define XLA_SERVICE_GPU_FUSED_MHA_THUNK_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/gpu/gpu_fused_mha_runner.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a DNN +// fMHA. It is generated by IrEmitter. +// +// This is thread-compatible. +class FusedMHAThunk : public Thunk { + public: + // Constructs a thunk for launching a DNN FMHA. + FusedMHAThunk(ThunkInfo thunk_info, GpufMHAConfig config, + BufferAllocation::Slice lhs_bmm1_slice, + BufferAllocation::Slice rhs_bmm1_slice, + BufferAllocation::Slice rhs_bmm2_slice, + BufferAllocation::Slice output_slice, + BufferAllocation::Slice scratch_slice, + BufferAllocation::Slice mask_slice, /* may be null */ + BufferAllocation::Slice bias_slice /* may be null */, + BufferAllocation::Slice activation_slice /* may be null */); + + FusedMHAThunk(const FusedMHAThunk&) = delete; + FusedMHAThunk& operator=(const FusedMHAThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + BufferAllocation::Slice lhs_bmm1_buffer_; + BufferAllocation::Slice rhs_bmm1_buffer_; + BufferAllocation::Slice rhs_bmm2_buffer_; + BufferAllocation::Slice output_buffer_; + BufferAllocation::Slice scratch_buffer_; + BufferAllocation::Slice mask_buffer_; + BufferAllocation::Slice bias_buffer_; + BufferAllocation::Slice activation_buffer_; + + FusedMultiHeadedAttentionRunner& GetOrCreateRunner( + const stream_executor::Stream* stream); + + // FusedMHA config + const GpufMHAConfig config_; + absl::Mutex mu_; + absl::flat_hash_map> + runner_cache_ ABSL_GUARDED_BY(mu_); +}; + +class FusedMHABackwardThunk : public Thunk { + public: + // Constructs a thunk for launching a DNN FMHA backward. + FusedMHABackwardThunk(ThunkInfo thunk_info, GpufMHABackwardConfig config, + BufferAllocation::Slice bmm1_grad_gemm1_rhs_slice, + BufferAllocation::Slice bmm1_grad_gemm2_rhs_slice, + BufferAllocation::Slice bmm2_grad_gemm1_lhs_slice, + BufferAllocation::Slice bmm2_grad_gemm2_rhs_slice, + BufferAllocation::Slice d_output_slice, + BufferAllocation::Slice scratch_slice, + BufferAllocation::Slice d_bmm1_lhs_slice, + BufferAllocation::Slice d_bmm1_rhs_slice, + BufferAllocation::Slice d_bmm2_rhs_slice, + BufferAllocation::Slice d_S_slice, + BufferAllocation::Slice mask_slice, + BufferAllocation::Slice d_bias_slice); + + FusedMHABackwardThunk(const FusedMHABackwardThunk&) = delete; + FusedMHABackwardThunk& operator=(const FusedMHABackwardThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + BufferAllocation::Slice bmm1_grad_gemm1_rhs_buffer_; + BufferAllocation::Slice bmm1_grad_gemm2_rhs_buffer_; + BufferAllocation::Slice bmm2_grad_gemm1_lhs_buffer_; + BufferAllocation::Slice bmm2_grad_gemm2_rhs_buffer_; + BufferAllocation::Slice d_output_buffer_; + BufferAllocation::Slice scratch_buffer_; + BufferAllocation::Slice d_bmm1_lhs_buffer_; + BufferAllocation::Slice d_bmm1_rhs_buffer_; + BufferAllocation::Slice d_bmm2_rhs_buffer_; + BufferAllocation::Slice d_s_buffer_; + BufferAllocation::Slice mask_buffer_; + BufferAllocation::Slice d_bias_buffer_; + + FusedMultiHeadedAttentionBackwardRunner& GetOrCreateRunner( + const stream_executor::Stream* stream); + + // FusedMHA backward config + const GpufMHABackwardConfig config_; + absl::Mutex mu_; + absl::flat_hash_map> + runner_cache_ ABSL_GUARDED_BY(mu_); +}; +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_FUSED_MHA_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_merger.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_merger.h new file mode 100644 index 0000000000000000000000000000000000000000..cefb945ba8a8f9b60613d4e2b6bd49c6505123c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_merger.h @@ -0,0 +1,82 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_FUSION_MERGER_H_ +#define XLA_SERVICE_GPU_FUSION_MERGER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// An HLO pass that attempts to merge fusion instructions to reduce memory +// bandwidth requirements and kernel launch overhead. +// +// Consider the example below. On the left-hand side, op A is the producer and +// ops B and C are its consumers. FusionMerger duplicates producer ops and fuses +// them into all consumers. The result is depicted on the right-hand side below. +// +// p p +// | / \ +// v / \ +// A +fusion+ +fusion+ +// / \ | A' | | A" | +// | | | | | | | | +// v v | v | | v | +// B C | B | | C | +// +------+ +------+ +// +// Op A has been cloned twice and fused with B and C. The kernel launch overhead +// is reduced from 3 to 2. The memory bandwidth requirements may be reduced. +// We trade 1 read of input(A) + 1 write and 2 reads of output(A) for 2 reads of +// input(A). In general the achieveable savings in memory bandwidth depend on +// the differences in memory read and written and the number of consumers. The +// FusionMeger pass takes this into account when making fusion decisions. +// +// The pass traverses the HLO module in reverse post-order (defs before uses). +// Fusion instructions are merged into their users if some conditions are met: +// * The result of merging the fusion instruction into its users would not +// increase bytes transferred. +// * Producer ops are fusible with _all_ consumers. If they are not fusible with +// at least one consumers, they won't be fused at all. +// * Producers are kLoop fusion ops. +// +// None of these restrictions are necessary for correctness. In fact, lifting +// the latter two could be beneficial. + +class FusionMerger : public HloModulePass { + public: + explicit FusionMerger(const se::DeviceDescription& d, + HloCostAnalysis::ShapeSizeFunction f) + : gpu_device_info_(d), shape_size_function_(f) {} + absl::string_view name() const override { return "fusion_merger"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::DeviceDescription gpu_device_info_; + HloCostAnalysis::ShapeSizeFunction shape_size_function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSION_MERGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_pipeline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..cecb1a9809127067365aab14189ddd85c7c16e0f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_pipeline.h @@ -0,0 +1,40 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_FUSION_PIPELINE_H_ +#define XLA_SERVICE_GPU_FUSION_PIPELINE_H_ + +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_pipeline.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Function wrapper around the (non-horizontal) XLA GPU fusion pipeline. +HloPassPipeline FusionPipeline( + const DebugOptions& debug_options, + HloCostAnalysis::ShapeSizeFunction shape_size_bytes_function, + const se::DeviceDescription& gpu_device_info); + +// Function wrapper around the horizontal XLA GPU fusion pipeline. +HloPassPipeline HorizontalFusionPipeline( + const se::DeviceDescription& gpu_device_info); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSION_PIPELINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_wrapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..3dd05047ce3428b801d902ef5038f5e598788778 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusion_wrapper.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSION_WRAPPER_H_ +#define XLA_SERVICE_GPU_FUSION_WRAPPER_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Wraps leftover unfused instruction that are in the entry computation that +// have no LHLO equivalent in fusions containing just that instruction. +class FusionWrapper : public HloModulePass { + public: + absl::string_view name() const override { return "fusion-wrapper"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSION_WRAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/copy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/copy.h new file mode 100644 index 0000000000000000000000000000000000000000..173517d73384c7eae9e36aab5f29bd7a509f3b9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/copy.h @@ -0,0 +1,45 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_COPY_H_ +#define XLA_SERVICE_GPU_FUSIONS_COPY_H_ + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/ir_emitter_context.h" + +namespace xla { +namespace gpu { + +// Special case of a fusion consisting only of a kCopy instruction that can be +// implemented using a memcpy. +class MemcpyFusion : public FusionInterface { + public: + MemcpyFusion(mlir::Value src, mlir::Value dst) : src_(src), dst_(dst) {} + + StatusOr Emit(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + KernelReuseCache& kernel_cache, + llvm::IRBuilder<>*) const final; + + private: + mlir::Value src_; + mlir::Value dst_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_COPY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusion_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusion_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..1cd527d0788081449b8d4edde66555a3d7bf2a6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusion_emitter.h @@ -0,0 +1,88 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_FUSION_EMITTER_H_ +#define XLA_SERVICE_GPU_FUSIONS_FUSION_EMITTER_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/gpu/kernel_reuse_cache.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/llvm_ir/ir_array.h" + +namespace xla { +namespace gpu { + +struct FusionEmissionResult { + std::vector> thunks; +}; + +class FusionInterface { + public: + virtual ~FusionInterface() = default; + + virtual StatusOr Emit( + IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, KernelReuseCache& kernel_cache, + llvm::IRBuilder<>* builder) const = 0; +}; + +class KernelFusionEmitterBase : public FusionInterface { + public: + // The downstream code that is used by this emitter operates on a mix of MLIR + // and HLO classes. Ideally this would not be the case, but it's hard to + // change. + StatusOr Emit(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + KernelReuseCache& kernel_cache, + llvm::IRBuilder<>* builder) const final; + virtual StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const = 0; + + protected: + virtual Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const = 0; + virtual int num_kernels() const { return 1; } +}; + +std::tuple, + std::vector /*outputs*/> +BuildKernelPrototype(IrEmitterContext& ir_emitter_context, + const std::string& suggested_name, + absl::Span arguments, + size_t num_inputs, + const LaunchDimensions& launch_dimensions, + llvm::IRBuilder<>* builder); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_FUSION_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusions.h new file mode 100644 index 0000000000000000000000000000000000000000..1899fea07caa606790d594bd37e88e7d17d403d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/fusions.h @@ -0,0 +1,41 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_FUSIONS_H_ +#define XLA_SERVICE_GPU_FUSIONS_FUSIONS_H_ + +#include +#include + +#include "absl/types/span.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" + +namespace xla { +namespace gpu { + +// Returns the emitter for the given fusion. Returns nullopt if the fusion +// type is not yet supported. +// `allocations` may be empty and `fusion_op` may be nullptr if buffer +// assignment didn't run yet. +std::optional> GetFusionEmitter( + HloFusionAnalysis& analysis, absl::Span allocations, + mlir::lmhlo::FusionOp fusion_op); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_FUSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/in_place_dynamic_update_slice.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/in_place_dynamic_update_slice.h new file mode 100644 index 0000000000000000000000000000000000000000..c6e15c2811b37aa76807bc972b8b0da8fc755de8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/in_place_dynamic_update_slice.h @@ -0,0 +1,77 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_IN_PLACE_DYNAMIC_UPDATE_SLICE_H_ +#define XLA_SERVICE_GPU_FUSIONS_IN_PLACE_DYNAMIC_UPDATE_SLICE_H_ + +#include + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emission_utils.h" + +namespace xla { +namespace gpu { + +// Fusion node where the root is either: +// 1. a dynamic-update-slice op +// 2. a bitcast of a dynamic-update-slice op +// 3. a tuple op returning the result of several dynamic-update-slice ops +// 4. a tuple op returning the result of several bitcast +// dynamic-update-slice ops +// +// Additionally, all the dynamic-update-slice ops have exactly one user. The +// fusion parameter that they update can have users (in addition to the +// dynamic-update-slice op) that read in either +// a. a dynamic-slice corresponding exactly to the slice of the parameter that +// is updated by the dynamic-update-slice op +// b. a dynamic-slice reading in a single element anywhere in the parameter. +// This is only allowed if the dynamic-update-slice op updates a single +// element +// +// In both cases, the additional users must not flow into any other output +// than the dynamic-slice-update corresponding to that particular slice of the +// parameter. +// +// The assumption is that each op's input (i.e. array to update) shares the +// same slice as its output. In this case, we have a special algorithm that +// modifies the output in place without touching the un-updated elements. The +// update slice is assumed to be the exact same for all the +// dynamic-update-slice ops. +class InPlaceDynamicUpdateSliceEmitter : public KernelFusionEmitterBase { + public: + explicit InPlaceDynamicUpdateSliceEmitter(const HloFusionAnalysis& analysis) + : dus_ops_( + GetOutputDefiningDynamicUpdateSlices(analysis.fusion_roots())) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override; + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + std::vector dus_ops_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_IN_PLACE_DYNAMIC_UPDATE_SLICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/input_slices.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/input_slices.h new file mode 100644 index 0000000000000000000000000000000000000000..886e23609732e65ccea2fe873c524ed1505c409a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/input_slices.h @@ -0,0 +1,58 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_INPUT_SLICES_H_ +#define XLA_SERVICE_GPU_FUSIONS_INPUT_SLICES_H_ + +#include + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" + +namespace xla { +namespace gpu { + +// Generates code for input-fusible slices. +// +// Prerequisite: ROOT is either a slice or a tuple of slices. The input shapes +// of all ROOT slices need to be the same while their output shapes can be +// different. On the other hand, the input ranges of slices can be +// overlapping. Further generalization/specialization when the needs are seen +// in the future. +class InputSlicesFusion : public KernelFusionEmitterBase { + public: + explicit InputSlicesFusion(HloFusionAnalysis& analysis) + : analysis_(analysis) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override; + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_INPUT_SLICES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/loop.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/loop.h new file mode 100644 index 0000000000000000000000000000000000000000..6d539355c6a5d326bb3604584e5e832710e6e912 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/loop.h @@ -0,0 +1,55 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_LOOP_H_ +#define XLA_SERVICE_GPU_FUSIONS_LOOP_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emitter_context.h" + +namespace xla { +namespace gpu { + +// Generic loop fusion. +class LoopFusion : public KernelFusionEmitterBase { + public: + explicit LoopFusion(HloFusionAnalysis& analysis) : analysis_(analysis) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override; + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_LOOP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/reduction.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/reduction.h new file mode 100644 index 0000000000000000000000000000000000000000..3b3e7897b2cc69f546bd8353afb62a8a8ef30a03 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/reduction.h @@ -0,0 +1,107 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_REDUCTION_H_ +#define XLA_SERVICE_GPU_FUSIONS_REDUCTION_H_ + +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" + +namespace xla { +namespace gpu { + +// Generates code for reduction to contiguous dimensions. +// +// Row reduction uses the following algorithm described in CUDA-like +// pseudocode: +// +// ``` +// __global__ void reduce(int num_rows, float *in, float out) { +// __shared__ float[32] cache; +// int offset = blockDim.x * blockIdx.x + threadIdx.x; +// if (offset >= num_rows) return; +// int tile_bound = std::min(offset + kTileSizeX, num_rows); +// float accum = 0; +// for (int i=offset; i Emit( + IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, KernelReuseCache& kernel_cache, + llvm::IRBuilder<>* builder) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_REDUCTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/thunk_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/thunk_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0ac5dad3f9009951e4b0df97fb91dba665590a90 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/thunk_util.h @@ -0,0 +1,37 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_THUNK_UTIL_H_ +#define XLA_SERVICE_GPU_FUSIONS_THUNK_UTIL_H_ + +#include +#include + +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/gpu/thunk.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Attempts to build an initializer constant for the given value. Returns an +// empty optional if the value is not a constant. +StatusOr>> BuildConstantInitializerThunk( + IrEmitterContext& ir_emitter_context, mlir::Operation* op, + mlir::Value init_value, mlir::Value dest); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_THUNK_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/tiling_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/tiling_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7765d02de9a6f1e22358968b7a29267589a17de0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/tiling_util.h @@ -0,0 +1,149 @@ +/*Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_TILING_UTIL_H_ +#define XLA_SERVICE_GPU_FUSIONS_TILING_UTIL_H_ + +#include + +#include "xla/service/gpu/kernel_mapping_scheme.h" +#include "xla/service/llvm_ir/ir_array.h" + +namespace xla { +namespace gpu { + +// Contains threading information. Note that for performance we might apply +// thread id "scaling" where the physical thread id (to achieve good SM +// occupancy) will differ from logical thread id. This struct contains +// logical thread ids, along with meta-information about the scaling applied. +struct TilingThreadIdInfo { + TilingThreadIdInfo(llvm::Value* thread_id, llvm::Value* thread_id_x, + llvm::Value* thread_id_y, llvm::Value* lane_id, + llvm::Value* block_id, llvm::Value* scaling) + : thread_id(thread_id), + thread_id_x(thread_id_x), + thread_id_y(thread_id_y), + lane_id(lane_id), + block_id(block_id), + scaling(scaling) {} + + llvm::Value* thread_id; + + // X-coordinate calculated from thread id: `thread_id % num_threads_x` + llvm::Value* thread_id_x; + + // Y-coordinate calculated from thread id: `thread_id / num_threads_x` + llvm::Value* thread_id_y; + + // Lane id: `thread_id % WarpSize` + llvm::Value* lane_id; + + // Block id. + llvm::Value* block_id; + + // Emits GEP into a shared memory, taking virtual thread scaling into + // account. Automatically inserts the first zero required by LLVM GEP. + // Defined on ThreadIdInfo to keep `scaling` private. + // + // Same semantics as CreateInBoundsGEP. + llvm::Value* GEPIntoSharedMemory( + llvm::IRBuilder<>* b, llvm::GlobalVariable* shared, + absl::Span idx_major_to_minor, + const llvm::Twine& name = "") const; + + // Calculate the pointee type of the llvm::Value returned by + // GEPIntoSharedMemory + llvm::Type* GEPIntoSharedMemoryType( + llvm::GlobalVariable* shared, + absl::Span idx_major_to_minor) const; + + private: + llvm::Value* scaling; +}; + +struct TilingKernelInfo { + // Tiling bounds. + std::array output_tile_bounds; + + // Starting tile, as calculated from block id only. + llvm_ir::IrArray::Index tile_origin; + + // Thread meta-info. + TilingThreadIdInfo thread_id_info; +}; + +// A function to generate the code to emit the entire tile. +// +// index: Absolute coordinate of the start of the tile in input. +// tile_dimensions: Size of the tile +using TileElementGenerator = + std::function tile_dimensions)>; + +// A function object to generate code to process one element in a tile. +// +// index: the index for the first output element of the current thread. +// y_loc: The y coordinate within a tile. +// x_loc: The x coordinate within a tile. +using EmitTileElementFunction = + std::function; + +// Emits code to iterate through a 2-dimensional tile with a given tile +// dimensions and given strides, and call the callback at each iteration., +// +// thread_id_y` and `thread_id_x` are the intra-tile coordinates for +// the first element to process, and `index` is the index for the origin of +// the tile. Emits bounds check to ensure that each processed element +// is within the boundary defined by `tile_dimensions`. +// +// Rough pseudocode: +// +// Given: tile_dimensions, x_offset, y_offset +// +// for (y = 0; y < tile_dimensions[0]; y += num_threads_y) { +// for (x = 0; x < tile_dimensions[1]; x++) { +// +// y_pos = y_offset + y +// x_pos = x_offset + x * stride +// +// if (x_loc < tile_width) { +// emit_elem_function(y_offset + y, x_loc); +// } +// } +// } +// +void EmitTile(llvm::IRBuilder<>* builder, const TilingScheme& tiling_scheme, + const llvm_ir::IrArray::Index& tile_origin_index, + const TilingThreadIdInfo& thread_id_info, + std::array tile_dimensions, + const EmitTileElementFunction& emit_elem_function); + +// Emits a kernel for the hlo instruction using the given kernel mapping +// scheme. +StatusOr EmitTilingKernel( + llvm::IRBuilder<>* builder, const TilingScheme& tiling_scheme, + llvm::Type* index_ty, const TileElementGenerator& tile_element_generator); + +llvm_ir::IrArray::Index GetUnnormalizedIndex( + const llvm_ir::IrArray::Index& normalized_shape_index, + const Shape& unnormalized_shape, llvm::IRBuilder<>* builder, + absl::Span dims_in_elems); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_TILING_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/transpose.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/transpose.h new file mode 100644 index 0000000000000000000000000000000000000000..85f7292d524077d6688dc5970346e3169e4da898 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/fusions/transpose.h @@ -0,0 +1,79 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_FUSIONS_TRANSPOSE_H_ +#define XLA_SERVICE_GPU_FUSIONS_TRANSPOSE_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/fusions/fusion_emitter.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emitter_context.h" + +namespace xla { +namespace gpu { + +// Emits a kernel for the given hlo instruction using a tiled 0-2-1 transpose +// algorithm to improve the memory access patterns for the input parameters +// with a shape that is a 0-2-1 transpose of the output tensor shape. The +// caller is responsible for making sure that it is safe to apply the shared +// memory transpose on the input parameters. +// +// For the purpose of tiling, the output tensors have a logical shape of three +// components 0-2-1 while the relevant input parameters have a logical shape +// of three components 0-1-2 in the order major to minor. The x- and y- +// dimensions of the tensors are tiled in square tiles with an edge length +// `kTileSize`. Each thread block of `kTileSize` x `kNumRows` threads +// transposes one tile: each thread copies kTileSize/kNumRows elements from +// the input to a shared memory tile, then the otherwise "regular HLO kernel" +// reads from the shared memory instead of the original input. +// +// This is similar to the following CUDA algorithm in TensorFlow: +// https://goo.gl/MStRV6. +// +// `kTileSize` should usually be same as warp size. We currently choose 32 for +// `kTileSize` and 4 for `kNumRows`. The CUDA algorithm uses 8 for `kNumRows`. +// +// TODO(b/33320379): Here each block transposes 1 tile. It may be more +// efficient to launch fewer blocks so each transposes many tiles. +class TransposeFusion : public KernelFusionEmitterBase { + public: + explicit TransposeFusion(HloFusionAnalysis& analysis) : analysis_(analysis) {} + StatusOr launch_dimensions( + IrEmitterContext& ir_emitter_context, int kernel_index) const override { + return analysis_.GetLaunchDimensions(); + } + + protected: + Status EmitKernel(IrEmitterContext& ir_emitter_context, + ElementalIrEmitter& elemental_emitter, + mlir::lmhlo::FusionOp fusion_op, + const HloFusionInstruction& fusion, + const LaunchDimensions& launch_dims, + std::vector inputs, + std::vector outputs, + llvm::IRBuilder<>* builder, + int kernel_index) const override; + + private: + HloFusionAnalysis& analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_FUSIONS_TRANSPOSE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h new file mode 100644 index 0000000000000000000000000000000000000000..9675d8968bfebf26762361a2d5880eef8e52929b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_algorithm_picker.h @@ -0,0 +1,78 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_GEMM_ALGORITHM_PICKER_H_ +#define XLA_SERVICE_GPU_GEMM_ALGORITHM_PICKER_H_ + +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/autotune_results.pb.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +#if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) +#include "xla/service/gpu/gpu_conv_runner.h" +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#include "xla/stream_executor/gpu/redzone_allocator.h" +#endif + +namespace xla { +namespace gpu { + +StatusOr GetBestBlasAlgorithm( + se::Stream* stream, se::RedzoneAllocator& allocator, + std::optional gemm_str, + const AutotuneConfig& autotune_config, se::DeviceMemoryBase lhs_buffer, + se::DeviceMemoryBase rhs_buffer, se::DeviceMemoryBase output_buffer, + absl::Span algorithms, + const Shape& output_shape, const HloModuleConfig& hlo_module_config, + double beta, + const std::function( + const se::blas::AlgorithmType&)>& run_benchmark); + +// GemmAlgorithmPicker supports two modes: device and deviceless. +// In device mode, we run autotuning on the device and store autotune results. +// In deviceless mode, we pass in some information related to the device and +// use stored autotune results to rewrite Gemm instructions. If the required +// autotune result is not stored, then algorithm is set to kRuntimeAutotuning. +class GemmAlgorithmPicker : public HloModulePass { + public: + explicit GemmAlgorithmPicker(AutotuneConfig config) : config_(config) {} + + absl::string_view name() const override { return "gemm-algorithm-picker"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + AutotuneConfig config_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_ALGORITHM_PICKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_broadcast_folding_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_broadcast_folding_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..46fdc839738768befc3fd25fab706f4c30b37e32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_broadcast_folding_rewriter.h @@ -0,0 +1,51 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_GEMM_BROADCAST_FOLDING_REWRITER_H_ +#define XLA_SERVICE_GPU_GEMM_BROADCAST_FOLDING_REWRITER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// cuBLAS GEMM has support for strided batched calls, where the stride is used +// to determine the offset between the batches. +// +// This allows (kCustomCall:gemm A kBroadcast(B)) or +// (kCustomCall:gemm kBroadcast(A) B) +// to be rewritten as (kCustomCall:gemm A B) with a zero stride for the +// broadcasted operand if the broadcast operates on all the batch dimensions. +// +// This pattern matches the above case and removes the unnecessary broadcast. +class GemmBroadcastFoldingRewriter : public HloModulePass { + public: + absl::string_view name() const override { + return "cublas-gemm-broadcast-folding-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_BROADCAST_FOLDING_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..65efd940450e468ed4424f727351da8ff5b0b2e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter.h @@ -0,0 +1,62 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_GEMM_REWRITER_H_ +#define XLA_SERVICE_GPU_GEMM_REWRITER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// cuBLAS GEMM in the most general form can run the following operation: +// +// (kAdd +// (kMultiply (kDot A B) alpha) +// (kMultiply C beta)) +// +// where A, B, C are matrixes and `alpha` and `beta` are host constants. +// The additional requirement is that C has no other users (otherwise, +// it does not make sense to fuse it inside the custom call). +// +// Both multiplication and addition can be avoided (equivalent to setting +// `alpha` to one and `beta` to zero). +// +// This pass pattern-matches the most general form of this instruction +// (we assume transposes are already folded), and rewrites it into a custom call +// where (A, B, C) are three operands respectively, and `alpha` and `beta` are +// stored in the backend config. +class GemmRewriter : public HloModulePass { + public: + explicit GemmRewriter(se::GpuComputeCapability gpu_version); + absl::string_view name() const override { return "cublas-gemm-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter_triton.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter_triton.h new file mode 100644 index 0000000000000000000000000000000000000000..db52fa54aadb31456780a82e24b3a9273d10caec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_rewriter_triton.h @@ -0,0 +1,173 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_GEMM_REWRITER_TRITON_H_ +#define XLA_SERVICE_GPU_GEMM_REWRITER_TRITON_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/instruction_fusion.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// Tells if f(a+b) == f(a) + f(b). +bool IsDistributiveOverAddition(const HloInstruction& hlo); + +// Allowlist of unary elementwise operations supported by Triton GEMM codegen. +std::vector TritonSupportedUnaryElementwise(PrimitiveType); + +// Allowlist of binary elementwise operations supported by Triton GEMM codegen. +std::vector TritonSupportedBinaryElementwise(PrimitiveType); + +// Allowlist of ternary elementwise operations supported by Triton GEMM codegen. +std::vector TritonSupportedTernaryElementwise(PrimitiveType); + +// Data types that are supported by the Triton emitters. +bool IsTritonSupportedDataType(PrimitiveType, se::GpuComputeCapability); + +// Checks elementwise operation against all supported by Triton GEMM codegen. +bool IsTritonSupportedElementwise(HloOpcode, PrimitiveType); + +// Filters GEMMs which can be handled using Triton. +FusionDecision CanTritonHandleGEMM(const HloInstruction&, + se::GpuComputeCapability gpu_version); + +// Filters GEMMs which are better to handle using Triton. +bool ShouldTritonHandleGEMM(HloInstruction&, + se::GpuComputeCapability gpu_version); + +class TensorIterationSpec { + public: + // Description of basic iteration: `count` elements separated by `stride`. + struct IterationSpecFragment { + int64_t stride; + int64_t count; + int64_t slice_start; + int64_t slice_limit; + // Logical subfragments when this iteration is composed + // of several HLO dimensions. + std::vector subfragments; + + bool is_sliced() const { return count != slice_limit - slice_start; } + bool operator!=(const IterationSpecFragment& other) const; + std::string ToString() const; + }; + // Description of complex iteration over a sequence of several strides. + // Describes a logically contiguous dimension of a tensor physically + // separated into multiple fragments by other dimensions. + using DimIterationSpec = std::vector; + + using StorageType = absl::flat_hash_map; + const DimIterationSpec& operator[](const int dimension) const { + return dim_iteration_specs_.at(dimension); + } + DimIterationSpec& operator[](const int dimension) { + return dim_iteration_specs_[dimension]; + } + const StorageType& Storage() const { return dim_iteration_specs_; } + void RemoveEmptyDimensions() { + absl::erase_if(dim_iteration_specs_, + [](const auto& it) { return it.second.empty(); }); + } + + // Compares physical layouts of tensors ignoring subfragments of dimensions. + bool operator==(const TensorIterationSpec& other) const; + + std::string ToString() const; + + private: + StorageType dim_iteration_specs_; +}; + +// Analysis of tensor iteration orders within tiled fusions. +class TritonFusionAnalysis { + Status ExecuteForDotFusion(const HloInstruction& dot, int split_k); + Status ExecuteForSoftmaxFusion(const HloInstruction& root); + + public: + // Execute the analysis of a fusion computation. + // `split_k` indicates whether this operation was converted to the split-K + // form and tells the analysis how to interpret the batch dimensions. + static StatusOr Execute( + const HloComputation& computation, int split_k = 1); + + // A scope is an HLO graph that can be tiled efficiently using same or + // compatible tile shapes on all operations. GEMM fusion has 3 scopes + // defined by left operand, right operand and output. + enum class Scope { LHS = 0, RHS = 1, OUTPUT = 2 }; + + using IterationSpecByInstructionMap = + ConstHloInstructionMap; + using IterationSpecByInstructionByScopeMap = + std::map; + + // Every parameter requires a separate piece of shared memory for asynchronous + // loads. Multiple parameters are approximately equivalent to multiple + // pipeline stages. + static constexpr int kMaxParameterPerScope = 4; + + // Scope -> HLO -> dot dimension number -> iteration spec at the HLO's output. + const TensorIterationSpec::DimIterationSpec* IterSpec(Scope scope, + const HloInstruction*, + int dimension) const; + // Parameter HLO instructions used in a scope of `dot`. + const ConstHloInstructionSet& ScopeParameters(const Scope scope) const { + return parameters_.at(scope); + } + + std::string ToString() const; + + private: + IterationSpecByInstructionByScopeMap iter_specs_; + // HLO computation parameters per scope. + std::map parameters_; +}; + +// Rewrite compatible dot() calls into custom calls with fused computations +// that target Triton-based matmul emitter. +class GemmRewriterTriton : public HloModulePass { + public: + explicit GemmRewriterTriton(se::GpuComputeCapability gpu_version) + : gpu_version_(gpu_version) {} + absl::string_view name() const override { return "triton-gemm-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_REWRITER_TRITON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..548ff737425557d154f208ae82ea76cdfd8b2cfb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gemm_thunk.h @@ -0,0 +1,57 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GEMM_THUNK_H_ +#define XLA_SERVICE_GPU_GEMM_THUNK_H_ + +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/matmul_utils.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// This is thread-compatible. +class GemmThunk : public Thunk { + public: + // Constructs a thunk that computes "output = (lhs rhs) * alpha" using + // BLAS gemm (alpha is stored in the instruction GemmBackendConfig). + GemmThunk(ThunkInfo thunk_info, GemmConfig config, + const BufferAllocation::Slice& lhs_buffer, + const BufferAllocation::Slice& rhs_buffer, + const BufferAllocation::Slice& output_buffer, bool deterministic); + + GemmThunk(const GemmThunk&) = delete; + GemmThunk& operator=(const GemmThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + + private: + const GemmConfig config_; + const BufferAllocation::Slice lhs_buffer_; + const BufferAllocation::Slice rhs_buffer_; + const BufferAllocation::Slice output_buffer_; + // Whether to run deterministically. + const bool deterministic_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GEMM_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_all_gather_optimizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_all_gather_optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..717c6088f06e4b5f87bcab369a34033fc09fee77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_all_gather_optimizer.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_ALL_GATHER_OPTIMIZER_H_ +#define XLA_SERVICE_GPU_GPU_ALL_GATHER_OPTIMIZER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Transforms binary_op(all-gather(reduce_scatter(a)), +// all-gather(reduce_scatter(b))) to allgather(binary_op(reduce_scatter(a), +// reduce_scatter(b))) + +class AllGatherOptimizer : public HloModulePass { + public: + AllGatherOptimizer() = default; + absl::string_view name() const override { return "all-gather-optimizer"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_ALL_GATHER_OPTIMIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_asm_opts_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_asm_opts_util.h new file mode 100644 index 0000000000000000000000000000000000000000..22a08f8657a99b7006134011a871d9aee3b6581b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_asm_opts_util.h @@ -0,0 +1,32 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_ASM_OPTS_UTIL_H_ +#define XLA_SERVICE_GPU_GPU_ASM_OPTS_UTIL_H_ + +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Create GpuAsmOpts out of DebugOptions. +stream_executor::GpuAsmOpts PtxOptsFromDebugOptions( + const DebugOptions& debug_options); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_ASM_OPTS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_async_collective_annotator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_async_collective_annotator.h new file mode 100644 index 0000000000000000000000000000000000000000..94955ff6395b616826edfa3bff63b36487ac11a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_async_collective_annotator.h @@ -0,0 +1,47 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_ASYNC_COLLECTIVE_ANNOTATOR_H_ +#define XLA_SERVICE_GPU_GPU_ASYNC_COLLECTIVE_ANNOTATOR_H_ + +#include + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Annotate async collectives with CollectiveBackendConfig. +class GpuAsyncCollectiveAnnotator : public HloModulePass { + public: + explicit GpuAsyncCollectiveAnnotator(HloPredicate is_collective_async) + : is_collective_async_(std::move(is_collective_async)) {} + absl::string_view name() const override { + return "gpu-async-collective-annotator"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + HloPredicate is_collective_async_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_ASYNC_COLLECTIVE_ANNOTATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_autotuning.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_autotuning.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..620b191fd4a9cfac804eb7133247471a7ccb6e71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_autotuning.pb.h @@ -0,0 +1,1494 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/gpu_autotuning.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include "xla/autotuning.pb.h" +#include "xla/service/hlo.pb.h" +#include "xla/xla_data.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +namespace xla { +namespace gpu { +class AlgorithmDenylist; +struct AlgorithmDenylistDefaultTypeInternal; +extern AlgorithmDenylistDefaultTypeInternal _AlgorithmDenylist_default_instance_; +class AlgorithmDenylistEntry; +struct AlgorithmDenylistEntryDefaultTypeInternal; +extern AlgorithmDenylistEntryDefaultTypeInternal _AlgorithmDenylistEntry_default_instance_; +class ConvInstructionLog; +struct ConvInstructionLogDefaultTypeInternal; +extern ConvInstructionLogDefaultTypeInternal _ConvInstructionLog_default_instance_; +class DenylistedAlgorithm; +struct DenylistedAlgorithmDefaultTypeInternal; +extern DenylistedAlgorithmDefaultTypeInternal _DenylistedAlgorithm_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::AlgorithmDenylist* Arena::CreateMaybeMessage<::xla::gpu::AlgorithmDenylist>(Arena*); +template<> ::xla::gpu::AlgorithmDenylistEntry* Arena::CreateMaybeMessage<::xla::gpu::AlgorithmDenylistEntry>(Arena*); +template<> ::xla::gpu::ConvInstructionLog* Arena::CreateMaybeMessage<::xla::gpu::ConvInstructionLog>(Arena*); +template<> ::xla::gpu::DenylistedAlgorithm* Arena::CreateMaybeMessage<::xla::gpu::DenylistedAlgorithm>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +// =================================================================== + +class ConvInstructionLog final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.ConvInstructionLog) */ { + public: + inline ConvInstructionLog() : ConvInstructionLog(nullptr) {} + ~ConvInstructionLog() override; + explicit PROTOBUF_CONSTEXPR ConvInstructionLog(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ConvInstructionLog(const ConvInstructionLog& from); + ConvInstructionLog(ConvInstructionLog&& from) noexcept + : ConvInstructionLog() { + *this = ::std::move(from); + } + + inline ConvInstructionLog& operator=(const ConvInstructionLog& from) { + CopyFrom(from); + return *this; + } + inline ConvInstructionLog& operator=(ConvInstructionLog&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const ConvInstructionLog& default_instance() { + return *internal_default_instance(); + } + static inline const ConvInstructionLog* internal_default_instance() { + return reinterpret_cast( + &_ConvInstructionLog_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(ConvInstructionLog& a, ConvInstructionLog& b) { + a.Swap(&b); + } + inline void Swap(ConvInstructionLog* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(ConvInstructionLog* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ConvInstructionLog* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ConvInstructionLog& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ConvInstructionLog& from) { + ConvInstructionLog::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(ConvInstructionLog* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.ConvInstructionLog"; + } + protected: + explicit ConvInstructionLog(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kOperandShapesFieldNumber = 2, + kResultAddressesFieldNumber = 3, + kOperandAddressesFieldNumber = 4, + kInstructionFieldNumber = 1, + }; + // repeated .xla.ShapeProto operand_shapes = 2; + int operand_shapes_size() const; + private: + int _internal_operand_shapes_size() const; + public: + void clear_operand_shapes(); + ::xla::ShapeProto* mutable_operand_shapes(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >* + mutable_operand_shapes(); + private: + const ::xla::ShapeProto& _internal_operand_shapes(int index) const; + ::xla::ShapeProto* _internal_add_operand_shapes(); + public: + const ::xla::ShapeProto& operand_shapes(int index) const; + ::xla::ShapeProto* add_operand_shapes(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >& + operand_shapes() const; + + // repeated uint64 result_addresses = 3; + int result_addresses_size() const; + private: + int _internal_result_addresses_size() const; + public: + void clear_result_addresses(); + private: + uint64_t _internal_result_addresses(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + _internal_result_addresses() const; + void _internal_add_result_addresses(uint64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + _internal_mutable_result_addresses(); + public: + uint64_t result_addresses(int index) const; + void set_result_addresses(int index, uint64_t value); + void add_result_addresses(uint64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + result_addresses() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + mutable_result_addresses(); + + // repeated uint64 operand_addresses = 4; + int operand_addresses_size() const; + private: + int _internal_operand_addresses_size() const; + public: + void clear_operand_addresses(); + private: + uint64_t _internal_operand_addresses(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + _internal_operand_addresses() const; + void _internal_add_operand_addresses(uint64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + _internal_mutable_operand_addresses(); + public: + uint64_t operand_addresses(int index) const; + void set_operand_addresses(int index, uint64_t value); + void add_operand_addresses(uint64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + operand_addresses() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + mutable_operand_addresses(); + + // .xla.HloInstructionProto instruction = 1; + bool has_instruction() const; + private: + bool _internal_has_instruction() const; + public: + void clear_instruction(); + const ::xla::HloInstructionProto& instruction() const; + PROTOBUF_NODISCARD ::xla::HloInstructionProto* release_instruction(); + ::xla::HloInstructionProto* mutable_instruction(); + void set_allocated_instruction(::xla::HloInstructionProto* instruction); + private: + const ::xla::HloInstructionProto& _internal_instruction() const; + ::xla::HloInstructionProto* _internal_mutable_instruction(); + public: + void unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction); + ::xla::HloInstructionProto* unsafe_arena_release_instruction(); + + // @@protoc_insertion_point(class_scope:xla.gpu.ConvInstructionLog) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto > operand_shapes_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t > result_addresses_; + mutable std::atomic _result_addresses_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t > operand_addresses_; + mutable std::atomic _operand_addresses_cached_byte_size_; + ::xla::HloInstructionProto* instruction_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class DenylistedAlgorithm final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.DenylistedAlgorithm) */ { + public: + inline DenylistedAlgorithm() : DenylistedAlgorithm(nullptr) {} + ~DenylistedAlgorithm() override; + explicit PROTOBUF_CONSTEXPR DenylistedAlgorithm(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DenylistedAlgorithm(const DenylistedAlgorithm& from); + DenylistedAlgorithm(DenylistedAlgorithm&& from) noexcept + : DenylistedAlgorithm() { + *this = ::std::move(from); + } + + inline DenylistedAlgorithm& operator=(const DenylistedAlgorithm& from) { + CopyFrom(from); + return *this; + } + inline DenylistedAlgorithm& operator=(DenylistedAlgorithm&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const DenylistedAlgorithm& default_instance() { + return *internal_default_instance(); + } + static inline const DenylistedAlgorithm* internal_default_instance() { + return reinterpret_cast( + &_DenylistedAlgorithm_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(DenylistedAlgorithm& a, DenylistedAlgorithm& b) { + a.Swap(&b); + } + inline void Swap(DenylistedAlgorithm* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(DenylistedAlgorithm* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DenylistedAlgorithm* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DenylistedAlgorithm& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DenylistedAlgorithm& from) { + DenylistedAlgorithm::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(DenylistedAlgorithm* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.DenylistedAlgorithm"; + } + protected: + explicit DenylistedAlgorithm(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kIdFieldNumber = 1, + kTensorOpsFieldNumber = 2, + }; + // int64 id = 1; + void clear_id(); + int64_t id() const; + void set_id(int64_t value); + private: + int64_t _internal_id() const; + void _internal_set_id(int64_t value); + public: + + // bool tensor_ops = 2; + void clear_tensor_ops(); + bool tensor_ops() const; + void set_tensor_ops(bool value); + private: + bool _internal_tensor_ops() const; + void _internal_set_tensor_ops(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.DenylistedAlgorithm) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int64_t id_; + bool tensor_ops_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AlgorithmDenylistEntry final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.AlgorithmDenylistEntry) */ { + public: + inline AlgorithmDenylistEntry() : AlgorithmDenylistEntry(nullptr) {} + ~AlgorithmDenylistEntry() override; + explicit PROTOBUF_CONSTEXPR AlgorithmDenylistEntry(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AlgorithmDenylistEntry(const AlgorithmDenylistEntry& from); + AlgorithmDenylistEntry(AlgorithmDenylistEntry&& from) noexcept + : AlgorithmDenylistEntry() { + *this = ::std::move(from); + } + + inline AlgorithmDenylistEntry& operator=(const AlgorithmDenylistEntry& from) { + CopyFrom(from); + return *this; + } + inline AlgorithmDenylistEntry& operator=(AlgorithmDenylistEntry&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AlgorithmDenylistEntry& default_instance() { + return *internal_default_instance(); + } + static inline const AlgorithmDenylistEntry* internal_default_instance() { + return reinterpret_cast( + &_AlgorithmDenylistEntry_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(AlgorithmDenylistEntry& a, AlgorithmDenylistEntry& b) { + a.Swap(&b); + } + inline void Swap(AlgorithmDenylistEntry* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AlgorithmDenylistEntry* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AlgorithmDenylistEntry* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AlgorithmDenylistEntry& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AlgorithmDenylistEntry& from) { + AlgorithmDenylistEntry::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AlgorithmDenylistEntry* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.AlgorithmDenylistEntry"; + } + protected: + explicit AlgorithmDenylistEntry(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kAlgosFieldNumber = 4, + kHloFieldNumber = 1, + kBlasVersionFieldNumber = 5, + kCcFieldNumber = 2, + kCudnnVersionFieldNumber = 3, + }; + // repeated .xla.gpu.DenylistedAlgorithm algos = 4; + int algos_size() const; + private: + int _internal_algos_size() const; + public: + void clear_algos(); + ::xla::gpu::DenylistedAlgorithm* mutable_algos(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >* + mutable_algos(); + private: + const ::xla::gpu::DenylistedAlgorithm& _internal_algos(int index) const; + ::xla::gpu::DenylistedAlgorithm* _internal_add_algos(); + public: + const ::xla::gpu::DenylistedAlgorithm& algos(int index) const; + ::xla::gpu::DenylistedAlgorithm* add_algos(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >& + algos() const; + + // string hlo = 1; + void clear_hlo(); + const std::string& hlo() const; + template + void set_hlo(ArgT0&& arg0, ArgT... args); + std::string* mutable_hlo(); + PROTOBUF_NODISCARD std::string* release_hlo(); + void set_allocated_hlo(std::string* hlo); + private: + const std::string& _internal_hlo() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_hlo(const std::string& value); + std::string* _internal_mutable_hlo(); + public: + + // string blas_version = 5; + void clear_blas_version(); + const std::string& blas_version() const; + template + void set_blas_version(ArgT0&& arg0, ArgT... args); + std::string* mutable_blas_version(); + PROTOBUF_NODISCARD std::string* release_blas_version(); + void set_allocated_blas_version(std::string* blas_version); + private: + const std::string& _internal_blas_version() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_blas_version(const std::string& value); + std::string* _internal_mutable_blas_version(); + public: + + // .xla.ComputeCapability cc = 2; + bool has_cc() const; + private: + bool _internal_has_cc() const; + public: + void clear_cc(); + const ::xla::ComputeCapability& cc() const; + PROTOBUF_NODISCARD ::xla::ComputeCapability* release_cc(); + ::xla::ComputeCapability* mutable_cc(); + void set_allocated_cc(::xla::ComputeCapability* cc); + private: + const ::xla::ComputeCapability& _internal_cc() const; + ::xla::ComputeCapability* _internal_mutable_cc(); + public: + void unsafe_arena_set_allocated_cc( + ::xla::ComputeCapability* cc); + ::xla::ComputeCapability* unsafe_arena_release_cc(); + + // .xla.CudnnVersion cudnn_version = 3; + bool has_cudnn_version() const; + private: + bool _internal_has_cudnn_version() const; + public: + void clear_cudnn_version(); + const ::xla::CudnnVersion& cudnn_version() const; + PROTOBUF_NODISCARD ::xla::CudnnVersion* release_cudnn_version(); + ::xla::CudnnVersion* mutable_cudnn_version(); + void set_allocated_cudnn_version(::xla::CudnnVersion* cudnn_version); + private: + const ::xla::CudnnVersion& _internal_cudnn_version() const; + ::xla::CudnnVersion* _internal_mutable_cudnn_version(); + public: + void unsafe_arena_set_allocated_cudnn_version( + ::xla::CudnnVersion* cudnn_version); + ::xla::CudnnVersion* unsafe_arena_release_cudnn_version(); + + // @@protoc_insertion_point(class_scope:xla.gpu.AlgorithmDenylistEntry) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm > algos_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr hlo_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr blas_version_; + ::xla::ComputeCapability* cc_; + ::xla::CudnnVersion* cudnn_version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// ------------------------------------------------------------------- + +class AlgorithmDenylist final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.AlgorithmDenylist) */ { + public: + inline AlgorithmDenylist() : AlgorithmDenylist(nullptr) {} + ~AlgorithmDenylist() override; + explicit PROTOBUF_CONSTEXPR AlgorithmDenylist(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AlgorithmDenylist(const AlgorithmDenylist& from); + AlgorithmDenylist(AlgorithmDenylist&& from) noexcept + : AlgorithmDenylist() { + *this = ::std::move(from); + } + + inline AlgorithmDenylist& operator=(const AlgorithmDenylist& from) { + CopyFrom(from); + return *this; + } + inline AlgorithmDenylist& operator=(AlgorithmDenylist&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const AlgorithmDenylist& default_instance() { + return *internal_default_instance(); + } + static inline const AlgorithmDenylist* internal_default_instance() { + return reinterpret_cast( + &_AlgorithmDenylist_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(AlgorithmDenylist& a, AlgorithmDenylist& b) { + a.Swap(&b); + } + inline void Swap(AlgorithmDenylist* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(AlgorithmDenylist* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AlgorithmDenylist* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AlgorithmDenylist& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AlgorithmDenylist& from) { + AlgorithmDenylist::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(AlgorithmDenylist* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.AlgorithmDenylist"; + } + protected: + explicit AlgorithmDenylist(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kEntriesFieldNumber = 1, + }; + // repeated .xla.gpu.AlgorithmDenylistEntry entries = 1; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + ::xla::gpu::AlgorithmDenylistEntry* mutable_entries(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >* + mutable_entries(); + private: + const ::xla::gpu::AlgorithmDenylistEntry& _internal_entries(int index) const; + ::xla::gpu::AlgorithmDenylistEntry* _internal_add_entries(); + public: + const ::xla::gpu::AlgorithmDenylistEntry& entries(int index) const; + ::xla::gpu::AlgorithmDenylistEntry* add_entries(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >& + entries() const; + + // @@protoc_insertion_point(class_scope:xla.gpu.AlgorithmDenylist) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry > entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// ConvInstructionLog + +// .xla.HloInstructionProto instruction = 1; +inline bool ConvInstructionLog::_internal_has_instruction() const { + return this != internal_default_instance() && _impl_.instruction_ != nullptr; +} +inline bool ConvInstructionLog::has_instruction() const { + return _internal_has_instruction(); +} +inline const ::xla::HloInstructionProto& ConvInstructionLog::_internal_instruction() const { + const ::xla::HloInstructionProto* p = _impl_.instruction_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloInstructionProto_default_instance_); +} +inline const ::xla::HloInstructionProto& ConvInstructionLog::instruction() const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.instruction) + return _internal_instruction(); +} +inline void ConvInstructionLog::unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + _impl_.instruction_ = instruction; + if (instruction) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.ConvInstructionLog.instruction) +} +inline ::xla::HloInstructionProto* ConvInstructionLog::release_instruction() { + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::HloInstructionProto* ConvInstructionLog::unsafe_arena_release_instruction() { + // @@protoc_insertion_point(field_release:xla.gpu.ConvInstructionLog.instruction) + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = nullptr; + return temp; +} +inline ::xla::HloInstructionProto* ConvInstructionLog::_internal_mutable_instruction() { + + if (_impl_.instruction_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloInstructionProto>(GetArenaForAllocation()); + _impl_.instruction_ = p; + } + return _impl_.instruction_; +} +inline ::xla::HloInstructionProto* ConvInstructionLog::mutable_instruction() { + ::xla::HloInstructionProto* _msg = _internal_mutable_instruction(); + // @@protoc_insertion_point(field_mutable:xla.gpu.ConvInstructionLog.instruction) + return _msg; +} +inline void ConvInstructionLog::set_allocated_instruction(::xla::HloInstructionProto* instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + if (instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(instruction)); + if (message_arena != submessage_arena) { + instruction = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, instruction, submessage_arena); + } + + } else { + + } + _impl_.instruction_ = instruction; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.ConvInstructionLog.instruction) +} + +// repeated .xla.ShapeProto operand_shapes = 2; +inline int ConvInstructionLog::_internal_operand_shapes_size() const { + return _impl_.operand_shapes_.size(); +} +inline int ConvInstructionLog::operand_shapes_size() const { + return _internal_operand_shapes_size(); +} +inline ::xla::ShapeProto* ConvInstructionLog::mutable_operand_shapes(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.ConvInstructionLog.operand_shapes) + return _impl_.operand_shapes_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >* +ConvInstructionLog::mutable_operand_shapes() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.ConvInstructionLog.operand_shapes) + return &_impl_.operand_shapes_; +} +inline const ::xla::ShapeProto& ConvInstructionLog::_internal_operand_shapes(int index) const { + return _impl_.operand_shapes_.Get(index); +} +inline const ::xla::ShapeProto& ConvInstructionLog::operand_shapes(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.operand_shapes) + return _internal_operand_shapes(index); +} +inline ::xla::ShapeProto* ConvInstructionLog::_internal_add_operand_shapes() { + return _impl_.operand_shapes_.Add(); +} +inline ::xla::ShapeProto* ConvInstructionLog::add_operand_shapes() { + ::xla::ShapeProto* _add = _internal_add_operand_shapes(); + // @@protoc_insertion_point(field_add:xla.gpu.ConvInstructionLog.operand_shapes) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::ShapeProto >& +ConvInstructionLog::operand_shapes() const { + // @@protoc_insertion_point(field_list:xla.gpu.ConvInstructionLog.operand_shapes) + return _impl_.operand_shapes_; +} + +// repeated uint64 result_addresses = 3; +inline int ConvInstructionLog::_internal_result_addresses_size() const { + return _impl_.result_addresses_.size(); +} +inline int ConvInstructionLog::result_addresses_size() const { + return _internal_result_addresses_size(); +} +inline void ConvInstructionLog::clear_result_addresses() { + _impl_.result_addresses_.Clear(); +} +inline uint64_t ConvInstructionLog::_internal_result_addresses(int index) const { + return _impl_.result_addresses_.Get(index); +} +inline uint64_t ConvInstructionLog::result_addresses(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.result_addresses) + return _internal_result_addresses(index); +} +inline void ConvInstructionLog::set_result_addresses(int index, uint64_t value) { + _impl_.result_addresses_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.gpu.ConvInstructionLog.result_addresses) +} +inline void ConvInstructionLog::_internal_add_result_addresses(uint64_t value) { + _impl_.result_addresses_.Add(value); +} +inline void ConvInstructionLog::add_result_addresses(uint64_t value) { + _internal_add_result_addresses(value); + // @@protoc_insertion_point(field_add:xla.gpu.ConvInstructionLog.result_addresses) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::_internal_result_addresses() const { + return _impl_.result_addresses_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::result_addresses() const { + // @@protoc_insertion_point(field_list:xla.gpu.ConvInstructionLog.result_addresses) + return _internal_result_addresses(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::_internal_mutable_result_addresses() { + return &_impl_.result_addresses_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::mutable_result_addresses() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.ConvInstructionLog.result_addresses) + return _internal_mutable_result_addresses(); +} + +// repeated uint64 operand_addresses = 4; +inline int ConvInstructionLog::_internal_operand_addresses_size() const { + return _impl_.operand_addresses_.size(); +} +inline int ConvInstructionLog::operand_addresses_size() const { + return _internal_operand_addresses_size(); +} +inline void ConvInstructionLog::clear_operand_addresses() { + _impl_.operand_addresses_.Clear(); +} +inline uint64_t ConvInstructionLog::_internal_operand_addresses(int index) const { + return _impl_.operand_addresses_.Get(index); +} +inline uint64_t ConvInstructionLog::operand_addresses(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.ConvInstructionLog.operand_addresses) + return _internal_operand_addresses(index); +} +inline void ConvInstructionLog::set_operand_addresses(int index, uint64_t value) { + _impl_.operand_addresses_.Set(index, value); + // @@protoc_insertion_point(field_set:xla.gpu.ConvInstructionLog.operand_addresses) +} +inline void ConvInstructionLog::_internal_add_operand_addresses(uint64_t value) { + _impl_.operand_addresses_.Add(value); +} +inline void ConvInstructionLog::add_operand_addresses(uint64_t value) { + _internal_add_operand_addresses(value); + // @@protoc_insertion_point(field_add:xla.gpu.ConvInstructionLog.operand_addresses) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::_internal_operand_addresses() const { + return _impl_.operand_addresses_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +ConvInstructionLog::operand_addresses() const { + // @@protoc_insertion_point(field_list:xla.gpu.ConvInstructionLog.operand_addresses) + return _internal_operand_addresses(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::_internal_mutable_operand_addresses() { + return &_impl_.operand_addresses_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +ConvInstructionLog::mutable_operand_addresses() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.ConvInstructionLog.operand_addresses) + return _internal_mutable_operand_addresses(); +} + +// ------------------------------------------------------------------- + +// DenylistedAlgorithm + +// int64 id = 1; +inline void DenylistedAlgorithm::clear_id() { + _impl_.id_ = int64_t{0}; +} +inline int64_t DenylistedAlgorithm::_internal_id() const { + return _impl_.id_; +} +inline int64_t DenylistedAlgorithm::id() const { + // @@protoc_insertion_point(field_get:xla.gpu.DenylistedAlgorithm.id) + return _internal_id(); +} +inline void DenylistedAlgorithm::_internal_set_id(int64_t value) { + + _impl_.id_ = value; +} +inline void DenylistedAlgorithm::set_id(int64_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:xla.gpu.DenylistedAlgorithm.id) +} + +// bool tensor_ops = 2; +inline void DenylistedAlgorithm::clear_tensor_ops() { + _impl_.tensor_ops_ = false; +} +inline bool DenylistedAlgorithm::_internal_tensor_ops() const { + return _impl_.tensor_ops_; +} +inline bool DenylistedAlgorithm::tensor_ops() const { + // @@protoc_insertion_point(field_get:xla.gpu.DenylistedAlgorithm.tensor_ops) + return _internal_tensor_ops(); +} +inline void DenylistedAlgorithm::_internal_set_tensor_ops(bool value) { + + _impl_.tensor_ops_ = value; +} +inline void DenylistedAlgorithm::set_tensor_ops(bool value) { + _internal_set_tensor_ops(value); + // @@protoc_insertion_point(field_set:xla.gpu.DenylistedAlgorithm.tensor_ops) +} + +// ------------------------------------------------------------------- + +// AlgorithmDenylistEntry + +// string hlo = 1; +inline void AlgorithmDenylistEntry::clear_hlo() { + _impl_.hlo_.ClearToEmpty(); +} +inline const std::string& AlgorithmDenylistEntry::hlo() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.hlo) + return _internal_hlo(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AlgorithmDenylistEntry::set_hlo(ArgT0&& arg0, ArgT... args) { + + _impl_.hlo_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.AlgorithmDenylistEntry.hlo) +} +inline std::string* AlgorithmDenylistEntry::mutable_hlo() { + std::string* _s = _internal_mutable_hlo(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.hlo) + return _s; +} +inline const std::string& AlgorithmDenylistEntry::_internal_hlo() const { + return _impl_.hlo_.Get(); +} +inline void AlgorithmDenylistEntry::_internal_set_hlo(const std::string& value) { + + _impl_.hlo_.Set(value, GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::_internal_mutable_hlo() { + + return _impl_.hlo_.Mutable(GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::release_hlo() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.hlo) + return _impl_.hlo_.Release(); +} +inline void AlgorithmDenylistEntry::set_allocated_hlo(std::string* hlo) { + if (hlo != nullptr) { + + } else { + + } + _impl_.hlo_.SetAllocated(hlo, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.hlo_.IsDefault()) { + _impl_.hlo_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.AlgorithmDenylistEntry.hlo) +} + +// .xla.ComputeCapability cc = 2; +inline bool AlgorithmDenylistEntry::_internal_has_cc() const { + return this != internal_default_instance() && _impl_.cc_ != nullptr; +} +inline bool AlgorithmDenylistEntry::has_cc() const { + return _internal_has_cc(); +} +inline const ::xla::ComputeCapability& AlgorithmDenylistEntry::_internal_cc() const { + const ::xla::ComputeCapability* p = _impl_.cc_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_ComputeCapability_default_instance_); +} +inline const ::xla::ComputeCapability& AlgorithmDenylistEntry::cc() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.cc) + return _internal_cc(); +} +inline void AlgorithmDenylistEntry::unsafe_arena_set_allocated_cc( + ::xla::ComputeCapability* cc) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cc_); + } + _impl_.cc_ = cc; + if (cc) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.AlgorithmDenylistEntry.cc) +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::release_cc() { + + ::xla::ComputeCapability* temp = _impl_.cc_; + _impl_.cc_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::unsafe_arena_release_cc() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.cc) + + ::xla::ComputeCapability* temp = _impl_.cc_; + _impl_.cc_ = nullptr; + return temp; +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::_internal_mutable_cc() { + + if (_impl_.cc_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::ComputeCapability>(GetArenaForAllocation()); + _impl_.cc_ = p; + } + return _impl_.cc_; +} +inline ::xla::ComputeCapability* AlgorithmDenylistEntry::mutable_cc() { + ::xla::ComputeCapability* _msg = _internal_mutable_cc(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.cc) + return _msg; +} +inline void AlgorithmDenylistEntry::set_allocated_cc(::xla::ComputeCapability* cc) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cc_); + } + if (cc) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(cc)); + if (message_arena != submessage_arena) { + cc = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, cc, submessage_arena); + } + + } else { + + } + _impl_.cc_ = cc; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.AlgorithmDenylistEntry.cc) +} + +// .xla.CudnnVersion cudnn_version = 3; +inline bool AlgorithmDenylistEntry::_internal_has_cudnn_version() const { + return this != internal_default_instance() && _impl_.cudnn_version_ != nullptr; +} +inline bool AlgorithmDenylistEntry::has_cudnn_version() const { + return _internal_has_cudnn_version(); +} +inline const ::xla::CudnnVersion& AlgorithmDenylistEntry::_internal_cudnn_version() const { + const ::xla::CudnnVersion* p = _impl_.cudnn_version_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_CudnnVersion_default_instance_); +} +inline const ::xla::CudnnVersion& AlgorithmDenylistEntry::cudnn_version() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.cudnn_version) + return _internal_cudnn_version(); +} +inline void AlgorithmDenylistEntry::unsafe_arena_set_allocated_cudnn_version( + ::xla::CudnnVersion* cudnn_version) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cudnn_version_); + } + _impl_.cudnn_version_ = cudnn_version; + if (cudnn_version) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.AlgorithmDenylistEntry.cudnn_version) +} +inline ::xla::CudnnVersion* AlgorithmDenylistEntry::release_cudnn_version() { + + ::xla::CudnnVersion* temp = _impl_.cudnn_version_; + _impl_.cudnn_version_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::CudnnVersion* AlgorithmDenylistEntry::unsafe_arena_release_cudnn_version() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.cudnn_version) + + ::xla::CudnnVersion* temp = _impl_.cudnn_version_; + _impl_.cudnn_version_ = nullptr; + return temp; +} +inline ::xla::CudnnVersion* AlgorithmDenylistEntry::_internal_mutable_cudnn_version() { + + if (_impl_.cudnn_version_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::CudnnVersion>(GetArenaForAllocation()); + _impl_.cudnn_version_ = p; + } + return _impl_.cudnn_version_; +} +inline ::xla::CudnnVersion* AlgorithmDenylistEntry::mutable_cudnn_version() { + ::xla::CudnnVersion* _msg = _internal_mutable_cudnn_version(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.cudnn_version) + return _msg; +} +inline void AlgorithmDenylistEntry::set_allocated_cudnn_version(::xla::CudnnVersion* cudnn_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.cudnn_version_); + } + if (cudnn_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(cudnn_version)); + if (message_arena != submessage_arena) { + cudnn_version = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, cudnn_version, submessage_arena); + } + + } else { + + } + _impl_.cudnn_version_ = cudnn_version; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.AlgorithmDenylistEntry.cudnn_version) +} + +// string blas_version = 5; +inline void AlgorithmDenylistEntry::clear_blas_version() { + _impl_.blas_version_.ClearToEmpty(); +} +inline const std::string& AlgorithmDenylistEntry::blas_version() const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.blas_version) + return _internal_blas_version(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AlgorithmDenylistEntry::set_blas_version(ArgT0&& arg0, ArgT... args) { + + _impl_.blas_version_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:xla.gpu.AlgorithmDenylistEntry.blas_version) +} +inline std::string* AlgorithmDenylistEntry::mutable_blas_version() { + std::string* _s = _internal_mutable_blas_version(); + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.blas_version) + return _s; +} +inline const std::string& AlgorithmDenylistEntry::_internal_blas_version() const { + return _impl_.blas_version_.Get(); +} +inline void AlgorithmDenylistEntry::_internal_set_blas_version(const std::string& value) { + + _impl_.blas_version_.Set(value, GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::_internal_mutable_blas_version() { + + return _impl_.blas_version_.Mutable(GetArenaForAllocation()); +} +inline std::string* AlgorithmDenylistEntry::release_blas_version() { + // @@protoc_insertion_point(field_release:xla.gpu.AlgorithmDenylistEntry.blas_version) + return _impl_.blas_version_.Release(); +} +inline void AlgorithmDenylistEntry::set_allocated_blas_version(std::string* blas_version) { + if (blas_version != nullptr) { + + } else { + + } + _impl_.blas_version_.SetAllocated(blas_version, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.blas_version_.IsDefault()) { + _impl_.blas_version_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:xla.gpu.AlgorithmDenylistEntry.blas_version) +} + +// repeated .xla.gpu.DenylistedAlgorithm algos = 4; +inline int AlgorithmDenylistEntry::_internal_algos_size() const { + return _impl_.algos_.size(); +} +inline int AlgorithmDenylistEntry::algos_size() const { + return _internal_algos_size(); +} +inline void AlgorithmDenylistEntry::clear_algos() { + _impl_.algos_.Clear(); +} +inline ::xla::gpu::DenylistedAlgorithm* AlgorithmDenylistEntry::mutable_algos(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylistEntry.algos) + return _impl_.algos_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >* +AlgorithmDenylistEntry::mutable_algos() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.AlgorithmDenylistEntry.algos) + return &_impl_.algos_; +} +inline const ::xla::gpu::DenylistedAlgorithm& AlgorithmDenylistEntry::_internal_algos(int index) const { + return _impl_.algos_.Get(index); +} +inline const ::xla::gpu::DenylistedAlgorithm& AlgorithmDenylistEntry::algos(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylistEntry.algos) + return _internal_algos(index); +} +inline ::xla::gpu::DenylistedAlgorithm* AlgorithmDenylistEntry::_internal_add_algos() { + return _impl_.algos_.Add(); +} +inline ::xla::gpu::DenylistedAlgorithm* AlgorithmDenylistEntry::add_algos() { + ::xla::gpu::DenylistedAlgorithm* _add = _internal_add_algos(); + // @@protoc_insertion_point(field_add:xla.gpu.AlgorithmDenylistEntry.algos) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::DenylistedAlgorithm >& +AlgorithmDenylistEntry::algos() const { + // @@protoc_insertion_point(field_list:xla.gpu.AlgorithmDenylistEntry.algos) + return _impl_.algos_; +} + +// ------------------------------------------------------------------- + +// AlgorithmDenylist + +// repeated .xla.gpu.AlgorithmDenylistEntry entries = 1; +inline int AlgorithmDenylist::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int AlgorithmDenylist::entries_size() const { + return _internal_entries_size(); +} +inline void AlgorithmDenylist::clear_entries() { + _impl_.entries_.Clear(); +} +inline ::xla::gpu::AlgorithmDenylistEntry* AlgorithmDenylist::mutable_entries(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.AlgorithmDenylist.entries) + return _impl_.entries_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >* +AlgorithmDenylist::mutable_entries() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.AlgorithmDenylist.entries) + return &_impl_.entries_; +} +inline const ::xla::gpu::AlgorithmDenylistEntry& AlgorithmDenylist::_internal_entries(int index) const { + return _impl_.entries_.Get(index); +} +inline const ::xla::gpu::AlgorithmDenylistEntry& AlgorithmDenylist::entries(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.AlgorithmDenylist.entries) + return _internal_entries(index); +} +inline ::xla::gpu::AlgorithmDenylistEntry* AlgorithmDenylist::_internal_add_entries() { + return _impl_.entries_.Add(); +} +inline ::xla::gpu::AlgorithmDenylistEntry* AlgorithmDenylist::add_entries() { + ::xla::gpu::AlgorithmDenylistEntry* _add = _internal_add_entries(); + // @@protoc_insertion_point(field_add:xla.gpu.AlgorithmDenylist.entries) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::AlgorithmDenylistEntry >& +AlgorithmDenylist::entries() const { + // @@protoc_insertion_point(field_list:xla.gpu.AlgorithmDenylist.entries) + return _impl_.entries_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fgpu_5fautotuning_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..d4d500d352c6033b4d6d7e7099fcd87a79516dc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_compiler.h @@ -0,0 +1,260 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_COMPILER_H_ +#define XLA_SERVICE_GPU_GPU_COMPILER_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/autotune_results.pb.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/executable.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/gpu/buffer_sharing.h" +#include "xla/service/gpu/executable.pb.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/gpu/gpu_target_config.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_pass_pipeline.h" +#include "xla/service/llvm_compiler.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +// TODO(b/232263665): It should be shared between GPU and CPU. +class GpuXlaRuntimeAotCompilationResult : public AotCompilationResult { + public: + GpuXlaRuntimeAotCompilationResult( + HloModuleProto hlo, std::string_view obj_file, + std::string_view mlir_module, EntryFunctionAttributes entry_func_attrs, + std::string_view gpu_asm_text, absl::Span gpu_binary, + absl::Span constants = {}) { + XlaRuntimeExecutableProto xla_runtime_executable; + *xla_runtime_executable.mutable_hlo_module_proto() = hlo; + xla_runtime_executable.set_obj_file(std::string(obj_file)); + xla_runtime_executable.set_mlir_module(std::string(mlir_module)); + *xla_runtime_gpu_executable_.mutable_xla_runtime_executable() = + xla_runtime_executable; + + *xla_runtime_gpu_executable_.mutable_entry_func_attrs() = entry_func_attrs; + xla_runtime_gpu_executable_.set_gpu_asm_text(std::string(gpu_asm_text)); + xla_runtime_gpu_executable_.set_gpu_binary(gpu_binary.data(), + gpu_binary.size()); + + for (const GpuExecutable::ConstantInfo& cst : constants) { + auto* cst_proto = xla_runtime_gpu_executable_.add_constants(); + cst_proto->set_symbol_name(cst.symbol_name); + cst_proto->set_allocation_index(cst.allocation_index); + cst_proto->set_content(cst.content.data(), cst.content.size()); + } + } + + explicit GpuXlaRuntimeAotCompilationResult( + XlaRuntimeGpuExecutableProto executable) + : xla_runtime_gpu_executable_(executable) {} + + StatusOr SerializeAsString() const override { + return xla_runtime_gpu_executable_.SerializeAsString(); + } + + static StatusOr> + FromString(const std::string& serialized) { + XlaRuntimeGpuExecutableProto xla_runtime_gpu_executable; + if (!xla_runtime_gpu_executable.ParseFromString(serialized)) { + return InternalError("Failed to parse serialized JitRtExecutableProto."); + } + return std::make_unique( + xla_runtime_gpu_executable); + } + + StatusOr> LoadExecutable( + Compiler* compiler, se::StreamExecutor* executor) const override; + + private: + XlaRuntimeGpuExecutableProto xla_runtime_gpu_executable_; +}; + +// The GPU compiler generates efficient GPU executables. +class GpuCompiler : public LLVMCompiler { + public: + GpuCompiler(se::Platform::Id platform_id, const char* target_triple, + const char* data_layout); + + using LLVMCompiler::Compile; + + // An attached device is passed in via stream_exec. We get GPU configuration + // from the attached device. GemmAlgorithmPicker and GpuConvAlgorithmPicker + // can run on the attached device. + StatusOr> RunHloPasses( + std::unique_ptr module, se::StreamExecutor* stream_exec, + const CompileOptions& options) override; + + // Run HloPasses without an attached deivce. So GemmAlgorithmPicker and + // GpuConvAlgorithmPicker can not run. + StatusOr> RunHloPassesWithoutDevice( + std::unique_ptr module, const CompileOptions& options, + const GpuTargetConfig& gpu_target_config, + const AutotuneResults& autotune_results); + + StatusOr> AssignBuffers( + HloModule* hlo_module, se::StreamExecutor* stream_exec) override; + + se::GpuComputeCapability GetGpuVersion(se::StreamExecutor* stream_exec); + + GpuTargetConfig GetGpuTargetConfig(se::StreamExecutor* stream_exec) { + return GpuTargetConfig(stream_exec); + } + + StatusOr> RunBackend( + std::unique_ptr module, se::StreamExecutor* stream_exec, + const CompileOptions& options) override; + + StatusOr>> + CompileAheadOfTime(std::unique_ptr module_group, + AotCompilationOptions const& options) override; + + StatusOr>> CompileToTargetBinary( + const HloModuleConfig& module_config, + std::unique_ptr llvm_module, + se::GpuComputeCapability gpu_version, se::StreamExecutor* stream_exec, + const CompileOptions& options, const HloModule* debug_module); + + se::Platform::Id PlatformId() const override { return platform_id_; } + + HloCostAnalysis::ShapeSizeFunction ShapeSizeBytesFunction() const override; + + // Returns a (deserialized) AotCompilationResult from a serialized + // AotCompilationResult. + StatusOr> LoadAotCompilationResult( + const std::string& serialized_aot_result) override { + return GpuXlaRuntimeAotCompilationResult::FromString(serialized_aot_result); + } + + StatusOr> Export( + Executable* executable) const override; + + Status RunPostSchedulingPipelines(HloModule* module, + int64_t scheduler_mem_limit) const; + + protected: + // During compilation with device, stream_exec != null and autotune_results + // == null. During deviceless AOT compilation, stream_exec == null and + // autotune_results != null. + // thread_pool is used to speed up compilation during autotuning. + virtual Status OptimizeHloPostLayoutAssignment( + HloModule* hlo_module, se::StreamExecutor* stream_exec, + const CompileOptions& options, const GpuTargetConfig& gpu_target_config, + const AutotuneResults* autotune_results, + tsl::thread::ThreadPool* thread_pool); + + // CollectivesScheduleLinearizer enforces a total ordering between collectives + // to work around divergence in executables introduced due to auto tuning, + // specifically the use of extra scratch space for convolutions. This + // function decided whether to apply this pass. If convolutions are present in + // the code and we are using "online" autotuning (i.e., not AOT) we need to + // use the pass, else we do not need to enable the pass. + virtual bool RequiresCollectiveScheduleLinearizer( + const HloModule* module, se::StreamExecutor* stream_exec) { + return false; + } + + // Add autotuning passes for convolution and gemm (except triton). + virtual Status AddConvAndGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, tsl::thread::ThreadPool* thread_pool) { + return OkStatus(); + } + + // Add autotuning passes for triton gemm. + virtual Status AddTritonGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, tsl::thread::ThreadPool* thread_pool) { + return OkStatus(); + } + + private: + Status LoadAutotuneResultsFromFile(const DebugOptions& debug_options); + Status SerializeAutotuneResultsToFile(const DebugOptions& debug_options); + + // During compilation with device, stream_exec != null and autotune_results + // == null. During deviceless AOT compilation, stream_exec == null and + // autotune_results != null. + Status OptimizeHloModule(HloModule* hlo_module, + se::StreamExecutor* stream_exec, + const CompileOptions& options, + const GpuTargetConfig& gpu_target_config, + const AutotuneResults* autotune_results); + + virtual Status OptimizeHloConvolutionCanonicalization( + HloModule* hlo_module, se::GpuComputeCapability gpu_version, + se::dnn::VersionInfo dnn_version, + se::DeviceMemoryAllocator* device_allocator) = 0; + + virtual HloDataflowAnalysis::CanShareBuffer GetCanShareBuffer() const { + return &FusionCanShareBufferHint; + } + + // TODO(timshen): Replace `debug_module` with some portable debug information + // that accommodates both HLO and MLIR. + virtual StatusOr>> + CompileTargetBinary(const HloModuleConfig& module_config, + llvm::Module* llvm_module, + se::GpuComputeCapability gpu_version, bool relocatable, + const HloModule* debug_module, + const CompileOptions& options) = 0; + + Status PrepareHloModuleForIrEmitting(HloModule* hlo_module); + + virtual StatusOr CanUseLinkModules(const HloModuleConfig& config) { + return false; + } + + virtual StatusOr> LinkModules( + se::StreamExecutor* stream_exec, + std::vector> modules, + const DebugOptions& debug_options) { + return Unimplemented("LinkModules is not implemented."); + } + + se::Platform::Id platform_id_; + + // The triple that represents our target. + const char* target_triple_; + + // The data layout of the emitted module. + const char* data_layout_; + + // The size in bytes of a pointer. Used by ShapeSizeBytesFunction. + const int64_t pointer_size_; + + GpuCompiler(const GpuCompiler&) = delete; + GpuCompiler& operator=(const GpuCompiler&) = delete; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..68eda89b715fa9e39d00cb914d81e1372f959cf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_constants.h @@ -0,0 +1,50 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_CONSTANTS_H_ +#define XLA_SERVICE_GPU_GPU_CONSTANTS_H_ + +#include + +namespace xla { +namespace gpu { + +// Minimum alignment for buffers passed as incoming arguments by TensorFlow. +// +// kEntryParameterAlignBytes is equal to EIGEN_MAX_ALIGN_BYTES, though including +// Eigen headers here to get that symbol may not be a good idea. +// EIGEN_MAX_ALIGN_BYTES may differ between CUDA-enabled builds vs CUDA-disabled +// builds and we don't want the IR generated by XLA:GPU to depend on that. +// +// TODO(b/111767313): Consider raising EIGEN_MAX_ALIGN_BYTES if it helps. +inline constexpr int64_t kEntryParameterAlignBytes = 16; + +// Minimum alignment for buffers allocated by XLA: the temp buffers and the live +// out (result) buffers. +// +// cudnn requires 128-bit (16-byte) alignment for TensorCore operations, but +// says that 1024-bit (128-byte) alignment "may deliver better performance". +// https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#tensor-ops-guidelines-for-dl-compiler +// +inline constexpr int64_t kXlaAllocatedBufferAlignBytes = 128; + +// Minimum alignment for constant buffers. +inline constexpr int64_t kConstantBufferAlignBytes = + kXlaAllocatedBufferAlignBytes; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONSTANTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_padding_legalization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_padding_legalization.h new file mode 100644 index 0000000000000000000000000000000000000000..15e5de46e5a9376312882e5e4df877000732e005 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_padding_legalization.h @@ -0,0 +1,49 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_CONV_PADDING_LEGALIZATION_H_ +#define XLA_SERVICE_GPU_GPU_CONV_PADDING_LEGALIZATION_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// An HLO pass that canonicalizes convolution instructions for GPU codegen. It +// inserts Pad instructions before Convolution instructions with uncanonicalized +// padding, so that they can be lowered to Cudnn/Miopen convolution. +class GpuConvPaddingLegalization : public HloModulePass { + public: + absl::string_view name() const override { + return "gpu-conv-padding-legalization"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation* computation); + // Returns if any changes are made to the parent computation. + bool CanonicalizeForwardConvolution(HloInstruction* conv); + bool CanonicalizeBackwardFilterConvolution(HloInstruction* backward_conv); + bool CanonicalizeBackwardInputConvolution(HloInstruction* backward_conv); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONV_PADDING_LEGALIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..4e36a69ceaa11cd03b3e74837cb705416350ba54 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_rewriter.h @@ -0,0 +1,54 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_CONV_REWRITER_H_ +#define XLA_SERVICE_GPU_GPU_CONV_REWRITER_H_ + +#include +#include + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Rewrites plain convolutions, backwards-filter convolutions, and +// backwards-input convolutions into CustomCall HLOs that call into +// Cudnn/Miopen. +// For integer convolution, it requires the following pattern: +// conv( +// convert(int8_x), convert(int8_y)) +// We transform it to: +// custom_call(int8_x, int8_y, target=cudnnForwardConvolution) +// Note that this pattern is necessary but not sufficient to map convolutions +// to CuDNN. More patterns will be matched in cudnn_fused_conv_rewriter. + +class GpuConvRewriter : public HloModulePass { + public: + absl::string_view name() const override { return "gpu-conv-rewriter"; } + + static bool ConvIsLowerable(HloInstruction* conv); + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONV_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..ff85fceb74cf6ea8600dc91a4b8d29f7fc896286 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_conv_runner.h @@ -0,0 +1,266 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_CONV_RUNNER_H_ +#define XLA_SERVICE_GPU_GPU_CONV_RUNNER_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/cublas_cudnn.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/lazy_op_runner.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// Structure to describe static properties of a GPU convolution. +struct GpuConvConfig { + // Field related to cuDNN's fused convolution are in FusionConfig & + // FusionParams structures. The result thus is defined as: + // activation(conv_result_scale * conv(x, w) + + // side_input_scale * side_input + broadcast(bias)) + // + // The most common fused conv is conv forward + relu/identity, for example. + // + // bias_buf is a single-dimensional array, with the length equal to the number + // of output features. It'll be broadcasted to the output shape in order to be + // added to the final results. + // + // side_input_buf, if valid, must have the same shape as the output buffer. + struct FusionConfig { + se::dnn::ActivationMode mode; + double side_input_scale; + double leakyrelu_alpha = 0.0; + }; + + PrimitiveType input_type; + PrimitiveType output_type; + CudnnConvKind kind; + se::dnn::AlgorithmDesc algorithm; + double conv_result_scale; + + se::dnn::BatchDescriptor input_descriptor; + se::dnn::FilterDescriptor filter_descriptor; + se::dnn::BatchDescriptor output_descriptor; + se::dnn::ConvolutionDescriptor conv_desc; + se::dnn::BatchDescriptor bias_descriptor; + + Shape input_shape; + Shape filter_shape; + Shape output_shape; + std::optional fusion; + + // String serialization of the subgraph of adjacent ops to be fused into the + // cuDNN convolution Custom Call. Currently used for FP8 convolutions only. + // Additional information is provided in gpu_fused_conv_rewriter.cc. + std::string serialized_graph; +}; + +// Implementation struct exposed for debugging and log analysis. +struct GpuConvParams { + const GpuConvConfig* config; // Not owned + struct FusionParams { + se::DeviceMemoryBase bias_buf; + se::DeviceMemoryBase side_input_buf; // nullable + }; + + se::DeviceMemoryBase input_buf; + se::DeviceMemoryBase filter_buf; + se::DeviceMemoryBase output_buf; + + // Buffers for operands of ops to be fused into the cuDNN + // convolution Custom Call. + std::vector operand_bufs; + + // Buffers for additional outputs of ops to be fused into the cuDNN + // convolution Custom Call. + std::vector aux_bufs; + + std::optional fusion; +}; + +// The XLA convolution plumbing is all dynamically-typed w.r.t. whether a +// convolution is fused (and has extra arguments) or unfused, which doesn't +// naturally play well with the typed APIs provided by StreamExecutor; rather +// than rewriting everything here, just propagate the dynamic typing to one more +// place by having a ConvRunner, FusedConvRunner or GraphConvRunner. +class GenericConvRunner { + public: + GenericConvRunner() = default; + + explicit GenericConvRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit GenericConvRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit GenericConvRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit GenericConvRunner(const GpuConvConfig& config) + : GenericConvRunner(FromGpuConvConfig(config)) {} + + static GenericConvRunner FromGpuConvConfig(const GpuConvConfig& config) { + if (config.kind == CudnnConvKind::kForwardGraph) { + return GenericConvRunner( + std::make_unique>( + config.algorithm)); + } else if (config.kind == CudnnConvKind::kForwardActivation) { + return GenericConvRunner( + std::make_unique>( + config.algorithm)); + } else { + return GenericConvRunner( + std::make_unique>( + config.algorithm)); + } + } + + se::dnn::AlgorithmDesc ToAlgorithmDesc() const { + return std::visit(ToAlgorithmDescVisitor{}, repr_); + } + + se::dnn::LazyOpRunner* AsConvRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get>>( + repr_) + .get(); + } + + se::dnn::LazyOpRunner* AsGraphConvRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get< + std::unique_ptr>>( + repr_) + .get(); + } + + se::dnn::LazyOpRunner* AsFusedConvRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get< + std::unique_ptr>>( + repr_) + .get(); + } + + private: + struct ToAlgorithmDescVisitor { + template + se::dnn::AlgorithmDesc operator()(const RunnerPtr& runner) { + return runner->ToAlgorithmDesc(); + } + + se::dnn::AlgorithmDesc operator()(const std::monostate&) { + CHECK(false) << "Internal error: uninitialized runner in ToAlgorithmDesc"; + } + }; + + using Repr = + std::variant>, + std::unique_ptr>, + std::unique_ptr>>; + Repr repr_; +}; + +struct RunConvOptions { + // Nullable output-parameter pointer for profiling results. + se::dnn::ProfileResult* profile_result = nullptr; + + // Use this runner cache (and its configured algorithm), instead of the one + // from the instruction. + GenericConvRunner* runner_cache; +}; + +// This file contains low-level routines for running cudnn convolutions. + +// Calls into cudnn to run the specified convolution. +// +// We provide one overload which takes a scratch buffer, and another which takes +// an allocator which is responsible for allocating the scratch space. In +// theory the second one shouldn't be necessary -- users of this function could +// just ask cudnn how much scratch space it needs for a particular convolution. +// But in practice, StreamExecutor does not expose such an API, and in the name +// of parsimony, perhaps it's better not to add it. Instead, the first time you +// call a convolution, you should call the version that takes a scratch +// allocator and take note of how much memory is used. The next time you call +// the same conv, you can provide an explicitly preallocated scratch buffer of +// that size, if you like. +Status RunGpuConv(const GpuConvConfig& conv_config, + absl::Span operand_buffers, + absl::Span result_buffers, + se::DeviceMemoryBase scratch_memory, se::Stream* stream, + RunConvOptions = {}); + +// Struct to describe properties of a convolution without being tied to specific +// IR. Will be used to help build Convolution thunks from either XLA HLO or +// LHLO GPU dialect in MLIR. +struct GpuConvDescriptor { + CudnnConvKind kind; + CudnnConvBackendConfig backend_config; + Shape operand0_shape; + Shape operand1_shape; + Shape result_shape; + size_t scratch_size; + Window window; + ConvolutionDimensionNumbers dnums; + int64_t feature_group_count; +}; + +// Returns the convolution configuration given a XLA HLO instruction. +StatusOr GetGpuConvConfig( + const HloCustomCallInstruction* cudnn_call); + +// Returns the convolution configuration given a convolution descriptor `desc` +// and a string representation of the convolution instruction `inst_as_string` +// (for error reporting). +StatusOr GetGpuConvConfig(const GpuConvDescriptor& desc, + absl::string_view inst_as_string); + +// Implementation details exposed for debugging and log analysis. +StatusOr GetGpuConvParams( + const GpuConvConfig& conv_config, + absl::Span operand_buffers, + absl::Span result_buffers); + +inline se::dnn::DataType BiasTypeForInputType(se::dnn::DataType input_type) { + switch (input_type) { + default: + return input_type; + case se::dnn::DataType::kInt8: + return se::dnn::DataType::kFloat; + } +} + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONV_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_convert_async_collectives_to_sync.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_convert_async_collectives_to_sync.h new file mode 100644 index 0000000000000000000000000000000000000000..01713f8dd3cef4158ef17d20466d8686e1a6473e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_convert_async_collectives_to_sync.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ +#define XLA_SERVICE_GPU_GPU_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ + +#include + +#include "xla/service/convert_async_collectives_to_sync.h" + +namespace xla { +namespace gpu { + +class GpuConvertAsyncCollectivesToSync : public ConvertAsyncCollectivesToSync { + public: + using ConvertAsyncCollectivesToSync::ConvertAsyncCollectivesToSync; + absl::string_view name() const override { + return "gpu-convert-async-collectives-to-sync"; + } + + Status ConvertAsyncInstructionsToSync( + HloComputation* computation, + absl::Span> async_pairs) + const override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_CONVERT_ASYNC_COLLECTIVES_TO_SYNC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_cost_model_stats_collection.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_cost_model_stats_collection.h new file mode 100644 index 0000000000000000000000000000000000000000..678327c899cae144a4fb9f79a3f093c195af5dc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_cost_model_stats_collection.h @@ -0,0 +1,59 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_COST_MODEL_STATS_COLLECTION_H_ +#define XLA_SERVICE_GPU_GPU_COST_MODEL_STATS_COLLECTION_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Calculates costs for each fusion op and stores the result in backend +// config. +class GpuCostModelStatsCollection : public HloModulePass { + public: + explicit GpuCostModelStatsCollection( + const se::DeviceDescription& d, + const GpuHloCostAnalysis::Options& cost_analysis_options) + : device_info_(d), cost_analysis_(cost_analysis_options, &device_info_) {} + + absl::string_view name() const override { + return "gpu_cost_model_stats_collection"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::DeviceDescription device_info_; + GpuHloCostAnalysis cost_analysis_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_COST_MODEL_STATS_COLLECTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable.h new file mode 100644 index 0000000000000000000000000000000000000000..7984ae2c8fab27e960cff2989fda2844cfdb71a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable.h @@ -0,0 +1,353 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_EXECUTABLE_H_ +#define XLA_SERVICE_GPU_GPU_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "absl/types/variant.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/executable.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/non_atomically_upgradeable_rw_lock.h" +#include "xla/service/gpu/runtime/executable.h" +#include "xla/service/gpu/runtime2/executable.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/hlo_execution_profile.h" +#include "xla/service/shaped_buffer.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Returns whether GpuExecutable runs with Xla Runtime. +bool IsXlaRuntimeExecutableEnabled(const HloModuleConfig& config); + +// Returns whether GpuExecutable runs with experimental XLA:GPU Runtime. +bool IsXlaGpu2RuntimeEnabled(const HloModuleConfig& config); + +// GPU-targeting implementation of the XLA Executable interface. +// +// Launches the given GPU kernel via the StreamExecutor. +// +// This is an immutable data type after initialization, and thus thread safe. +class GpuExecutable : public Executable { + public: + using OwnedThunkSequence = std::unique_ptr; + using OwnedGpuRuntimeProgram = std::unique_ptr; + using OwnedGpu2RuntimeProgram = std::unique_ptr; + + struct ConstantInfo { + std::string symbol_name; + std::vector content; + int allocation_index = -1; + }; + + struct OutputInfo { + // Corresponding allocation index. + int allocation_index; + + // Output is passed-through from a parameter. + bool passthrough = false; + + // Whether this output is hinted to alias a parameter (BufferAllocation* + // would indicate the aliased parameter), and what kind of alias it is. + std::optional alias_config; + }; + + struct Params { + std::string asm_text; + std::vector binary; + se::GpuComputeCapability gpu_version; + // The GpuExecutable will either execute Thunks, XLA runtime executable + // (native function) or experimental XLA runtime executable (IREE VM + // function) depending on which is supplied. + std::variant + executable; + xla::EntryFunctionAttributes entry_func_attrs; + std::vector constants; + absl::flat_hash_map output_info; + std::string module_name; + xla::Shape output_shape; + std::vector allocations; + bool enable_persistent_temp_buffers; + std::unique_ptr debug_buffer_assignment = nullptr; + + // A callable that dumps out a debug string upon device OOM. It's not the + // string itself, as the string can be huge and increase peak host memory + // usage for the common (non-OOM) case. + std::function verbose_buffer_assignment_string_dumper = [] { + return std::string(); + }; + + std::unique_ptr debug_module = nullptr; + bool enable_debug_info_manager = true; + }; + + // Analyze the entry function to construct buffer allocation and other output + // information. + // + // TODO(ezhulenev): Once Xla runtime enabled by default, hide this method as + // an implementation detail of GpuExecutable. + static Status SetUpMlirAllocation( + mlir::func::FuncOp func, llvm::ArrayRef buffer_sizes, + std::vector* allocations, + absl::flat_hash_map* output_info, + Shape* output_shape); + + // Returns an Executable that is loaded from an object file (XLA program + // compiled to a native function using the XLA Runtime stack). + static StatusOr> LoadFromObjFile( + std::shared_ptr hlo_module, absl::string_view obj_file, + absl::string_view mlir_module, + xla::EntryFunctionAttributes entry_func_attrs, DebugOptions debug_options, + absl::string_view asm_text, absl::string_view binary, + std::vector constants, se::GpuComputeCapability gpu_version, + stream_executor::StreamExecutor* executor); + + // Constructor to use when loading a GpuExecutable from an object file (native + // function compiled for XLA Runtime). Omits setting class members that aren't + // used in XLA Runtime execution mode. + GpuExecutable(std::shared_ptr hlo_module, std::string asm_text, + std::vector binary, + std::vector constants, + se::GpuComputeCapability gpu_version, + xla::EntryFunctionAttributes entry_func_attrs, + absl::string_view module_name, Shape xla_output_shape, + std::vector allocations, + absl::flat_hash_map output_info, + std::unique_ptr runtime_executable); + + static StatusOr> Create(Params params); + ~GpuExecutable() override; + + int64_t SizeOfGeneratedCodeInBytes() const override; + + // This should be called after set_ir_module_string. + const std::string& ir_module_string() const { return ir_module_string_; } + + // This should be called before ExecuteOnStream. + void set_ir_module_string(const std::string& ir_module_string) { + ir_module_string_ = ir_module_string; + } + + // Returns the compiled code for the computation. + // + // The compiled code is PTX in Cuda and unused empty string in ROCm. + // This may be left empty for saving memory if we have a non-empty binary. + // If both text() and binary() are empty, that means the HLO required no + // custom kernels to be compiled. + const std::string& text() const { return text_; } + + // Returns the binary stored in this GpuExecutable. + // + // The binary is cubin in Cuda, and HSA code object in ROCm. It may be empty, + // in which case compilation is left up to the GPU driver. If both text() and + // binary() are empty, that means the HLO required no custom kernels to be + // compiled. + const std::vector& binary() const { return binary_; } + + // ExecuteAsyncOnStream will fail if the compute capability of the stream + // doesn't match the compute capability passed to this object's constructor. + StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + std::vector arguments, + HloExecutionProfile* hlo_execution_profile) override; + + StatusOr ExecuteAsyncOnStream( + const ServiceExecutableRunOptions* run_options, + absl::Span arguments, + HloExecutionProfile* hlo_execution_profile) override; + + using VariantArguments = std::variant, + absl::Span>; + StatusOr ExecuteAsyncOnStreamImpl( + const ServiceExecutableRunOptions* run_options, + VariantArguments arguments); + + absl::Span GetAllocations() const { + return allocations_; + } + + const std::vector& constants() const { return constants_; } + + xla::EntryFunctionAttributes entry_func_attrs() const { + return entry_func_attrs_; + } + + StatusOr GetObjFile() const; + StatusOr GetMlirModule() const; + + private: + // Use GpuExecutable::Create() to create an instance. + explicit GpuExecutable(Params params); + + // If `block_host_until_done` is false, execution will not block the host + // until the kernels have completed. This is used as an optimization for + // clients, such as Tensorflow, that use a single stream of execution for + // computations, and allow host-side deallocation from the allocator before + // GPU execution completes. + Status ExecuteThunksOrXlaRuntime( + const ServiceExecutableRunOptions* run_options, + const BufferAllocations& buffer_allocations, bool block_host_until_done, + NonAtomicallyUpgradeableRWLock& gpu_lock); + + using BufferAllocToDeviceMemoryMap = + absl::flat_hash_map; + + // Loads the PTX or CUBIN for this executable and initializes all + // constants that haven't already been initialized by the CUDA driver. Loaded + // modules are owned by this executable. + // + // Returns a map from buffer allocation indices to device memory pointers + // (only for allocations that contain constants). + // + // The returned map is cached. If the above process has already been run for + // the given stream, it is skipped and the cached map is immediately returned + // instead. + StatusOr ResolveConstantGlobals( + stream_executor::Stream* stream); + + // Allocate the temp buffers and store them with the GpuExecutable. This + // function only allocates buffers on the first run for each executor. + Status PopulatePersistentTempBuffers(se::StreamExecutor* executor) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(persistent_temp_buffers_mu_); + + // GpuExecutable check with either AMD's ISA version, or Nvidia's major minor + // version for compute capability, depending on the hardware. + Status CheckCompatibilityWithServiceExecutableRunOptions( + const ServiceExecutableRunOptions* run_options); + + StatusOr GenerateBufferAllocations( + VariantArguments arguments, + const GpuExecutable::BufferAllocToDeviceMemoryMap* globals, + se::DeviceMemoryAllocator* memory_allocator, int device_ordinal, + const BufferAllocToDeviceMemoryMap& + buffer_alloc_to_persistent_memory_map); + + StatusOr BufferForAllocation( + VariantArguments arguments, + const GpuExecutable::BufferAllocToDeviceMemoryMap* globals, + const BufferAllocation& allocation, + se::DeviceMemoryAllocator* memory_allocator, int device_ordinal, + int64_t arg_idx); + + // The LLVM IR, in string format, of the unoptimized module generated for + // this GpuExecutable. We save a string instead of an llvm::Module* because + // leaving llvm::Module* in a singleton can cause the heap checker to emit + // false positives. + // + // This string should be modified only before ExecuteOnStream. + std::string ir_module_string_; + + // The compiled code for the computation. + const std::string text_; + + // The GPU machine code for the computation, targeting GPUs at + // compute_capability_. + // + // May be empty, in which case we leave compilation up to the GPU driver. +#ifdef TENSORFLOW_USE_ROCM + std::vector binary_; +#else + const std::vector binary_; +#endif + // The GPU version for compute compatibility check. + se::GpuComputeCapability gpu_version_; + + // The thunks to be invoked by this GpuExecutable. They are generated by the + // IrEmitter (null if XLA:GPU runtime is enabled). + OwnedThunkSequence thunks_; + + // Gpu runtime executable that encapsulates all the state for running Gpu + // runtime custom calls implementing gpu abstraction layer (available only if + // Xla runtime is enabled). + std::unique_ptr gpu_runtime_executable_; + + // XLA:GPU runtime executable that encapsulates all the state for running + // XLA:GPU executables compiled to IREE VM modules, including VM module + // itself. Available only if experimental XLA:GPU runtime is enabled. + std::unique_ptr gpu2_runtime_executable_; + + xla::EntryFunctionAttributes entry_func_attrs_; + + std::string module_name_; + + xla::Shape output_shape_; + + // Owns the buffer data at runtime. It provides information to allocate + // memory for every output/temp buffers. + const std::vector allocations_; + + bool enable_persistent_temp_buffers_ = false; + + absl::Mutex persistent_temp_buffers_mu_; + // Temp buffers can be allocated once and be reused whenever the GpuExecutable + // is executed. The persistent temp buffer is stored in a map that maps from + // a BufferAllocation to the temp buffer. + absl::flat_hash_map + persistent_temp_buffers_ ABSL_GUARDED_BY(persistent_temp_buffers_mu_); + + std::shared_ptr debug_buffer_assignment_; + std::function verbose_buffer_assignment_string_dumper_; + + absl::Mutex module_handle_mutex_; + // Cache of module handles. Required to keep loaded modules alive until this + // executable is destroyed. + absl::flat_hash_map + module_handles_ ABSL_GUARDED_BY(module_handle_mutex_); + // Cache of constant buffer allocation maps used by `ResolveConstantGlobals`. + absl::flat_hash_map> + module_globals_ ABSL_GUARDED_BY(module_handle_mutex_); + + std::vector constants_; + const absl::flat_hash_map output_info_; + // Retains shared ownership of on-device constants that are managed by XLA and + // potentially shared with other executables. + std::vector> shared_constants_; + bool enable_debug_info_manager_; + + GpuExecutable(const GpuExecutable&) = delete; + GpuExecutable& operator=(const GpuExecutable&) = delete; +}; + +StatusOr> +GetOutputInfo(const HloModule& hlo_module, const BufferAssignment& assignment); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h new file mode 100644 index 0000000000000000000000000000000000000000..ffb8785bf7cce924623addb7746554640257883d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_executable_run_options.h @@ -0,0 +1,133 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_EXECUTABLE_RUN_OPTIONS_H_ +#define XLA_SERVICE_GPU_GPU_EXECUTABLE_RUN_OPTIONS_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/service/global_device_id.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Key for naming up a particular NCCL clique. This is just a set of unique +// device IDs (i.e. GPU IDs) and a stream_id. The device IDs must be global +// within a cluster. The stream_id is used to create different NCCL clique and +// communicators for collectives executed on different streams within an +// executable. +class NcclCliqueKey { + public: + explicit NcclCliqueKey(std::vector devices, + int64_t stream_id = 0) + : devices_(std::move(devices)), stream_id_(stream_id) {} + + template + friend H AbslHashValue(H h, const NcclCliqueKey& k) { + return H::combine(std::move(h), k.devices_, k.stream_id_); + } + friend bool operator==(const NcclCliqueKey& a, const NcclCliqueKey& b) { + return a.devices_ == b.devices_ && a.stream_id_ == b.stream_id_; + } + + const std::vector& devices() const { return devices_; } + + std::string ToString() const { + return absl::StrCat("stream[", stream_id_, "]", + GlobalDeviceIdsToString(devices_)); + } + + private: + const std::vector devices_; + const int64_t stream_id_; +}; + +using NcclUniqueIdCallback = + std::function(const NcclCliqueKey&)>; + +// GPU-specific executable options. +// We keep these separate from ExecutableRunOptions to avoid adding +// dependencies to ExecutableRunOptions. +class GpuExecutableRunOptions { + public: + // Sets a mapping from local device ordinals to global device IDs. + // Used only on NVidia GPUs for cross-host NCCL collectives. If set, the + // elements of `device_assignment` are interpreted as global device IDs, not + // local device ordinals. + GpuExecutableRunOptions& set_gpu_global_device_ids( + std::optional> gpu_global_device_ids); + const std::optional>& gpu_global_device_ids() + const; + + // Callback that returns a ncclUniqueId encoded as a string for a group of + // communicating GPU devices. Used only on NVidia GPUs. + GpuExecutableRunOptions& set_nccl_unique_id_callback( + NcclUniqueIdCallback nccl_unique_id_callback); + const NcclUniqueIdCallback& nccl_unique_id_callback() const; + + // Whether the run requires an exclusive lock on the GPU. + bool requires_exclusive_lock_on_gpu() const { + return requires_exclusive_lock_on_gpu_; + } + + // Require writers lock on the GPU. + GpuExecutableRunOptions& set_requires_exclusive_lock_on_gpu() { + requires_exclusive_lock_on_gpu_ = true; + return *this; + } + + bool enable_mock_nccl_collectives() const { + return enable_mock_nccl_collectives_; + } + + // Enable mocking nccl collective operations on the GPU + GpuExecutableRunOptions& set_enable_mock_nccl_collectives() { + enable_mock_nccl_collectives_ = true; + return *this; + } + + private: + bool requires_exclusive_lock_on_gpu_ = false; + bool enable_mock_nccl_collectives_ = false; + std::optional> gpu_global_device_ids_; + NcclUniqueIdCallback nccl_unique_id_callback_; +}; + +// NCCL-related execution parameters. +struct NcclExecuteParams { + NcclExecuteParams(const ServiceExecutableRunOptions& run_options, + se::StreamExecutor* stream_executor); + + se::StreamExecutor* stream_executor; + RunId run_id; + const DeviceAssignment* device_assn; // never null + const std::map* gpu_global_device_ids; // may be null + const NcclUniqueIdCallback* nccl_unique_id_callback; // may be null + + StatusOr GetGlobalDeviceId() const; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_EXECUTABLE_RUN_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_float_support.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_float_support.h new file mode 100644 index 0000000000000000000000000000000000000000..c9e0e2ac0c48e71925e67b96ae9598a1100bc572 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_float_support.h @@ -0,0 +1,52 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_FLOAT_SUPPORT_H_ +#define XLA_SERVICE_GPU_GPU_FLOAT_SUPPORT_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/float_support.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +class GpuFloatSupport : public FloatSupport { + public: + explicit GpuFloatSupport(PrimitiveType low_precision_type) + : FloatSupport(low_precision_type) {} + + bool SupportsLowPrecisionOperand(const HloInstruction& hlo, + int64_t operand_index) const override { + return FloatSupport::SupportsLowPrecisionOperand(hlo, operand_index) || + IsSupported(hlo); + } + + bool SupportsLowPrecisionOutput(const HloInstruction& hlo) const override { + return FloatSupport::SupportsLowPrecisionOutput(hlo) || IsSupported(hlo); + } + + bool SupportsMixedPrecisions(const HloInstruction& hlo) const override; + + private: + bool IsSupported(const HloInstruction& hlo) const; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_FLOAT_SUPPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fused_mha_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fused_mha_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..637a3c474c4f7e6d9aeba0874596a4a55ebe996c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fused_mha_runner.h @@ -0,0 +1,393 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_FUSED_MHA_RUNNER_H_ +#define XLA_SERVICE_GPU_GPU_FUSED_MHA_RUNNER_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/cublas_cudnn.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/lazy_op_runner.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// This is an interim structure to hold the parameters to construct a +// GpufMHAConfig. +// Struct to describe properties of a FMHA without being tied to specific +// IR. Will be used to help build FMHA thunks from either XLA HLO or +// LHLO GPU dialect in MLIR. +struct GpufMHADescriptor { + CudnnfMHAKind kind; + CudnnfMHABackendConfig backend_config; + Shape lhs_bmm1_shape; + Shape rhs_bmm1_shape; + Shape rhs_bmm2_shape; + Shape intermediate_lhs_bmm2_shape; + // This will contain both output shape and activation shape + std::vector output_shapes; + DotDimensionNumbers bmm1_dnums; + DotDimensionNumbers bmm2_dnums; + + std::optional mask_shape; + std::optional bias_shape; +}; + +struct GpufMHABackwardDescriptor { + CudnnfMHAKind kind; + CudnnfMHABackendConfig backend_config; + Shape bmm1_grad_gemm1_rhs_shape; + Shape bmm1_grad_gemm2_rhs_shape; + Shape bmm2_grad_gemm1_lhs_shape; + Shape bmm2_grad_gemm2_rhs_shape; + Shape d_output_shape; + Shape d_bmm1_lhs_shape; + Shape d_bmm1_rhs_shape; + Shape d_bmm2_rhs_shape; + DotDimensionNumbers bmm1_grad_gemm1_dnums; + DotDimensionNumbers bmm1_grad_gemm2_dnums; + DotDimensionNumbers bmm2_grad_gemm1_dnums; + DotDimensionNumbers bmm2_grad_gemm2_dnums; + + std::optional mask_shape; + std::optional d_bias_shape; +}; +// Structure to describe static properties of a GPU fused Multi-Headed +// Attention. +struct GpufMHAConfig { + static StatusOr For(const GpufMHADescriptor& fmha_desc); + PrimitiveType + input_type; // Capture the primitive type of one of the inputs of BMM1 + PrimitiveType output_type; + CudnnfMHAKind kind; + std::optional fmha_scale; + std::optional dropout_rate; + std::optional seed; + + se::dnn::AlgorithmDesc algorithm; + + // bias -> [1, num_attn_heads, q_seq_len, kv_seq_len] + // mask -> [batch_size, 1, q_seq_len, kv_seq_len] + se::dnn::MatmulTensorDescriptor lhs_bmm1; + se::dnn::MatmulTensorDescriptor rhs_bmm1; + se::dnn::MatmulTensorDescriptor rhs_bmm2; + se::dnn::MatmulTensorDescriptor intermediate_lhs_bmm2; + se::dnn::TensorDescriptor output; + + std::optional activation; + std::optional mask; + std::optional bias; +}; + +// Structure to describe static properties of a GPU fused Multi-Headed +// Attention backward. +struct GpufMHABackwardConfig { + static StatusOr For( + const GpufMHABackwardDescriptor& fmha_desc); + PrimitiveType + input_type; // Capture the primitive type of one of the inputs of BMM1 + PrimitiveType output_type; + CudnnfMHAKind kind; + std::optional fmha_scale; + std::optional dropout_rate; + std::optional seed; + + se::dnn::AlgorithmDesc algorithm; + + // mask -> [batch_size, 1, q_seq_len, kv_seq_len] + // d_bias -> [1, num_heads, q_seq_len, kv_seq_len] + se::dnn::MatmulTensorDescriptor bmm1_grad_gemm1_rhs; + se::dnn::MatmulTensorDescriptor bmm1_grad_gemm2_rhs; + se::dnn::MatmulTensorDescriptor bmm2_grad_gemm1_lhs; + se::dnn::MatmulTensorDescriptor bmm2_grad_gemm2_rhs; + se::dnn::MatmulTensorDescriptor d_output; + se::dnn::TensorDescriptor d_bmm1_lhs; + se::dnn::TensorDescriptor d_bmm1_rhs; + se::dnn::TensorDescriptor d_bmm2_rhs; + se::dnn::TensorDescriptor d_s; + std::optional d_bias; + std::optional mask; +}; + +// Implementation struct exposed for debugging and log analysis. +struct GpufMHAParams { + static StatusOr For( + const GpufMHAConfig& config, se::DeviceMemoryBase lhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm2_buffer, se::DeviceMemoryBase output_buffer, + std::optional mask_buffer, + std::optional bias_buffer, + std::optional activation_buffer); + + const GpufMHAConfig* config; // Not owned + se::DeviceMemoryBase lhs_bmm1_buffer; + se::DeviceMemoryBase rhs_bmm1_buffer; + se::DeviceMemoryBase rhs_bmm2_buffer; + se::DeviceMemoryBase output_buffer; + std::optional activation_buffer; + std::optional mask_buffer; + std::optional bias_buffer; +}; + +struct GpufMHABackwardParams { + static StatusOr For( + const GpufMHABackwardConfig& config, + se::DeviceMemoryBase bmm1_grad_gemm1_rhs_buffer, + se::DeviceMemoryBase bmm1_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm1_lhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase d_output_buffer, + se::DeviceMemoryBase d_bmm1_lhs_buffer, + se::DeviceMemoryBase d_bmm1_rhs_buffer, + se::DeviceMemoryBase d_bmm2_rhs_buffer, se::DeviceMemoryBase d_s_buffer, + std::optional mask_buffer, + std::optional d_bias_buffer); + + const GpufMHABackwardConfig* config; // Not owned + se::DeviceMemoryBase bmm1_grad_gemm1_rhs_buffer; + se::DeviceMemoryBase bmm1_grad_gemm2_rhs_buffer; + se::DeviceMemoryBase bmm2_grad_gemm1_lhs_buffer; + se::DeviceMemoryBase bmm2_grad_gemm2_rhs_buffer; + se::DeviceMemoryBase d_output_buffer; + se::DeviceMemoryBase d_bmm1_lhs_buffer; + se::DeviceMemoryBase d_bmm1_rhs_buffer; + se::DeviceMemoryBase d_bmm2_rhs_buffer; + se::DeviceMemoryBase d_s_buffer; + std::optional d_bias_buffer; + std::optional mask_buffer; +}; + +class FusedMultiHeadedAttentionRunner { + public: + using Repr = + std::variant>>; + + FusedMultiHeadedAttentionRunner() = default; + + explicit FusedMultiHeadedAttentionRunner( + std::unique_ptr> runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionRunner(Repr runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionRunner(const GpufMHAConfig& config) + : FusedMultiHeadedAttentionRunner(CreateRunner(config)) { + if (std::holds_alternative(repr_)) { + CHECK(false) << "Cannot construct FusedMultiHeadedAttentionRunner with " + "std::monostate"; + } + } + + se::dnn::AlgorithmDesc ToAlgorithmDesc() const { + return std::visit(ToAlgorithmDescVisitor{}, repr_); + } + + se::dnn::LazyOpRunner* AsFusedMHARunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>(repr_)); + return std::get< + std::unique_ptr>>( + repr_) + .get(); + } + + private: + // The CreateRunner function is defined as static because it + // doesn't need access to any non-static member variables of the + // FusedMultiHeadedAttentionRunner class. Defining it static makes it easy to + // use and makes it clear that it is a utility function that doesn't rely on + // the state of any specific instance of the class. + static Repr CreateRunner(const GpufMHAConfig& config) { + switch (config.kind) { + case CudnnfMHAKind::kBmmBmm: + case CudnnfMHAKind::kSoftmaxDropout: + case CudnnfMHAKind::kSoftmax: + case CudnnfMHAKind::kScaleBiasSoftmax: + case CudnnfMHAKind::kScaleBiasSoftmaxDropout: + case CudnnfMHAKind::kScaleMaskSoftmax: + case CudnnfMHAKind::kScaleMaskSoftmaxDropout: + case CudnnfMHAKind::kScaleBiasMaskSoftmax: + case CudnnfMHAKind::kScaleBiasMaskSoftmaxDropout: + return std::make_unique>( + config.algorithm); + default: + LOG(FATAL) << "Internal error: unsupported CUDNN MHA kind in " + "FusedMultiHeadedAttentionRunner"; + } + } + + struct ToAlgorithmDescVisitor { + template + se::dnn::AlgorithmDesc operator()(const RunnerPtr& runner) { + return runner->ToAlgorithmDesc(); + } + + se::dnn::AlgorithmDesc operator()(const std::monostate&) { + CHECK(false) << "Internal error: uninitialized runner in ToAlgorithmDesc"; + } + }; + + Repr repr_; +}; + +class FusedMultiHeadedAttentionBackwardRunner { + public: + using Repr = std::variant< + std::monostate, // To allow XXX default ctor + std::unique_ptr>>; + + FusedMultiHeadedAttentionBackwardRunner() = default; + + explicit FusedMultiHeadedAttentionBackwardRunner( + std::unique_ptr> + runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionBackwardRunner(Repr runner) + : repr_(std::move(runner)) {} + + explicit FusedMultiHeadedAttentionBackwardRunner( + const GpufMHABackwardConfig& config) + : FusedMultiHeadedAttentionBackwardRunner(CreateRunner(config)) { + if (std::holds_alternative(repr_)) { + CHECK(false) + << "Cannot construct FusedMultiHeadedAttentionBackwardRunner with " + "std::monostate"; + } + } + + se::dnn::AlgorithmDesc ToAlgorithmDesc() const { + return std::visit(ToAlgorithmDescVisitor{}, repr_); + } + + se::dnn::LazyOpRunner* + AsFusedMHABackwardRunner() { + CHECK(std::holds_alternative< + std::unique_ptr>>( + repr_)); + return std::get>>(repr_) + .get(); + } + + private: + // The CreateRunner function is defined as static because it + // doesn't need access to any non-static member variables of the + // FusedMultiHeadedAttentionBackwardRunner class. Defining it static makes it + // easy to use and makes it clear that it is a utility function that doesn't + // rely on the state of any specific instance of the class. + static Repr CreateRunner(const GpufMHABackwardConfig& config) { + switch (config.kind) { + case CudnnfMHAKind::kBackwardBmmBmm: + case CudnnfMHAKind::kBackwardSoftmaxDropout: + case CudnnfMHAKind::kBackwardSoftmax: + case CudnnfMHAKind::kBackwardScaleBiasSoftmax: + case CudnnfMHAKind::kBackwardScaleBiasSoftmaxDropout: + case CudnnfMHAKind::kBackwardScaleBiasMaskSoftmax: + case CudnnfMHAKind::kBackwardScaleBiasMaskSoftmaxDropout: + case CudnnfMHAKind::kBackwardScaleMaskSoftmax: + case CudnnfMHAKind::kBackwardScaleMaskSoftmaxDropout: + return std::make_unique< + se::dnn::LazyOpRunner>( + config.algorithm); + default: + LOG(FATAL) << "Internal error: unsupported CUDNN MHA kind in " + "FusedMultiHeadedAttentionBackwardRunner"; + } + } + + struct ToAlgorithmDescVisitor { + template + se::dnn::AlgorithmDesc operator()(const RunnerPtr& runner) { + return runner->ToAlgorithmDesc(); + } + + se::dnn::AlgorithmDesc operator()(const std::monostate&) { + CHECK(false) << "Internal error: uninitialized runner in ToAlgorithmDesc"; + } + }; + + Repr repr_; +}; + +struct RunFusedMHAOptions { + // Nullable output-parameter pointer for profiling results. + // Profile results remain unused for now since cuDNN FMHA has only one + // algorithm for now. + se::dnn::ProfileResult* profile_result = nullptr; + + // Use this runner cache (and its configured algorithm), instead of the one + // from the instruction. + FusedMultiHeadedAttentionRunner* runner_cache; +}; + +struct RunFusedMHABackwardOptions { + // Nullable output-parameter pointer for profiling results. + // Profile results remain unused for now since cuDNN FMHA has only one + // algorithm for now. + se::dnn::ProfileResult* profile_result = nullptr; + + // Use this runner cache (and its configured algorithm), instead of the one + // from the instruction. + FusedMultiHeadedAttentionBackwardRunner* runner_cache; +}; + +Status RunGpuFMHA(const GpufMHAConfig& fmha_config, + se::DeviceMemoryBase lhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm1_buffer, + se::DeviceMemoryBase rhs_bmm2_buffer, + se::DeviceMemoryBase output_buffer, + se::DeviceMemoryBase scratch_buffer, + std::optional mask_buffer, + std::optional bias_buffer, + std::optional activation_buffer, + se::Stream* stream, RunFusedMHAOptions = {}); + +Status RunGpuFMHABackward(const GpufMHABackwardConfig& fmha_config, + se::DeviceMemoryBase bmm1_grad_gemm1_rhs_buffer, + se::DeviceMemoryBase bmm1_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm1_lhs_buffer, + se::DeviceMemoryBase bmm2_grad_gemm2_rhs_buffer, + se::DeviceMemoryBase d_output_buffer, + se::DeviceMemoryBase scratch_buffer, + se::DeviceMemoryBase d_bmm1_lhs_buffer, + se::DeviceMemoryBase d_bmm1_rhs_buffer, + se::DeviceMemoryBase d_bmm2_rhs_buffer, + se::DeviceMemoryBase d_s_buffer, + std::optional mask_buffer, + std::optional d_bias_buffer, + se::Stream* stream, RunFusedMHABackwardOptions = {}); + +std::string ToString(const GpufMHAConfig& config); + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_GPU_FUSED_MHA_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fusible.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fusible.h new file mode 100644 index 0000000000000000000000000000000000000000..ec02a6c2d04ad4e833b086cfdf160029b2e3c026 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_fusible.h @@ -0,0 +1,197 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_FUSIBLE_H_ +#define XLA_SERVICE_GPU_GPU_FUSIBLE_H_ + +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/reduction_utils.h" +#include "xla/service/instruction_fusion.h" +#include "xla/stream_executor/device_description.h" + +// TODO(b/112957171): Extract logic to determine fusibility of HLO ops from +// GpuInstructionFusion, FusionMerger, and GpuMultiOutputFusion. + +namespace xla { +namespace gpu { + +// Check if the operation accesses the same inputs multiple times +// while generating its outputs. +bool IfFusedReadsElementsMultipleTimes(const HloInstruction& instr); + +// Check if the operation is memory or computationally expensive +// to repeat. +bool IsExpensiveToRepeat(const HloInstruction& instr); + +// Fusion passes frequently do checks across all pairs of "interesting" nodes. +// Computing e.g. FusionFitsInBudget(a, b) requires computing expensive +// properties of `a` and `b` individually. This cache lets us avoid recomputing +// those properties n^2 times. +// +// Invariant: After modifying or removing a fusion node, call Invalidate(node). +struct FusionInfoCache { + public: + // Must be called after modifying or removing a fusion node (or other node + // that's part of this cache). + void Invalidate(const HloInstruction* instr) { + shared_memory_usage.erase(instr); + num_unnested_reductions.erase(instr); + } + + // The rest of the members of this class are for internal use within + // gpu_fusible. You shouldn't need to use them yourself. + absl::flat_hash_map shared_memory_usage; + absl::flat_hash_map num_unnested_reductions; +}; + +// Returns projected shared memory usage of a given instruction in bytes. +int64_t SharedMemoryUsage(const HloInstruction& instr, + FusionInfoCache* cache = nullptr); + +// Returns projected shared memory usage of a reduction fusion. +int64_t ReductionProjectedShmemUsageBytes( + const ReductionDimensions& reduction_dimensions, + const std::vector>& instr_index_groups); + +inline constexpr int64_t MaxOperandsAndOutputsPerFusion() { return 64; } + +// Whether the op tranposes the physical data layout. Fusing such ops may lead +// to uncoalesced data access and may thus not be beneficial. +bool IsPhysicallyTransposing(const HloInstruction& instr); + +// Note that reduction ops are lowered in different ways. Reduce input fusions +// are lowered by IrEmitterUnnested::EmitReductionToVector and must be rooted at +// reduction-to-vector ops. Other reduction ops are lowered by +// GpuElementalIrEmitter and fused like elementwise ops. + +// Whether `instr` is an input fusion rooted at a reduction-to-vector op or a +// multi-output input fusion with at least one reduction-to-vector op root. +bool IsReduceInputFusion(const HloInstruction& instr); + +// Whether `instr` is fusible as root of a reduce input fusions, i.e. `instr` +// is either an unfused reduction-to-vector op or a reduce input fusion. +bool IsInputFusibleReduction(const HloInstruction& instr); + +// Whether `instr` is a nestable variadic reduction +// or a loop fusion rooted with such. +bool IsNestableVariadicReduction(const HloInstruction& instr); + +// Whether `instr` is fusible as root of a scatter input fusions, i.e. `instr` +// is either an unfused scatter op or a scatter input fusion. +bool IsInputFusibleScatter(const HloInstruction& instr); + +// Determines whether the combination of `instr1` and `instr2` into a (possibly +// multi-output) fusion fits within a "budget" -- i.e., does have more operands +// and outputs than is allowed or occupy too much shared memory. If the fusion +// is a producer/consumer fusion and `instr1` is the consumer and `instr2` is +// the producer, set consumer_producer_fusion to true to enable more fusion. +FusionDecision FusionFitsInBudget(const HloInstruction& instr1, + const HloInstruction& instr2, + const se::DeviceDescription& device_info, + bool is_consumer_producer_fusion = false, + FusionInfoCache* cache = nullptr); + +// Check if fusing producer and consumer will generate a heavy computation, e.g. +// producer has a complex computation per output and consumer calls this +// computations multiple times. +bool CreatesHeavyComputation(const HloInstruction& producer, + const HloInstruction& consumer); + +// Returns the instruction that determines the emitter used for lowering, +// sometimes referred to as "the real hero". +const HloInstruction* GetRealHeroForMultiOutputFusion( + const HloInstruction& instr); + +// Whether 'hero1' and 'hero2' are compatible if the two fusions containing +// 'hero1' and 'hero2' are merged together. For example merging two fusions with +// a reduction hero and a transpose here, respectively, does not work. +FusionDecision FusionHeroesAreCompatible(const HloInstruction* hero1, + const HloInstruction* hero2); + +// Whether instruction shapes are compatible for multi-output fusion, i.e. +// whether the emitters support lowering the resulting fusion. +// This function works for both, sibling and producer-consumer multi-output +// fusion. +// So far, multi-output fusion is supported for loop fusions and reduce +// input fusions only. It is up to the caller to ensure the instructions +// themselves are fusible! +FusionDecision ShapesCompatibleForMultiOutputFusion( + const HloInstruction& instr1, const HloInstruction& instr2); + +// Whether the instructions are compatible for producer-consumer fusion +// i.e. whether the producer and consumer are loop/input fusible and +// they are not library calls. +// Used both by instruction fusion and fusion-fusion merging. +FusionDecision IsProducerConsumerFusible(const HloInstruction& producer, + const HloInstruction& consumer); + +// Whether the producer is a valid candidate for a multi-output fusion. +// That is, the root tuple of the multi-output fusion will contain the results +// of both, the producer and consumer. +FusionDecision IsProducerMultiOutputFusible(const HloInstruction& producer); +// Whether `instr` is a candidate for sibling fusion or as a consumer in +// a producer-consumer multi-output fusion. +bool IsFusibleAsMultiOutputFusionRoot(const HloInstruction& instr); + +// Determines the fusion kind to be used when fusing `producer` and `consumer`. +HloInstruction::FusionKind ChooseFusionKind(const HloInstruction& producer, + const HloInstruction& consumer); + +// Returns whether `consumer` is the only non-root user of `instr`. +bool IsConsumerTheOnlyNonRootUser(const HloInstruction& instr, + const HloInstruction& consumer); + +// Returns number of instructions in the fusible `instr`. If `instr` is not a +// fusion instruction, 1 is returned. +size_t GetInstrCountOfFusible(const HloInstruction& instr); + +// Returns the outputs of the fusible `instr`. +absl::InlinedVector GetOutputsOfFusible( + const HloInstruction& instr); + +// Returns the output size of the fusible `instr`. +size_t GetOutputSizeOfFusible(const HloInstruction& instr); + +// Returns instructions which are roots of the fusion, following the operands of +// GTE instructions in the root tuple. Groups multiple subsequent instructions +// with the same root. CHECKs that the fusion never outputs the same instruction +// twice, as well as that there are no explicitly created tuples or nested gtes +// in fusion output. +// +// For input: (tuple (gte R1) (gte R1) O2) +// Expected output: [R1, O2] +// +// For input: (tuple R1 R2 O2) +// Expected output: [R1, R2, O2] +// +// For input: (tuple (gte R1) (gte R1) R2 O3) +// Expected output: [R1, R2, O3] +// +// For input: R1 +// Expected output: [R1] +std::vector GetFusionRoots( + const HloComputation& computation); + +// Whether the instruction is a reduction hero for the given root. +bool IsRealReductionHero(const HloInstruction& root, + const HloInstruction& hero); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_FUSIBLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_cost_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_cost_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..10b44ba5c3bca92f16a1886d62ffbdaf5e4fce1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_cost_analysis.h @@ -0,0 +1,109 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_HLO_COST_ANALYSIS_H_ +#define XLA_SERVICE_GPU_GPU_HLO_COST_ANALYSIS_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Cost analysis for GPUs. +class GpuHloCostAnalysis : public HloCostAnalysis { + // Each instruction creating a new basic block roughly doubles the total + // number of basic blocks and the IR code size accordingly. + static constexpr int64_t kMaxBasicBlockSplitsPerFusion = 10; + static constexpr int64_t kMaxIRSize = 10000; + + public: + explicit GpuHloCostAnalysis( + const Options& options, + const se::DeviceDescription* device_info = nullptr) + : HloCostAnalysis(options), device_info_(device_info) {} + + Status Preprocess(const HloInstruction* hlo) override; + + float ScalingRatio(const HloInstruction& hlo) const; + int64_t NumOfDevices(const HloInstruction& hlo) const; + + Status HandleCustomCall(const HloInstruction* call) override; + + int64_t GetConvolutionFlops(const HloInstruction* convolution) override; + + Status HandleElementwiseOp(const HloInstruction* hlo); + Status HandleElementwiseUnary(const HloInstruction* hlo) override; + Status HandleElementwiseBinary(const HloInstruction* hlo) override; + + Status HandleAllReduce(const HloInstruction* allreduce) override; + + // Estimate the total size of IR accounting for both duplication + // of producer code by consumer and the total number of basic blocks. + // Tell if merged IR size would be too slow to compile. + bool ProducerConsumerMergedTooLarge(const HloInstruction& producer, + const HloInstruction& consumer); + + // IR size scale of an instruction: 1 for most instructions, + // but for fusions is the number of instructions emitted including the + // duplication due to non-element-wise accesses. + float IrSize(const HloInstruction& hlo) const; + + // Total common elementwise utilization of two instructions within a fusion. + // If two parameters have several common elementwise use roots returned is + // the sum of these utilizations. Can also be used to query if a parameter + // is used elementwise from the fusion's root. + float CommonElementwiseUtilization(const HloInstruction* a, + const HloInstruction* b) const; + + const se::DeviceDescription* device_info_; + + protected: + std::unique_ptr CreateNestedCostAnalysis() override; + int64_t FusionParameterReadBytes(const HloInstruction* hlo) const override; + Status FusionCalculateUtilizations(const HloInstruction* fusion) override; + + size_t immediate_constant_max_elements() const override { return 8; } + + bool KeyToCopyFromSubcomputation(absl::string_view key) const override; + + // Some instructions create new LLVM basic blocks; with our current code + // generation this means in the worst case doubling the IR size of a fusion + // containing such an instruction. + // Count these to avoid unmanageable IR code size. + float IrBasicBlockSplitCount(const HloInstruction& hlo) const; + + // To estimate where within the computation an instruction output can be + // reused and where it has to be recomputed again we group accesses to the + // instruction by their origin from "element-wise use roots". All access + // paths from such a root to the instruction are element-wise. + absl::flat_hash_map> + elementwise_use_roots_; + + // Elementwise utilization of instruction's input subtree if it is a root. + // This is different from hlo_properties_[instr][kUtilizationKey] which + // is the utilization of the instruction by other roots. + absl::flat_hash_map root_utilizations_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_HLO_COST_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_schedule.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_schedule.h new file mode 100644 index 0000000000000000000000000000000000000000..792dfbd2633c11154506882633becd33e8f930be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_hlo_schedule.h @@ -0,0 +1,42 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_HLO_SCHEDULE_H_ +#define XLA_SERVICE_GPU_GPU_HLO_SCHEDULE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +int64_t GetSizeOfShape(const Shape& shape, int pointer_size); + +// Determines the schedule of HLO instructions for a module run on the GPU. +Status ScheduleGpuModule(HloModule* module, int64_t pointer_size, + int64_t memory_limit, + const se::DeviceDescription& gpu_device_info); +HloInstructionSequence PostProcessSchedule(const HloInstructionSequence& input); + +int64_t GetSchedulerMemoryLimit(const HloModule* module, + const se::DeviceDescription& gpu_device_info, + int pointer_size); + +constexpr absl::string_view kFingerprintBeforeLHS = "fingerprint_before_lhs"; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_HLO_SCHEDULE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_layout_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_layout_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..27ca9bcfb72be850489bb74622c9d71a36e19fb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_layout_assignment.h @@ -0,0 +1,68 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_LAYOUT_ASSIGNMENT_H_ +#define XLA_SERVICE_GPU_GPU_LAYOUT_ASSIGNMENT_H_ + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/computation_layout.h" +#include "xla/service/layout_assignment.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// GPU-specific layout assignment pass which preassigns layouts to satisfy +// layout constraints for operands and results of library calls. +class GpuLayoutAssignment : public LayoutAssignment { + public: + explicit GpuLayoutAssignment( + ComputationLayout* entry_computation_layout, + se::StreamExecutor* stream_executor, + ChannelLayoutConstraints* channel_constraints = nullptr) + : LayoutAssignment(entry_computation_layout, channel_constraints), + stream_executor_(stream_executor) {} + ~GpuLayoutAssignment() override = default; + + protected: + Status AddBackendConstraints(LayoutConstraints* constraints) override; + + private: + Status AddBackendConstraintsToDnnConvCustomCall( + HloCustomCallInstruction* instr, LayoutConstraints* constraints); + + // dim_groups are ordered from major to minor dimensions. + Status SetOperandMajorToMinorLayout( + const HloInstruction* instruction, int64_t operand, + std::initializer_list> dim_groups); + + Status SetDotOperandLayout(const HloInstruction* instruction, int64_t operand, + absl::Span batch_dims, + absl::Span row_dims, + absl::Span col_dims); + + Status SetDotLayout(const HloInstruction* instruction, + LayoutConstraints* constraints); + + bool PropagateReductionLayoutToOperand(const HloInstruction* user) override; + + se::StreamExecutor* stream_executor_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_LAYOUT_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_performance_model.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_performance_model.h new file mode 100644 index 0000000000000000000000000000000000000000..419255686f352fa47642c9e71283f3b33b8bb11e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_performance_model.h @@ -0,0 +1,160 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_PERFORMANCE_MODEL_H_ +#define XLA_SERVICE_GPU_GPU_PERFORMANCE_MODEL_H_ + +#include +#include + +#include "absl/time/time.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/stream_executor/device_description.h" + +#if GOOGLE_CUDA +#include + +#include "third_party/gpus/cuda/nvml/include/nvml.h" +// Below is a list of function pointers to be used +// for querying device properties through nvml library. +#define NVML_FUNCTOR(name, rettype, args) rettype(*xla_##name) args = nullptr; + +NVML_FUNCTOR(nvmlInit, nvmlReturn_t, ()) +NVML_FUNCTOR(nvmlShutdown, nvmlReturn_t, ()) +NVML_FUNCTOR(nvmlDeviceGetHandleByIndex, nvmlReturn_t, + (unsigned int index, nvmlDevice_t* device)) +NVML_FUNCTOR(nvmlDeviceGetNvLinkCapability, nvmlReturn_t, + (nvmlDevice_t device, unsigned int link, + nvmlNvLinkCapability_t capability, unsigned int* capResult)) + +#endif + +namespace xla { +namespace gpu { + +struct EstimateRunTimeData { + int64_t flops; + int64_t bytes_written; + int64_t num_threads; + absl::Duration write_time; + absl::Duration exec_time; +}; + +class GpuPerformanceModel { + public: + struct RunTimes { + absl::Duration time_unfused; + absl::Duration time_fused; + }; + + static EstimateRunTimeData EstimateRunTimeForInstruction( + const HloInstruction* instr, const GpuHloCostAnalysis* cost_analysis); + + static RunTimes EstimateRunTimes( + const HloInstruction* producer, const GpuHloCostAnalysis* cost_analysis, + std::vector fused_consumers = {}, + bool multi_output = false); + + // Writes estimated execution time to FusionBackendConfig.reification_cost. + static void RecordEstimatedRunTime(HloInstruction* instruction, + const GpuHloCostAnalysis* cost_analysis); + static absl::Duration ComputeTime( + const se::DeviceDescription& gpu_device_info, int64_t n_flops, + int64_t n_threads); + + static absl::Duration ProducerInputAccessTime( + const GpuHloCostAnalysis* cost_analysis, + const se::DeviceDescription& gpu_device_info, + const HloInstruction* producer, + const HloInstruction* fused_consumer = nullptr); +}; + +class GpuPerformanceWithCollectiveModel : public GpuPerformanceModel { + public: + // Different algorithms that can be used to perform the collective. + enum CollectiveAlgo { + RING = 0, + TREE, + }; + + // Table for max system bandwidths GB/s for using NCCL's low latency + // algorithm. This is used for intra-node estimate. + static constexpr std::array kLowLatencyMaxBandwidths = { + 39.0 /* Volta*/, 87.7 /* Ampere*/, 87.7 /* Hopper*/ + }; + + // Max bandwidth in GB/s for ring low latency 128 algorithm per channel on a + // single-node + static constexpr std::array kPerChannelMaxRingLL128Bandwidths = { + 20.0 /* Volta */, + 20.0 /* Ampere */, + 36.7 /* Hopper */, + }; + + // Nvlink unidirectional bandwidth for different compute cap. Note this is per + // lane bandwidth. + static constexpr double kSm60NvlinkBandwidth = 18.0; + static constexpr double kSm70NvlinkBandwidth = 20.0; + static constexpr double kSm80NvlinkBandwidth = 20.0; + static constexpr double kSm90NvlinkBandwidth = 20.0; + + // PCIE bandwidth for PCI Gen3 x16 + static constexpr double kPciBandwidth = 12.0; + + // Discount factor for ring algorithm + static constexpr double kRingAlgorithmDiscountFactor = 0.92; + + // Different tiers for intra-node bandwidth. + static constexpr std::array kIntraNodeSpeeds = { + 40.0, 30.0, 20.0, 18.0, 15.0, 12.0, 10.0, 9.0, 7.0, 6.0, 5.0, 4.0, 3.0}; + // SM90 has different bandwidths. + static constexpr std::array kIntraNodeSpeedsSm90 = { + 60.0, 40.0, 30.0, 24.0, 20.0, 15.0, 12.0, 6.0, 3.0}; + + // Maximum number of channels allowed by NCCL + static constexpr int64_t kMaxNumChannelsRing = 16; + + // ll128 is by default enabled for Volta, Ampere and Hopper, ll128 by default + // launches 640 threads. + static constexpr int64_t kLL128NumThreads = 640; + + static absl::Duration ComputeCollectiveTime( + const HloInstruction& instr, const GpuHloCostAnalysis* cost_analysis, + const se::DeviceDescription& gpu_device_info); + + // Returns NVLink bw in GB/s + static float GetNvlinkBw(se::CudaComputeCapability compute_capability); + + // Initialize nvml library. + static bool InitNvml(); + + // Shut down nvml library. + static bool ShutdownNvml(); + + // This checks if the nvlink supports direct P2P communication, + // If not, we will use PCIE bandwidth to estimate latency. + static uint32_t CheckIfNvlinkSupportsP2P(); + + private: + static absl::Duration ComputeAllreduceTime( + const HloInstruction& instr, const GpuHloCostAnalysis* cost_analysis, + const se::DeviceDescription& gpu_device_info); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_PERFORMANCE_MODEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_reduce_scatter_creator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_reduce_scatter_creator.h new file mode 100644 index 0000000000000000000000000000000000000000..4bc1da7d003fccdb3775caaea3e0d0cadee91176 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_reduce_scatter_creator.h @@ -0,0 +1,39 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_REDUCE_SCATTER_CREATOR_H_ +#define XLA_SERVICE_GPU_GPU_REDUCE_SCATTER_CREATOR_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Transforms dynamic-slice(all-reduce) to a reduce-scatter. +class ReduceScatterCreator : public HloModulePass { + public: + ReduceScatterCreator() = default; + absl::string_view name() const override { return "reduce-scatter-creator"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_REDUCE_SCATTER_CREATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_sanitize_constant_names.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_sanitize_constant_names.h new file mode 100644 index 0000000000000000000000000000000000000000..70bbebd426ca5f9c133f7a9469f877c03814ab08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_sanitize_constant_names.h @@ -0,0 +1,41 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_SANITIZE_CONSTANT_NAMES_H_ +#define XLA_SERVICE_GPU_GPU_SANITIZE_CONSTANT_NAMES_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Sanitizes HLO instruction names for the GPU backend. Currently, it only +// replaces . and - in the HLO constant instruction names with _ to please the +// LLVM PTX backend. +class GpuSanitizeConstantNames : public HloModulePass { + public: + absl::string_view name() const override { return "sanitize-constant-names"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_SANITIZE_CONSTANT_NAMES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_scatter_expander.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_scatter_expander.h new file mode 100644 index 0000000000000000000000000000000000000000..7a91c309b1728b2218d2ab5d10411f5044f45e4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_scatter_expander.h @@ -0,0 +1,38 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_SCATTER_EXPANDER_H_ +#define XLA_SERVICE_GPU_GPU_SCATTER_EXPANDER_H_ + +#include "xla/service/scatter_expander.h" + +namespace xla { + +// Legalizes scatters on the GPU. +class GpuScatterExpander : public ScatterExpander { + public: + // Although we pass kEliminateAllScatters, we override this behavior in + // InstruuctionMatchesPattern and select only some scatters to expand. + GpuScatterExpander() : ScatterExpander(kEliminateAllScatters) {} + + absl::string_view name() const override { return "gpu_scatter_expander"; } + + protected: + bool InstructionMatchesPattern(HloInstruction* inst) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_SCATTER_EXPANDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_target_config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_target_config.h new file mode 100644 index 0000000000000000000000000000000000000000..1845bc755116cfb9cfe81a87e447cc0b851d1dae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_target_config.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_TARGET_CONFIG_H_ +#define XLA_SERVICE_GPU_GPU_TARGET_CONFIG_H_ + +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/dnn.h" + +namespace xla { +namespace gpu { + +struct GpuTargetConfig { + GpuTargetConfig() = default; + explicit GpuTargetConfig(const stream_executor::GpuTargetConfigProto& proto); + explicit GpuTargetConfig(stream_executor::StreamExecutor* s); + + stream_executor::GpuTargetConfigProto ToProto() const; + + stream_executor::DeviceDescription gpu_device_info; + std::string platform_name; + stream_executor::dnn::VersionInfo dnn_version_info; + std::string device_description_str; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_TARGET_CONFIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_transfer_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_transfer_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..5dcc291a9ff4036996088e8d91ecfb8533e2e133 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/gpu_transfer_manager.h @@ -0,0 +1,107 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_GPU_TRANSFER_MANAGER_H_ +#define XLA_SERVICE_GPU_GPU_TRANSFER_MANAGER_H_ + +#include + +#include "xla/service/generic_transfer_manager.h" +#include "xla/service/gpu/infeed_manager.h" +#include "xla/service/transfer_manager.h" +#include "xla/shape_tree.h" +#include "xla/statusor.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// An implementation of the XLA GenericTransferManager that +// handles GPU-specific infeed. +class GpuTransferManager : public GenericTransferManager { + public: + GpuTransferManager(se::Platform::Id id, unsigned pointer_size); + ~GpuTransferManager() override; + + Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal) override; + Status TransferLiteralFromOutfeed(se::StreamExecutor* executor, + MutableBorrowingLiteral literal) override; + Status ReadDynamicShapes(se::Stream* stream, + const ShapedBuffer* device_buffer, + Shape* device_shape) override; + + private: + GpuTransferManager(const GpuTransferManager&) = delete; + GpuTransferManager& operator=(const GpuTransferManager&) = delete; + + // This class keeps a pool of pinned memory + // (StreamExecutor::HostMemoryAllocate()) that serves ReadDynamicShapes(). + // This is a bit of a hack: Callers like TensorFlow already have a full pinned + // memory allocator, and we could in theory use it here and elsewhere in XLA. + // But because GpuTransferManager is a singleton, we can't really access that. + // + // To keep things relatively simple, our allocator does the following. + // + // - Allocate one chunk of 128 KiB pinned memory. + // - Divide each chunk into 128-byte buffers. + // - During ReadDynamicShapes(), "check out" one buffer for each dynamic + // subshape. Copy one subshape into one buffer. If it doesn't fit or + // there are no free buffers, fall back to an unpinned memcpy. + // + // A 128-byte buffer is large enough to hold a shape of rank 128/sizeof(int32) + // = 32, which is much larger than we normally see in XLA programs. A 128 KiB + // chunk is large enough to hold 128 KiB/128B = 1024 dynamically-shaped + // buffers, which is also way larger than we should need, even if we're + // running multiple programs in parallel. + // + // This pool is lazily initialized on first use. It would be better to + // initialize it in the constructor, but doing so poses a challenge in the + // presence of multiple GPUs. We need a StreamExecutor in order to allocate + // pinned memory. We don't care which GPU's SE we use, because SE allocates + // pinned memory with the PORTABLE flag, making it available to all CUDA + // contexts. But we do need to avoid calling platform->ExecutorForDevice for + // a device that we're not "supposed" to use, because this will create a CUDA + // context for that device, consuming significant resources on the GPU, + // b/228207839. + // + // Lazy initialization works around this, because at that point we have a + // stream, and therefore we have an already-initialized StreamExecutor. + void EnsurePinnedBuffersAllocated(se::StreamExecutor* executor) + ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + static constexpr int64_t kPinnedChunkBytes = 128 * 1024; + static constexpr int64_t kPinnedBufferBytes = 128; + + absl::Mutex mu_; + + // The StreamExecutor on which our pinned memory was allocated. We use this + // when freeing the pinned memory. Lazily initialized. + se::StreamExecutor* pinned_chunk_se_ ABSL_GUARDED_BY(mu_) = nullptr; + + // Chunk of pinned memory of size kPinnedChunkBytes. The pointers in + // pinned_buffers_ point into this chunk. Lazily initialized. + char* pinned_chunk_ ABSL_GUARDED_BY(mu_) = nullptr; + + // Host buffers for reading dynamic shapes. Each buffer has size + // kPinnedBufferBytes. Lazily initialized. + std::vector pinned_buffers_ ABSL_GUARDED_BY(mu_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_GPU_TRANSFER_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_algorithm_denylist.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_algorithm_denylist.h new file mode 100644 index 0000000000000000000000000000000000000000..5dfcb189a954e7fab04ce975abc4d04924cb3032 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_algorithm_denylist.h @@ -0,0 +1,34 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HLO_ALGORITHM_DENYLIST_H_ +#define XLA_SERVICE_GPU_HLO_ALGORITHM_DENYLIST_H_ + +#include + +#include "xla/autotuning.pb.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +absl::Span GetDisabledConvAlgorithms( + ComputeCapability cc, CudnnVersion cudnn_version, + const std::string& blas_version, const std::string& hlo); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_ALGORITHM_DENYLIST_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..131d9c090424702728170e84bd776d78c3234edb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_analysis.h @@ -0,0 +1,139 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HLO_FUSION_ANALYSIS_H_ +#define XLA_SERVICE_GPU_HLO_FUSION_ANALYSIS_H_ + +#include +#include +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/hlo_traversal.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/service/gpu/kernel_mapping_scheme.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/gpu/reduction_utils.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +class HloFusionAnalysis { + public: + // The type of emitted fusion. + enum class EmitterFusionKind { + kLoop, + kTriton, + kReduction, + kTranspose, + kInputSlices, + kScatter, + }; + + static StatusOr Create( + FusionBackendConfig backend_config, + std::vector hlo_roots, + FusionBoundaryFn boundary_fn, const se::DeviceDescription* device_info); + static StatusOr Create( + const HloFusionInstruction* fusion, + const se::DeviceDescription* device_info); + + const std::vector& fusion_roots() const { + return fusion_roots_; + } + const FusionBoundaryFn& fusion_boundary() const { + return fusion_boundary_fn_; + } + + // Determines the fusion type for the emitter. + EmitterFusionKind GetEmitterFusionKind() const; + + // Determines the launch dimensions for the fusion. The fusion kind must not + // be `kTriton`. + StatusOr GetLaunchDimensions(); + + // Calculates the reduction information. Returns `nullptr` if the fusion is + // not a reduction. + const ReductionCodegenInfo* GetReductionCodegenInfo(); + + // Calculates the transpose tiling information. Returns `nullptr` if the + // fusion is not a transpose. + const TilingScheme* GetTransposeTilingScheme(); + + // Calculates the loop fusion config. Returns `nullptr` if the fusion is not a + // loop. + const LaunchDimensionsConfig* GetLoopFusionConfig(); + + // Returns the hero reduction of the computation. + const HloInstruction* FindHeroReduction() const; + + private: + HloFusionAnalysis(FusionBackendConfig fusion_backend_config, + std::vector fusion_roots, + FusionBoundaryFn fusion_boundary_fn, + std::vector fusion_arguments, + std::vector fusion_heroes, + const se::DeviceDescription* device_info, + std::optional tiled_transpose) + : fusion_backend_config_(std::move(fusion_backend_config)), + fusion_roots_(std::move(fusion_roots)), + fusion_boundary_fn_(std::move(fusion_boundary_fn)), + fusion_arguments_(std::move(fusion_arguments)), + fusion_heroes_(std::move(fusion_heroes)), + device_info_(device_info), + tiled_transpose_(tiled_transpose) {} + + const Shape& GetElementShape() const; + int SmallestInputDtypeBits() const; + int64_t MaxBeneficialColumnReductionUnrollBasedOnBlockSize() const; + std::vector> GroupDisjointReductions() + const; + bool IsUnrollingColumnReductionBeneficial(const Shape& input_shape, + int64_t num_kept_minor, + bool reduction_is_race_free) const; + bool CanVectorizeReduction(const ReductionDimensions& reduction_dimensions, + int num_threads_x, Vector3 reduction_tiling, + const Shape& input_shape, + bool reduction_is_race_free) const; + int CalculateVirtualThreadScalingFactorForReduction( + const ReductionDimensions& reduction_dimensions) const; + ReductionCodegenInfo ComputeReductionCodegenInfo( + const HloInstruction* hero_reduction) const; + bool HasConsistentTransposeHeros() const; + + FusionBackendConfig fusion_backend_config_; + std::vector fusion_roots_; + FusionBoundaryFn fusion_boundary_fn_; + // The HLO instructions that are inputs into the fusion. These instructions + // are /outside/ the fusion. + std::vector fusion_arguments_; + std::vector fusion_heroes_; + const se::DeviceDescription* device_info_; + std::optional tiled_transpose_; + + std::optional reduction_codegen_info_; + std::optional transpose_tiling_scheme_; + std::optional loop_fusion_config_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_FUSION_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_stats.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..22e9348200d5b4185e5b5245402fc664da047151 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_fusion_stats.h @@ -0,0 +1,60 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HLO_FUSION_STATS_H_ +#define XLA_SERVICE_GPU_HLO_FUSION_STATS_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +// Read-only pass logging statistics about HLO fusion ops in the module. Enabled +// at VLOG level 1 only. +namespace xla { +namespace gpu { + +class HloOpcodeHistogram : public std::map, int64_t> { + public: + std::string ToString(); +}; + +class HloFusionStatsVisitor : public ConstDfsHloVisitorWithDefault { + public: + Status RunOnModule(HloModule* module); + + std::string ToString(); + + protected: + Status DefaultAction(const xla::HloInstruction* instr) final; + + Status HandleFusion(const HloInstruction* fusion) override; + + private: + int64_t num_fusions_ = 0; + int64_t num_loop_fusions_ = 0; + int64_t num_input_fusions_ = 0; + HloOpcodeHistogram loop_fusion_opcode_histogram_; + HloOpcodeHistogram input_fusion_opcode_histogram_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_FUSION_STATS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profile.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profile.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..a72a24080ed645f4ec9b58abec38249616c088aa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profile.pb.h @@ -0,0 +1,803 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/gpu/hlo_op_profile.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include "xla/service/hlo.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +namespace xla { +namespace gpu { +class DeviceHloInstructionProfiles; +struct DeviceHloInstructionProfilesDefaultTypeInternal; +extern DeviceHloInstructionProfilesDefaultTypeInternal _DeviceHloInstructionProfiles_default_instance_; +class DeviceHloInstructionProfiles_EntriesEntry_DoNotUse; +struct DeviceHloInstructionProfiles_EntriesEntry_DoNotUseDefaultTypeInternal; +extern DeviceHloInstructionProfiles_EntriesEntry_DoNotUseDefaultTypeInternal _DeviceHloInstructionProfiles_EntriesEntry_DoNotUse_default_instance_; +class HloInstructionProfile; +struct HloInstructionProfileDefaultTypeInternal; +extern HloInstructionProfileDefaultTypeInternal _HloInstructionProfile_default_instance_; +class HloInstructionProfileList; +struct HloInstructionProfileListDefaultTypeInternal; +extern HloInstructionProfileListDefaultTypeInternal _HloInstructionProfileList_default_instance_; +} // namespace gpu +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::gpu::DeviceHloInstructionProfiles* Arena::CreateMaybeMessage<::xla::gpu::DeviceHloInstructionProfiles>(Arena*); +template<> ::xla::gpu::DeviceHloInstructionProfiles_EntriesEntry_DoNotUse* Arena::CreateMaybeMessage<::xla::gpu::DeviceHloInstructionProfiles_EntriesEntry_DoNotUse>(Arena*); +template<> ::xla::gpu::HloInstructionProfile* Arena::CreateMaybeMessage<::xla::gpu::HloInstructionProfile>(Arena*); +template<> ::xla::gpu::HloInstructionProfileList* Arena::CreateMaybeMessage<::xla::gpu::HloInstructionProfileList>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace gpu { + +// =================================================================== + +class HloInstructionProfile final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.HloInstructionProfile) */ { + public: + inline HloInstructionProfile() : HloInstructionProfile(nullptr) {} + ~HloInstructionProfile() override; + explicit PROTOBUF_CONSTEXPR HloInstructionProfile(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInstructionProfile(const HloInstructionProfile& from); + HloInstructionProfile(HloInstructionProfile&& from) noexcept + : HloInstructionProfile() { + *this = ::std::move(from); + } + + inline HloInstructionProfile& operator=(const HloInstructionProfile& from) { + CopyFrom(from); + return *this; + } + inline HloInstructionProfile& operator=(HloInstructionProfile&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const HloInstructionProfile& default_instance() { + return *internal_default_instance(); + } + static inline const HloInstructionProfile* internal_default_instance() { + return reinterpret_cast( + &_HloInstructionProfile_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(HloInstructionProfile& a, HloInstructionProfile& b) { + a.Swap(&b); + } + inline void Swap(HloInstructionProfile* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(HloInstructionProfile* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInstructionProfile* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInstructionProfile& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInstructionProfile& from) { + HloInstructionProfile::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(HloInstructionProfile* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.HloInstructionProfile"; + } + protected: + explicit HloInstructionProfile(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kInstructionFieldNumber = 1, + kClockCyclesFieldNumber = 2, + }; + // .xla.HloInstructionProto instruction = 1; + bool has_instruction() const; + private: + bool _internal_has_instruction() const; + public: + void clear_instruction(); + const ::xla::HloInstructionProto& instruction() const; + PROTOBUF_NODISCARD ::xla::HloInstructionProto* release_instruction(); + ::xla::HloInstructionProto* mutable_instruction(); + void set_allocated_instruction(::xla::HloInstructionProto* instruction); + private: + const ::xla::HloInstructionProto& _internal_instruction() const; + ::xla::HloInstructionProto* _internal_mutable_instruction(); + public: + void unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction); + ::xla::HloInstructionProto* unsafe_arena_release_instruction(); + + // int64 clock_cycles = 2; + void clear_clock_cycles(); + int64_t clock_cycles() const; + void set_clock_cycles(int64_t value); + private: + int64_t _internal_clock_cycles() const; + void _internal_set_clock_cycles(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:xla.gpu.HloInstructionProfile) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::xla::HloInstructionProto* instruction_; + int64_t clock_cycles_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; +// ------------------------------------------------------------------- + +class HloInstructionProfileList final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.HloInstructionProfileList) */ { + public: + inline HloInstructionProfileList() : HloInstructionProfileList(nullptr) {} + ~HloInstructionProfileList() override; + explicit PROTOBUF_CONSTEXPR HloInstructionProfileList(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + HloInstructionProfileList(const HloInstructionProfileList& from); + HloInstructionProfileList(HloInstructionProfileList&& from) noexcept + : HloInstructionProfileList() { + *this = ::std::move(from); + } + + inline HloInstructionProfileList& operator=(const HloInstructionProfileList& from) { + CopyFrom(from); + return *this; + } + inline HloInstructionProfileList& operator=(HloInstructionProfileList&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const HloInstructionProfileList& default_instance() { + return *internal_default_instance(); + } + static inline const HloInstructionProfileList* internal_default_instance() { + return reinterpret_cast( + &_HloInstructionProfileList_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(HloInstructionProfileList& a, HloInstructionProfileList& b) { + a.Swap(&b); + } + inline void Swap(HloInstructionProfileList* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(HloInstructionProfileList* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + HloInstructionProfileList* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const HloInstructionProfileList& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const HloInstructionProfileList& from) { + HloInstructionProfileList::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(HloInstructionProfileList* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.HloInstructionProfileList"; + } + protected: + explicit HloInstructionProfileList(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kEntriesFieldNumber = 1, + }; + // repeated .xla.gpu.HloInstructionProfile entries = 1; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + ::xla::gpu::HloInstructionProfile* mutable_entries(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >* + mutable_entries(); + private: + const ::xla::gpu::HloInstructionProfile& _internal_entries(int index) const; + ::xla::gpu::HloInstructionProfile* _internal_add_entries(); + public: + const ::xla::gpu::HloInstructionProfile& entries(int index) const; + ::xla::gpu::HloInstructionProfile* add_entries(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >& + entries() const; + + // @@protoc_insertion_point(class_scope:xla.gpu.HloInstructionProfileList) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile > entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; +// ------------------------------------------------------------------- + +class DeviceHloInstructionProfiles_EntriesEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + DeviceHloInstructionProfiles_EntriesEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR DeviceHloInstructionProfiles_EntriesEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit DeviceHloInstructionProfiles_EntriesEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const DeviceHloInstructionProfiles_EntriesEntry_DoNotUse& other); + static const DeviceHloInstructionProfiles_EntriesEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_DeviceHloInstructionProfiles_EntriesEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "xla.gpu.DeviceHloInstructionProfiles.EntriesEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; + +// ------------------------------------------------------------------- + +class DeviceHloInstructionProfiles final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.gpu.DeviceHloInstructionProfiles) */ { + public: + inline DeviceHloInstructionProfiles() : DeviceHloInstructionProfiles(nullptr) {} + ~DeviceHloInstructionProfiles() override; + explicit PROTOBUF_CONSTEXPR DeviceHloInstructionProfiles(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DeviceHloInstructionProfiles(const DeviceHloInstructionProfiles& from); + DeviceHloInstructionProfiles(DeviceHloInstructionProfiles&& from) noexcept + : DeviceHloInstructionProfiles() { + *this = ::std::move(from); + } + + inline DeviceHloInstructionProfiles& operator=(const DeviceHloInstructionProfiles& from) { + CopyFrom(from); + return *this; + } + inline DeviceHloInstructionProfiles& operator=(DeviceHloInstructionProfiles&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const DeviceHloInstructionProfiles& default_instance() { + return *internal_default_instance(); + } + static inline const DeviceHloInstructionProfiles* internal_default_instance() { + return reinterpret_cast( + &_DeviceHloInstructionProfiles_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(DeviceHloInstructionProfiles& a, DeviceHloInstructionProfiles& b) { + a.Swap(&b); + } + inline void Swap(DeviceHloInstructionProfiles* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(DeviceHloInstructionProfiles* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DeviceHloInstructionProfiles* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DeviceHloInstructionProfiles& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DeviceHloInstructionProfiles& from) { + DeviceHloInstructionProfiles::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(DeviceHloInstructionProfiles* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.gpu.DeviceHloInstructionProfiles"; + } + protected: + explicit DeviceHloInstructionProfiles(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kEntriesFieldNumber = 2, + }; + // map entries = 2; + int entries_size() const; + private: + int _internal_entries_size() const; + public: + void clear_entries(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& + _internal_entries() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* + _internal_mutable_entries(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& + entries() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* + mutable_entries(); + + // @@protoc_insertion_point(class_scope:xla.gpu.DeviceHloInstructionProfiles) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + DeviceHloInstructionProfiles_EntriesEntry_DoNotUse, + std::string, ::xla::gpu::HloInstructionProfileList, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> entries_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// HloInstructionProfile + +// .xla.HloInstructionProto instruction = 1; +inline bool HloInstructionProfile::_internal_has_instruction() const { + return this != internal_default_instance() && _impl_.instruction_ != nullptr; +} +inline bool HloInstructionProfile::has_instruction() const { + return _internal_has_instruction(); +} +inline const ::xla::HloInstructionProto& HloInstructionProfile::_internal_instruction() const { + const ::xla::HloInstructionProto* p = _impl_.instruction_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_HloInstructionProto_default_instance_); +} +inline const ::xla::HloInstructionProto& HloInstructionProfile::instruction() const { + // @@protoc_insertion_point(field_get:xla.gpu.HloInstructionProfile.instruction) + return _internal_instruction(); +} +inline void HloInstructionProfile::unsafe_arena_set_allocated_instruction( + ::xla::HloInstructionProto* instruction) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + _impl_.instruction_ = instruction; + if (instruction) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:xla.gpu.HloInstructionProfile.instruction) +} +inline ::xla::HloInstructionProto* HloInstructionProfile::release_instruction() { + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::HloInstructionProto* HloInstructionProfile::unsafe_arena_release_instruction() { + // @@protoc_insertion_point(field_release:xla.gpu.HloInstructionProfile.instruction) + + ::xla::HloInstructionProto* temp = _impl_.instruction_; + _impl_.instruction_ = nullptr; + return temp; +} +inline ::xla::HloInstructionProto* HloInstructionProfile::_internal_mutable_instruction() { + + if (_impl_.instruction_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::HloInstructionProto>(GetArenaForAllocation()); + _impl_.instruction_ = p; + } + return _impl_.instruction_; +} +inline ::xla::HloInstructionProto* HloInstructionProfile::mutable_instruction() { + ::xla::HloInstructionProto* _msg = _internal_mutable_instruction(); + // @@protoc_insertion_point(field_mutable:xla.gpu.HloInstructionProfile.instruction) + return _msg; +} +inline void HloInstructionProfile::set_allocated_instruction(::xla::HloInstructionProto* instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.instruction_); + } + if (instruction) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(instruction)); + if (message_arena != submessage_arena) { + instruction = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, instruction, submessage_arena); + } + + } else { + + } + _impl_.instruction_ = instruction; + // @@protoc_insertion_point(field_set_allocated:xla.gpu.HloInstructionProfile.instruction) +} + +// int64 clock_cycles = 2; +inline void HloInstructionProfile::clear_clock_cycles() { + _impl_.clock_cycles_ = int64_t{0}; +} +inline int64_t HloInstructionProfile::_internal_clock_cycles() const { + return _impl_.clock_cycles_; +} +inline int64_t HloInstructionProfile::clock_cycles() const { + // @@protoc_insertion_point(field_get:xla.gpu.HloInstructionProfile.clock_cycles) + return _internal_clock_cycles(); +} +inline void HloInstructionProfile::_internal_set_clock_cycles(int64_t value) { + + _impl_.clock_cycles_ = value; +} +inline void HloInstructionProfile::set_clock_cycles(int64_t value) { + _internal_set_clock_cycles(value); + // @@protoc_insertion_point(field_set:xla.gpu.HloInstructionProfile.clock_cycles) +} + +// ------------------------------------------------------------------- + +// HloInstructionProfileList + +// repeated .xla.gpu.HloInstructionProfile entries = 1; +inline int HloInstructionProfileList::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int HloInstructionProfileList::entries_size() const { + return _internal_entries_size(); +} +inline void HloInstructionProfileList::clear_entries() { + _impl_.entries_.Clear(); +} +inline ::xla::gpu::HloInstructionProfile* HloInstructionProfileList::mutable_entries(int index) { + // @@protoc_insertion_point(field_mutable:xla.gpu.HloInstructionProfileList.entries) + return _impl_.entries_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >* +HloInstructionProfileList::mutable_entries() { + // @@protoc_insertion_point(field_mutable_list:xla.gpu.HloInstructionProfileList.entries) + return &_impl_.entries_; +} +inline const ::xla::gpu::HloInstructionProfile& HloInstructionProfileList::_internal_entries(int index) const { + return _impl_.entries_.Get(index); +} +inline const ::xla::gpu::HloInstructionProfile& HloInstructionProfileList::entries(int index) const { + // @@protoc_insertion_point(field_get:xla.gpu.HloInstructionProfileList.entries) + return _internal_entries(index); +} +inline ::xla::gpu::HloInstructionProfile* HloInstructionProfileList::_internal_add_entries() { + return _impl_.entries_.Add(); +} +inline ::xla::gpu::HloInstructionProfile* HloInstructionProfileList::add_entries() { + ::xla::gpu::HloInstructionProfile* _add = _internal_add_entries(); + // @@protoc_insertion_point(field_add:xla.gpu.HloInstructionProfileList.entries) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::xla::gpu::HloInstructionProfile >& +HloInstructionProfileList::entries() const { + // @@protoc_insertion_point(field_list:xla.gpu.HloInstructionProfileList.entries) + return _impl_.entries_; +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// DeviceHloInstructionProfiles + +// map entries = 2; +inline int DeviceHloInstructionProfiles::_internal_entries_size() const { + return _impl_.entries_.size(); +} +inline int DeviceHloInstructionProfiles::entries_size() const { + return _internal_entries_size(); +} +inline void DeviceHloInstructionProfiles::clear_entries() { + _impl_.entries_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& +DeviceHloInstructionProfiles::_internal_entries() const { + return _impl_.entries_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >& +DeviceHloInstructionProfiles::entries() const { + // @@protoc_insertion_point(field_map:xla.gpu.DeviceHloInstructionProfiles.entries) + return _internal_entries(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* +DeviceHloInstructionProfiles::_internal_mutable_entries() { + return _impl_.entries_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::xla::gpu::HloInstructionProfileList >* +DeviceHloInstructionProfiles::mutable_entries() { + // @@protoc_insertion_point(field_mutable_map:xla.gpu.DeviceHloInstructionProfiles.entries) + return _internal_mutable_entries(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace gpu +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fgpu_2fhlo_5fop_5fprofile_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profiles.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profiles.h new file mode 100644 index 0000000000000000000000000000000000000000..e8b73f73fd22a12e7e69ea945e5e5d9ef817838e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_op_profiles.h @@ -0,0 +1,3092 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HLO_OP_PROFILES_H_ +#define XLA_SERVICE_GPU_HLO_OP_PROFILES_H_ + +namespace xla { +namespace gpu { + +// The data below is obtained with +// xla/service/gpu:hlo_op_profiler_run + +constexpr char kDeviceHloOpProfiles[] = R"pb( + entries { + key: "sm_90" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 351 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S8 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: S8 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 375 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: S16 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 298 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S32 } + } + clock_cycles: 3 + } + entries { + instruction { + opcode: "power" + shape { element_type: S32 } + } + clock_cycles: 66 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 698 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: S64 } + } + clock_cycles: 10 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 238 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 308 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U8 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 301 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U32 } + } + clock_cycles: 119 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U32 } + } + clock_cycles: 3 + } + entries { + instruction { + opcode: "power" + shape { element_type: U32 } + } + clock_cycles: 66 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 621 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: U64 } + } + clock_cycles: 10 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 238 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 466 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 329 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 105 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 217 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 182 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 245 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 94 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F16 } + } + clock_cycles: 333 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 98 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 200 + } + entries { + instruction { + opcode: "add" + shape { element_type: F16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F16 } + } + clock_cycles: 449 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F16 } + } + clock_cycles: 45 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 491 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F16 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 400 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 326 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 80 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 196 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 157 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 221 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F32 } + } + clock_cycles: 77 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 933 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F32 } + } + clock_cycles: 77 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 179 + } + entries { + instruction { + opcode: "add" + shape { element_type: F32 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 428 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F32 } + } + clock_cycles: 24 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F32 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 487 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F32 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1656 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 568 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 382 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 403 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 800 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1210 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 277 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 561 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 333 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 393 + } + entries { + instruction { + opcode: "add" + shape { element_type: F64 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 866 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 530 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F64 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 2179 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F64 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C64 } + } + clock_cycles: 579 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C64 } + } + clock_cycles: 635 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C64 } + } + clock_cycles: 631 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 807 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 614 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 2815 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C64 } + } + clock_cycles: 723 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 4113 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C64 } + } + clock_cycles: 2348 + } + entries { + instruction { + opcode: "add" + shape { element_type: C64 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 6047 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 452 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C64 } + } + clock_cycles: 77 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 4706 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C64 } + } + clock_cycles: 7 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 1779 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 1333 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 1288 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 2337 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2299 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 5036 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 1997 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 6181 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 4419 + } + entries { + instruction { + opcode: "add" + shape { element_type: C128 } + } + clock_cycles: 14 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 12453 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 2270 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C128 } + } + clock_cycles: 38 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 7339 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C128 } + } + clock_cycles: 14 + } + } + } + entries { + key: "sm_86" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 370 + } + entries { + instruction { + opcode: "power" + shape { element_type: S8 } + } + clock_cycles: 392 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 367 + } + entries { + instruction { + opcode: "power" + shape { element_type: S16 } + } + clock_cycles: 396 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 306 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 918 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 601 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 306 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 388 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 302 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 399 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U32 } + } + clock_cycles: 115 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 838 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 604 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 925 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 691 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 108 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 396 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 266 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 284 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F16 } + } + clock_cycles: 226 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 212 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F16 } + } + clock_cycles: 482 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 975 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 867 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 662 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 86 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 381 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 244 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 262 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F32 } + } + clock_cycles: 176 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F32 } + } + clock_cycles: 75 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 662 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F32 } + } + clock_cycles: 75 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 190 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 486 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 925 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 6339 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 1717 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 1652 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 1900 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 608 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 2073 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F64 } + } + clock_cycles: 2412 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 698 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 1789 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 986 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 1609 + } + entries { + instruction { + opcode: "add" + shape { element_type: F64 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 3747 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 2016 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F64 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 5511 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F64 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C64 } + } + clock_cycles: 1360 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C64 } + } + clock_cycles: 1400 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 950 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 842 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 2383 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 3193 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 5353 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 687 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 3351 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 6613 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 4028 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 4161 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 7599 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 6962 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 11318 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 5878 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 15606 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 9939 + } + entries { + instruction { + opcode: "add" + shape { element_type: C128 } + } + clock_cycles: 97 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 39027 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 7941 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C128 } + } + clock_cycles: 270 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 18205 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C128 } + } + clock_cycles: 97 + } + } + } + + entries { key: "sm_80" + value { entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 417 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 468 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 1094 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 420 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 417 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 391 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 454 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 908 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 744 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 1195 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 321 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 346 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 124 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 499 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 259 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 504 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1221 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1638 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 572 + })pb" + R"pb( + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 699 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1223 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 329 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 597 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 397 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 733 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 1080 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 831 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 1861 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 1037 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 1029 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 6618 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 4131 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 2309 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 2371 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2405 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 3945 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 2284 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 5304 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 3618 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 13564 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 3037 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 6054 + } + } + } + + entries { + key: "sm_70" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 345 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 345 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 954 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 302 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 526 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 309 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 544 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 749 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 820 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 1227 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 865 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 137 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 544 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 354 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 388 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 122 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F16 } + } + clock_cycles: 841 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 134 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 556 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 1279 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 1168 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 823 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 110 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 514 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 333 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 361 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 529 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 660 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1214 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1392 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 673 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 474 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 676 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 618 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1061 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 290 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 667 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 391 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 709 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 1178 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 682 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 1679 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C64 } + } + clock_cycles: 1762 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 1450 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 1141 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C64 } + } + clock_cycles: 1787 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 3935 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 7025 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 948 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 4277 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 2386 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 1881 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 1875 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 2622 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2328 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 4531 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 2408 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 5388 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 3867 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 13794 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 3001 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 6046 + } + } + } + + entries { + key: "sm_60" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 438 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 479 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 758 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 2037 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 2937 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 307 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 293 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 1708 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 2993 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 1661 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 213 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 778 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 598 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 538 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F16 } + } + clock_cycles: 402 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 130 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 453 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 1717 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 1672 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 168 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 731 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 435 + } + )pb" + R"pb( + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 589 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F32 } + } + clock_cycles: 343 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 1024 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 417 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 873 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1779 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 1649 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 1175 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 639 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 911 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 935 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1421 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F64 } + } + clock_cycles: 1098 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 355 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 1187 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 645 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 917 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 1394 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 959 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 2667 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 1726 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 1518 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 4142 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 5069 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C64 } + } + clock_cycles: 4053 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 9469 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C64 } + } + clock_cycles: 1317 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 5617 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 3416 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 2730 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 2765 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 3106 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 2895 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 5922 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 3496 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 7014 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 5400 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 21766 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 4133 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 10458 + } + } + } + + entries { + key: "sm_75" + value { + entries { + instruction { + opcode: "divide" + shape { element_type: S8 } + } + clock_cycles: 360 + } + entries { + instruction { + opcode: "power" + shape { element_type: S8 } + } + clock_cycles: 336 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S16 } + } + clock_cycles: 357 + } + entries { + instruction { + opcode: "power" + shape { element_type: S16 } + } + clock_cycles: 339 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S32 } + } + clock_cycles: 296 + } + entries { + instruction { + opcode: "divide" + shape { element_type: S64 } + } + clock_cycles: 979 + } + entries { + instruction { + opcode: "power" + shape { element_type: S64 } + } + clock_cycles: 495 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U8 } + } + clock_cycles: 293 + } + entries { + instruction { + opcode: "power" + shape { element_type: U8 } + } + clock_cycles: 334 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U16 } + } + clock_cycles: 290 + } + entries { + instruction { + opcode: "power" + shape { element_type: U16 } + } + clock_cycles: 336 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U32 } + } + clock_cycles: 118 + } + entries { + instruction { + opcode: "divide" + shape { element_type: U64 } + } + clock_cycles: 812 + } + entries { + instruction { + opcode: "power" + shape { element_type: U64 } + } + clock_cycles: 515 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F16 } + } + clock_cycles: 792 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F16 } + } + clock_cycles: 815 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F16 } + } + clock_cycles: 132 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F16 } + } + clock_cycles: 342 + } + entries { + instruction { + opcode: "log" + shape { element_type: F16 } + } + clock_cycles: 239 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F16 } + } + clock_cycles: 239 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F16 } + } + clock_cycles: 262 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F16 } + } + clock_cycles: 126 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F16 } + } + clock_cycles: 794 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F16 } + } + clock_cycles: 123 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F16 } + } + clock_cycles: 175 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F16 } + } + clock_cycles: 414 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F16 } + } + clock_cycles: 74 + } + entries { + instruction { + opcode: "power" + shape { element_type: F16 } + } + clock_cycles: 1120 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F32 } + } + clock_cycles: 783 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F32 } + } + clock_cycles: 737 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F32 } + } + clock_cycles: 83 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F32 } + } + clock_cycles: 319 + } + entries { + instruction { + opcode: "log" + shape { element_type: F32 } + } + clock_cycles: 201 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F32 } + } + clock_cycles: 218 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F32 } + } + clock_cycles: 181 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F32 } + } + clock_cycles: 74 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F32 } + } + clock_cycles: 717 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F32 } + } + clock_cycles: 74 + } + )pb" + R"pb( + entries { + instruction { + opcode: "tanh" + shape { element_type: F32 } + } + clock_cycles: 167 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F32 } + } + clock_cycles: 414 + } + entries { + instruction { + opcode: "power" + shape { element_type: F32 } + } + clock_cycles: 1085 + } + entries { + instruction { + opcode: "cbrt" + shape { element_type: F64 } + } + clock_cycles: 6494 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: F64 } + } + clock_cycles: 1800 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: F64 } + } + clock_cycles: 1630 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: F64 } + } + clock_cycles: 1929 + } + entries { + instruction { + opcode: "log" + shape { element_type: F64 } + } + clock_cycles: 596 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: F64 } + } + clock_cycles: 1774 + } + entries { + instruction { + opcode: "logistic" + shape { element_type: F64 } + } + clock_cycles: 2430 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: F64 } + } + clock_cycles: 705 + } + entries { + instruction { + opcode: "sine" + shape { element_type: F64 } + } + clock_cycles: 1805 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: F64 } + } + clock_cycles: 984 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: F64 } + } + clock_cycles: 1535 + } + entries { + instruction { + opcode: "add" + shape { element_type: F64 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: F64 } + } + clock_cycles: 3744 + } + entries { + instruction { + opcode: "divide" + shape { element_type: F64 } + } + clock_cycles: 1915 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: F64 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "power" + shape { element_type: F64 } + } + clock_cycles: 5538 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: F64 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C64 } + } + clock_cycles: 1702 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C64 } + } + clock_cycles: 1503 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C64 } + } + clock_cycles: 1474 + } + entries { + instruction { + opcode: "log" + shape { element_type: C64 } + } + clock_cycles: 835 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C64 } + } + clock_cycles: 737 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C64 } + } + clock_cycles: 2232 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C64 } + } + clock_cycles: 1632 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C64 } + } + clock_cycles: 2989 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C64 } + } + clock_cycles: 2263 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C64 } + } + clock_cycles: 4847 + } + entries { + instruction { + opcode: "power" + shape { element_type: C64 } + } + clock_cycles: 3219 + } + entries { + instruction { + opcode: "cosine" + shape { element_type: C128 } + } + clock_cycles: 6474 + } + entries { + instruction { + opcode: "exponential" + shape { element_type: C128 } + } + clock_cycles: 4962 + } + entries { + instruction { + opcode: "exponential-minus-one" + shape { element_type: C128 } + } + clock_cycles: 4037 + } + entries { + instruction { + opcode: "log" + shape { element_type: C128 } + } + clock_cycles: 7286 + } + entries { + instruction { + opcode: "log-plus-one" + shape { element_type: C128 } + } + clock_cycles: 6848 + } + entries { + instruction { + opcode: "rsqrt" + shape { element_type: C128 } + } + clock_cycles: 10748 + } + entries { + instruction { + opcode: "sine" + shape { element_type: C128 } + } + clock_cycles: 5391 + } + entries { + instruction { + opcode: "sqrt" + shape { element_type: C128 } + } + clock_cycles: 15981 + } + entries { + instruction { + opcode: "tanh" + shape { element_type: C128 } + } + clock_cycles: 9653 + } + entries { + instruction { + opcode: "add" + shape { element_type: C128 } + } + clock_cycles: 95 + } + entries { + instruction { + opcode: "atan2" + shape { element_type: C128 } + } + clock_cycles: 38206 + } + entries { + instruction { + opcode: "divide" + shape { element_type: C128 } + } + clock_cycles: 8040 + } + entries { + instruction { + opcode: "multiply" + shape { element_type: C128 } + } + clock_cycles: 273 + } + entries { + instruction { + opcode: "power" + shape { element_type: C128 } + } + clock_cycles: 18550 + } + entries { + instruction { + opcode: "subtract" + shape { element_type: C128 } + } + clock_cycles: 97 + } + } + } +)pb"; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_OP_PROFILES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_to_ir_bindings.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_to_ir_bindings.h new file mode 100644 index 0000000000000000000000000000000000000000..3696968160ad1fee484ab917403d1fe12752bfaf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_to_ir_bindings.h @@ -0,0 +1,116 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HLO_TO_IR_BINDINGS_H_ +#define XLA_SERVICE_GPU_HLO_TO_IR_BINDINGS_H_ + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/map_util.h" +#include "xla/service/llvm_ir/ir_array.h" + +namespace xla { +namespace gpu { + +// This class encapsulates the bindings between HloInstructions and LLVM IR +// values that represent their addresses. +class HloToIrBindings { + public: + HloToIrBindings(llvm::IRBuilder<>* b, llvm::Module* llvm_module, + bool is_nested) + : is_nested_(is_nested), b_(b), module_(llvm_module) {} + + void EmitBasePointersForHlos( + absl::Span io_hlos, + absl::Span non_io_hlos); + + // Rebinds the given HLO to the LLVM IR value that represent its address. + void BindHloToIrValue(const HloInstruction& hlo, llvm::Value* ir_value, + ShapeIndexView shape_index = {}); + + // Unbinds all IR values that's defined in an LLVM function, e.g., function + // arguments and stack variables. Global variables will be kept in bindings_. + // + // This method is called after emitting code for each top-level HLO. The local + // IR values are out of scope at that point and should not be used. + void UnbindAllLocalIrValues(); + + // Returns whether `hlo` is bound to an LLVM IR value. + bool BoundToIrValue(const HloInstruction& hlo) const { + return base_ptrs_.contains(&hlo); + } + + llvm::Value* GetTempBufferBase() const { return temp_buffer_base_; } + void SetTempBufferBase(llvm::Value* v) { temp_buffer_base_ = v; } + + // A helper method that returns the base pointer of the IrArray containing the + // output of "inst".at the given ShapeIndex. + llvm::Value* GetBasePointer(const HloInstruction& hlo, + ShapeIndexView shape_index = {}) const { + auto it = base_ptrs_.find(&hlo); + CHECK(it != base_ptrs_.end()) << hlo.ToString(); + return it->second.element(shape_index); + } + + // Returns the IrArray which contains the output of hlo. + // + // consumer is the HLO in which this IrArray is used -- we use this to (try + // to) add metadata indicating that the array is invariant within consumer. + // + // To get the buffer into which hlo should write its own output, call + // GetIrArray(hlo, hlo). + llvm_ir::IrArray GetIrArray(const HloInstruction& hlo, + const HloInstruction& consumer, + const ShapeIndex& shape_index = {}); + + std::string ToString() const; + + private: + // Emits IR to resolve (possibly) recursive GetTupleElement instructions. + llvm::Value* EmitGetTupleElement(const HloInstruction* gte, + llvm::Value* base_ptr); + + // Returns an llvm typed ir representation of 'ir_value' based on 'hlo' shape. + llvm::Value* GetTypedIrValue(const HloInstruction& hlo, + ShapeIndexView shape_index, + llvm::Value* ir_value); + + const bool is_nested_; + + llvm::IRBuilder<>* b_; + llvm::Module* module_; + + // Stores the underlying llvm::IrArray for each HloInstruction. + // For an instruction that generates multiple outputs, the root will be a + // tuple shape. The IrArray for each element output is stored in the subnode + // in the ShapeTree. + absl::flat_hash_map> + base_ptrs_; + + // The address of the memory block that contains all temporary buffers. + llvm::Value* temp_buffer_base_ = nullptr; +}; + +// Converts `ir_value` with type i8* to a typed LLVM Value* based on `shape`. +llvm::Value* CastToTypedValue(const Shape& shape, llvm::Value* ir_value, + llvm::IRBuilder<>* b); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_TO_IR_BINDINGS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_traversal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_traversal.h new file mode 100644 index 0000000000000000000000000000000000000000..799a427de94fcc8a46b8679bf280f828eba77eab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/hlo_traversal.h @@ -0,0 +1,81 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_HLO_TRAVERSAL_H_ +#define XLA_SERVICE_GPU_HLO_TRAVERSAL_H_ + +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { +namespace gpu { + +enum class TraversalResult { + // Visit the operands of this node. + kVisitOperands, + // Do not visit any more nodes. + kAbortTraversal, + // Do not visit the operands of this node (but continue the traversal + // otherwise). If the node visitation function returns this, the `boundary` + // condition will not be evaluated. + kDoNotVisitOperands, +}; + +using FusionBoundaryFn = std::function; + +// Boundary function for HloFusionInstructions. +bool DefaultFusionBoundaryFn(const HloInstruction& producer, + const HloInstruction& consumer); + +// Creates a fusion boundary function for fusing the given producer and +// consumer. `fused_consumer` must be a consumer of `fused_producer`. +FusionBoundaryFn MakeProducerConsumerFusion( + const HloInstruction& fused_producer, const HloInstruction& fused_consumer); + +// Visit the HLO nodes starting from `roots` in BFS order (consumers before +// producers). Each node will be visited exactly once. The graph is not +// traversed along edges for which `boundary` returns true. +void HloBfsConsumersFirstTraversal( + absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +// Visit the HLO nodes starting from `roots`, returning true if the return value +// of `visit` for any of nodes is true. Uses the same order as +// `HloBfsConsumersFirstTraversal`. +bool HloAnyOf(absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +// Visit the HLO nodes stating from `roots`, returning the first +// node for which `visit` returns true, or `nullptr` if no node matches. Uses +// the same order as `HloBfsConsumersFirstTraversal`. +const HloInstruction* HloFindIf( + absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +// Visit the producers of all parameters that are needed by the fusion. +void FindFusionArguments( + absl::Span roots, + const FusionBoundaryFn& boundary, + const std::function& visit); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HLO_TRAVERSAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_input_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_input_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..0dc45c90adb5f765cc86b94793100ae5b2bc1c53 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_input_fusion.h @@ -0,0 +1,62 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HORIZONTAL_INPUT_FUSION_H_ +#define XLA_SERVICE_GPU_HORIZONTAL_INPUT_FUSION_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// This optimization pass horizontally fuses kInput fusions to both reduce the +// kernel launch overhead and increase parallelism degree. See +// GpuHorizontalFusion for general description and motivation about horizontal +// fusion. GpuHorizontalFusion deals with kLoop fusions while this pass deals +// with kInput fusions. +// +// Following GpuHorizontalFusion, a simple yet effective heuristic is used +// to search the fusion candidates while avoiding creating cycles. That is, +// we simply search for fusion candidates by looking for instructions whose +// outputs are all consumed by the same instruction. This catches the typical +// target cases; often, the candidate instructions are just consumed by the +// ROOT tuple of the entry computation. +class GpuHorizontalInputFusion : public HloModulePass { + public: + explicit GpuHorizontalInputFusion(const se::DeviceDescription& d) + : device_info_(d) {} + + absl::string_view name() const override { + return "gpu_horizontal_input_fusion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation*); + + const se::DeviceDescription& device_info_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HORIZONTAL_INPUT_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_loop_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_loop_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..4d81ba65412f4d6370f93e8d172dc84be3c5666d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/horizontal_loop_fusion.h @@ -0,0 +1,142 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_HORIZONTAL_LOOP_FUSION_H_ +#define XLA_SERVICE_GPU_HORIZONTAL_LOOP_FUSION_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// This optimization pass horizontally fuses computations for reducing kernel +// launch overhead while increasing kernel launch dims on GPU. The initial +// motivation of this horizontal fusion is due to the observation that the +// training optimizer phase (e.g., AdamOptimizer and L2Loss, etc.) typically +// has many small kernels as a result of applying the same formula on many +// training parameters (or variables in Tensorflow). Fusing these small +// kernels, hence, provides performance gain. +// +// Theoretically speaking, we may implement a cycle detection algorithm to make +// sure no cycles are created after fusion. However, cycle detection check is +// somewhat cumbersome; also, we observe that naive horizontal fusion of +// arbitrary kernels may not be profitable due to control divergence and +// possible increase of memory bandwidth pressure due to uncoalesced memory +// accesses (note that horizontal fusion does not change the amount of memory +// read+written at all). In practice, a simple yet effective heuristic is used +// to avoid these issues while addressing the known beneficial cases. That is, +// we simply search for fusion candidates by looking for instructions whose +// outputs are all consumed by the same instruction. This catches the cases in +// the training optimizer phase, as the candidate instructions are typically +// consumed only by the ROOT tuple of the entry computation. +// +// The following illustrates the mechanism of the horizontal fusion. Before +// fusion, there are two trivial kernels in the illustrating example. One has +// only a Mul op, while the other consists of only an Add op. Since they are +// only consumed by the same (ROOT) tuple instruction, horizontal fusion is +// triggered. +// +// i0 i1 i2 i3 +// | | | | +// v v v v +// Mul Add +// | | +// v v +// (ROOT) tuple +// +// We fuse into one of two possible patterns, depending on whether all the +// fused operations have the same shape or not. +// +// case 1: if Mul and Add's output shape and type are the same, then we fuse +// them into the below pattern: i0 i1 i2 i3 +// | | | | +// v v v v +// Mul Add +// | | +// v v +// (ROOT) tuple +// the fused kernel will be kLoop type, i.e, GPU code is emitted through +// IrEmitterUnnested::EmitLoopFusion +// +// case 2: if Mul and Add's output shape are diffent, then we fuse them into +// the below pattern that adds extra indexing: +// i0 i1 i2 i3 +++ (Slice) Input Fusion +// | | | | + +// v v v v + +// Mul Add + +// | | + +// v v + +// Reshape0 Reshape1 + +// | | + +// v v + +// Concatenate + +// | | + +// v v + +// Slice0 Slice1 +++ +// | | +// v v +// Reshape2 Reshape3 +// | | +// v v +// (ROOT) tuple +// +// the fused kernel will be kInput type, and, the GPU code is emitted through +// IrEmitterUnnested::EmitInputFusibleNonStridedSlices +// +// In theory, the pattern in case 1 could also be fused into the case2 target +// graph, but we prefer to fuse into kLoop type, because the codegen for it does +// not have the slicing range check cost introduced by case 2 pattern. +// +// Note that the fusion style by case 2 provides an important advantage that +// kernels of different shapes can be horizontally fused. The first pair of +// reshapes (i.e., Reshape0 and Reshape1) reshape the dims to 1 dimension, so +// that the outputs of the fused kernels can (always) be concatenated. The +// second pair of reshapes (Reshape2 and Reshape3) restore the original shapes +// to the output tensors. +// +// No extra copies are introduced by the horizontal fusion. Besides Reshape2 +// and Reshape3, the other instructions are fused into an input fusion; the +// output dims of the concatenate will be used as the kernel launch dims. +// Instruction bitcasts can be used for Reshape2 and Reshape3 as long as the +// outputs of Mul and Add are row-major. +// +// Note, reshapes are added only if the tensors isn't already a vector. +class GpuHorizontalLoopFusion : public HloModulePass { + public: + GpuHorizontalLoopFusion() = default; + explicit GpuHorizontalLoopFusion(absl::string_view prefix) + : prefix_(prefix) {} + + absl::string_view name() const override { + return "gpu_horizontal_loop_fusion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + StatusOr RunOnComputation(HloComputation*); + std::string prefix_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_HORIZONTAL_LOOP_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..055e3139affa768b1f2afb363a9b77717b975532 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_manager.h @@ -0,0 +1,67 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This header declares classes for the infeed manager and the infeed +// buffer that are used by the GPU runtime to transfer buffers into an +// executing GPU computation, e.g., to feed data into a while loop. + +#ifndef XLA_SERVICE_GPU_INFEED_MANAGER_H_ +#define XLA_SERVICE_GPU_INFEED_MANAGER_H_ + +#include "absl/base/thread_annotations.h" +#include "xla/literal.h" +#include "xla/service/gpu/xfeed_queue.h" +#include "xla/shape_tree.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" + +namespace xla { +namespace gpu { + +// TODO(b/30467474) Once GPU infeed implementation settles, consider +// folding back the cpu and gpu infeed implementations into a generic +// one if possible. +// +// Current limitations: +// * Does not handle multiple devices/replicas. +// +// * Buffer space on GPU is allocated on every infeed enqueue request, +// and it does not handle the case when it runs out of +// memory. Potential solution is to pre-allocate a fixed amount of +// memory and block when that memory is full. + +// Client-side class used to enqueue infeed buffers. +class InfeedManager + : public BlockingXfeedQueue>> { + public: + explicit InfeedManager(se::StreamExecutor* executor); + + Status TransferLiteralToInfeed(se::StreamExecutor* executor, + const LiteralSlice& literal); + + private: + se::Stream* stream() const { return stream_.get(); } + + // Stream used to enqueue infeed device copies. + std::unique_ptr stream_; +}; + +// Returns the GPU infeed manager for the given stream executor, +InfeedManager* GetOrCreateInfeedManager(se::StreamExecutor* executor); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_INFEED_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..c2d1cd325e2f184ebbeb9c72679da2b01b71aeae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/infeed_thunk.h @@ -0,0 +1,49 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_INFEED_THUNK_H_ +#define XLA_SERVICE_GPU_INFEED_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that infeeds data. Data must be already resident on the +// device. This thunk performs an intra-device copy from that location +// to the buffer allocated for the infeed op. +class InfeedThunk : public Thunk { + public: + // Constructs a InfeedThunk that copies data from the on-device + // infeed queue into the buffers in the given shape tree. + InfeedThunk(ThunkInfo thunk_info, std::vector dest_slices); + + InfeedThunk(const InfeedThunk&) = delete; + InfeedThunk& operator=(const InfeedThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const std::vector dest_slices_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_INFEED_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/instruction_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/instruction_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..bf036cbdd45017627276ae73cb5161332de04218 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/instruction_fusion.h @@ -0,0 +1,86 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_INSTRUCTION_FUSION_H_ +#define XLA_SERVICE_GPU_INSTRUCTION_FUSION_H_ + +#include + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/fusion_node_indexing_evaluation.h" +#include "xla/service/fusion_queue.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/instruction_fusion.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +class GpuInstructionFusion : public InstructionFusion { + public: + explicit GpuInstructionFusion(bool may_duplicate, + const se::DeviceDescription& d) + : InstructionFusion(GpuInstructionFusion::IsExpensive, may_duplicate), + device_info_(d) {} + + static bool IsExpensive(const HloInstruction& instruction); + + using HloPassInterface::Run; + StatusOr Run(HloModule* module, + const absl::flat_hash_set& + execution_threads) override { + fusion_node_evaluations_.clear(); + return InstructionFusion::Run(module, execution_threads); + } + + protected: + std::unique_ptr GetFusionQueue( + HloComputation* computation) override; + FusionDecision ShouldFuse(HloInstruction* consumer, + int64_t operand_index) override; + + HloInstruction::FusionKind ChooseKind( + const HloInstruction* producer, const HloInstruction* consumer) override; + + private: + // This method is called by ShouldFuse() to do all the computationally + // inexpensive checks whether we should fuse the operand into 'consumer'. + FusionDecision ShouldFuseInexpensiveChecks(HloInstruction* consumer, + int64_t operand_index); + + HloInstruction* FuseInstruction(HloInstruction* fusion_instruction, + HloInstruction* producer) override; + + // Keep track of the number of times each instruction inside a fusion node is + // indexed with different index vectors. + absl::flat_hash_map + fusion_node_evaluations_; + + se::DeviceDescription device_info_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_INSTRUCTION_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emission_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emission_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a7daa4ccaadcfddba6fc01c7d9416b63a6142552 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emission_utils.h @@ -0,0 +1,219 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_IR_EMISSION_UTILS_H_ +#define XLA_SERVICE_GPU_IR_EMISSION_UTILS_H_ + +#include +#include +#include + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/buffer_assignment.h" + +namespace xla { +namespace gpu { + +// If a dimensions is smaller than this, untiled transposition may be more +// efficient. +inline constexpr int64_t kMinDimensionToTransposeTiled = 16; +// But if both swap dimensions are larger than 'kMinDimensionToTransposeTiled2', +// and the product of the dimensions to be swapped is larger than +// 'kMinTotalDimensionsToTransposeTiled', tiled transposition may be more +// efficient. +inline constexpr int64_t kMinDimensionToTransposeTiled2 = 8; +inline constexpr int64_t kMinTotalDimensionsToTransposeTiled = 64 * 128; + +// Matrix multiplication before the rewrite. +// +// This function should never return "true" on instructions after +// GemmRewriter pass has finished. +bool IsMatrixMultiplication(const HloInstruction& dot); + +inline constexpr int64_t WarpSize() { return 32; } + +// Fusions that use Triton have FusionBackendConfig.kind equal to this string. +inline constexpr absl::string_view kTritonGemmFusionKind = "__triton_gemm"; + +// SoftmaxRewriterTriton sets backend_config of Triton Softmax custom fusions to +// this string. +inline constexpr absl::string_view kTritonSoftmaxFusionKind = + "__triton_softmax"; + +inline constexpr absl::string_view kUncompilableFusion = + "__uncompilable_fusion"; + +// Returns true if `hlo` will be implemented as a call to a cuSolver routine. +// +// This returns true if `hlo` is a CustomCall HLO with a call target equal to +// one of the kCusolver... constants, but returns *false* for HLOs with +// say, a kCholesky opcode. +bool IsCustomCallToCusolver(const HloInstruction& hlo); + +// Cholesky decomposition. Takes a (batched) matrix as input, and returns a +// tuple of (result, workspace, info), where result is the result of the +// Cholesky decomposition, workspace is scratch space for cuSolver, and info +// is a success/failure code per batch element. +extern const char* const kCusolverCholeskyCallTarget; + +// Returns whether unnested_hlo is an input fusion whose root is either a slice +// or a tuple of slices. If verify_no_strides is true, returns false unless all +// ROOT slices have no strides. +bool IsInputFusibleSlices(mlir::Operation* unnested_hlo, + bool verify_no_strides); + +// Emits call to "vprintf" with given format and arguments. +llvm::Value* EmitPrintf(absl::string_view fmt, + absl::Span arguments, + llvm::IRBuilder<>* builder); + +// Emits code to shuffle data between threads of a warp. This has the same +// semantics as the PTX "shfl.sync.down" instruction but works for values that +// aren't 32 bits in size. The last operand of the emitted "shfl" is +// `WarpSize() - 1`. +// +// This function emits a "full-warp" shuffle, which all threads of a warp +// participate in. *Do not use this function from a divergent context:* You +// can't correctly do so on both Volta and earlier GPUs. +// +// https://docs.nvidia.com/cuda/parallel-thread-execution/#data-movement-and-conversion-instructions-shfl-sync +llvm::Value* EmitFullWarpShuffleDown(llvm::Value* value, llvm::Value* offset, + llvm::IRBuilder<>* builder); + +// Emits code that determines whether the current thread is thread 0 within +// block 0 of the kernel. +llvm::Value* IsBlock0Thread0(llvm::IRBuilder<>* b); + +int PartitionLmhloOperandsAndOutputs(mlir::Operation* op); +llvm::SmallVector GetHloOperands(mlir::Operation* op); +llvm::SmallVector GetHloOutputs(mlir::Operation* op); + +bool WritesMlirBuffer(mlir::Operation* op, mlir::Value operand); + +template +std::vector ToStdVector(const llvm::SmallVectorImpl& v) { + return std::vector(v.begin(), v.end()); +} + +StatusOr GetAllocationSlice( + mlir::Value v, absl::Span allocations, + std::string* constant_name = nullptr); + +bool CanEmitFusedDynamicUpdateSliceInPlaceForGpu( + mlir::lmhlo::FusionOp fusion, + absl::Span allocations); + +// Returns the dynamic-update-slice instructions defining the results of a +// fusion node. A dynamic slice update is said to be "defining" of a result if +// that result is the output of a dynamic slice update, or if that result is the +// output of a bitcast of a dynamic slice update---since such bitcast may be +// handled as a no-op. +std::vector GetOutputDefiningDynamicUpdateSlices( + const std::vector& roots); + +// Returns the DynamicUpdateSliceOp(s) defining the results of a fusion node. +// A dynamic slice update is said to be "defining" of a result if that result is +// the output of a dynamic slice update, or if that result is the output of a +// bitcast of a dynamic slice update---since such bitcast may be handled as a +// no-op. +std::vector +GetOutputDefiningDynamicUpdateSliceOps(mlir::lmhlo::FusionOp fusion); + +Shape GetShape(mlir::Value value); + +// `is_boundary` returns `true` for edges that are on the boundary of the +// fusion, i.e., they go from an instruction inside the fusion to one outside, +// or vice versa. +const HloInstruction& FindNonTrivialHero( + const HloInstruction& instr, + const std::function& is_boundary); +const HloInstruction& FindNonTrivialHero(const HloInstruction& instr); + +/// Description of how to emit a given transposition. +struct TransposeDescription { + // Transpose instruction. + const HloInstruction* instr; + + // Normalized transpose dimensions. + Vector3 dimensions; + + // Permutations of normalized transpose dimensions. + Vector3 permutation; + + TransposeDescription(Vector3 dimensions, Vector3 permutation) + : TransposeDescription(/*instr=*/nullptr, dimensions, permutation) {} + + TransposeDescription(const HloInstruction* instr, Vector3 dimensions, + Vector3 permutation) + : instr(instr), dimensions(dimensions), permutation(permutation) {} + + std::string ToString() const { + return absl::StrCat("dimensions=", VectorString(dimensions), + ", permutation=", VectorString(permutation)); + } + + // Transpose instruction input shape. + const Shape& input_shape() const { return instr->operand(0)->shape(); } + + // Returns true, if both descriptions have the same dimensions and + // permutation, even if they're produced by different instructions. + bool IsEquivalent(const TransposeDescription& other) const { + return dimensions == other.dimensions && permutation == other.permutation; + } +}; + +std::optional FindTiledTranspose( + const HloInstruction& instr); + +std::optional FindTiledLogicalTranspose( + const HloInstruction& instr); + +std::optional GetDescriptionForTiledTransposeEmitter( + const HloInstruction& root, const HloInstruction& hero); + +bool IsIntermediate(const HloInstruction* instr, int allowed_operand_count = 1); + +// Log and verify an LLVM module. +void LogAndVerify(const llvm::Module* m); + +// Returns the llvm type for the indices used in the kernel that contains the +// hlo instruction. Such indices include the index for the parallel loop and +// the indices for the tensors accessed by the kernel. The return type is i32 +// iff the following conditions are met: +// . The launch_size of the kernel is within the range of i32. +// . The sizes of all the tensors accessed within the kernel are within the +// range of i32. +// Otherwise, the return type is i64. +llvm::Type* GetIndexTypeForKernel(const HloInstruction* hlo, + int64_t launch_size, llvm::IRBuilder<>* b); + +// The same as GetIndexTypeForKernel, but works with MLIR ops. +llvm::Type* GetIndexTypeForKernel(mlir::Operation* op, int64_t launch_size, + llvm::IRBuilder<>* b); + +// Returns a sanitized (doesn't need quoting) identifier name from a location. +std::string GetIrNameFromLoc(mlir::Location loc); + +// Whether the module's target is an AMD GPU. +bool IsAMDGPU(const llvm::Module* module); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMISSION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..8ac0b2075d3cd7a2c77844257a69d8c6138a78ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter.h @@ -0,0 +1,155 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_IR_EMITTER_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_H_ + +#include + +#include "llvm/IR/Function.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/hlo_to_ir_bindings.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/llvm_ir/fused_ir_emitter.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/ir_builder_mixin.h" +#include "xla/service/llvm_ir/loop_emitter.h" + +namespace xla { +namespace gpu { + +// Abstract base class for translating HLO graphs to LLVM IR for a GPU. +// +// There are two concrete subclasses of IrEmitter: IrEmitterNested and +// IrEmitterUnnested. In the unnested variety, each HLO gets its own kernel +// function, whereas in the nested version the whole computation is emitted as +// one *non-kernel* function. +// +// In XLA, kernel functions never call other kernel functions. This means that +// if we have a kernel -- e.g. implementing a kReduce HLO -- that wants to use +// an HLO computation as a "subroutine" -- e.g. the HLO computation that +// specifies how to reduce two elements -- then the subroutine computation must +// be emitted using IrEmitterNested. +// +// Fusion nodes are a special case. A fusion node is emitted using +// IrEmitterUnnested, but the code is generated using FusedIrEmitter, which is +// not a subclass of gpu::IrEmitter, and in fact is better understood as an IR +// generator generator. See comments on that class. +class IrEmitter : public DfsHloVisitorWithDefault, + public IrBuilderMixin { + public: + IrEmitter(const IrEmitter&) = delete; + IrEmitter& operator=(const IrEmitter&) = delete; + + Status DefaultAction(HloInstruction* hlo) override; + Status HandleConstant(HloInstruction* constant) override; + Status HandleGetTupleElement(HloInstruction* get_tuple_element) override; + Status HandleConvolution(HloInstruction* convolution) override; + Status HandleFft(HloInstruction* fft) override; + Status HandleAllReduce(HloInstruction* crs) override; + Status HandleInfeed(HloInstruction* infeed) override; + Status HandleOutfeed(HloInstruction* outfeed) override; + Status HandleSend(HloInstruction* send) override; + Status HandleSendDone(HloInstruction* send_done) override; + Status HandleRecv(HloInstruction* recv) override; + Status HandleRecvDone(HloInstruction* recv_done) override; + Status HandleParameter(HloInstruction* parameter) override; + Status HandleTuple(HloInstruction* tuple) override; + Status HandleScatter(HloInstruction* scatter) override; + Status HandleFusion(HloInstruction* fusion) override; + Status HandleCall(HloInstruction* call) override; + Status HandleCustomCall(HloInstruction* custom_call) override; + Status HandleBatchNormInference(HloInstruction* batch_norm) override; + Status HandleBatchNormTraining(HloInstruction* batch_norm) override; + Status HandleBatchNormGrad(HloInstruction* batch_norm) override; + Status HandleAddDependency(HloInstruction* add_dependency) override; + + Status FinishVisit(HloInstruction* root) override { return OkStatus(); } + + llvm::IRBuilder<>* builder() { return &b_; } + + protected: + // Constructs an IrEmitter with the given IrEmitter context. + // ir_emitter_context is owned by the caller and should outlive the IrEmitter + // object. + explicit IrEmitter(IrEmitterContext* ir_emitter_context, bool is_nested); + + // Helper for calling HloToIrBindings::GetIrArray. + // + // Gets the IrArray which contains inst. This array has metadata that makes + // it valid only within the IR that implements consumer. If you are + // implementing an HLO and want to get its own output buffer, call + // GetIrArray(hlo, hlo). + llvm_ir::IrArray GetIrArray(const HloInstruction& inst, + const HloInstruction& consumer, + const ShapeIndex& shape_index = {}) { + return bindings_.GetIrArray(inst, consumer, shape_index); + } + // A convenient helper for calling HloToIrBindings::GetBasePointer. + llvm::Value* GetBasePointer(const HloInstruction& inst, + ShapeIndexView shape_index = {}) const { + return bindings_.GetBasePointer(inst, shape_index); + } + + // Generates the IrArray for each output of an hlo instruction and returns + // a vector containing such IrArrays. + std::vector ConstructIrArrayForOutputs( + const HloInstruction& hlo); + + // Emit a single-threaded or multi-threaded loop that computes every element + // in the result of the given HLO instruction. This produces a series of + // nested loops (e.g. one for each dimension of the `hlo`'s shape). The body + // of the inner-most loop is provided by the body_emitter function. + virtual Status EmitTargetElementLoop( + const HloInstruction& hlo, + const llvm_ir::ElementGenerator& body_emitter) = 0; + + IrEmitterContext* ir_emitter_context_; + llvm::Module* module_; + + // The following fields track the IR emission state. According to LLVM memory + // management rules, their memory is owned by the module. + llvm::IRBuilder<> b_; + + // Mapping from HLO to its underlying LLVM value. + HloToIrBindings bindings_; + + // Bind all argument IrArrays of `fusion` to `fused_emitter`. + void BindFusionArguments(const HloInstruction* fusion, + FusedIrEmitter* fused_emitter); + + // Emit a fence for AMDGPU if necessary. + void MaybeEmitFenceForAMDGPU(llvm::AtomicOrdering atomic_ordering, + const char* sync_scope_id); + + private: + // A helper method for HandleSort(). It adds the inner comparison loop where + // we compare elements pointed to by 'keys_index' and 'compare_keys_index'. + void EmitCompareLoop(int64_t dimension_to_sort, + const llvm_ir::IrArray::Index& keys_index, + const llvm_ir::IrArray::Index& compare_keys_index, + const llvm_ir::IrArray& keys_array); + + // A convenience method to determine whether or not IR is emitted for AMDGPU. + bool IsEmittingForAMDGPU() const; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_context.h new file mode 100644 index 0000000000000000000000000000000000000000..a981f0d2a2244bb2827bd2c1c0a014d25a84b15a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_context.h @@ -0,0 +1,117 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_IR_EMITTER_CONTEXT_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_CONTEXT_H_ + +#include +#include +#include +#include + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/gpu_executable.h" +#include "xla/service/name_uniquer.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// IrEmitterContext encapsulates common (mutable and immutable) data structures +// used by both IrEmitterNested and IrEmitterUnnested, such as the buffer +// assignment and the name uniquer. +class IrEmitterContext { + public: + IrEmitterContext(const HloModule* hlo_module, + const BufferAssignment* buffer_assignment, + std::string platform_name, + const se::DeviceDescription& gpu_device_info, + mlir::MLIRContext* mlir_context, llvm::Module* llvm_module) + : hlo_module_(hlo_module), + buffer_assignment_(buffer_assignment), + platform_name_(std::move(platform_name)), + gpu_device_info_(gpu_device_info), + mlir_context_(mlir_context), + llvm_module_(llvm_module) {} + // Disallow copy and assign. + IrEmitterContext(const IrEmitterContext&) = delete; + IrEmitterContext& operator=(const IrEmitterContext&) = delete; + + // Simple accessors. + const HloModule& hlo_module() const { return *hlo_module_; } + const BufferAssignment& buffer_assignment() const { + return *buffer_assignment_; + } + absl::string_view platform_name() const { return platform_name_; } + const se::DeviceDescription& gpu_device_info() const { + return gpu_device_info_; + } + se::CudaComputeCapability cuda_compute_capability() const { + auto* cc = std::get_if( + &gpu_device_info_.gpu_compute_capability()); + return cc != nullptr ? *cc : se::CudaComputeCapability(); + } + se::RocmComputeCapability rocm_compute_capability() const { + auto* cc = std::get_if( + &gpu_device_info_.gpu_compute_capability()); + return cc != nullptr ? *cc : se::RocmComputeCapability(); + } + mlir::MLIRContext* mlir_context() { return mlir_context_; } + llvm::Module* llvm_module() { return llvm_module_; } + NameUniquer* name_uniquer() { return &name_uniquer_; } + + std::vector& constants() { return constants_; } + + absl::Span allocations() const { + if (buffer_assignment_) { + return buffer_assignment_->Allocations(); + } + return allocations_; + } + + void set_allocations(absl::Span allocations) { + CHECK_EQ(nullptr, buffer_assignment_); + allocations_ = allocations; + } + + // Emit a constant with a given number of element, given byte size of the + // element, given symbol name and content. + void emit_constant(int64_t num_elements, int64_t bytes_per_element, + absl::string_view symbol_name, int allocation_idx, + llvm::ArrayRef content, llvm::IRBuilder<>* b); + + const DebugOptions& debug_options() const { + return hlo_module_->config().debug_options(); + } + + private: + const HloModule* hlo_module_; + const BufferAssignment* buffer_assignment_; + absl::Span allocations_; + std::string platform_name_; + const se::DeviceDescription& gpu_device_info_; + mlir::MLIRContext* mlir_context_; + llvm::Module* llvm_module_; + NameUniquer name_uniquer_; + std::vector constants_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_nested.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_nested.h new file mode 100644 index 0000000000000000000000000000000000000000..9f1b6e1baf9839768b4fc226dcef974ea8da28fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_nested.h @@ -0,0 +1,78 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_IR_EMITTER_NESTED_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_NESTED_H_ + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/gpu/ir_emitter_context.h" +#include "xla/service/hlo_module_config.h" + +namespace xla { +namespace gpu { + +// Emits LLVM IR for a "nested computation" into a non-kernel device function. +// +// This is used to emit code for HloComputations that don't require a separate +// kernel call. For example, IrEmitterNested is used to emit code for a kReduce +// HLO's elementwise reduction computation. Notably, IrEmitterNested is *not* +// used to emit code for fusion nodes -- fusion nodes use FusedIrEmitter, which +// is a different beast altogether. +// +// IrEmitterNested generates a non-kernel function with the following +// parameters: +// +// - N pointers to the buffers of each of the N parameters to the computation, +// - a pointer to the output buffer of the computation, and +// - a pointer to the top-level temp buffer. +Status CallNestedComputation(llvm::IRBuilder<>* builder, + IrEmitterContext& ir_emitter_context, + const HloComputation& computation, + absl::Span operands, + llvm::Value* output); + +// Like CallNestedComputation, but parameters and results are scalars. +StatusOr> CallNestedComputationWithScalars( + llvm::IRBuilder<>* builder, IrEmitterContext& ir_emitter_context, + const HloComputation& computation, + absl::Span parameter_elements); + +// Like CallNestedComputationWithScalars, but parameters are scalar addresses. +StatusOr> CallNestedComputationWithScalarAddrs( + llvm::IRBuilder<>* builder, IrEmitterContext& ir_emitter_context, + const HloComputation& computation, + absl::Span parameter_elements_addrs); + +// Emits an atomic operation that implements `nested_computation` in the +// sequentially consistent memory model. `output_address` and `source_address` +// are the arguments of the nested computation. For example, +// atomicAdd(output_address, *source_address). +// +// If the computation can be implemented using a single atomic operation, it +// will, otherwise it will be emitted as a compare-and-swap and a loop. +// +// The computation must have exactly two parameters. +Status EmitAtomicOperationForNestedComputation( + llvm::IRBuilder<>* builder, IrEmitterContext& ir_emitter_context, + const HloComputation& computation, llvm::Value* output_address, + llvm::Value* source_address, llvm::Type* element_type); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_NESTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_triton.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_triton.h new file mode 100644 index 0000000000000000000000000000000000000000..9edf27853e22fd97b597269f2a2a6535d4617427 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_triton.h @@ -0,0 +1,97 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_IR_EMITTER_TRITON_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_TRITON_H_ + +#include + +#include "absl/strings/string_view.h" +#include "llvm/IR/Module.h" +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/gpu/gemm_rewriter_triton.h" +#include "xla/service/gpu/hlo_traversal.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "triton/Dialect/Triton/IR/Dialect.h" + +namespace xla { +namespace gpu { + +struct TritonWrapperResult { + int64_t shmem_bytes; +}; + +// Compute the launch dimensions for the given Triton MatMul. +LaunchDimensions GetMatMulLaunchDimensions( + const TritonFusionAnalysis& analysis, + absl::Span roots, + const FusionBoundaryFn& fusion_boundary, + const AutotuneResult::TritonGemmKey& config); +// Use tiling and execution parameters from 'config'. +Status EmitMatMul(mlir::OpBuilder b, absl::string_view libdevice_path, + const TritonFusionAnalysis& analysis, + const HloComputation* computation, mlir::triton::FuncOp fn, + const AutotuneResult::TritonGemmKey& config, + int shmem_budget); + +// Compute the launch dimensions for the given Triton SoftMax. +LaunchDimensions GetSoftMaxLaunchDimensions( + absl::Span roots, + const FusionBoundaryFn& fusion_boundary, + const AutotuneResult::TritonGemmKey& config); +// Generate Softmax in Triton IR inside 'fn'. +// Use execution parameters from 'config'. +Status EmitSoftMax(mlir::OpBuilder b, absl::string_view libdevice_path, + const TritonFusionAnalysis& analysis, + const HloComputation* computation, mlir::triton::FuncOp fn, + const AutotuneResult::TritonGemmKey& config, + int shmem_budget); + +using TritonIrEmitter = std::function; + +// Generate Triton IR by running the provided generator and compile it into LLVM +// IR. +// MatMul and SoftMax above are some such IR generators. +StatusOr TritonWrapper( + const TritonFusionAnalysis& analysis, absl::string_view fn_name, + const HloComputation* hlo_computation, absl::string_view fusion_kind, + const se::CudaComputeCapability& cc, + const se::DeviceDescription& device_info, + const AutotuneResult::TritonGemmKey& config, llvm::Module* llvm_module, + TritonIrEmitter ir_emitter, mlir::MLIRContext& mlir_context); + +// Creates the initial Triton module for the given fusion. Visible for testing, +// use TritonWrapper instead. +StatusOr> CreateTritonModule( + const TritonFusionAnalysis& analysis, absl::string_view fn_name, + const HloComputation* hlo_computation, + const se::DeviceDescription& device_info, + const AutotuneResult::TritonGemmKey& config, TritonIrEmitter ir_emitter, + mlir::MLIRContext& mlir_context); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_TRITON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.h new file mode 100644 index 0000000000000000000000000000000000000000..0a2830aae4c9d551e35a1a05e17f78f4bb4b90c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/ir_emitter_unnested.h @@ -0,0 +1,442 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_IR_EMITTER_UNNESTED_H_ +#define XLA_SERVICE_GPU_IR_EMITTER_UNNESTED_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/service/gpu/elemental_ir_emitter.h" +#include "xla/service/gpu/fusions/tiling_util.h" +#include "xla/service/gpu/hlo_fusion_analysis.h" +#include "xla/service/gpu/ir_emitter.h" +#include "xla/service/gpu/kernel_mapping_scheme.h" +#include "xla/service/gpu/kernel_reuse_cache.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/llvm_util.h" + +namespace xla { +namespace gpu { + +struct BufferSlice { + // The root buffer to look at. + BufferAllocation::Slice buffer_slice; + + // The global constant name of the buffer, if it's a constant. + std::string constant_name; + + // The buffer is modified by the kernel. + bool written = false; + + Shape shape; +}; + +// Emits LLVM IR for an "unnested computation". +// +// An unnested computation is an HloComputation which you run by executing one +// or more kernels for each HloInstruction it contains. Examples of unnested +// computations: +// +// - An HloModule's root computation, +// - The body of an HLO while loop, +// - The true/false computation of an HLO conditional. +// +// Note the opportunity for confusion -- the while loop's computation is nested +// within the root computation, but it's emitted using IrEmitterUnnested! Don't +// think about it too hard. +// +// Examples of things that are not unnested computations: +// +// - The body of a fusion node. IrEmitterUnnested emits the relevant code +// within a kernel function using FusedIrEmitter. (FusedIrEmitter is not +// really an IrEmitter, but is more an "IR generator generator".) +// +class IrEmitterUnnested : public IrEmitter { + public: + absl::string_view platform_name() const { + return ir_emitter_context_->platform_name(); + } + + using ValueVector3 = std::array; + using ValueVector2 = std::array; + + using ConstantGenerator = std::function; + + IrEmitterUnnested(const IrEmitterUnnested&) = delete; + IrEmitterUnnested& operator=(const IrEmitterUnnested&) = delete; + + static std::unique_ptr Create( + IrEmitterContext* ir_emitter_context); + + // Transfers the ownship of thunk_sequence_ out. + std::unique_ptr ConsumeThunkSequence() { + return std::make_unique(std::move(thunk_sequence_)); + } + + // Emits code for the given LMHLO region. + // + // Also populates related information to 'ir_emitter_context_' for + // large-constant initializations. Large constants don't get initializers in + // the generated code and so must be initialized by XLA. The value of these + // constants will be stored in 'content'. Constants with initializers in the + // generated code will have empty 'content'. + Status EmitLmhloRegion( + mlir::Region* region, + const absl::flat_hash_map& + hlo_for_lmhlo); + + static void GetDependentDialects(mlir::DialectRegistry& registry); + + private: + explicit IrEmitterUnnested(IrEmitterContext* ir_emitter_context); + + Status EmitUnreachable(mlir::Operation* op, std::string error_message); + + // IrEmitterUnnested handles the following instructions differently from + // IrEmitter. It also mixes in some special handling for custom kernels + // via the ThunkEmitter. + Status EmitConstant(mlir::Operation* op); + + Status EmitConditional( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitConvolutionThunk(mlir::Operation* op); + Status EmitGemmThunk(mlir::Operation* op); +#if GOOGLE_CUDA || TF_HIPBLASLT + Status EmitCublasLtMatmulThunk(mlir::Operation* op); +#endif // GOOGLE_CUDA || TF_HIPBLASLT +#if GOOGLE_CUDA + Status EmitCublasLtMatmulThunkF8(mlir::Operation* op); + Status EmitConvolutionReorderThunk(mlir::Operation* op); + Status EmitTritonFusion( + const HloFusionAnalysis& hlo_fusion_analysis, mlir::Operation* op, + const AutotuneResult::TritonGemmKey& config, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitFusedMHAThunk(mlir::Operation* op); + Status EmitFusedMHABackwardThunk(mlir::Operation* op); +#endif // GOOGLE_CUDA +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + Status EmitCholeskyThunk(mlir::Operation* op); +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + Status EmitCustomCallThunk(mlir::Operation* op); + Status EmitFftThunk(mlir::Operation* op); + Status EmitFusion( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitSelectAndScatter( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitWhile( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitInfeed(mlir::Operation* op); + Status EmitOutfeed(mlir::Operation* op); + Status EmitRngGetAndUpdateState(mlir::Operation* op); + Status EmitScatter( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + Status EmitSort( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + Status EmitTriangularSolveCustomCall(mlir::Operation* op); +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + + template + Status EmitNcclThunk(mlir::Operation* op); + template + Status EmitNcclAsyncDone(Thunk::Kind kind, mlir::Operation* op); + + template + Status EmitReplicaOrPartitionId(mlir::Operation* op); + + template + Status EmitCollectivePermute(mlir::Operation* op); + + Status EmitOp( + mlir::Operation* op, + const absl::flat_hash_map& + hlo_for_lmhlo); + + static Thunk::ThunkInfo GetThunkInfo(mlir::Operation* op); + + Status EmitTargetElementLoop( + const HloInstruction& hlo, + const llvm_ir::ElementGenerator& body_emitter) override; + + // Add a owning Thunk object to the thunk sequence. + void AddThunkToThunkSequence(std::unique_ptr thunk) { + thunk_sequence_.emplace_back(std::move(thunk)); + } + + // Load data from potentially unaligned address. If address is offset by + // `alignment_bytes`, data is read in the unit of `alignment_bytes` to avoid + // memory read misalignment in CUDA; otherwise, the entire data are loaded + // from the given memory address. + // + // address: the memory address to load data from. + // data_type: the type of data to load. + // alignment_bytes: the number of bytes required to align. The number of + // bytes of the data_type must be divisible by alignment_bytes. + llvm::Value* CreateLoad(llvm::Value* address, llvm::Type* data_type, + int alignment_bytes); + + // Store data at a potentially unaligned address. If the address is offset by + // `alignment_bytes`, data is stored in the unit of `alignment_bytes` to avoid + // memory write misalignment in CUDA; otherwise, the entire data is stored at + // the given memory address. + // + // data: the data to be stored. + // address: the memory address to store data. + // alignment_bytes: the number of bytes required to align. The number of + // bytes of the data_type must be divisible by alignment_bytes. + void CreateStore(llvm::Value* data, llvm::Value* address, + int alignment_bytes); + + // Input = {static array, dynamic_dim0, dynamic_dim1} + // Output = {dynamic array(with dynamic dimension meta data at the end)} + // For a tensor with static dimension [2][<=5] and dynamic dimension [2][3] + // (`_` stands for padding) + // Input = {{1,2,3,_,_,4,5,6_,_}, 2, 3} + // Output = {{1,2,3,4,5,6,_,_,_,_,2,3}} + + // pseudo code for padToStatic on a 2d array + // ``` + // void padToStatic(int** input, int** output, int threads_per_block, + // int meta_data_offset, int max_num_element, + // int static_dim0_size, int static_dim1_size) { + // int* source_array = input[0]; + // int* dest_array = output[0]; + + // // extract the dynamic dimension from the source array's metadata + // int* dyn_dim0_size = source_array + meta_data_offset; + // int* dyn_dim1_size = source_array + meta_data_offset + sizeof(int); + + // // only one thread need to store the dynamic index + // int thread_id = GetThreadId(); + // int block_id = GetBlockId(); + // if (thread_id == 0 && block_id == 0) { + // *output[1] = *dyn_dim0_size; + // *output[2] = *dyn_dim1_size; + // } + + // int dyn_element_total = 1; + // dyn_element_total *= *dyn_dim0_size; + // dyn_element_total *= *dyn_dim1_size; + // linear_index = block_id * threads_per_block + thread_id; + // if (linear_index < max_num_element) { + // Index static_index = + // delinerized(linerized_index, static_dim0_size, static_dim1_size); + // if (linerized_index < dyn_element_total) { + // Index dyn_index = + // delinerized(linerized_index, *dyn_dim0_size, *dyn_dim1_size); + // dest_array[dyn_index.dim0][dyn_index.dim1] = + // source_array[static_index.dim0][static_index.dim1]; + // } + // } + // return; + // } + // ``` + Status EmitPadToStatic(mlir::Operation* op); + + // Input = {dynamic array(with dynamic dimension meta data at the end)} + // Output = {static array, dynamic_dim0, dynamic_dim1} + // For a tensor with static dimension [2][<=5] and dynamic dimension [2][3] + // (`_` stands for padding) + // Input = {{1,2,3,4,5,6,_,_,_,_,2,3}} + // Output = {{1,2,3,_,_,4,5,6_,_}, 2, 3} + + // pseudo code for sliceToDynamic on a 2d array + // ``` + // void sliceToDynamic(int** input, int** output, int threads_per_block, + // int meta_data_offset, int max_num_element, + // int static_dim0_size, int static_dim1_size) { + // int* source_array = input[0]; + // int* dest_array = output[0]; + + // // calculate the location where metadata needs to be inserted + // int* dyn_dim0_size = dest_array + meta_data_offset; + // int* dyn_dim1_size = dest_array + meta_data_offset + sizeof(int); + + // // only one thread need to store the dynamic index + // int thread_id = GetThreadId(); + // int block_id = GetBlockId(); + // if (thread_id == 0 && block_id == 0) { + // *dyn_dim0_size = *output[1]; + // *dyn_dim1_size = *output[2]; + // } + + // int dyn_element_total = 1; + // dyn_element_total *= *dyn_dim0_size; + // dyn_element_total *= *dyn_dim1_size; + // linear_index = block_id * threads_per_block + thread_id; + // if (linear_index < max_num_element) { + // Index static_index = + // delinerized(linerized_index, static_dim0_size, static_dim1_size); + // if (linerized_index < dyn_element_total) { + // Index dyn_index = + // delinerized(linerized_index, *dyn_dim0_size, *dyn_dim1_size); + // dest_array[static_index.dim0][static_index.dim1] = + // source_array[dyn_index.dim0][dyn_index.dim1]; + // } + // } + // return; + // } + // ``` + Status EmitSliceToDynamic(mlir::Operation* op); + + StatusOr GetAllocationSlice(mlir::Value v); + + int64_t ByteSizeOf(const Shape& shape) const { + return llvm_ir::ByteSizeOf( + shape, ir_emitter_context_->llvm_module()->getDataLayout()); + } + + // Emits code for an in-place scatter, modifying `thunk`s launch dimensions in + // the process. Scatter indices are taken from `scatter_indices_gen`, updates + // from `updates_gen`. The output buffer is expected to have the operand + // values in it already. If unique_indices is false, we will use an atomic + // update. Using true for unique_indices behaves properly only when it is + // guaranteed that the indices to be updated do not overlap. The caller is + // responsible for ensuring this is the case. + Status EmitScatter( + mlir::lmhlo::ScatterOp scatter, const LaunchDimensions& launch_dimensions, + const llvm_ir::IrArray& output, + const llvm_ir::ElementGenerator& scatter_indices_gen, + const llvm_ir::ElementGenerator& updates_gen, + std::function get_index_type, + const absl::flat_hash_map& + hlo_for_lmhlo); + + // Structure describing a scatter operation for IR emission. + // TODO(jurahul): Migrate element generators to use MLIR. + // Migrate update_computation to be an MLIR Region. + struct ScatterDescriptor { + std::string name; + Shape operand_shape; + Shape scatter_indices_shape; + Shape updates_shape; + mlir::mhlo::ScatterDimensionNumbersAttr dim_numbers; + bool unique_indices; + const HloComputation* update_computation; + llvm_ir::IrArray output; + llvm_ir::ElementGenerator scatter_indices_gen; + llvm_ir::ElementGenerator updates_gen; + std::function get_index_type; + }; + + // Emits code for an in-place scatter using the provided scatter operation + // description. + Status EmitScatter(const ScatterDescriptor& desc, + const LaunchDimensions& launch_dimensions); + + Status EmitScatter(mlir::lmhlo::FusionOp fusion_op, + const HloComputation* fused_computation, + HloFusionAnalysis& fusion_analysis); + + // Builds a kernel thunk for a non-fusion operation, without reuse. + // + // All input and output tensors of `op` are passed to the kernel. + // + // TODO(tdanyluk): Consider also reusing non-fusion kernels. + StatusOr /*inputs*/, + std::vector /*outputs*/>> + BuildKernelThunkForNonFusionOp(mlir::Operation* op, + const LaunchDimensions& launch_dimensions); + + // Builds a kernel thunk for a non-fusion operation, without reuse. + // + // Only the tensors specified in `needed_operands` are passed to the kernel. + // + // TODO(tdanyluk): Consider also reusing non-fusion kernels. + StatusOr /*inputs*/, + std::vector /*outputs*/>> + BuildKernelThunkForNonFusionOp(mlir::Operation* op, + mlir::ValueRange needed_operands, + const LaunchDimensions& launch_dimensions); + + Status BuildInitializerThunk(mlir::Operation* op, mlir::Value init_value, + mlir::Value dest); + + // Returns a WhileThunk that invokes thunk sequences for 'condition' and + // 'body' sub-computations of while instruction 'hlo'. + StatusOr> BuildWhileThunk( + mlir::lmhlo::WhileOp while_op, const Thunk::ThunkInfo& thunk_info, + const absl::flat_hash_map& + hlo_for_lmhlo); + + // Returns a ForThunk which executes 'loop_limit' invocations of a thunk + // sequence from the 'body' sub-computation of the while instruction 'hlo'. + StatusOr> BuildForThunk( + mlir::lmhlo::WhileOp while_op, const Thunk::ThunkInfo& thunk_info, + int64_t loop_limit, + const absl::flat_hash_map& + hlo_for_lmhlo); + + // Returns a ConditionalThunk which executes the thunk sequence for the + // 'branch_computation' corresponding to the predicate/branch_index of the + // given conditional instruction. + StatusOr> BuildConditionalThunk( + const HloInstruction* conditional); + + Status AssertNonDeterminismIsOkay(const std::string& op_name); + + // The thunk sequence this IrEmitter generates for the input computation. + ThunkSequence thunk_sequence_; + + // Maps async start ops to their executors so done can access the thunk. + // Executor may be null if the start op is degenerate (so not emitted). + absl::flat_hash_map + async_executors_; + + // Begin optional members for XLA HLO -> LMHLO: + absl::flat_hash_map> + scratch_nested_computations_; + // End optional members for XLA HLO -> LMHLO. + + // Returns the ShapedSlices for the given operands. + StatusOr> GetShapedSlices( + mlir::Operation::operand_range operands); + + GpuElementalIrEmitter elemental_emitter_; + + KernelReuseCache kernel_reuse_cache_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_IR_EMITTER_UNNESTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_arguments.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_arguments.h new file mode 100644 index 0000000000000000000000000000000000000000..a7953030b01e7f88fd8958ac2aecbc3740ee617a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_arguments.h @@ -0,0 +1,92 @@ +/*Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_KERNEL_ARGUMENTS_H_ +#define XLA_SERVICE_GPU_KERNEL_ARGUMENTS_H_ + +#include +#include +#include + +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/service/buffer_assignment.h" +#include "xla/shape.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// An argument descriptor for kernels. +// Thread-safe. +class KernelArgument { + public: + static StatusOr Create( + absl::Span allocations, mlir::Value value, + bool is_written); + + mlir::Value value() const { return value_; } + const Shape& shape() const { return shape_; } + const BufferAllocation::Slice& slice() const { return slice_; } + bool written() const { return written_; } + int64_t alignment() const { return alignment_; } + std::optional first_with_same_slice() const { + return first_with_same_slice_; + } + bool aliased() const { return aliased_; } + + private: + KernelArgument(mlir::Value value, Shape shape, BufferAllocation::Slice slice, + bool written) + : value_(value), shape_(shape), slice_(slice), written_(written) {} + + mlir::Value value_; + Shape shape_; + BufferAllocation::Slice slice_; + bool aliased_ = true; + int64_t alignment_ = 1; + bool written_ = true; + // Holds the index of the first argument which has the same slice as this, + // if this is not the first such argument. + std::optional first_with_same_slice_; + + friend class KernelArguments; +}; + +class KernelArguments { + public: + static StatusOr Create( + absl::Span allocations, + mlir::lmhlo::FusionOp fusion); + + static StatusOr Create( + absl::Span allocations, + mlir::Operation* non_fusion_op, mlir::ValueRange needed_operands); + + const std::vector& args() const { return args_; } + + private: + explicit KernelArguments(std::vector args) + : args_(ProcessArguments(std::move(args))) {} + + static std::vector ProcessArguments( + std::vector kernel_arguments); + + std::vector args_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_ARGUMENTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_mapping_scheme.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_mapping_scheme.h new file mode 100644 index 0000000000000000000000000000000000000000..4a6f0f7ae3c6fa1904b8d2a0adb2364213e8070d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_mapping_scheme.h @@ -0,0 +1,265 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_KERNEL_MAPPING_SCHEME_H_ +#define XLA_SERVICE_GPU_KERNEL_MAPPING_SCHEME_H_ + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/llvm_ir/loop_emitter.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +// Describes tiling used by the kernel. +// +// Used by reductions and 021 transpose algorithm. Both algorithms operate over +// "logical" 3D views over input arrays, hence tiling and number of threads +// information has only 3 dimensions. +// +// In the presence of virtual threadIdx/blockIdx scaling, all accessors are +// "logical", unless otherwise specified. +class TilingScheme { + public: + enum { DimZ = 0, DimY, DimX, DimTot }; + + enum IndexingOrder { + // Thread reads consecutive elements. + LinearIndexingX, + // Thread reads strided elements while keeping memory coalescing. + StridedIndexingX, + }; + + TilingScheme(Vector3 dims_in_elems, Vector3 tile_sizes, Vector3 num_threads, + IndexingOrder indexing_order, int vector_size, + int scaling_factor, Vector2 tiling_dimensions = Vector2{1, 2}) + : dims_in_elems_(dims_in_elems), + tile_sizes_(tile_sizes), + tiling_dimensions_(tiling_dimensions), + num_threads_(num_threads), + indexing_order_(indexing_order), + vector_size_(vector_size), + thread_id_virtual_scaling_(scaling_factor) { + CHECK_EQ(tile_sizes[2] % vector_size_, 0) + << "tile sizes = " << absl::StrJoin(tile_sizes, ", ") + << "; vector size = " << vector_size_; + } + + static std::string IndexingOrderToString(IndexingOrder order) { + switch (order) { + case LinearIndexingX: + return "linear"; + case StridedIndexingX: + return "strided"; + } + } + + std::string ToString() const { + return absl::StrJoin( + {absl::StrFormat("dims_in_elems = {%s}", + absl::StrJoin(dims_in_elems_, ", ")), + absl::StrFormat("tile_sizes = {%s}", absl::StrJoin(tile_sizes_, ", ")), + absl::StrFormat("num_threads = {%s}", + absl::StrJoin(num_threads_, ", ")), + absl::StrFormat("indexing_order = %s", + IndexingOrderToString(indexing_order_)), + absl::StrFormat("vector_size = %d", vector_size_), + absl::StrFormat("thread_id_virtual_scaling = %d", + thread_id_virtual_scaling_), + absl::StrFormat("tiling_dimensions = {%s}", + absl::StrJoin(tiling_dimensions_, ", "))}, + ", "); + } + + // Number of elements in each dimension (Z/Y/X respectively). + absl::Span GetDimsInElems() const { return dims_in_elems_; } + + Vector3 GetDimsInBlocks() const { + return {GetDimInBlock(0), GetDimInBlock(1), GetDimInBlock(2)}; + } + + // Number of blocks required to "cover" the given dimension. + int64_t GetDimInBlock(int d) const { + return CeilOfRatio(dims_in_elems_[d], GetBlockTileSizeFor(d)); + } + + // Tile size for a given dimensions per thread. + // + // Equals to the number of iterations in the loop each tile will make. + int64_t GetTileSizeFor(int d) const { return tile_sizes_.at(d); } + + // The tiling dimension for dimension 'd' of the shared memory tile. + int64_t GetTilingDimension(int d) const { return tiling_dimensions_.at(d); } + + // Tile size for a given dimension per entire thread block. + int64_t GetBlockTileSizeFor(int d) const { + return num_threads_.at(d) * tile_sizes_.at(d); + } + + // Number of threads in given dimension. + int64_t GetNumThreadsFor(int d) const { return num_threads_.at(d); } + + // Number of logical threads per block. + int64_t GetNumThreadsPerBlock() const { + return GetNumThreadsFor(0) * GetNumThreadsFor(1) * GetNumThreadsFor(2); + } + + // Number of logical blocks. + int64_t GetNumberOfBlocks() const { + return GetDimInBlock(0) * GetDimInBlock(1) * GetDimInBlock(2); + } + + // Number of physical blocks launched (with scaling applied). + int64_t GetNumberOfBlocksPhysical() const { + return CeilOfRatio(GetNumberOfBlocks(), thread_id_virtual_scaling_); + } + + // Number of physical threads per block launched (with scaling applied). + int64_t GetNumThreadsPerBlockPhysical() const { + return GetNumThreadsPerBlock() * thread_id_virtual_scaling_; + } + + IndexingOrder GetIndexingOrder() const { return indexing_order_; } + int GetVectorSize() const { return vector_size_; } + + // Scaling factor for transforming physical threadId to logical. + int GetThreadIdScalingFactor() const { return thread_id_virtual_scaling_; } + + private: + // The number of elements in each dimension. + const Vector3 dims_in_elems_; + + // The number of elements for each dimension of a tile. + const Vector3 tile_sizes_; + + // The dimensions which are used for the shared memory tile. + const Vector2 tiling_dimensions_; + + // Number of threads implicitly assigned to each dimension. + const Vector3 num_threads_; + + const IndexingOrder indexing_order_; + + // Vector size for dimension X. + const int vector_size_; + + // Scaling apply to transform physical threadIdx into logical. + const int64_t thread_id_virtual_scaling_ = 1; +}; + +class ReductionCodegenInfo { + public: + using IndexGroups = std::vector>; + + explicit ReductionCodegenInfo(TilingScheme mapping_scheme, + int num_partial_results, bool is_row_reduction, + bool is_race_free, IndexGroups index_groups, + const HloInstruction* first_reduce) + : tiling_scheme_(mapping_scheme), + num_partial_results_(num_partial_results), + is_row_reduction_(is_row_reduction), + is_race_free_(is_race_free), + index_groups_(std::move(index_groups)), + first_reduce_(first_reduce) { + if (!is_row_reduction && num_partial_results > 1) { + CHECK_EQ(num_partial_results, + mapping_scheme.GetTileSizeFor(TilingScheme::DimX)); + } + } + + const TilingScheme& GetTilingScheme() const { return tiling_scheme_; } + const IndexGroups& GetIndexGroups() const { return index_groups_; } + Shape GetReduceOperandShape() const { + return first_reduce_->operand(0)->shape(); + } + + int GetNumPartialResults() const { return num_partial_results_; } + bool IsRaceFree() const { return is_race_free_; } + + private: + friend class ReductionCodegenState; + + const TilingScheme tiling_scheme_; + int num_partial_results_; + bool is_row_reduction_; + bool is_race_free_; + IndexGroups index_groups_; + const HloInstruction* first_reduce_; +}; + +class ReductionCodegenState { + public: + struct ReductionCalculationState { + llvm::GlobalVariable* shared_cache; + llvm::Value* initial_value; + llvm::AllocaInst* partial_result_address; + llvm::AllocaInst* input_address; + llvm_ir::ElementGenerator input_gen; + }; + + explicit ReductionCodegenState( + const ReductionCodegenInfo& reduction_codegen_info) + : reduction_codegen_info_(reduction_codegen_info) {} + + const TilingScheme& GetTilingScheme() const { + return reduction_codegen_info_.tiling_scheme_; + } + + int GetNumPartialResults() const { + return reduction_codegen_info_.num_partial_results_; + } + + bool IsRowReduction() const { + return reduction_codegen_info_.is_row_reduction_; + } + + bool IsRaceFree() const { return reduction_codegen_info_.IsRaceFree(); } + + const ReductionCalculationState& GetCalculationStateFor( + const HloInstruction* instruction, int operand_idx) const { + const ReductionOpState& op_state = state_.at(instruction); + CHECK_LT(operand_idx, op_state.size()); + return op_state[operand_idx]; + } + + void SetCalculationStateFor( + const ReductionCalculationState& calculation_state, + const HloInstruction* instruction, int operand_idx) { + ReductionOpState& op_state = state_[instruction]; + CHECK_EQ(operand_idx, op_state.size()); + op_state.push_back(calculation_state); + } + + private: + ReductionCodegenInfo reduction_codegen_info_; + + // One state per reduction operand. + using ReductionOpState = absl::InlinedVector; + + // HloInstruction -> operand_idx -> cache + absl::flat_hash_map state_; +}; + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_MAPPING_SCHEME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_reuse_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_reuse_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..33cddb7d5c15cea8d026a49ef531407af5988112 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_reuse_cache.h @@ -0,0 +1,74 @@ +/*Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_KERNEL_REUSE_CACHE_H_ +#define XLA_SERVICE_GPU_KERNEL_REUSE_CACHE_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/service/gpu/kernel_arguments.h" +#include "xla/service/gpu/launch_dimensions.h" + +namespace xla { +namespace gpu { + +// Caches identical Kernels for deduplication. +// Thread-compatible. +class KernelReuseCache { + public: + struct Entry { + std::string kernel_name; + LaunchDimensions launch_dimensions; + int64_t shmem_bytes; + }; + + // Retrieves the cache entry for the given computation, or generates it using + // the given generator function and stores it in the cache. + std::pair Get( + const HloComputation* fused_computation, + absl::Span kernel_arguments, + absl::string_view discriminator, const std::function& generator); + + // Like `Get`, but for generator functions that can fail. + std::pair, bool /*was_cached*/> GetWithStatus( + const HloComputation* fused_computation, + absl::Span kernel_arguments, + absl::string_view discriminator, + const std::function()>& generator); + + private: + absl::flat_hash_map cache_; +}; + +// Calculates the fingerprint of a (fused_computation, kernel_arguments, +// discriminator) tuple. +// +// If a given fusion is implemented using multiple kernels, then for each +// kernel we should provide a discriminator, such as "init" and "impl". +// +// If the same fingerprint is returned twice, then we can reuse the kernel +// generated for the first computation. +std::string GetComputationFingerprint( + const HloComputation* fused_computation, + absl::Span kernel_arguments, + absl::string_view discriminator = ""); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_REUSE_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..8b5f6c91cb89c163364d1c6d04591d040944c2ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/kernel_thunk.h @@ -0,0 +1,117 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_KERNEL_THUNK_H_ +#define XLA_SERVICE_GPU_KERNEL_THUNK_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/kernel_arguments.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" + +namespace xla { +namespace gpu { + +class GpuExecutable; + +// This class stores everything that StreamExecutor needs for launching a +// kernel. It implements the ExecuteOnStream interface for GpuExecutable to +// invoke the corresponding kernel. +// +// This is thread-compatible. +class KernelThunk : public Thunk { + public: + // Constructs a thunk for the given kernel. + // + // KernelThunk takes args as `BufferAllocation::Slice`s (wrapped in + // `KernelArgument`s). Each slice directly corresponds to an argument or + // output of the computation. Also, the values must correspond to each arg + // directly, not to their base allocation (e.g. they can be the result of an + // `mlir::memref::ViewOp`). + KernelThunk(mlir::Operation* op, std::string kernel_name, + absl::Span kernel_arguments, + LaunchDimensions launch_dimensions, int64_t shmem_bytes); + KernelThunk(const KernelThunk&) = delete; + KernelThunk& operator=(const KernelThunk&) = delete; + ~KernelThunk() override = default; + + std::string ToStringExtra(int indent) const override; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + for (auto& value : values_) { + value = nullptr; + } + } + + const std::vector& arguments() const { + return args_; + } + const std::vector& written() const { return written_; } + + const std::string& kernel_name() const { return kernel_name_; } + const LaunchDimensions& launch_dimensions() const { + return launch_dimensions_; + } + // The shared memory required by the kernel. + int64_t shmem_bytes() const { return shmem_bytes_; } + absl::Span values() const { return values_; } + + private: + // Buffer slices passed to the kernel as arguments. + std::vector args_; + + // args_[i] is written iff (written_[i] == true). + std::vector written_; + + // Entry kernel name for the computation. + const std::string kernel_name_; + + // The thread and block dimension used to launch the kernel. + const LaunchDimensions launch_dimensions_; + + int64_t shmem_bytes_; + + // mlir::Value(s) corresponding to the buffer slice arguments. + std::vector values_; + + mutable absl::Mutex mutex_; + + // Loaded kernels for each `StreamExecutor`. Requires pointer stability of + // values. + absl::flat_hash_map> + kernel_cache_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_KERNEL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/launch_dimensions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/launch_dimensions.h new file mode 100644 index 0000000000000000000000000000000000000000..5bde8059e3bb5ec1c0acb27892aef1fe5fe6369d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/launch_dimensions.h @@ -0,0 +1,134 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_LAUNCH_DIMENSIONS_H_ +#define XLA_SERVICE_GPU_LAUNCH_DIMENSIONS_H_ + +#include +#include + +#include "xla/shape.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Encapsulates the launch dimensions of a kernel, e.g., the block count and the +// number of threads per block. +class LaunchDimensions { + public: + struct Dim3D { + int64_t x, y, z; + + bool operator==(const Dim3D& other) const { + return x == other.x && y == other.y && z == other.z; + } + + bool operator!=(const Dim3D& other) const { return !(*this == other); } + }; + + // The default constructor creates a launch dimension that indicate + // single-threaded execution. + LaunchDimensions() + : block_counts_({1, 1, 1}), thread_counts_per_block_({1, 1, 1}) {} + + LaunchDimensions(int64_t block_x_count, int64_t thread_x_count_per_block) + : block_counts_({block_x_count, 1, 1}), + thread_counts_per_block_({thread_x_count_per_block, 1, 1}) {} + + LaunchDimensions(const Dim3D& block_counts, + const Dim3D& thread_counts_per_block) + : block_counts_(block_counts), + thread_counts_per_block_(thread_counts_per_block) {} + + Dim3D block_counts() const { return block_counts_; } + + Dim3D thread_counts_per_block() const { return thread_counts_per_block_; } + + // Returns the total number of threads in a block. + int64_t total_nb_threads() const { + return thread_counts_per_block_.x * thread_counts_per_block_.y * + thread_counts_per_block_.z; + } + + int64_t launch_bound() const { + return block_counts_.x * thread_counts_per_block_.x * block_counts_.y * + thread_counts_per_block_.y * block_counts_.z * + thread_counts_per_block_.z; + } + + std::string ToString() const { + return absl::StrCat("blocks: {", block_counts_.x, ", ", block_counts_.y, + ", ", block_counts_.z, "}, threads/block: {", + thread_counts_per_block_.x, ", ", + thread_counts_per_block_.y, ", ", + thread_counts_per_block_.z, "}"); + } + + bool operator==(const LaunchDimensions& other) const { + return block_counts_ == other.block_counts_ && + thread_counts_per_block_ == other.thread_counts_per_block_; + } + + bool operator!=(const LaunchDimensions& other) const { + return !(*this == other); + } + + private: + Dim3D block_counts_; + Dim3D thread_counts_per_block_; +}; + +std::ostream& operator<<(std::ostream& out, + const LaunchDimensions& launch_dims); + +struct LaunchDimensionsConfig { + // The kernel implementation will be unrolled if `unroll_factor` is + // greater than one. + int unroll_factor = 1; + // A wave is a group of blocks that execute at the same time on the + // GPU. If there are more blocks then the number that can run + // concurrently, there are multiple waves of blocks running + // sequentially. If `few_waves` is true, each thread will loop over + // a block of unroll_factor elements. Otherwise each thread will + // handle only unroll_factor. + bool few_waves = false; + // If `row_optimized` is true, then the block size will equal to + // `hlo.shape().dimensions().back()/unroll_factor`. + // Currently few_waves and row_vectorized do not work together. + bool row_vectorized = false; + + std::string ToString() { + return absl::StrCat("unroll_factor=", unroll_factor, + ", few_waves=", few_waves, + ", row_vectorized=", row_vectorized); + } +}; + +// Returns -1 if the shape doesn't allow the row vectorization code path. +// If supported, return the number of threads to use in that case. +int64_t ThreadsPerBlockRowVectorized( + const Shape& shape, const se::DeviceDescription& gpu_device_info, + LaunchDimensionsConfig dim_config); + +// Calculates the launch dimensions used to invoke `hlo`. +StatusOr CalculateLaunchDimensions( + const Shape& shape, const se::DeviceDescription& gpu_device_info, + LaunchDimensionsConfig dim_config = {}); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_LAUNCH_DIMENSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..9ff362c2df33911b099e860409b8019eab3e003a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/gpu_backend_lib.h @@ -0,0 +1,72 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// LLVM-based compiler backend. +#ifndef XLA_SERVICE_GPU_LLVM_GPU_BACKEND_GPU_BACKEND_LIB_H_ +#define XLA_SERVICE_GPU_LLVM_GPU_BACKEND_GPU_BACKEND_LIB_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "llvm/IR/Module.h" +#include "llvm/Target/TargetMachine.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/types.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +namespace nvptx { + +std::string CantFindCudaMessage(absl::string_view msg, + absl::string_view xla_gpu_cuda_data_dir); + +// Get path to NVVM libdevice file. +std::string LibDevicePath(absl::string_view xla_gpu_cuda_data_dir); + +// Link libdevice if functions using it are detected in the module. +Status LinkLibdeviceIfNecessary(llvm::Module* module, + const std::string& libdevice_path); + +// Compiles the argument module and returns it. libdevice_dir_path is the parent +// directory of the libdevice bitcode libraries. The contents of the module may +// be changed. +// +// The Compile.* interfaces each create their own llvm::LLVMContext objects for +// thread safety, but note that LLVM's multithreaded support is very +// preliminary; multithreaded use is not recommended at this time. +StatusOr CompileToPtx( + llvm::Module* module, se::GpuComputeCapability gpu_version, + const DebugOptions& debug_options, + std::function configure_target = nullptr); +} // namespace nvptx + +namespace amdgpu { +// Compiles the argument module and returns it with LLVM AMDGPU backend. +// rocdl_dir_path is the parent directory of ROCm-Device-Libs bitcode libraries. +// The contents of the module may be changed. +StatusOr> CompileToHsaco( + llvm::Module* module, se::GpuComputeCapability gpu_version, + const DebugOptions& debug_options, const std::string& rocdl_dir_path, + const std::string& module_config_cache_key); +} // namespace amdgpu + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_LLVM_GPU_BACKEND_GPU_BACKEND_LIB_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..5c6a07ae3514e6ac667362c123dd40d160b3df45 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/utils.h @@ -0,0 +1,51 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_LLVM_GPU_BACKEND_UTILS_H_ +#define XLA_SERVICE_GPU_LLVM_GPU_BACKEND_UTILS_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/types.h" + +namespace llvm { +class LLVMContext; +class Module; +} // namespace llvm + +namespace xla { +namespace gpu { + +// Convenience function for loading a LLVM module from an IR file. The module +// is created in the given LLVM context. +// +// If loading fails for some reason, dies printing a diagnostic error. +std::unique_ptr LoadIRModule(const std::string& filename, + llvm::LLVMContext* llvm_context); + +// Convenience function for replacing the extension of the given filename. +// If the filename has no extension, the new extension is appended to its name. +// +// For example: +// ReplaceFilenameExtension("/foo/baz.txt", "cc") --> "/foo/baz.cc" +std::string ReplaceFilenameExtension(absl::string_view filename, + absl::string_view new_extension); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_LLVM_GPU_BACKEND_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/loop_double_buffer_transformer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/loop_double_buffer_transformer.h new file mode 100644 index 0000000000000000000000000000000000000000..b9fb70a1853f41fe69f69af61c0c011bf26ccd86 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/loop_double_buffer_transformer.h @@ -0,0 +1,54 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_LOOP_DOUBLE_BUFFER_TRANSFORMER_H_ +#define XLA_SERVICE_GPU_LOOP_DOUBLE_BUFFER_TRANSFORMER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// This pass performs the unrolling-by-2 loop transformation +// to effectively achieve double buffering between inputs and outputs +// of previously rolled iterations. +// This pass only runs on loops with known trip counts. +// For even number of iterations, unrolling-by-2 will be done directly. +// For odd number of iterations, the first iteration of the loop will be +// peeled outside of the while loop to make the trip count an even number, +// then proceed to unroll by 2. +// It also updates the trip count property of the loop to the correct one (n/2). +class LoopDoubleBufferTransformer : public HloModulePass { + public: + LoopDoubleBufferTransformer() = default; + ~LoopDoubleBufferTransformer() override = default; + absl::string_view name() const override { + return "loop-double-buffer-transformer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_LOOP_DOUBLE_BUFFER_TRANSFORMER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/matmul_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/matmul_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..78c11c5bccae85e32557e14ad5389de8be2c1252 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/matmul_utils.h @@ -0,0 +1,275 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_MATMUL_UTILS_H_ +#define XLA_SERVICE_GPU_MATMUL_UTILS_H_ + +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/service/gpu/backend_configs.pb.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/stream_executor/blas.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#include "xla/stream_executor/scratch_allocator.h" + +#elif TENSORFLOW_USE_ROCM +#include "rocm/rocm_config.h" +#if TF_HIPBLASLT +#include "xla/stream_executor/rocm/hip_blas_lt.h" +#include "xla/stream_executor/scratch_allocator.h" +#endif // TF_HIPBLASLT +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +namespace xla { +namespace gpu { + +StatusOr> GetNonContractingDims( + const Shape& shape, absl::Span batch_dims, + absl::Span contracting_dims); + +// Batch dimensions of an operand of a dot instruction. +// Just an unified accessor to lhs_batch_dimensions and rhs_batch_dimensions. +const tsl::protobuf::RepeatedField& BatchDimensionsForOperand( + const HloInstruction& dot, int operand_number); + +// Index of the only contracting dimension of dot instruction operand. +int64_t ContractingDimensionIndex(const HloInstruction& dot, + int operand_number); + +// Index of the only non-contracting dimension of dot instruction operand. +int64_t NonContractingDimensionIndex(const HloInstruction& dot, + int operand_number); + +// Normalize shape to (batch, rows, columns) logical dimensions. +StatusOr GetBatchRowColumnShape(const Shape& shape, + absl::Span batch_dims, + absl::Span row_dims, + absl::Span col_dims); + +struct MatrixLayout { + enum class Order { + kRowMajor, // Elements in the same row are contiguous in memory. + kColumnMajor, // Elements in the same column are contiguous in memory. + }; + + // Returns the matrix layout for a logical shape (batch, rows, columns). + static StatusOr For(const Shape& shape); + // Returns the matrix layout with the given batch, row, col dimensions. + static StatusOr For(const Shape& shape, + absl::Span batch_dims, + absl::Span row_dims, + absl::Span col_dims); + // Returns the matrix layout for the output. + static StatusOr For(const Shape& shape, + size_t lhs_num_batch_dims, + size_t lhs_num_row_dims, + size_t rhs_num_batch_dims, + size_t rhs_num_col_dims); + + void Transpose(); + + PrimitiveType dtype; + // `num_rows` / `num_cols` are for the "logical" matrix shape: + // i.e. the contracting dim has size `num_cols` for LHS operands and + // `num_rows` for RHS operands. + int64_t num_rows; + int64_t num_cols; + Order order; + int64_t leading_dim_stride; + int64_t batch_size; + int64_t batch_stride; // `batch_stride` is set to `0` when `batch_size == 1`. +}; + +// GPU folding rule for the `TransposeFolding` pass. +StatusOr CanFoldTransposeOperandIntoDot(const HloInstruction& dot, + int64_t operand_idx); + +struct GemmConfig { + static StatusOr For(const HloInstruction* gemm); + static StatusOr For(mlir::lmhlo_gpu::GEMMOp op); + + static StatusOr For( + const Shape& lhs_shape, absl::Span lhs_batch_dims, + absl::Span lhs_contracting_dims, const Shape& rhs_shape, + absl::Span rhs_batch_dims, + absl::Span rhs_contracting_dims, const Shape& output_shape, + double alpha_real, double alpha_imag, double beta, + std::optional algorithm, int64_t compute_precision); + + // As above with additional `c_shape` and `bias_shape_ptr` parameter, both + // which are only necessarily for F8 gemms. + static StatusOr For( + const Shape& lhs_shape, absl::Span lhs_batch_dims, + absl::Span lhs_contracting_dims, const Shape& rhs_shape, + absl::Span rhs_batch_dims, + absl::Span rhs_contracting_dims, const Shape& c_shape, + const Shape* bias_shape_ptr, const Shape& output_shape, double alpha_real, + double alpha_imag, double beta, std::optional algorithm, + int64_t compute_precision); + + template ::value || + std::is_same::value>> + static StatusOr For(CublasLtMatmulMaybeF8Op op) { + mlir::mhlo::DotDimensionNumbersAttr dot_dims = op.getDotDimensionNumbers(); + + int64_t compute_precision = 0; // Default + if (op.getPrecisionConfig().has_value()) { + auto precision_config = op.getPrecisionConfig(); + for (auto attr : precision_config.value()) { + int64_t value = static_cast( + attr.template cast().getValue()); + if (value > compute_precision) { + compute_precision = value; + } + } + } + + Shape bias_shape; + if (op.getBias() != nullptr) { + bias_shape = GetShape(op.getBias()); + } + return GemmConfig::For( + GetShape(op.getA()), dot_dims.getLhsBatchingDimensions(), + dot_dims.getLhsContractingDimensions(), GetShape(op.getB()), + dot_dims.getRhsBatchingDimensions(), + dot_dims.getRhsContractingDimensions(), GetShape(op.getC()), + op.getBias() == nullptr ? nullptr : &bias_shape, GetShape(op.getD()), + op.getAlphaReal().convertToDouble(), + op.getAlphaImag().convertToDouble(), op.getBeta().convertToDouble(), + op.getAlgorithm(), compute_precision); + } + + MatrixLayout lhs_layout; + MatrixLayout rhs_layout; + MatrixLayout c_layout; + MatrixLayout output_layout; + complex128 alpha; + double beta; + std::optional algorithm; + int64_t compute_precision; +}; + +StatusOr GetBlasComputationType( + PrimitiveType lhs_dtype, PrimitiveType output_dtype, + int64_t compute_precision); + +namespace cublas_lt { + +// Returns the type for the alpha and beta scalars. +se::blas::DataType GetScaleType(se::blas::DataType c_type, + se::blas::ComputationType computation_type); + +} // namespace cublas_lt + +// Run the given GEMM instruction `gemm` subject to the configuration +// in `gemm_config` and the passed buffers. +// +// If `algorithm` is provided, it overrides the one specified in `config`. +Status RunGemm(const GemmConfig& config, se::DeviceMemoryBase lhs_buffer, + se::DeviceMemoryBase rhs_buffer, + se::DeviceMemoryBase output_buffer, bool deterministic_ops, + se::Stream* stream, + std::optional algorithm = std::nullopt, + se::blas::ProfileResult* profile_result = nullptr); + +namespace cublas_lt { + +StatusOr EpilogueAddsVectorBias(GemmBackendConfig_Epilogue epilogue); +StatusOr EpilogueHasAuxiliaryOutput(GemmBackendConfig_Epilogue epilogue); + +} // namespace cublas_lt + +StatusOr AsBlasDataType(PrimitiveType dtype); + +#if GOOGLE_CUDA || TF_HIPBLASLT + +namespace cublas_lt { + +StatusOr AsBlasLtEpilogue( + mlir::lmhlo_gpu::CublasLtMatmulEpilogue epilogue); + +class MatmulPlan { + public: + static StatusOr From(const GemmConfig& config, + se::gpu::BlasLt::Epilogue epilogue); + + Status ExecuteOnStream( + se::Stream* stream, se::DeviceMemoryBase a_buffer, + se::DeviceMemoryBase b_buffer, se::DeviceMemoryBase c_buffer, + se::DeviceMemoryBase d_buffer, + se::DeviceMemoryBase bias_buffer, // may be null + se::DeviceMemoryBase aux_buffer, // may be null + se::DeviceMemoryBase a_scale_buffer, se::DeviceMemoryBase b_scale_buffer, + se::DeviceMemoryBase c_scale_buffer, se::DeviceMemoryBase d_scale_buffer, + se::DeviceMemoryBase d_amax_buffer, + const se::gpu::BlasLt::MatmulAlgorithm& algorithm, + se::ScratchAllocator& scratch_allocator, + se::blas::ProfileResult* profile_result = nullptr) const; + + StatusOr> GetAlgorithms( + se::Stream* stream) const; + + private: + MatmulPlan(se::gpu::BlasLt::MatmulPlan plan, complex128 alpha, double beta, + bool must_swap_operands) + : plan_(std::move(plan)), + alpha_(alpha), + beta_(beta), + must_swap_operands_(must_swap_operands) {} + + template + Status DoMatmul(se::Stream* stream, se::DeviceMemoryBase a_buffer, + se::DeviceMemoryBase b_buffer, se::DeviceMemoryBase c_buffer, + se::DeviceMemoryBase d_buffer, + se::DeviceMemoryBase bias_buffer, // may be null + se::DeviceMemoryBase aux_buffer, // may be null + se::DeviceMemoryBase a_scale, se::DeviceMemoryBase b_scale, + se::DeviceMemoryBase c_scale, se::DeviceMemoryBase d_scale, + se::DeviceMemoryBase d_amax, + const se::gpu::BlasLt::MatmulAlgorithm& algorithm, + se::ScratchAllocator& scratch_allocator, + se::blas::ProfileResult* profile_result) const; + + se::gpu::BlasLt::MatmulPlan plan_; + complex128 alpha_; + double beta_; + bool must_swap_operands_; +}; + +} // namespace cublas_lt + +#endif // GOOGLE_CUDA || TF_HIPBLASLT + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_MATMUL_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/memset_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/memset_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..4529571b0ebca8b4e0b591a27cea7b52e0ed5a04 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/memset_thunk.h @@ -0,0 +1,88 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_MEMSET_THUNK_H_ +#define XLA_SERVICE_GPU_MEMSET_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "xla/stream_executor/stream_executor.h" + +// This file contains thunks that set a buffer's elements to a particular value. +// This can be faster than emitting a kernel to set the elements. + +namespace xla { +namespace gpu { + +// Thunk that zeroes out a given chunk of memory. +class MemzeroThunk : public Thunk { + public: + explicit MemzeroThunk(ThunkInfo thunk_info, + const BufferAllocation::Slice& dest, + mlir::Value dest_value) + : Thunk(Kind::kMemzero, thunk_info), + dest_(dest), + dest_value_(dest_value) {} + + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + dest_value_ = nullptr; + } + + const BufferAllocation::Slice& destination() const { return dest_; } + mlir::Value dest_value() const { return dest_value_; } + + private: + const BufferAllocation::Slice dest_; + mlir::Value dest_value_; +}; + +// Thunk that sets a given chunk of memory to a particular 32-bit value. The +// destination chunk must have size divisible by 32 bits. +class Memset32BitValueThunk : public Thunk { + public: + explicit Memset32BitValueThunk(ThunkInfo thunk_info, uint32_t value, + const BufferAllocation::Slice& dest, + mlir::Value dest_value) + : Thunk(Kind::kMemset32BitValue, thunk_info), + value_(value), + dest_(dest), + dest_value_(dest_value) {} + + Status ExecuteOnStream(const ExecuteParams& params) override; + + void ClearCompileTimeInfo() override { + Thunk::ClearCompileTimeInfo(); + dest_value_ = nullptr; + } + + const BufferAllocation::Slice& destination() const { return dest_; } + uint32_t value() const { return value_; } + mlir::Value dest_value() const { return dest_value_; } + + private: + const uint32_t value_; + const BufferAllocation::Slice dest_; + mlir::Value dest_value_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_MEMSET_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/metrics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/metrics.h new file mode 100644 index 0000000000000000000000000000000000000000..d660743838a26fcf4097a56399c0c3df0d538a27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/metrics.h @@ -0,0 +1,53 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_METRICS_H_ +#define XLA_SERVICE_GPU_METRICS_H_ + +#include + +namespace xla { + +// HLO passes (HLO -> HLO). +void RecordHloPassesDuration(uint64_t time_usecs); + +// Compiling HLO to LLVM. +void RecordHloToLlvmDuration(uint64_t time_usecs); + +// The entire LLVM to PTX pipeline, including both LLVM optimization (LLVM -> +// LLVM) and compiling LLVM -> PTX. +void RecordLlvmPassesAndLlvmToPtxDuration(uint64_t time_usecs); + +// LLVM passes (linking and optimization) only (LLVM -> LLVM). +void RecordLlvmPassesDuration(uint64_t time_usecs); + +// Compiling LLVM to PTX only. +void RecordLlvmToPtxDuration(uint64_t time_usecs); + +// Compiling PTX to cubin. +void RecordPtxToCubinDuration(uint64_t time_usecs); + +// Counts compiled programs numbers. +void IncrementCompiledProgramsCount(); + +// Gets compiled programs numbers. +int64_t GetCompiledProgramsCount(); + +// Records the size of the XLA device binary in bytes. +void RecordXlaDeviceBinarySize(int64_t size); + +} // namespace xla + +#endif // XLA_SERVICE_GPU_METRICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/move_copy_to_users.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/move_copy_to_users.h new file mode 100644 index 0000000000000000000000000000000000000000..a01d8e97d186f4ab5b3181d310664fda636e8e31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/move_copy_to_users.h @@ -0,0 +1,40 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_MOVE_COPY_TO_USERS_H_ +#define XLA_SERVICE_GPU_MOVE_COPY_TO_USERS_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { + +// Sink kCopy operations as far down the graph as possible. +class MoveCopyToUsers : public HloModulePass { + public: + absl::string_view name() const override { return "move_copy_to_users"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // end namespace xla + +#endif // XLA_SERVICE_GPU_MOVE_COPY_TO_USERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/multi_output_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/multi_output_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..103694857407ac4d8464a2cda6c20b61f8e28cf3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/multi_output_fusion.h @@ -0,0 +1,133 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_MULTI_OUTPUT_FUSION_H_ +#define XLA_SERVICE_GPU_MULTI_OUTPUT_FUSION_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_reachability.h" +#include "xla/service/gpu/gpu_fusible.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Multi-output fusion of sibling and producer-consumer instructions for the +// GPU backend to reduce memory bandwidth requirements. +// +// 0) Before multi- 1) Sibling multi- 2) Producer-consumer +// output fusion output fusion multi-output fusion +// +// p p p +// | | | +// v v v +// A A +-fusion--+ +// / \ | | A | +// | | +-fusion--+ | / \ | +// v v | / \ | | B | | +// B C | B C | | | | | +// \ / | | | | | v v | +// v v | v v | | tuple | +// ROOT | tuple | +---------+ +// +---------+ / \ +// / \ gte_b gte_a +// gte_b gte_c | | +// | | | v +// \ / | C +// v v \ / +// ROOT v v +// ROOT +// +// Multi-output fusion ops have a tuple op at their root containing multiple +// elements as outputs. GetTupleElement ops (depicted as gte_* above) are +// inserted to extract tuple elements for consumers. +// +// The two different flavors of multi-output fusion this pass performs are +// depicted above. +// 1) Fusion of sibling ops reduces memory bandwidth requirements, because +// common input parameters have to be read only once. +// 2) Fusion of producer-consumer ops reduces memory bandwidth requirements by +// saving one read from memory. In the example above, B does not need to read +// the output of A from memory, while C still does (using gte_a). +// Note that sibling (1) and producer-consumer (2) multi-output fusion can be +// combined. +// +// The GpuMultiOutputFusion pass modifies the HLO in reverse post-order (defs +// before uses). First, it attempts to fuse the consumer ops of the current op, +// which are siblings (1). Hereafter, it attempts to fuse the current op with +// one of its consumers (2). This order avoids a phase ordering issue (described +// in go/fusionfusion). It ensures that all GetTupleElement ops inserted as a +// by-product of multi-output fusion will occur before the current op in the +// order of traversal, and hence, not get into the way of subsequent fusion +// attempts. +// +// The GpuMultiOutputFusion pass ensures several conditions are met for fusion. +// Some of them are relevant for correctness. In particular, no cycles must be +// introduced into the HLO module. Moreover, the code emitters for multi-output +// fusion must support the combination of ops and their shapes. Other +// restrictions are rather arbitrary and lifting them could be beneficial. +// * Sibling fusion (1) requires at least one op to be a kFusion. +// * Sibling fusion (1) does not fuse kInput fusions with kLoop fusions, i.e. +// the fusion kinds must match. + +class GpuMultiOutputFusion : public HloModulePass { + public: + explicit GpuMultiOutputFusion( + const se::DeviceDescription& device_info, + HloCostAnalysis::ShapeSizeFunction shape_size_function) + : device_info_(device_info), shape_size_function_(shape_size_function) {} + + absl::string_view name() const override { return "multi_output_fusion"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + bool FuseSiblings(HloInstruction* parent, FusionInfoCache* fusion_info_cache, + GpuHloCostAnalysis* cost_analysis); + + StatusOr DoMultiOutputFusion(); + + // Recompute reachability for the current computation. + void RecomputeReachability(); + + void DumpFusionState(const HloInstruction& consumer, absl::string_view label, + const HloInstruction* producer = nullptr); + + // Computation for the pass. + HloComputation* computation_; + + // The reachability map of current computation. + std::unique_ptr reachability_; + + se::DeviceDescription device_info_; + HloCostAnalysis::ShapeSizeFunction shape_size_function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_MULTI_OUTPUT_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_gather_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_gather_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..dfd4e39b4ebb593372b4105df0d9abe76ac0e2f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_gather_thunk.h @@ -0,0 +1,64 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_ALL_GATHER_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_ALL_GATHER_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +struct NcclAllGatherConfig { + NcclCollectiveConfig config; +}; + +// Thunk that performs a NCCL-based All-Gather among CUDA GPU-based replicas. +class NcclAllGatherStartThunk : public NcclCollectiveThunk { + public: + NcclAllGatherStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::AllGatherStartOp op, + std::vector buffers); + + static const char* GetHloOpName() { return "all-gather-start"; } + + static Status CheckImplementable(mlir::lmhlo_gpu::AllGatherStartOp op, + int64_t replica_count, + int64_t partition_count); + static bool IsDegenerate(mlir::lmhlo_gpu::AllGatherStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::AllGatherStartOp op); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + + private: + const NcclAllGatherConfig config_; + const std::vector buffers_; +}; + +Status RunAllGather(std::vector& buffers, se::Stream& stream, + ncclComm_t comm); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_ALL_GATHER_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_reduce_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_reduce_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..b70e7dc317f15625810bb6620be4fb365c5ca158 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_reduce_thunk.h @@ -0,0 +1,115 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_ALL_REDUCE_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_ALL_REDUCE_THUNK_H_ + +#include +#include + +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +struct NcclAllReduceConfig { + NcclCollectiveConfig config; + ReductionKind reduction_kind; +}; + +// Thunk that performs a NCCL-based All-Reduce or Reduce-Scatter among CUDA +// GPU-based replicas. +class NcclAllReduceReduceScatterThunkBase : public NcclCollectiveThunk { + public: + static std::optional MatchAllReduceComputation( + mlir::Region& computation); + + NcclAllReduceReduceScatterThunkBase(Kind kind, ThunkInfo thunk_info, + NcclAllReduceConfig config, + std::vector buffers, + bool is_sync); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + + const NcclAllReduceConfig config_; + const std::vector buffers_; +}; + +// ----------------------------------------------------------------------------- +// AllReduce thunk. +// ----------------------------------------------------------------------------- + +class NcclAllReduceStartThunk : public NcclAllReduceReduceScatterThunkBase { + public: + NcclAllReduceStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::AllReduceStartOp op, + std::vector buffers); + + static const char* GetHloOpName() { return "all-reduce-start"; } + + static Status CheckImplementable(mlir::lmhlo_gpu::AllReduceStartOp op, + int64_t replica_count, + int64_t partition_count); + static bool IsDegenerate(mlir::lmhlo_gpu::AllReduceStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::AllReduceStartOp op); + + protected: + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; +}; + +// ----------------------------------------------------------------------------- +// ReduceScatter thunk +// ----------------------------------------------------------------------------- +class NcclReduceScatterStartThunk : public NcclAllReduceReduceScatterThunkBase { + public: + NcclReduceScatterStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::ReduceScatterStartOp op, + std::vector buffers); + + static const char* GetHloOpName() { return "reduce-scatter-start"; } + + static Status CheckImplementable(mlir::lmhlo_gpu::ReduceScatterStartOp op, + int64_t replica_count, + int64_t partition_count); + static bool IsDegenerate(mlir::lmhlo_gpu::ReduceScatterStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::ReduceScatterStartOp op); + + protected: + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; +}; + +// ----------------------------------------------------------------------------- + +Status RunAllReduce(ReductionKind reduction_kind, + std::vector& buffers, se::Stream& stream, + ncclComm_t comm); + +Status RunReduceScatter(ReductionKind reduction_kind, + std::vector& buffers, + se::Stream& stream, ncclComm_t comm); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_ALL_REDUCE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_to_all_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_to_all_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..e6e60c5d0fb65e37316afce98291a0a8e9e255b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_all_to_all_thunk.h @@ -0,0 +1,68 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_ALL_TO_ALL_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_ALL_TO_ALL_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +struct NcclAllToAllConfig { + NcclCollectiveConfig config; + bool has_split_dimension; +}; + +// Thunk that performs a NCCL-based All-to-All among CUDA GPU-based replicas. +class NcclAllToAllStartThunk : public NcclCollectiveThunk { + public: + NcclAllToAllStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::AllToAllStartOp op, + std::vector buffers); + + // Returns whether the given instruction can be lowered to a nccl all-to-all + // call. + static Status CheckImplementable(mlir::lmhlo_gpu::AllToAllStartOp op, + int64_t replica_count, + int64_t partition_count); + + static const char* GetHloOpName() { return "all-to-all-start"; } + static bool IsDegenerate(mlir::lmhlo_gpu::AllToAllStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::AllToAllStartOp op); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + + private: + const NcclAllToAllConfig config_; + const std::vector buffers_; +}; + +Status RunAllToAll(bool has_split_dimension, + std::vector& buffers, se::Stream& stream, + ncclComm_t comm); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_ALL_TO_ALL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_permute_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_permute_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..8f2a675e782c2b827e02e495bf4c1d150000f26b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_permute_thunk.h @@ -0,0 +1,70 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_COLLECTIVE_PERMUTE_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_COLLECTIVE_PERMUTE_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/nccl_p2p_thunk_common.h" + +namespace xla { +namespace gpu { + +// Thunk that performs a NCCL-based collective permute. +class NcclCollectivePermuteStartThunk : public NcclCollectiveThunk { + public: + static NcclP2PConfig GetNcclP2PConfig( + mlir::lmhlo_gpu::CollectivePermuteStartOp op, int64_t replica_count, + int64_t partition_count); + + static Status CheckImplementable(mlir::lmhlo_gpu::CollectivePermuteStartOp op, + int64_t replica_count, + int64_t partition_count); + + static bool IsDegenerate(mlir::lmhlo_gpu::CollectivePermuteStartOp op, + int64_t replica_count, int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode( + mlir::lmhlo_gpu::CollectivePermuteStartOp op); + + static const char* GetHloOpName() { return "collective-permute-start"; } + + NcclCollectivePermuteStartThunk(ThunkInfo thunk_info, + mlir::lmhlo_gpu::CollectivePermuteStartOp op, + int64_t replica_count, + int64_t partition_count, + const Buffer& buffer); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + + private: + const NcclP2PConfig config_; + const Buffer buffer_; +}; + +Status RunCollectivePermute(NcclP2PConfig::SourceTargetMapEntry source_target, + DeviceBufferPair& buffer, se::Stream& stream, + ncclComm_t comm, absl::string_view device_string, + int64_t current_id); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_COLLECTIVE_PERMUTE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..a4b5c1ec5041436519a739427f36f3c4089985e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_collective_thunk.h @@ -0,0 +1,216 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_COLLECTIVE_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_COLLECTIVE_THUNK_H_ + +#include +#include +#include +#include + +#include "absl/functional/function_ref.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/ir_emission_utils.h" +#include "xla/service/gpu/thunk.h" +#include "xla/service/llvm_ir/llvm_util.h" +#include "xla/translate/mhlo_to_hlo/attribute_exporter.h" +#include "xla/xla_data.pb.h" + +#if XLA_ENABLE_XCCL +#include "xla/service/gpu/nccl_utils.h" +#endif // XLA_ENABLE_XCCL + +struct ncclComm; +using ncclComm_t = ncclComm*; + +namespace xla { +namespace gpu { + +class NcclClique; + +struct NcclCollectiveConfig { + NcclCollectiveConfig(); + NcclCollectiveConfig(NcclCollectiveConfig&&); + ~NcclCollectiveConfig(); + + NcclCollectiveConfig& operator=(NcclCollectiveConfig&&); + + int64_t operand_count; + std::vector operand_element_type; + std::vector replica_groups; + RendezvousKey::CollectiveOpKind collective_op_kind; + int64_t op_id; + CollectiveOpGroupMode group_mode; + + template + void SetCollectiveOpKindAndID(OpT op); + bool IsDegenerate(int64_t replica_count, int64_t partition_count) const; +}; + +template +void NcclCollectiveConfig::SetCollectiveOpKindAndID(OpT op) { + if (op.getChannelId()) { + collective_op_kind = RendezvousKey::kCrossModule; + op_id = static_cast(op.getChannelId()->getHandle()); + } else { + collective_op_kind = RendezvousKey::kCrossReplica; + mlir::ModuleOp parent = op->template getParentOfType(); + mlir::IntegerAttr unique_id = + parent->getAttrOfType("hlo.unique_id"); + op_id = static_cast(unique_id.getInt()); + } +} + +template +NcclCollectiveConfig GetNcclCollectiveConfigForMlir( + OpT op, std::optional use_global_device_ids) { + NcclCollectiveConfig config; + config.operand_count = op.getInputs().size(); + config.operand_element_type.reserve(config.operand_count); + for (int i = 0; i < config.operand_count; i++) { + const Shape shape = GetShape(op.getInputs()[i]); + config.operand_element_type.push_back(shape.element_type()); + } + config.replica_groups = ConvertReplicaGroups(op.getReplicaGroups()).value(); + config.SetCollectiveOpKindAndID(op); + config.group_mode = GetCollectiveOpGroupMode(op.getChannelId().has_value(), + use_global_device_ids) + .value(); + return config; +} + +// Thunk base class for NCCL collective operations. +class NcclCollectiveThunk : public Thunk { + public: + NcclCollectiveThunk(Kind kind, ThunkInfo thunk_info, bool is_sync); + + struct Buffer { + int64_t element_count; + BufferAllocation::Slice source_buffer; + BufferAllocation::Slice destination_buffer; + mlir::Value source_value; + mlir::Value destination_value; + }; + + class AsyncExecutor { + public: + // Executes the function on the async communications stream and records a + // completion event. + Status Execute( + absl::FunctionRef + fn, + const ExecuteParams& params, ncclComm_t comm, + AsyncStreamKind stream_kind); + // Blocks the compute stream until async communication is complete. + Status Await(const ExecuteParams& params); + + private: + absl::Mutex mu_; + // Store done events (by device ordinal) for the done thunk to wait on. + absl::flat_hash_map done_events_ ABSL_GUARDED_BY(mu_); + }; + + // Returns whether NCCL operations appear possible to perform; e.g. if we + // haven't done a build with the CUDA compiler enabled, we can't compile the + // NCCL header, and thus this will be false. + // + // When this is false, the ExecuteOnStream() call will simply return a status + // error. + static bool NcclIsEnabled(); + static Status CheckImplementable(); + + // Logging support. + static std::string GetDeviceString(const NcclExecuteParams& params); + + AsyncExecutor* async_executor() { return async_.get(); } + Status ExecuteOnStream(const ExecuteParams& params) override; + + protected: + virtual Status RunNcclCollective(const ExecuteParams& params, + se::Stream& stream, ncclComm_t comm) = 0; + virtual const NcclCollectiveConfig& config() const = 0; + virtual AsyncStreamKind GetAsyncStreamKind() const { + return kAsyncStreamCollective; + } + + private: + bool IsAsync() const { return async_ != nullptr; } + int64_t GetStreamId() const { + return xla::gpu::GetStreamId(IsAsync(), GetAsyncStreamKind()); + } + +#if XLA_ENABLE_XCCL + bool first_call_to_execute_ = true; +#endif // XLA_ENABLE_XCCL + std::unique_ptr async_; // null if not async. +}; + +class NcclCollectiveDoneThunk : public Thunk { + public: + NcclCollectiveDoneThunk(Thunk::Kind kind, ThunkInfo thunk_info, + NcclCollectiveThunk::AsyncExecutor& async); + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + NcclCollectiveThunk::AsyncExecutor& async_; +}; + +Status IsValidOperand(mlir::Value operand, Thunk::Kind reduction_op); + +template +Status AddOpDescription(Status status, OpT op, int64_t replica_count, + int64_t partition_count) { + if (status.ok()) { + return status; + } + CollectiveOpGroupMode group_mode = NcclThunkType::GetGroupMode(op); + return Status( + status.code(), + absl::StrFormat( + "%s\n" + "%s with replica_count: %d, partition_count: %d, group_mode: %s, " + "operand_count: %d\n%s", + status.message(), NcclThunkType::GetHloOpName(), replica_count, + partition_count, CollectiveOpGroupModeToString(group_mode), + op->getNumOperands() / 2, llvm_ir::DumpToString(op.getOperation()))); +} + +#if XLA_ENABLE_XCCL +// TODO(hanbinyoon): Consider moving to nccl_utils.h when deprecating Thunks. +StatusOr LockNcclComm( + const NcclExecuteParams& params, + const std::vector& replica_groups, + CollectiveOpGroupMode group_mode, int64_t op_id, int64_t stream_id, + bool enable_clique_optimization); +#endif // XLA_ENABLE_XCCL + +struct DeviceBufferPair { + PrimitiveType element_type; + int64_t element_count; + se::DeviceMemoryBase source_buffer; + se::DeviceMemoryBase destination_buffer; +}; +StatusOr> ConvertToDeviceBuffers( + const Thunk::ExecuteParams& params, + const std::vector& buffers, + const std::vector& element_types); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_COLLECTIVE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_p2p_thunk_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_p2p_thunk_common.h new file mode 100644 index 0000000000000000000000000000000000000000..25814402491fc0c29f1eb89f85cf71faac840bda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_p2p_thunk_common.h @@ -0,0 +1,136 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_P2P_THUNK_COMMON_H_ +#define XLA_SERVICE_GPU_NCCL_P2P_THUNK_COMMON_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" + +namespace xla { +namespace gpu { + +// Records the information for implementing CollectivePermute, Send and Recv. +struct NcclP2PConfig { + // Record the target ID for sending a data and the source ID from which to + // receive a data. Either target or source can be optional. + struct SourceTargetMapEntry { + std::optional source; + std::optional target; + }; + + using IdToSourceTargetMap = + absl::flat_hash_map; + + // Returns the source and target ID corresponding to the given ID (these IDs + // are replica_ids for cross replica permute or partition_ids for cross + // partition permute). The source ID is the id which will send data to this + // ID and the target ID is the id to which this ID will send its data. Either + // can be optional. + static SourceTargetMapEntry GetSourceTarget( + const IdToSourceTargetMap& id_to_source_target, int64_t id) { + auto it = id_to_source_target.find(id); + if (it != id_to_source_target.end()) return it->second; + return SourceTargetMapEntry{}; + } + + NcclCollectiveConfig config; + IdToSourceTargetMap id_to_source_target; +}; + +// Extracts source/target pairs for send/recv from frontend attributes. +StatusOr>> GetSourceTargetPairs( + mlir::DictionaryAttr frontend_attributes); + +// Returns the GroupMode for Send and Recv. +template +std::enable_if_t || + std::is_same_v, + CollectiveOpGroupMode> +GetGroupModeForSendRecv(OpT op) { + return GetCollectiveOpGroupMode(op.getChannelHandle().getHandle() > 1, + std::nullopt) + .value(); +} + +// Constructs the NcclP2PConfig for Send and Recv. +template +std::enable_if_t || + std::is_same_v, + NcclP2PConfig> +GetNcclP2PConfigForSendRecv(OpT op, int64_t replica_count, + int64_t partition_count) { + NcclP2PConfig p2p_config; + auto& config = p2p_config.config; + + config.operand_count = 1; + const Shape shape = GetShape(op.getOperand(0)); + config.operand_element_type.push_back(shape.element_type()); + + const int64_t channel_id = op.getChannelHandle().getHandle(); + config.group_mode = GetGroupModeForSendRecv(op); + // Emulate SetCollectiveOpKindAndID. + // Send and Recv ops have a non-optional channel id while collective-permute + // has an optional channel id. We use 0 to encode the send/recv transformed + // from collective-permute without a channel id. + if (channel_id >= 1) { + config.collective_op_kind = RendezvousKey::kCrossModule; + config.op_id = channel_id; + } else { + config.collective_op_kind = RendezvousKey::kCrossReplica; + mlir::ModuleOp parent = op->template getParentOfType(); + mlir::IntegerAttr unique_id = + parent->getAttrOfType("hlo.unique_id"); + config.op_id = static_cast(unique_id.getInt()); + } + + // All execution instances of a send/recv together form a replica group. + const int64_t num_participants = + config.group_mode == CollectiveOpGroupMode::kCrossReplica + ? replica_count + : partition_count; + config.replica_groups.emplace_back(); + ReplicaGroup& replica_group = config.replica_groups.front(); + for (int i = 0; i < num_participants; ++i) { + replica_group.add_replica_ids(i); + } + + auto source_target_pairs = GetSourceTargetPairs(op.getFrontendAttributes()); + TF_CHECK_OK(source_target_pairs.status()); + for (const std::pair& source_target : + *source_target_pairs) { + int64_t source = source_target.first; + int64_t target = source_target.second; + + p2p_config.id_to_source_target.insert({target, {}}).first->second.source = + source; + p2p_config.id_to_source_target.insert({source, {}}).first->second.target = + target; + } + + return p2p_config; +} + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_P2P_THUNK_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_recv_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_recv_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..d8dbc22f9822926a6dd3b34ef9ea83f4e8b08d42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_recv_thunk.h @@ -0,0 +1,66 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_RECV_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_RECV_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/nccl_p2p_thunk_common.h" + +namespace xla { +namespace gpu { + +// Thunk that performs a NCCL-recv. +class NcclRecvThunk : public NcclCollectiveThunk { + public: + static NcclP2PConfig GetNcclP2PConfig(mlir::lmhlo::RecvOp, + int64_t replica_count, + int64_t partition_count); + + static Status CheckImplementable(mlir::lmhlo::RecvOp op, + int64_t replica_count, + int64_t partition_count); + + static CollectiveOpGroupMode GetGroupMode(mlir::lmhlo::RecvOp op); + static const char* GetHloOpName() { return "recv"; } + + NcclRecvThunk(ThunkInfo thunk_info, mlir::lmhlo::RecvOp op, + int64_t replica_count, int64_t partition_count, + const Buffer& buffer); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + AsyncStreamKind GetAsyncStreamKind() const override { + return kAsyncStreamP2P; + } + + private: + const NcclP2PConfig config_; + const Buffer buffer_; +}; + +Status RunRecv(NcclP2PConfig::SourceTargetMapEntry source_target, + DeviceBufferPair& buffer, se::Stream& stream, ncclComm_t comm, + absl::string_view device_string, int64_t current_id); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_RECV_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_send_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_send_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..b57b1ee3279d70ce78b65c26c0a7f71a237c9c85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_send_thunk.h @@ -0,0 +1,65 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_SEND_THUNK_H_ +#define XLA_SERVICE_GPU_NCCL_SEND_THUNK_H_ + +#include + +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/service/gpu/nccl_p2p_thunk_common.h" + +namespace xla { +namespace gpu { + +// Thunk that performs a NCCL-send. +class NcclSendThunk : public NcclCollectiveThunk { + public: + static NcclP2PConfig GetNcclP2PConfig(mlir::lmhlo::SendOp, + int64_t replica_count, + int64_t partition_count); + + static Status CheckImplementable(mlir::lmhlo::SendOp op, + int64_t replica_count, + int64_t partition_count); + static CollectiveOpGroupMode GetGroupMode(mlir::lmhlo::SendOp op); + static const char* GetHloOpName() { return "send"; } + + NcclSendThunk(ThunkInfo thunk_info, mlir::lmhlo::SendOp op, + int64_t replica_count, int64_t partition_count, + const Buffer& buffer); + + protected: + const NcclCollectiveConfig& config() const override { return config_.config; } + Status RunNcclCollective(const ExecuteParams& params, se::Stream& stream, + ncclComm_t comm) override; + AsyncStreamKind GetAsyncStreamKind() const override { + return kAsyncStreamP2P; + } + + private: + const NcclP2PConfig config_; + const Buffer buffer_; +}; + +Status RunSend(NcclP2PConfig::SourceTargetMapEntry source_target, + DeviceBufferPair& buffer, se::Stream& stream, ncclComm_t comm, + absl::string_view device_string, int64_t current_id); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_SEND_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..1d8c9571a81d890a62507aa47d2340293c337e4e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nccl_utils.h @@ -0,0 +1,138 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NCCL_UTILS_H_ +#define XLA_SERVICE_GPU_NCCL_UTILS_H_ + +#if TENSORFLOW_USE_ROCM +#define __HIP_DISABLE_CPP_FUNCTIONS__ +#endif + +#include +#include +#include + +#include "absl/synchronization/mutex.h" +#include "xla/service/collective_ops_utils.h" +#include "xla/service/gpu/gpu_executable_run_options.h" +#include "xla/service/gpu/thunk.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +// Common place for all collective thunks to include nccl/rccl headers. +#if TENSORFLOW_USE_ROCM +#include "rocm/rocm_config.h" +#if (TF_ROCM_VERSION >= 50200) +#include "rocm/include/rccl/rccl.h" +#else +#include "rocm/include/rccl.h" +#endif +#else +#include "third_party/nccl/nccl.h" +#endif + +namespace xla { +namespace gpu { + +ncclRedOp_t ToNcclReduction(ReductionKind kind); +StatusOr> ToNcclDataTypeAndCountMultiplier( + PrimitiveType element_type, Thunk::Kind reduction_op); + +bool IsGlobalNcclConfig(); + +Status ToStatus(ncclResult_t s, const char* file, int64_t line, + const char* expr); + +// Macros to return or warn on CUDA/NCCL errors. (The same macro works for both +// NCCL and CUDA errors.) +// +// It's tempting to say these macros belong in an XLA header somewhere, but in +// practice we don't do much direct-to-CUDA-API stuff outside of this file. +#define XLA_CUDA_STATUS(expr) \ + xla::gpu::ToStatus(expr, __FILE__, __LINE__, #expr) + +#define XLA_CUDA_RETURN_IF_ERROR(expr) \ + do { \ + Status s = XLA_CUDA_STATUS(expr); \ + if (!s.ok()) { \ + return s; \ + } \ + } while (0) + +#define XLA_CUDA_WARN_IF_ERROR(expr) \ + do { \ + Status s = XLA_CUDA_STATUS(expr); \ + if (!s.ok()) { \ + LOG(ERROR) << s.ToString(); \ + } \ + } while (0) + +size_t GetNumLocalParticipants( + const std::vector& participants, + const std::vector* local_devices); // may be null + +StatusOr GetNcclUniqueIdCallback( + const NcclUniqueIdCallback* unique_id_callback, // may be null + bool is_local); + +// Represents a type that requires mutually exclusive access. +template +class Lockable { + public: + // RAII type that will release the exclusive lock when it is destroyed. + using Lock = std::unique_ptr>; + + Lockable() = default; + explicit Lockable(T value) : value_(std::move(value)) {} + Lockable(const Lockable&) = delete; + Lockable(Lockable&&) = delete; + Lockable& operator=(const Lockable&) = delete; + Lockable& operator=(Lockable&&) = delete; + + Lock Acquire() { + absl::MutexLock lock(&mutex_); + mutex_.Await(absl::Condition(&is_unlocked_)); + is_unlocked_ = false; + + return {&value_, [this](T*) { + absl::MutexLock lock(&mutex_); + CHECK(!is_unlocked_); + is_unlocked_ = true; + }}; + } + + private: + T value_; + absl::Mutex mutex_; + bool is_unlocked_ ABSL_GUARDED_BY(mutex_) = true; +}; + +TSL_LIB_GTL_DEFINE_INT_TYPE(OpId, int64_t); + +struct NcclComm : public Lockable { + explicit NcclComm(ncclComm_t comm) : Lockable(comm) {} +}; + +StatusOr AcquireNcclComm( + RunId run_id, OpId op_id, std::vector participants, + size_t num_local_participants, + const NcclUniqueIdCallback& unique_id_callback, int rank, int64_t stream_id, + bool enable_clique_optimization); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NCCL_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/non_atomically_upgradeable_rw_lock.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/non_atomically_upgradeable_rw_lock.h new file mode 100644 index 0000000000000000000000000000000000000000..ea09016bd6f30b7047e0f90198a10a23177e5321 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/non_atomically_upgradeable_rw_lock.h @@ -0,0 +1,95 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NON_ATOMICALLY_UPGRADEABLE_RW_LOCK_H_ +#define XLA_SERVICE_GPU_NON_ATOMICALLY_UPGRADEABLE_RW_LOCK_H_ + +#include +#include + +#include "absl/synchronization/mutex.h" + +namespace xla { +namespace gpu { + +// Augments absl::ReaderMutexLock with a poor man's upgrade/downgrade pair using +// RAII. Instead of a true upgrade (or downgrade), we simply drop the read +// (write) lock and then reacquire it as a write (read) lock. +class ABSL_SCOPED_LOCKABLE NonAtomicallyUpgradeableRWLock { + public: + explicit NonAtomicallyUpgradeableRWLock(absl::Mutex* mu) + ABSL_SHARED_LOCK_FUNCTION(mu) + : mu_(mu), is_reader_(true) { + mu_->ReaderLock(); + } + + NonAtomicallyUpgradeableRWLock(const NonAtomicallyUpgradeableRWLock&) = + delete; + NonAtomicallyUpgradeableRWLock(NonAtomicallyUpgradeableRWLock&&) = delete; + NonAtomicallyUpgradeableRWLock& operator=( + const NonAtomicallyUpgradeableRWLock&) = delete; + NonAtomicallyUpgradeableRWLock& operator=(NonAtomicallyUpgradeableRWLock&&) = + delete; + + ~NonAtomicallyUpgradeableRWLock() ABSL_UNLOCK_FUNCTION() { + if (is_reader_) { + mu_->ReaderUnlock(); + } else { + mu_->WriterUnlock(); + } + } + + // Upgrade and downgrade the reader lock via RAII. + class ABSL_SCOPED_LOCKABLE WriterLock { + public: + explicit WriterLock(NonAtomicallyUpgradeableRWLock* parent) + ABSL_EXCLUSIVE_LOCK_FUNCTION(parent->mu_) + : parent_(parent) { + assert(parent_->is_reader_); + parent_->mu_->ReaderUnlock(); + parent_->mu_->WriterLock(); + parent_->is_reader_ = false; + } + + WriterLock(const WriterLock&) = delete; + WriterLock(WriterLock&&) = delete; + WriterLock& operator=(const WriterLock&) = delete; + WriterLock& operator=(WriterLock&&) = delete; + + ~WriterLock() ABSL_UNLOCK_FUNCTION() { + parent_->mu_->WriterUnlock(); + parent_->mu_->ReaderLock(); + parent_->is_reader_ = true; + } + + private: + NonAtomicallyUpgradeableRWLock* parent_; + }; + + // Update the reader lock to a writer lock. The function is invalid if the + // lock is already upgraded. + WriterLock UpgradeToWriterMutexLock() ABSL_NO_THREAD_SAFETY_ANALYSIS { + return WriterLock(this); + } + + private: + absl::Mutex* const mu_; + bool is_reader_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NON_ATOMICALLY_UPGRADEABLE_RW_LOCK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nvptx_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nvptx_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..ea2162aa95aec5d5f7a2f4872d1e88f96eb4f6a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/nvptx_compiler.h @@ -0,0 +1,156 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_NVPTX_COMPILER_H_ +#define XLA_SERVICE_GPU_NVPTX_COMPILER_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/node_hash_map.h" +#include "xla/autotune_results.pb.h" +#include "xla/service/gpu/gpu_compiler.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" +#include "tsl/platform/threadpool.h" + +namespace xla { +namespace gpu { + +void WarnIfBadDriverJITVersion(); + +// NVPTXCompiler generates efficient GPU executables for NVPTX target. +class NVPTXCompiler : public GpuCompiler { + public: + NVPTXCompiler(); + + Status OptimizeHloConvolutionCanonicalization( + HloModule* hlo_module, se::GpuComputeCapability gpu_version, + se::dnn::VersionInfo dnn_version, + se::DeviceMemoryAllocator* device_allocator) override; + + Status OptimizeHloPostLayoutAssignment( + HloModule* hlo_module, se::StreamExecutor* stream_exec, + const CompileOptions& options, const GpuTargetConfig& gpu_target_config, + const AutotuneResults* autotune_results, + tsl::thread::ThreadPool* thread_pool) override; + + bool RequiresCollectiveScheduleLinearizer( + const HloModule* module, se::StreamExecutor* stream_exec) override; + + Status AddConvAndGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, + tsl::thread::ThreadPool* thread_pool) override; + + Status AddTritonGemmAutotuningPasses( + HloPassPipeline* pipeline, HloModule* hlo_module, + AutotuneConfig& autotune_config, + tsl::thread::ThreadPool* thread_pool) override; + + HloDataflowAnalysis::CanShareBuffer GetCanShareBuffer() const override; + + StatusOr>> CompileTargetBinary( + const HloModuleConfig& module_config, llvm::Module* llvm_module, + se::GpuComputeCapability gpu_version, bool relocatable, + const HloModule* debug_module, const CompileOptions& options) override; + + private: + StatusOr CanUseLinkModules( + const HloModuleConfig& module_config) override; + + StatusOr> LinkModules( + se::StreamExecutor* stream_exec, + std::vector> modules, + const DebugOptions& debug_options) override; + + absl::Mutex mutex_; + + enum class LinkingMethod { + kNone, + kNvLink, + kDriver, + }; + absl::flat_hash_map linking_methods_ + ABSL_GUARDED_BY(mutex_); + + StatusOr ChooseLinkingMethod( + const std::string& preferred_cuda_dir); + + // Tries to compile the given ptx string to cubin. Returns a vector with the + // compiled cubin if compilation succeeded. + StatusOr> CompileGpuAsmOrGetCachedResult( + const std::string& ptx, se::CudaComputeCapability cc, + const HloModuleConfig& hlo_module_config, absl::string_view module_name, + bool relocatable, const CompileOptions& options); + + // The compilation_cache_ map is a cache from {ptx string, cc_major, cc_minor} + // -> cubin so we don't recompile the same ptx twice. This is important for + // some interactive workflows. (We also cache at the HLO level, but sometimes + // we can't realize that two modules are the same until we lower to ptx.) + // + // Compilation of distinct PTX happens in parallel. If more than one thread + // attempts to compile the same PTX, the fist thread to obtain + // cache_value_->mutex_ performs the compilation. The rest wait() on + // cache_value_->compilation_done_cv_ until the compilation is done. + // + // If compiling the ptx fails, we return an empty cubin, cross our fingers, + // and leave compilation up to the driver. + struct CompilationCacheKey { + CompilationCacheKey(std::string ptx, int cc_major, int cc_minor, + bool relocatable) + : ptx(std::move(ptx)), + cc_major(cc_major), + cc_minor(cc_minor), + relocatable(relocatable) {} + template + friend H AbslHashValue(H h, const CompilationCacheKey& key) { + return H::combine(std::move(h), key.ptx, key.cc_major, key.cc_minor, + key.relocatable); + } + friend bool operator==(const CompilationCacheKey& a, + const CompilationCacheKey& b) { + return a.cc_major == b.cc_major && a.cc_minor == b.cc_minor && + a.ptx == b.ptx && a.relocatable == b.relocatable; + } + std::string ptx; + int cc_major; + int cc_minor; + bool relocatable; + }; + struct CompilationCacheValue { + bool compilation_done = false; + std::vector cubin_data; + // mutex and condition variable to serialize compilation completing. + absl::Mutex mutex; + absl::CondVar compilation_done_cv; + }; + + // Don't even think about switching this to flat_hash_map; iterator stability + // is critical here. + absl::node_hash_map + compilation_cache_ ABSL_GUARDED_BY(mutex_); + + NVPTXCompiler(const NVPTXCompiler&) = delete; + NVPTXCompiler& operator=(const NVPTXCompiler&) = delete; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_NVPTX_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..4da268a26b0b996a489e5eb8c9906d96d00fe637 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_manager.h @@ -0,0 +1,74 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_OUTFEED_MANAGER_H_ +#define XLA_SERVICE_GPU_OUTFEED_MANAGER_H_ + +#include +#include + +#include "xla/literal.h" +#include "xla/service/gpu/xfeed_queue.h" +#include "xla/shape_tree.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/notification.h" + +namespace xla { +namespace gpu { + +// TODO(b/30467474) Once GPU outfeed implementation settles, consider +// folding back the cpu and gpu outfeed implementations into a generic +// one if possible. + +// Defines a buffer holding the destination for an outfeed in host memory and a +// notification when that triggers when the transfer is done. +class OutfeedBuffer { + public: + explicit OutfeedBuffer(int64_t length) : length_(length) {} + + // Waits for the device transfer to be finished. + void WaitUntilAvailable() { done_.WaitForNotification(); } + + int64_t length() const { return length_; } + void set_destination(std::unique_ptr destination) { + destination_ = std::move(destination); + } + MutableBorrowingLiteral* destination() { return destination_.get(); } + + // Callback to signal that this buffer is consumed. + void Done() { done_.Notify(); } + + private: + std::unique_ptr destination_; + const int64_t length_; + tsl::Notification done_; +}; + +// Manages a thread-safe queue of buffers. The buffers are supposed to be +// produced by the transfer manager and consumed by the device. +class OutfeedManager + : public XfeedQueue>*> { + public: + Status TransferLiteralFromOutfeed(se::StreamExecutor* executor, + MutableBorrowingLiteral literal); +}; + +// Returns the GPU outfeed manager for the given stream executor. +OutfeedManager* GetOrCreateOutfeedManager(se::StreamExecutor* executor); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_OUTFEED_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..e6abb189a605188c1bf955d9962fa469cd0e5225 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/outfeed_thunk.h @@ -0,0 +1,48 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_OUTFEED_THUNK_H_ +#define XLA_SERVICE_GPU_OUTFEED_THUNK_H_ + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that outfeeds data. Data must be already resident on the host. This +// thunk performs a device to host copy from the buffer allocated for the +// outfeed op to the host location. +class OutfeedThunk : public Thunk { + public: + // Constructs a OutfeedThunk that copies data to the host-side + // outfeed queue from the buffers in the given shape tree. + OutfeedThunk(ThunkInfo thunk_info, std::vector source_slices); + + OutfeedThunk(const OutfeedThunk&) = delete; + OutfeedThunk& operator=(const OutfeedThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + const std::vector source_slices_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_OUTFEED_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/parallel_loop_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/parallel_loop_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..b6ed37ca74220f3ecc502604511f61113a292bde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/parallel_loop_emitter.h @@ -0,0 +1,93 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_PARALLEL_LOOP_EMITTER_H_ +#define XLA_SERVICE_GPU_PARALLEL_LOOP_EMITTER_H_ + +#include "llvm/IR/IRBuilder.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/loop_emitter.h" + +namespace xla { +namespace gpu { + +// Emits a parallel loop for every element in the given array shape. This loop +// emitted will be executed by multiple threads in parallel. Therefore, each +// thread instance of the loop iterates over part of the array, and they +// collectively iterates over the entire array. +class ParallelLoopEmitter { + public: + // `launch_dimensions` specify the number of threads and blocks to + // parallelize the loop on. `launch_config` specify some detail on + // how to parallelize. + ParallelLoopEmitter(llvm_ir::BodyEmitter body_emitter, const Shape& shape, + const LaunchDimensions& launch_dimensions, + llvm::IRBuilder<>* b, + LaunchDimensionsConfig launch_config = {}); + + // Constructs a loop emitter for a loop that generates on element of each of N + // arrays on each iteration. + // + // This is used in multi-output fusion. target_element_generator should + // produce a struct with N elements, one for each of target_arrays. + ParallelLoopEmitter(const llvm_ir::ElementGenerator& target_element_generator, + absl::Span target_arrays, + const LaunchDimensions& launch_dimensions, + llvm::IRBuilder<>* b, + LaunchDimensionsConfig launch_config = {}); + + ParallelLoopEmitter(const ParallelLoopEmitter&) = delete; + ParallelLoopEmitter& operator=(const ParallelLoopEmitter&) = delete; + + std::vector EmitIndexAndSetExitBasicBlock( + absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_index); + + Status EmitLoop(absl::string_view loop_name = "", + llvm::Type* index_type = nullptr); + + private: + struct LinearBaseAndThreadIdx { + llvm::Value* linear_base; + llvm::Value* thread_idx; + }; + + LinearBaseAndThreadIdx EmitLinearBaseAndThreadIdx(llvm::Type* index_type, + llvm::Value* base_index); + Status EmitSerialLoop(absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_indvar = nullptr); + + // The thread and block dimension to parallelize the loop on. + const LaunchDimensions launch_dimensions_; + const LaunchDimensionsConfig launch_config_; + + // An IR emitter that generates the loop body. + llvm_ir::BodyEmitter body_emitter_; + + // The shape that the emitted loop iterates through. + Shape shape_; + + // Points to the exit block of the emitted loop. If the given shape is + // scalar, no loops are emitted and exit_bb_ is nullptr in that case. + llvm::BasicBlock* exit_bb_; + + llvm::IRBuilder<>* b_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_PARALLEL_LOOP_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/precompiled_kernels.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/precompiled_kernels.h new file mode 100644 index 0000000000000000000000000000000000000000..3d1e96afafbeb269bc4f3bcbeb3dfa8df6e807d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/precompiled_kernels.h @@ -0,0 +1,60 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_PRECOMPILED_KERNELS_H_ +#define XLA_SERVICE_GPU_PRECOMPILED_KERNELS_H_ + +#include "xla/status.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/stream.h" +#include "xla/types.h" + +// Hardcoded GPU kernels for various simple tasks. + +namespace xla { +namespace gpu { + +// In GPU memory, does +// +// char* base_ptr = ...; +// void* ptrs_out = ...; +// for (i = 0; i < n; i++) { +// ptrs_out[i] = base_ptr + i * stride; +// } +// +// This is useful for functions like cublasTrsmBatched that operate on an array +// of pointers in GPU memory. In XLA these aren't usually arbitrary pointers +// but rather are all contiguous values. +// +// Instead of using a kernel, a simpler way of doing this would be to create +// this buffer on the host and then copy it to device. But using a kernel +// instead of an H2D copy avoids a few performance pitfalls. +// +// - Only one H2D copy can run on a given GPU at a time. If there's already +// a copy ongoing as part of other work on the GPU, our copy here will +// block. In contrast, multiple kernels can run simultaneously. +// +// - H2D copies from CUDA unpinned memory can acquire a global lock in the +// driver and slow down *all* work on the GPU. So to do this right, we'd +// need to allocate the host memory as pinned, one alloc per stream. Then +// we'd need to manage this memory without leaks. This becomes complex! +Status MakeBatchPointers(se::Stream* stream, const se::GpuAsmOpts& asm_opts, + se::DeviceMemoryBase base_ptr, int stride_bytes, int n, + se::DeviceMemoryBase ptrs_out); + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_PRECOMPILED_KERNELS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..73881e82614eab3b57372dfd2b8547ba3556c2cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/prepare_hlo_for_ir_emitting_pipeline.h @@ -0,0 +1,36 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_PREPARE_HLO_FOR_IR_EMITTING_PIPELINE_H_ +#define XLA_SERVICE_GPU_PREPARE_HLO_FOR_IR_EMITTING_PIPELINE_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_dataflow_analysis.h" +#include "xla/service/hlo_pass_pipeline.h" + +namespace xla { +namespace gpu { + +// Function wrapper around the XLA GPU base pre-IR emission module preparation +// pipeline. This pipeline must be run right before IR emission to ensure +// correctness of the input module. +HloPassPipeline PrepareHloModuleForIrEmittingPipeline( + HloModule& hlo_module, + HloDataflowAnalysis::CanShareBuffer can_share_buffer); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_PREPARE_HLO_FOR_IR_EMITTING_PIPELINE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/priority_fusion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/priority_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..b43a7954a5e58e02a3bd5c402b8ae6fd8444c97e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/priority_fusion.h @@ -0,0 +1,79 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_PRIORITY_FUSION_H_ +#define XLA_SERVICE_GPU_PRIORITY_FUSION_H_ + +#include + +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/fusion_queue.h" +#include "xla/service/gpu/gpu_hlo_cost_analysis.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/instruction_fusion.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +class GpuPriorityFusion : public InstructionFusion { + public: + explicit GpuPriorityFusion( + const se::DeviceDescription& d, + const GpuHloCostAnalysis::Options& cost_analysis_options) + : InstructionFusion(GpuPriorityFusion::IsExpensive), + device_info_(d), + cost_analysis_options_(cost_analysis_options) {} + + absl::string_view name() const override { return "priority-fusion"; } + + static bool IsExpensive(const HloInstruction& instruction); + + protected: + std::unique_ptr GetFusionQueue( + HloComputation* computation) override; + FusionDecision ShouldFuse(HloInstruction* consumer, + int64_t operand_index) override; + + HloInstruction::FusionKind ChooseKind( + const HloInstruction* producer, const HloInstruction* consumer) override; + + private: + // This method is called by ShouldFuse() to do all the computationally + // inexpensive checks whether we should fuse the operand into 'consumer'. + FusionDecision ShouldFuseInexpensiveChecks(HloInstruction* consumer, + int64_t operand_index); + + HloInstruction* FuseInstruction(HloInstruction* fusion_instruction, + HloInstruction* producer) override; + + se::DeviceDescription device_info_; + + // Cost model options that defines priorities in the queue. + GpuHloCostAnalysis::Options cost_analysis_options_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_PRIORITY_FUSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_degenerate_dim_remover.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_degenerate_dim_remover.h new file mode 100644 index 0000000000000000000000000000000000000000..e146a3a01cbd016e98adec16abe25c789fcd9ec6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_degenerate_dim_remover.h @@ -0,0 +1,56 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_REDUCTION_DEGENERATE_DIM_REMOVER_H_ +#define XLA_SERVICE_GPU_REDUCTION_DEGENERATE_DIM_REMOVER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Enforces the invariant that reduction input and output have no degenerate +// (size 1) dimension. Since these dimensions are physically meaningless, they +// are removed using bitcasts. +// +// For example, +// +// f[1] out = reduce(f[100, 1, 1] input, dimensions={0, 1}) +// +// becomes: +// +// +// f[100] tmp1 = f[100] bitcast(f[100, 1, 1], input) +// f[] tmp2 = reduce(f[100] tmp1, dimensions={0}) +// f[1] out = f[] bitcast(tmp2) +// +class ReductionDegenerateDimRemover : public HloModulePass { + public: + absl::string_view name() const override { + return "reduction-degenerate-dim-remover"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_DEGENERATE_DIM_REMOVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_dimension_grouper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_dimension_grouper.h new file mode 100644 index 0000000000000000000000000000000000000000..b0d02bde2253e75efd5e6a39b699efabf87c0c7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_dimension_grouper.h @@ -0,0 +1,56 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_REDUCTION_DIMENSION_GROUPER_H_ +#define XLA_SERVICE_GPU_REDUCTION_DIMENSION_GROUPER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Groups adjacent (logically and physically) reduced dimensions in reduction +// input. +// +// Precondition: ReductionLayoutNormalizer has been run (physical proximity and +// logical proximity become the same). +// +// For example, +// +// f[] out = reduce(f[10,20,30] input, dimensions={0,1,2}) +// +// becomes: +// +// f[600] tmp = f[600] bitcast(f[10,20,30] input) +// f[] out = reduce(f[600] tmp, dimensions={0}) +// +class ReductionDimensionGrouper : public HloModulePass { + public: + absl::string_view name() const override { + return "reduction-dimension-grouper"; + } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_DIMENSION_GROUPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_layout_normalizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_layout_normalizer.h new file mode 100644 index 0000000000000000000000000000000000000000..b7f0defd619f25d1271b8d808d6317d280c264cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_layout_normalizer.h @@ -0,0 +1,54 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_REDUCTION_LAYOUT_NORMALIZER_H_ +#define XLA_SERVICE_GPU_REDUCTION_LAYOUT_NORMALIZER_H_ + +#include + +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Enforces default (minor-to-major) layout on all reduction inputs. +// Note that since reduction output can request a custom layout, +// this pass only guarantees standard layout for the input. +// +// For example, +// +// f[20,30]{0,1} out = reduce(f[10,20,30]{2,0,1} input, dimensions={0}) +// +// becomes: +// +// f[20,10,30] tmp = f[20,10,30] bitcast(f[10,20,30]{2,0,1} input) +// f[20,30]{0,1} out = reduce(f[20,10,30]{2,1,0} tmp, dimensions={1}) +class ReductionLayoutNormalizer : public HloModulePass { + public: + absl::string_view name() const override { + return "reduction-layout-normalizer"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_LAYOUT_NORMALIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..776055acd4bacd74e56bb4346db682f5c9135bc8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_splitter.h @@ -0,0 +1,52 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_REDUCTION_SPLITTER_H_ +#define XLA_SERVICE_GPU_REDUCTION_SPLITTER_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { +namespace gpu { + +// Splits a reduce op into two consecutive reduce ops if +// * the reduce dimensions are not contiguous and +// * at least one reduce dimension is large (i.e. corresponds to a large input +// shape dimension). +// +// Reductions with non-contiguous dimensions are emitted as simple element-wise +// loops. This is inefficient when reducing large input shape dimensions. +// Splitting such reductions allows using more efficient reduction emitters. +// +// This pass splits reduce ops into two consecutive reduce ops. Run it to a +// fixpoint to split reduce ops along multiple large dimensions. +// +// Precondition: ReductionDimensionGrouper has been run and adjacent reduce +// dimentsions have been grouped. Reduction layouts have been normalized. + +class ReductionSplitter : public HloModulePass { + public: + absl::string_view name() const override { return "reduction-splitter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REDUCTION_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..610200c888464249d46f640b077cfa290f502e68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/reduction_utils.h @@ -0,0 +1,69 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_REDUCTION_UTILS_H_ +#define XLA_SERVICE_GPU_REDUCTION_UTILS_H_ + +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/hlo_module_config.h" +#include "xla/util.h" + +namespace xla { +namespace gpu { + +// Need at least 1024 threads/block for reasonable tree reduction +// performance (assuming all data fits). +int64_t MinThreadsXRowReduction(const HloModuleConfig& hlo_module_config); + +// When doing batched row reduction, how big the batch dimension could be. +inline constexpr int64_t BatchedReductionRaceFreeBound() { return 8; } + +// Returns true if either the dimensions being reduced or the dimensions being +// kept are contiguous in the input of the reduce instruction. +bool IsReductionFromOrToContiguousDimensions(const HloInstruction& reduce); + +struct ReductionDimensions { + // Indicates whether the reduction is a row reduction or a column reduction. + bool is_row_reduction; + + // Contains the size of the three contiguous components for + // the reduction [depth, height, width] (major-to-minor ordering). + // + // For row reduction, we do: [D, H, W] -> [D, H]. + // For column reduction, we do: [D, H, W] -> [D, W]. + Vector3 dimensions; +}; + +// Given the input shape and dimensions to reduce for a reduction, returns +// ReductionDimensions. +// +// Prerequisite: the reduction instruction passes the check +// IsReductionFromOrToContiguousDimensions, which guarantees either the +// dimensions to reduce or the dimensions to keep are consecutive. +ReductionDimensions GetReductionKindAndContiguousComponents( + const HloInstruction& reduce); + +// Get tiling per thread for the given reduction in dimensions [D, H, W]. +Vector3 GetReductionTiling(const ReductionDimensions& reduction_dimensions); + +// Returns whether the given reduction can be safely generated without atomics : +// that is, at most one block will write to every output element. +bool ReductionIsRaceFree(const HloModuleConfig& hlo_module_config, + const ReductionDimensions& reduction_dimensions); + +} // namespace gpu +} // namespace xla +#endif // XLA_SERVICE_GPU_REDUCTION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/replica_id_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/replica_id_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..23f694a0654a8cfd7e0e64961519274a022c7a1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/replica_id_thunk.h @@ -0,0 +1,53 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_REPLICA_ID_THUNK_H_ +#define XLA_SERVICE_GPU_REPLICA_ID_THUNK_H_ + +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/thunk.h" + +namespace xla { +namespace gpu { + +// Thunk that implements the ReplicaId(Idx == 0) or PartitionId(Idx == 1). +class ReplicaOrPartitionIdThunk : public Thunk { + Status ExecuteOnStream(const ExecuteParams& params) override; + + protected: + ReplicaOrPartitionIdThunk(Kind kind, ThunkInfo thunk_info, + const BufferAllocation::Slice& dest) + : Thunk(kind, thunk_info), dest_(dest) {} + + private: + const BufferAllocation::Slice dest_; +}; + +class ReplicaIdThunk : public ReplicaOrPartitionIdThunk { + public: + ReplicaIdThunk(ThunkInfo thunk_info, const BufferAllocation::Slice& dest) + : ReplicaOrPartitionIdThunk(Kind::kReplicaId, thunk_info, dest) {} +}; + +class PartitionIdThunk : public ReplicaOrPartitionIdThunk { + public: + PartitionIdThunk(ThunkInfo thunk_info, const BufferAllocation::Slice& dest) + : ReplicaOrPartitionIdThunk(Kind::kPartitionId, thunk_info, dest) {} +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_REPLICA_ID_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cholesky.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cholesky.h new file mode 100644 index 0000000000000000000000000000000000000000..23e8da20198921873c241ff23e64eb79b451ae80 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cholesky.h @@ -0,0 +1,30 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_CHOLESKY_H_ +#define XLA_SERVICE_GPU_RUNTIME_CHOLESKY_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime cholesky custom calls. +void RegisterCholeskyCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CHOLESKY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/collectives.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/collectives.h new file mode 100644 index 0000000000000000000000000000000000000000..23bd700cc151fc07220ef2c6d698cfff1d400e62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/collectives.h @@ -0,0 +1,79 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_COLLECTIVES_H_ +#define XLA_SERVICE_GPU_RUNTIME_COLLECTIVES_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/nccl_collective_thunk.h" +#include "xla/stream_executor/event.h" + +namespace xla { +namespace gpu { + +// Support for running async collective operations communicating via events. +// Registers XLA Gpu runtime collective custom calls. +void RegisterCollectiveCustomCalls(runtime::DirectCustomCallRegistry& registry); + +class CollectivesSupport { + public: + // Maybe block host after the first call to the collective operation with the + // given uid, to ensure that all devices have allocated the required buffers + // for their communicators before allowing any device to continue enqueuing + // operations. Otherwise, the allocations can cause deadlock in the CUDA + // driver. + // + // This basically ports workaround from cr/435058849 to Xla runtime (see + // details in the b/215649390). + absl::Status MaybeBlockAfterFirstRun(int32_t uid, int32_t device_ordinal, + se::Stream* stream); + + private: + absl::Mutex mutex_; + + // Store if a particular collective operation was executed at least once. We + // rely on unique `uid` assigned to each collective operation by the lowering + // pass. + absl::flat_hash_set executed_ ABSL_GUARDED_BY(mutex_); +}; + +// Support for running async collective operations communicating via events. +class AsyncCollectivesSupport { + public: + explicit AsyncCollectivesSupport(absl::Span async_streams); + + absl::Status RecordEvent(int32_t uid, AsyncStreamKind async_stream_kind); + absl::StatusOr PopEvent(int32_t uid); + + se::Stream* async_comm_stream(AsyncStreamKind async_stream_kind) const { + return async_comm_streams_[async_stream_kind]; + } + + private: + absl::Mutex mutex_; + absl::InlinedVector async_comm_streams_; + + // Store done events for the Done ops to wait upon. + absl::flat_hash_map done_events_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_COLLECTIVES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/concurrent_region.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/concurrent_region.h new file mode 100644 index 0000000000000000000000000000000000000000..c662282ef6efa279c9812429b62b3280b465c63c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/concurrent_region.h @@ -0,0 +1,75 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_CONCURRENT_REGION_H_ +#define XLA_SERVICE_GPU_RUNTIME_CONCURRENT_REGION_H_ + +#include + +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/service_executable_run_options.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime kernel launch custom calls. +void RegisterConcurrentRegionCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// The state to keep track of the information regarding concurrent regions +// between custom calls. +class ConcurrentRegionStatus { + public: + explicit ConcurrentRegionStatus( + const ServiceExecutableRunOptions* run_options, + int num_borrowed_streams = 10); + + ~ConcurrentRegionStatus(); + + absl::Status StartConcurrentRegion(se::Stream* capture_stream, int64_t size); + void EndConcurrentRegion(); + + // Temporarily disable concurrent execution when we run GPU graphs op-by-op. + // If disabled_ is set to true, StartConcurrentRegion will become an no-op and + // IsInConcurrentRegion always returns false. + void DisableConcurrentRegion() { disabled_ = true; } + void EnableConcurrentRegion() { disabled_ = false; } + + // Get a stream on which the concurrent-executable kernel runs. It returns a + // different stream each time to avoid building dependencies in the CUDA + // graph. + se::Stream* GetNextStream(); + + absl::StatusOr GetStream(int index); + + bool IsInConcurrentRegion(); + + private: + const int num_borrowed_streams_; + std::vector borrowed_streams_; + const ServiceExecutableRunOptions* run_options_; + + bool disabled_ = false; + int32_t stream_index_; + + // It is set to nullptr if not in a concurrent region. + se::Stream* capture_stream_; + int region_size_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CONCURRENT_REGION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv.h new file mode 100644 index 0000000000000000000000000000000000000000..d8622c16136b41572df650bb23f7e175450de79a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv.h @@ -0,0 +1,67 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_CONV_H_ +#define XLA_SERVICE_GPU_RUNTIME_CONV_H_ + +#include +#include + +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/gpu_conv_runner.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime Conv custom calls. +void RegisterConvCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Register type names for convoluttion attributes defined by MHLO dialect. +void RegisterConvTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Add attributes encoding for convoluttion attributes defined by MHLO dialect. +void PopulateConvAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +//===----------------------------------------------------------------------===// +// Cache conv runners between invocations of convolution custom calls. +//===----------------------------------------------------------------------===// + +struct ConvRunner { + explicit ConvRunner(GpuConvConfig config) + : config(std::move(config)), runner(this->config) {} + GpuConvConfig config; + GenericConvRunner runner; +}; + +class StreamExecutorConvRunners : public runtime::StateVector {}; + +// Xla executable keeps a mapping from stream executors to convolution runners. +class ConvRunners { + public: + StreamExecutorConvRunners* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map runners_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CONV_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv_reorder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv_reorder.h new file mode 100644 index 0000000000000000000000000000000000000000..654e9dd56bcb5bdad0ab4ede49c1dfc7bd909219 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/conv_reorder.h @@ -0,0 +1,31 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_CONV_REORDER_H_ +#define XLA_SERVICE_GPU_RUNTIME_CONV_REORDER_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime convolution reorder custom calls. +void RegisterConvReorderCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CONV_REORDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cublas_lt_matmul.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cublas_lt_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..ee7f501caf12c3db7d9344bb720c1b46a9e34073 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/cublas_lt_matmul.h @@ -0,0 +1,50 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_CUBLAS_LT_MATMUL_H_ +#define XLA_SERVICE_GPU_RUNTIME_CUBLAS_LT_MATMUL_H_ + +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "xla/service/gpu/matmul_utils.h" +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#else +#include "rocm/rocm_config.h" +#include "xla/stream_executor/rocm/hip_blas_lt.h" +#endif +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime cuBLASLt custom calls. +void RegisterMatmulCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Add cuBLASLt attributes encoding +void PopulateCublasLtMatmulAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +#if GOOGLE_CUDA || TF_HIPBLASLT +// Keep cublas_lt::MatmulPlan's for all matmul instances in the executable. +class MatmulPlans : public runtime::StateVector {}; +#endif // GOOGLE_CUDA || TF_HIPBLASLT + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CUBLAS_LT_MATMUL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/custom_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/custom_call.h new file mode 100644 index 0000000000000000000000000000000000000000..df1c9f9fca3ef5e6a68c868cb665a8d05059c8df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/custom_call.h @@ -0,0 +1,29 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_CUSTOM_CALL_H_ +#define XLA_SERVICE_GPU_RUNTIME_CUSTOM_CALL_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +void RegisterXlaClassicCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_CUSTOM_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/executable.h new file mode 100644 index 0000000000000000000000000000000000000000..05967e17afa3c6f87547562ad4ceb1ed6836539e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/executable.h @@ -0,0 +1,196 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_EXECUTABLE_H_ +#define XLA_SERVICE_GPU_RUNTIME_EXECUTABLE_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/runtime/executable.h" +#include "xla/runtime/ffi.h" +#include "xla/runtime/jit_executable.h" +#include "xla/runtime/module_registry.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/non_atomically_upgradeable_rw_lock.h" +#include "xla/service/gpu/runtime/collectives.h" +#include "xla/service/gpu/runtime/conv.h" +#include "xla/service/gpu/runtime/cublas_lt_matmul.h" +#include "xla/service/gpu/runtime/fft.h" +#include "xla/service/gpu/runtime/fused_attention.h" +#include "xla/service/gpu/runtime/gemm.h" +#include "xla/service/gpu/runtime/graph_launch.h" +#include "xla/service/gpu/runtime/kernel_launch.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Register custom calls implementing Xla Gpu runtime. +void RegisterXlaGpuRuntimeCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Register mapping from XLA (SE) enums/structs type ids to symbol names. +void RegisterXlaGpuTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Register encoding for (L)MHLO attributes required by the runtime functions. +void RegisterXlaGpuAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +// Xla Gpu program lowered to the Xla runtime dialects. Gpu runtime executable +// jit-compiles this program to an executable artifact (via lowering to LLVM). +// +// We have this program as an intermediate step between lowering from HLO to +// runtime executable to be able to introspect the compilation process. Once we +// have this program, the Xla gpu compiler job is done, and lowering to LLVM is +// the responsibility of backend-agnostic Xla runtime passes. This is the last +// stage when IR is still at a fairly high level of abstraction and has a lot of +// Gpu specific details in it. +struct GpuRuntimeProgram { + GpuRuntimeProgram(std::string entry_point, std::string module, + std::vector buffer_sizes, + DebugOptions debug_options) + : entry_point(std::move(entry_point)), + module(std::move(module)), + buffer_sizes(std::move(buffer_sizes)), + debug_options(std::move(debug_options)) {} + + std::string entry_point; + std::string module; + std::vector buffer_sizes; + DebugOptions debug_options; +}; + +// Gpu runtime executable encapsulates the Xla runtime executable compiled from +// an Xla program and owns all the state required for running it (e.g. it owns +// various caches required for performance). +// +// TODO(ezhulenev): Once thunks are removed from Xla, it might make sense to +// merge this executable into GpuExecutable. Today we keep it separate to manage +// the complexity of mixing two execution modes in the same file. GpuExecutable +// provides an API at XLA level of abstraction (streams and buffers), and this +// executable provides a lower level API exposing some of the implementation +// details. +class GpuRuntimeExecutable { + using ModulesState = ::xla::runtime::ModulesState; + using FfiModulesState = ::xla::runtime::ffi::FfiModulesState; + + public: + // Creates GpuRuntimeExecutable from the Xla Gpu Program. + static StatusOr> Create( + std::string module_name, std::unique_ptr program); + + // Creates GpuRuntimeExecutable from the AOT compiled binary. + static StatusOr> Create( + std::string module_name, absl::Span buffer_sizes, + runtime::Executable executable, DebugOptions debug_options); + + // Executes entry function with the given buffer arguments. + Status Execute(const ServiceExecutableRunOptions* run_options, + const std::string& asm_text, + const std::vector& binary, + const BufferAllocations& buffer_allocations, + NonAtomicallyUpgradeableRWLock& gpu_lock, + const BufferAllocation* temp_alloc = nullptr); + + // Returns object file behind the runtime executable. This object file can + // be exported and loaded later to instantiate another executable. + StatusOr GetObjFile() const; + + // Returns MLIR module behind this executable if it is available. + StatusOr GetMlirModule() const; + + std::string_view module_name() const { return module_name_; } + + private: + GpuRuntimeExecutable(std::string module_name, + std::vector buffer_sizes, + std::unique_ptr jit_executable, + DebugOptions debug_options, ModulesState modules_state, + FfiModulesState ffi_modules_state); + + GpuRuntimeExecutable(std::string module_name, + std::vector buffer_sizes, + std::unique_ptr aot_executable, + DebugOptions debug_options, ModulesState modules_state, + FfiModulesState ffi_modules_state); + + std::string module_name_; + + // Depending on the state of `executable_` returns a reference to active + // Xla runtime executable. + runtime::Executable& executable(); + + std::vector buffer_sizes_; + + // In JIT compilation mode `JitExecutable` is used. In AOT compilation mode + // `Executable` is used. + std::variant, + std::unique_ptr> + executable_; + + const DebugOptions debug_options_; + + // Keep gpu kernels loaded by this executable. + GpuExecutableKernels gpu_kernels_; + + // Keep gemm configs for all gemm operation in the program. + GemmConfigs gemm_configs_; + + // Keep a cache for conv configs for all conv operations in the program. + ConvRunners conv_runners_; + + // Keep a cache for fused_dot_attention configs for all fused_dot_attention + // operations in the program. + FusedAttentionRunners fused_attention_runners_; + + // Keep a cache for fused_dot_attention configs for all fused_dot_attention + // backward + // operations in the program. + FusedAttentionBackwardRunners fused_attention_backward_runners_; + + // Support for running collective operations. + CollectivesSupport collectives_; + + // Keep a cache of fft plans for all FFT operations in the program. + FftPlans fft_plans_; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + // Keep matmul execution plans (only if cuBLASLt is available). + MatmulPlans cublas_lt_matmul_plans_; + // Keep captured and instantiated GPU graphs instances. + GraphInstances graph_instances_; + CapturedFunctionExecutionCounts captured_function_counts_; + OrdinalToFallback ordinal_to_fallback_; +#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM + + // Keep an executable state for all registered runtime modules. + ModulesState modules_state_; + + // Keeps an executable state for all registered FFI modules. + FfiModulesState ffi_modules_state_; + + // Dynamic custom calls exported from XLA runtime modules (and FFI modules). + runtime::DynamicCustomCallRegistry dynamic_custom_calls_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fft.h new file mode 100644 index 0000000000000000000000000000000000000000..bc45e310272dc75857bcbdcc534ada5e952f4f46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fft.h @@ -0,0 +1,40 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_FFT_H_ +#define XLA_SERVICE_GPU_RUNTIME_FFT_H_ + +#include + +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/fft_thunk.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime fft custom calls. +void RegisterFftCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Adds attributes encoding set for fft custom calls +void PopulateFftAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +// Keep FftPlanCache for all FFT instances in the executable. +class FftPlans : public runtime::StateVector> {}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fused_attention.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fused_attention.h new file mode 100644 index 0000000000000000000000000000000000000000..d6458f31c4a27bf4407ee19a699ee9ac520786cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/fused_attention.h @@ -0,0 +1,108 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_FUSED_ATTENTION_H_ +#define XLA_SERVICE_GPU_RUNTIME_FUSED_ATTENTION_H_ + +#include +#include + +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/service/gpu/gpu_fused_mha_runner.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime fused attention custom calls. +void RegisterFusedAttentionCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Register type names for fused attention attributes defined by MHLO dialect. +void RegisterFusedAttentionTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Add attributes encoding for fused attention attributes defined by LMHLO +// dialect. +void PopulateFusedAttentionForwardDAGSignatureAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +// Registers XLA Gpu runtime fused attention backward custom calls. +void RegisterFusedAttentionBackwardCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Add attributes encoding for fused attention backward attributes defined by +// LMHLO dialect. +void PopulateFusedAttentionBackwardDAGSignatureAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +void PopulateFusedAttentionAlgorithmConfigAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding); + +//===----------------------------------------------------------------------===// +// Cache fused dot attention runners between invocations of fused dot attention +// custom calls. +//===----------------------------------------------------------------------===// +struct FusedAttentionRunner { + explicit FusedAttentionRunner(GpufMHAConfig config) + : config(std::move(config)), runner(this->config) {} + GpufMHAConfig config; + FusedMultiHeadedAttentionRunner runner; +}; + +struct FusedAttentionBackwardRunner { + explicit FusedAttentionBackwardRunner(GpufMHABackwardConfig config) + : config(std::move(config)), runner(this->config) {} + GpufMHABackwardConfig config; + FusedMultiHeadedAttentionBackwardRunner runner; +}; + +class StreamExecutorFusedAttentionRunners + : public runtime::StateVector {}; + +class StreamExecutorFusedAttentionBackwardRunners + : public runtime::StateVector {}; + +// Xla executable keeps a mapping from stream executors to fused attention +// runners. +class FusedAttentionRunners { + public: + StreamExecutorFusedAttentionRunners* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map + runners_ ABSL_GUARDED_BY(mutex_); +}; + +// Xla executable keeps a mapping from stream executors to fused attention +// backward runners. +class FusedAttentionBackwardRunners { + public: + StreamExecutorFusedAttentionBackwardRunners* operator()( + se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map + runners_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_FUSED_ATTENTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/gemm.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/gemm.h new file mode 100644 index 0000000000000000000000000000000000000000..828c8a10602f0571c75c0ef1efe1a8737955600a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/gemm.h @@ -0,0 +1,36 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_GEMM_H_ +#define XLA_SERVICE_GPU_RUNTIME_GEMM_H_ + +#include "absl/container/node_hash_map.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/state.h" +#include "xla/service/gpu/matmul_utils.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime Gemm# custom calls. +void RegisterGemmCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Keep GemmConfigs for all gemm/matmul instances in the executable. +class GemmConfigs : public runtime::StateVector {}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_GEMM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/graph_launch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/graph_launch.h new file mode 100644 index 0000000000000000000000000000000000000000..e4841541bc781e685a23fa2a1cb617454719b8db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/graph_launch.h @@ -0,0 +1,139 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_GRAPH_LAUNCH_H_ +#define XLA_SERVICE_GPU_RUNTIME_GRAPH_LAUNCH_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/node_hash_map.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/executable.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/stream_executor/stream_executor.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "xla/stream_executor/gpu/gpu_graph.h" +#endif // #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime graph launch custom calls. +void RegisterGraphLaunchCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +struct GraphInstance; // Forward declare +class StreamExecutorGraphInstances; // Forward declare + +// A state vector that keeps track of the number of times a capture function +// gets executed. Graph capture function ordinal is the key in this container. +class CapturedFunctionExecutionCount + : public runtime::StateVector>> {}; + +// Create the i-th value if the capture function with ordinal i causes graph +// update failure. +class OrdinalToFallback : public runtime::StateVector {}; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +// A state vector that owns all instantiated GPU graphs. Graph capture function +// ordinal is the key in this container. +class StreamExecutorGraphInstances + : public runtime::StateVector {}; + +// Instantiated GPU graph instance guarded with a mutex for exclusive access. +struct GraphInstance { + GraphInstance(size_t ptr_hash, se::gpu::OwnedGpuGraphExec exec) + : ptr_hash(ptr_hash), exec(std::move(exec)), mutex(new absl::Mutex) {} + + // Graph instance is fully identified by the hash of its pointer arguments + // because currently it's guaranteed that all shapes and launch dimensions + // will be constant from run to run. + size_t ptr_hash ABSL_GUARDED_BY(*mutex); + se::gpu::OwnedGpuGraphExec exec ABSL_GUARDED_BY(*mutex); + + // Access to a graph instance must be synchronized, because we potentially can + // run concurrent graph instance updates. + std::unique_ptr mutex; +}; + +#else // #if !GOOGLE_CUDA && !TENSORFLOW_USE_ROCM + +// Define empty struct and empty state when GPU is not enabled. +struct GraphInstance {}; +class StreamExecutorGraphInstances + : public runtime::StateVector {}; + +#endif // #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + +// Xla executable keeps a mapping from stream executors to graph instances. +// +// Graph instances allocate on-device memory, so we periodically destroy +// them to free up some space on device. JAX for example keeps all XLA +// executables alive, and destroys them when the process shuts down, so we can +// end up with thousands of unused (or rarely used) graphs in device memory. +class GraphInstances { + public: + struct Impl; + + GraphInstances(std::string module_name, int64_t num_graphs); + ~GraphInstances(); + + std::shared_ptr operator()( + se::StreamExecutor* executor); + + // Instantiates all Gpu graphs defined by the given executable using user + // provided run options. This guarantees that once we start execution, all Gpu + // graphs are ready, and will only require cheap update operation and will not + // require allocating new resources (we avoid non deterministic OOM errors). + // + // If timeout is not nullopt it will evict all previously instantiated graphs + // that were used more than `eviction_timeout_seconds` seconds ago. + Status InstantiateAllGraphs( + const ServiceExecutableRunOptions* run_options, + const runtime::Executable& executable, + const runtime::CustomCall::UserData& user_data, void* ptr, + OrdinalToFallback::Snapshot* ordinal_to_fallback, + std::optional eviction_timeout_seconds = std::nullopt); + + // Returns true if all Gpu graphs were already instantiated. + bool InstantiatedAllGraphs(const ServiceExecutableRunOptions* run_options, + const runtime::Executable& executable); + + private: + std::shared_ptr impl_; +}; + +// Xla executable keeps a mapping from stream executors to execution counts. +class CapturedFunctionExecutionCounts { + public: + CapturedFunctionExecutionCount* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map + counts_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_GRAPH_LAUNCH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/io_feed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/io_feed.h new file mode 100644 index 0000000000000000000000000000000000000000..ef4e42d770e49a9cdb875145136849037df9ec63 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/io_feed.h @@ -0,0 +1,30 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_IO_FEED_H_ +#define XLA_SERVICE_GPU_RUNTIME_IO_FEED_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime infeed and outfeed custom calls. +void RegisterIoFeedCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_IO_FEED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/kernel_launch.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/kernel_launch.h new file mode 100644 index 0000000000000000000000000000000000000000..80040b0f55f411fd898c32848cd9914bf5123592 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/kernel_launch.h @@ -0,0 +1,56 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_KERNEL_LAUNCH_H_ +#define XLA_SERVICE_GPU_RUNTIME_KERNEL_LAUNCH_H_ + +#include +#include +#include + +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/state.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime kernel launch custom calls. +void RegisterKernelLaunchCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +// Kernels loaded by Gpu executable for a single stream executor. +class StreamExecutorKernels + : public runtime::StateVector> {}; + +// Xla runtime Gpu executable owns the pre-compiled device module (PTX and +// Cubin for Nvidia Gpus) for all device kernels, and the cache keeps a mapping +// from stream executor to pre-loaded kernels +class GpuExecutableKernels { + public: + StreamExecutorKernels* operator()(se::StreamExecutor* executor); + + private: + mutable absl::Mutex mutex_; + absl::node_hash_map kernels_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_KERNEL_LAUNCH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memcpy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memcpy.h new file mode 100644 index 0000000000000000000000000000000000000000..cd4ecb4d5020a8e8fa5cbd5a2f12cb81bc485ffb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memcpy.h @@ -0,0 +1,30 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_MEMCPY_H_ +#define XLA_SERVICE_GPU_RUNTIME_MEMCPY_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime memcpy custom calls. +void RegisterMemcpyCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_MEMCPY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memset.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memset.h new file mode 100644 index 0000000000000000000000000000000000000000..e6d717941865ff366b15c4f5a92ad1e95c43532e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/memset.h @@ -0,0 +1,30 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_MEMSET_H_ +#define XLA_SERVICE_GPU_RUNTIME_MEMSET_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime memset custom calls. +void RegisterMemsetCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_MEMSET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/send_recv.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/send_recv.h new file mode 100644 index 0000000000000000000000000000000000000000..fcbe1ddcc9f9c0398a0d831f0701fdb9a065332b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/send_recv.h @@ -0,0 +1,56 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_SEND_RECV_H_ +#define XLA_SERVICE_GPU_RUNTIME_SEND_RECV_H_ + +#include +#include + +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call_registry.h" +#include "xla/stream_executor/event.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime Send/Recv custom calls. +void RegisterSendRecvCustomCalls(runtime::DirectCustomCallRegistry& registry); + +// Register type names for communication attributes defined by MHLO dialect. +void RegisterSendRecvTypeIdNames(runtime::TypeIDNameRegistry& registry); + +// Adds attributes encoding for Send/Recv custom calls +void PopulateSendRecvAttrEncoding(runtime::CustomCallAttrEncodingSet& encoding); + +//===----------------------------------------------------------------------===// +// Support for running asynchronous Send/Recv SendDone/RecvDone operations. +//===----------------------------------------------------------------------===// + +class SendRecvEvents { + public: + absl::Status PushEvent(int32_t handle, tsl::AsyncValueRef event); + absl::StatusOr> PopEvent(int32_t handle); + + private: + absl::Mutex mutex_; + absl::flat_hash_map> events_ + ABSL_GUARDED_BY(mutex_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_SEND_RECV_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/sleep_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/sleep_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0bcaed7c56cfb35a6a15d0c9d0f0b785e5b45d28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/sleep_kernel.h @@ -0,0 +1,21 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_RUNTIME_SLEEP_KERNEL_H_ +#define XLA_SERVICE_GPU_RUNTIME_SLEEP_KERNEL_H_ + +namespace xla::gpu { + +void* GetSleepKernel(); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_SLEEP_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/stream_synchronization.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/stream_synchronization.h new file mode 100644 index 0000000000000000000000000000000000000000..11d3175057c8c2457ca63918e63319fdae774125 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/stream_synchronization.h @@ -0,0 +1,31 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_STREAM_SYNCHRONIZATION_H_ +#define XLA_SERVICE_GPU_RUNTIME_STREAM_SYNCHRONIZATION_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla { +namespace gpu { + +// Registers XLA Gpu runtime stream synchronization custom calls. +void RegisterStreamSynchronizationCustomCalls( + runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_STREAM_SYNCHRONIZATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/support.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/support.h new file mode 100644 index 0000000000000000000000000000000000000000..57bce214a73e1107fc83d6a25d9426bb72dd3038 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/support.h @@ -0,0 +1,162 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_SUPPORT_H_ +#define XLA_SERVICE_GPU_RUNTIME_SUPPORT_H_ + +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "llvm/ADT/ArrayRef.h" +#include "xla/mlir/runtime/transforms/custom_call_encoding.h" +#include "xla/runtime/custom_call.h" +#include "xla/service/gpu/matmul_utils.h" +#include "xla/shape_util.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/device_memory.h" + +namespace xla { +namespace gpu { + +template +using FunctionWrapper = xla::runtime::CustomCall::FunctionWrapper; + +struct DotDimensionNumbers { + absl::Span lhs_batch; + absl::Span lhs_contract; + absl::Span rhs_batch; + absl::Span rhs_contract; +}; + +// Disable expensive CustomCall checks in optimized build. +inline constexpr runtime::CustomCall::RuntimeChecks checks = // NOLINT +#if defined(NDEBUG) + runtime::CustomCall::RuntimeChecks::kLess; +#else + runtime::CustomCall::RuntimeChecks::kDefault; +#endif + +template +absl::StatusOr ToAbsl(StatusOr status_or) { + if (!status_or.ok()) return status_or.status(); + return std::move(status_or).value(); +} + +inline se::DeviceMemoryBase GetDeviceAddress( + const runtime::FlatMemrefView& memref) { + return se::DeviceMemoryBase(memref.data, memref.size_in_bytes); +} + +inline se::DeviceMemoryBase GetDeviceAddress( + const runtime::MemrefView& memref) { + uint64_t size = primitive_util::ByteWidth(memref.dtype); + for (auto dim : memref.sizes) size *= dim; + return se::DeviceMemoryBase(memref.data, size); +} + +inline se::DeviceMemoryBase GetDeviceAddress( + const runtime::StridedMemrefView& memref) { + uint64_t size = primitive_util::ByteWidth(memref.dtype); + for (auto dim : memref.sizes) size *= dim; + return se::DeviceMemoryBase(memref.data, size); +} + +inline Shape ToShape(const runtime::StridedMemrefView& memref) { + // Recover `minor_to_major` dimensions permutation from strides. + auto indexed_strides_range = + llvm::map_range(llvm::enumerate(memref.strides), [](auto pair) { + return std::pair{pair.value(), pair.index()}; + }); + + auto indexed_strides = llvm::to_vector(indexed_strides_range); + llvm::stable_sort(indexed_strides); + + llvm::SmallVector minor_to_major; + minor_to_major.reserve(indexed_strides.size()); + for (auto& pair : indexed_strides) minor_to_major.push_back(pair.second); + + return ShapeUtil::MakeShapeWithDenseLayout(memref.dtype, memref.sizes, + minor_to_major); +} + +inline StatusOr GetGemmConfig( + const runtime::StridedMemrefView& lhs, + const runtime::StridedMemrefView& rhs, + const runtime::StridedMemrefView& out, int64_t algorithm, double alpha_real, + double alpha_imag, double beta, absl::Span lhs_batch, + absl::Span lhs_contract, absl::Span rhs_batch, + absl::Span rhs_contract, int64_t compute_precision, + const std::optional c = std::nullopt, + const std::optional& bias = std::nullopt) { + Shape c_shape = ToShape(c.value_or(out)); + Shape bias_shape; + Shape* bias_shape_ptr = nullptr; + if (bias) { + bias_shape = ToShape(*bias); + bias_shape_ptr = &bias_shape; + } + return GemmConfig::For(ToShape(lhs), lhs_batch, lhs_contract, ToShape(rhs), + rhs_batch, rhs_contract, c_shape, bias_shape_ptr, + ToShape(out), alpha_real, alpha_imag, beta, algorithm, + compute_precision); +} + +// adds Dot Dimension Attribute encodings for calls to Gemm and cuBLASLt +inline void PopulateDotDimsAttrEncoding( + runtime::CustomCallAttrEncodingSet& encoding) { + using DotDimsAttr = mlir::mhlo::DotDimensionNumbersAttr; + encoding.Add< + xla::runtime::AggregateAttrEncoding>( + encoding, + xla::runtime::AggregateAttrDef() + .Add("lhs_batch", &DotDimsAttr::getLhsBatchingDimensions) + .Add("lhs_contract", &DotDimsAttr::getLhsContractingDimensions) + .Add("rhs_batch", &DotDimsAttr::getRhsBatchingDimensions) + .Add("rhs_contract", &DotDimsAttr::getRhsContractingDimensions)); +} + +// Appends to `diagnostic_engine` a handler that appends all emitted errors to +// the `diagnostic` string. If `append_annotation_stack` is true, it will append +// current profiler annotation stack to the diagnostic message (annotation used +// in Xprof). +void AppendDiagnosticToString(runtime::DiagnosticEngine& diagnostic_engine, + std::string* diagnostic, + bool append_annotation_stack = false); + +// Sets the current tracing scope that will be added to all emitted diagnostics. +void SetCurrentTracingScope(std::string_view scope); +void ResetCurrentTracingScope(); + +} // namespace gpu +} // namespace xla + +namespace xla { +namespace runtime { + +// using llvm::ArrayRef; + +XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING( + xla::gpu::DotDimensionNumbers, + AggregateMember>("lhs_batch"), + AggregateMember>("lhs_contract"), + AggregateMember>("rhs_batch"), + AggregateMember>("rhs_contract")); + +} // namespace runtime +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_SUPPORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk.h new file mode 100644 index 0000000000000000000000000000000000000000..ea669e903dd6f0f5cc4eb56f8588c4f3e23f2808 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk.h @@ -0,0 +1,28 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_TOPK_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_H_ + +#include "xla/runtime/custom_call_registry.h" + +namespace xla::gpu { + +// Registers XLA Gpu runtime TopK custom calls. +void RegisterTopkCustomCall(runtime::DirectCustomCallRegistry& registry); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.cu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.cu.h new file mode 100644 index 0000000000000000000000000000000000000000..908401c9979af87e133cae929071366ef9e23c18 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.cu.h @@ -0,0 +1,280 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_CU_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_CU_H_ + +// This file contains bespoke and optimized implementation for TopK shapes. When +// adding support for new shapes/dtypes, you also need to modify the rewritter +// on topk_specializer.cc for these changes to be picked up. + +#include +#include +#include + +#include "xla/service/gpu/runtime/topk_kernel_common.h" + +namespace xla::gpu { + +// Default implementation for KV holder. Useful for testing while adding support +// for a new type, but generally bitpacking those values is more efficient. See +// implementations below. +template +struct Descending { + class KVT { + public: + __device__ KVT() = default; + __device__ KVT& operator=(const KVT&) = default; + __device__ KVT& operator=(KVT&&) = default; + __device__ KVT(const KVT&) = default; + __device__ KVT(KVT&&) = default; + + __device__ KVT(T k, V v) : k_(k), v_(v) {} + __forceinline__ __device__ void Write(T* key, uint32_t* value) const { + *key = k_; + *value = v_; + } + + __device__ __forceinline__ KVT ShuffleDown(int offset) const { + unsigned FULL_MASK = 0xffffffff; + // The static casts here are necessary because some types will be + // broadened (e.g. bfloat16 -> f32), so we need to narrow them back after + // the shuffle. + return KVT(static_cast(__shfl_down_sync(FULL_MASK, k_, offset)), + static_cast(__shfl_down_sync(FULL_MASK, v_, offset))); + } + + private: + T k_; + V v_; + friend class Descending; + }; + + __device__ __forceinline__ static constexpr bool Gt(const KVT& lhs, + const KVT& rhs) { + return lhs.k_ == rhs.k_ ? lhs.v_ < rhs.v_ : lhs.k_ > rhs.k_; + } +}; + +// ----------------------------------------------------------------------------- +// More efficient implementation of Descending. +// ----------------------------------------------------------------------------- + +// Strided indexing. +__device__ __forceinline__ int Idx(int i) { + return blockDim.x * i + threadIdx.x; +} + +// TopK implements a faster TopK for K < 16. +// +// To compute the final largest K elements, we shard the data threads and each +// of them computes the top k elements for the data in its slice. When all lanes +// in a warp are done with their TopK, we merge all the lane-local topks into +// lane 0 using warp-local reductions. The lane-local topk is computed at +// PerWarpTopK() and the warp reduction is computed in Reduce(). The warp-local +// results are stored in shared memory. +// +// Once all warps are done, we load all previously produced results into a +// single warp and repeat the reduction described above. This is implemented in +// MergeTopKs() and we reuse the Reduce() implementation described above. On +// MergeTopKs we also write the final results to the user-provided buffer. +// +// === Detailed Design +// +// The high level goals of this implementations are: +// - Low latency for small N (i.e. kilobytes). +// - High throughput for large N and/or large batch. +// +// Non-goals: +// - K > 32. Register pressure will be too high. +// - Sharding over multiple SMs. As explained later, we can use TopK's +// structure to get this "for free". +// +// The core observation of this implementation is that reading/writing to main +// memory is the bottleneck in usual the Sort/TopK implementations and that for +// K<16 a linear scan with in-register data is faster than using a heap with +// shared memory, especially when K is a power of two. +// +// The heap for K=7 looks like: +// +// a0 +// a1 a2 +// a3 a4 a5 a6 +// +// When performing a push/pop, in the worst case scenario we need to compare it +// with the root, both of its children, and one of the two subtrees. This means +// that using a heap for K=7 only save us 2/7 comparions. Additionally, if the +// tree were unbalanced(e.g. K=8), we would not be able to unroll this +// computation. +// +// If we're using linear insertion, the worst case results in the full K +// comparisons comparisons, but with care all of those values can be kept in +// registers, replacing somewhat load/store instructions with movs. This +// performance are more than enough to surpass the heap. +// +// We split the data evenly over T (<=1024) threads, and use the algorithm above +// to maintain a sorted list of K elements in registers and perform linear +// insertions on every new element. Once a warp is done with their local slice, +// we reduce the slice-local data using shfl and the insertion described above, +// by adding the other lane's TopK results to the local lane. Once the warp is +// done, lane 0 writes its results to shared memory. This step has complexity: +// theta(k * slice_size + k^2 * log2(k)) +// +// On a second pass, we use a single warp to consume the results of the previous +// step and merge them into a final topk, using an analogous algorithm to what +// has been previously described. Complexity of this stage is: +// theta(k^2 * log2(k)). +// +// This algorithm only uses a single block per batch dimension, but for large N, +// we can split the input into B batches of size N/B, calculate each of their +// topks and then compute a final topk, fixing the indices in the process. +// +// Future improvements: +// - Use optimal sort/merge networks to reduce the complexity the algorithm and +// allow better scaling past K=16. This is fairly tricky to implement +// efficiently, so it was let out of v1. +// +template class Traits = Descending> +class TopK { + public: + using Trait = Traits; + using KVT = typename Trait::KVT; + + __device__ TopK(void* buffer, int num_outputs) + : buffer_(reinterpret_cast(buffer)), num_outputs_(num_outputs) {} + + __device__ void Run(KT* key, int n, KT* keys, uint32_t* values) { + PerWarpTopK(key, n); + MergeTopKs(keys, values); + } + + private: + // Compute a per-warp topk of a slice of data. + __device__ void PerWarpTopK(KT* key, int n) { + KVT tmp[K]; + // TODO(doak): Use bitonic sort. +#pragma unroll + for (int i = 0; i < K; i++) tmp[i] = KVT(key[Idx(i)], Idx(i)); +#pragma unroll + for (int i = 0; i < K; i++) { +#pragma unroll + for (int j = i + 1; j < K; j++) { + KVT ti = tmp[i]; + KVT tj = tmp[j]; + bool cmp = Trait::Gt(ti, tj); + tmp[i] = cmp ? ti : tj; + tmp[j] = cmp ? tj : ti; + } + } + + for (int idx = K; idx < n; idx++) { + KVT kv(key[Idx(idx)], Idx(idx)); + Push(tmp, kv); + } + + Reduce(tmp, 32); + + if (threadIdx.x % 32 != 0) return; + int warp_id = threadIdx.x / 32; + for (int i = 0; i < K; i++) { + buffer_[i * 32 + warp_id] = tmp[i]; + } + } + + // Merge the per-warp topks into a single topk. The final data is written to + // `keys` and `values` + __device__ void MergeTopKs(KT* keys, uint32_t* values) { + KVT tmp[K]; + // We only use one warp for this step. + if (threadIdx.x / 32 != 0) return; + __syncthreads(); +#pragma unroll + for (int i = 0; i < K; i++) tmp[i] = buffer_[i * 32 + threadIdx.x]; + Reduce(tmp, blockDim.x / 32); + if (threadIdx.x != 0) return; + for (int i = 0; i < num_outputs_; ++i) { + tmp[i].Write(&keys[i], &values[i]); + } + } + + // Merge `tmp` (a reverse-sorted array) from (0, `num_lanes`) lanes. The + // resulting array is stored in the tmp array of lane 0. For all other lanes, + // `tmp` is unspecified after this function is called. + __device__ __forceinline__ void Reduce(KVT tmp[K], int num_lanes) { + int lane_id = threadIdx.x % 32; + for (int offset = num_lanes / 2; offset > 0; offset /= 2) { +#pragma unroll + for (int i = 0; i < K; i++) { + KVT kv = tmp[i].ShuffleDown(offset); + if (lane_id >= offset) continue; + Push(tmp, kv); + } + } + } + + // Given a K-array of previously reverse-sorted KVTs, add kv to to it and + // remove the smallest element of the resulting array. Preserves the sorted + // order of `tmp`. + static __device__ __forceinline__ bool Push(KVT tmp[K], const KVT& kv) { + if (Trait::Gt(tmp[K - 1], kv)) return false; + tmp[K - 1] = kv; + if constexpr (K >= 2) { +#pragma unroll + for (int i = K - 2; i >= 0; --i) { + if (Trait::Gt(tmp[i], kv)) break; + // Swap + KVT t = tmp[i]; + tmp[i] = tmp[i + 1]; + tmp[i + 1] = t; + } + } + return true; + } + + int source_ = 0; + KVT* buffer_; + int num_outputs_; +}; + +// This shared memory buffer needs to be declared outside of the templated +// Run(), as otherwise it would generate name conflicts from the multiple +// instantiations of Run() from the multiple monomorphizations of Run(). +extern __device__ __shared__ int shmem[]; + +template +__launch_bounds__(kTopKMaxThreadsPerBlock, 1) __global__ + void Run(KT* data, int n, KT* result, uint32_t* result_idxs, int k) { + TopK top_k(shmem, k); + int slice_size = n / blockDim.x; + if (threadIdx.x < n % blockDim.x) { + slice_size++; + } + top_k.Run(&data[n * blockIdx.x], slice_size, &result[k * blockIdx.x], + &result_idxs[k * blockIdx.x]); +} + +template +void* GetTopKKernelForK(int n) { + // TODO(doak): Switch to uint32_t if we don't have an efficient + // implemementation for uint16_t. + return n < std::numeric_limits::max() + ? reinterpret_cast(&Run) + : reinterpret_cast(&Run); +} + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_CU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..6afd56d35fe9d6c4788781d8776879fe69dc0e7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel.h @@ -0,0 +1,43 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_H_ + +#include +#include + +#include "absl/status/status.h" +#include "xla/stream_executor/gpu/gpu_stream.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/platform.h" +#include "xla/xla_data.pb.h" + +namespace xla::gpu { + +// Input: [batch_size, num_elements]dtype +// Output: +// - top_elements: [batch_size, k] dtype +// - top_indices: [batch_size, k] u32 +// Where `top_elements` contains the largest elements of the input, and +// `top_indices` their original indices. +absl::Status RunTopk(::tensorflow::se::gpu::GpuStreamHandle stream, + PrimitiveType dtype, void* data, size_t num_elements, + void* top_elements, uint32_t* top_indices, size_t k, + size_t batch_size); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel_common.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel_common.h new file mode 100644 index 0000000000000000000000000000000000000000..a805b4507aa09c7df2124e22ec9e311f44a3eea9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/topk_kernel_common.h @@ -0,0 +1,34 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_COMMON_H_ +#define XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_COMMON_H_ + +// Contains shared declarations between topk_kernel.cc and topk_kernel.cu.cc +// but avoids including ABSL, etc. which some CUDA compilers cannot +// handle. + +namespace xla::gpu { + +// We perform 2 32-way reductions, which means the largest number of threads per +// block we support is 1024. +static constexpr size_t kTopKMaxThreadsPerBlock = 1024; + +template +void* GetTopKKernelForK(int n); + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_RUNTIME_TOPK_KERNEL_COMMON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/tracing.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/tracing.h new file mode 100644 index 0000000000000000000000000000000000000000..7f5efe48accac438642b8074e0a55e7e34c5a9d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/tracing.h @@ -0,0 +1,34 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_TRACING_H_ +#define XLA_SERVICE_GPU_RUNTIME_TRACING_H_ + +#include + +#include "xla/runtime/custom_call_registry.h" +#include "xla/runtime/type_id.h" + +namespace xla { +namespace gpu { + +void RegisterTracingTypeIdNames(runtime::TypeIDNameRegistry& registry); + +void RegisterTracingCustomCalls(runtime::DirectCustomCallRegistry& registry); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_TRACING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/triangular_solve.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/triangular_solve.h new file mode 100644 index 0000000000000000000000000000000000000000..947633ed2d0793eb153321e6d69e12a3c43a41f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime/triangular_solve.h @@ -0,0 +1,52 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_TRIANGULAR_SOLVE_H_ +#define XLA_SERVICE_GPU_RUNTIME_TRIANGULAR_SOLVE_H_ + +#include + +#include "xla/runtime/custom_call.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +using runtime::CustomCall; + +struct TriangularSolve { + // Adaptor from XlaCustomCall API to properly typed TriangularSolve handler. + static absl::Status run(const ServiceExecutableRunOptions* run_options, + const DebugOptions* debug_options, + CustomCall::RemainingArgs args, + std::string_view backend_config); + + absl::Status operator()(const ServiceExecutableRunOptions* run_options, + const DebugOptions* debug_options, + runtime::StridedMemrefView a, + runtime::StridedMemrefView b, + runtime::StridedMemrefView result, + runtime::FlatMemrefView temp, bool left_side, + bool lower, bool unit_diagonal, + TriangularSolveOptions::Transpose transpose_a) const; + + static TriangularSolve Handler() { return TriangularSolve(); } +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_TRIANGULAR_SOLVE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime2/executable.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime2/executable.h new file mode 100644 index 0000000000000000000000000000000000000000..ac61847680c07bd7be659b3c5a4bf2b1da0e6147 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime2/executable.h @@ -0,0 +1,176 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME2_EXECUTABLE_H_ +#define XLA_SERVICE_GPU_RUNTIME2_EXECUTABLE_H_ + +#include +#include +#include +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/status.h" +#include "xla/statusor.h" + +//===----------------------------------------------------------------------===// +// TODO(ezhulenev): We currently do not build with experimental XLA:GPU runtime +// in open source because we do not have bazel dependency from XLA to IREE. +#if XLA_DISABLE_GPU2_RUNTIME +//===----------------------------------------------------------------------===// + +namespace xla::gpu { +struct Gpu2RuntimeProgram { + Gpu2RuntimeProgram(std::unique_ptr, + mlir::OwningOpRef, std::string, + std::vector, DebugOptions) {} +}; + +struct Gpu2RuntimeExecutable { + static StatusOr> Create( + std::unique_ptr, std::string_view, + const std::vector&) { + return absl::UnimplementedError( + "Experimental XLA:GPU runtime is not supported in OSS build"); + } + + Status Execute(const ServiceExecutableRunOptions* run_options, + const BufferAllocations& buffer_allocations, + const BufferAllocation* temp_alloc) { + return absl::UnimplementedError( + "Experimental XLA:GPU runtime is not supported in OSS build"); + } +}; + +} // namespace xla::gpu + +//===----------------------------------------------------------------------===// +#else // !XLA_DISABLE_GPU2_RUNTIME +//===----------------------------------------------------------------------===// + +#include +#include + +#include "third_party/iree/runtime/src/iree/vm/api.h" // IWYU pragma: keep +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/runtime2/compiler.h" +#include "xla/xla.pb.h" + +namespace xla { +namespace gpu { + +// Forward declare. +struct HalDevice; + +// XLA:GPU program lowered to the IREE input dialects. XLA:GPU runtime +// executable jit-compiles this program to an executable artifact (via lowering +// to IREE VM executable). +// +// Top level module has a single HAL executable source that contains all device +// kernels for an XLA module. After lowering from LMHLO executable source is +// just a placeholder; it gets updated with a real device kernels source only +// before we pass IR to IREE compiler (see Gpu2RuntimeExecutable below), +// because in the XLA compilation pipeline backend compiler runs last. +// +// We have this program as an intermediate step between lowering from LMHLO to +// VM executable to be able to introspect the compilation process. Once we have +// this program, the Xla gpu compiler job is done, and lowering to IREE VM is +// the responsibility of IREE compiler. +struct Gpu2RuntimeProgram { + Gpu2RuntimeProgram(std::unique_ptr ctx, + mlir::OwningOpRef module, + std::string entry_point, std::vector buffer_sizes, + DebugOptions debug_options) + : ctx(std::move(ctx)), + module(std::move(module)), + entry_point(std::move(entry_point)), + buffer_sizes(std::move(buffer_sizes)), + debug_options(std::move(debug_options)) {} + + std::unique_ptr ctx; + mlir::OwningOpRef module; + std::string entry_point; + std::vector buffer_sizes; + DebugOptions debug_options; +}; + +// Gpu runtime executable encapsulates the Xla runtime executable compiled from +// an Xla program and owns all the state required for running it (e.g. it owns +// various caches required for performance). +class Gpu2RuntimeExecutable { + public: + using Bytecode = RuntimeCompiler::Bytecode; + + // Creates Gpu2RuntimeExecutable from the XLA:GPU program. + static StatusOr> Create( + std::unique_ptr program, std::string_view asm_text, + const std::vector& binary); + + ~Gpu2RuntimeExecutable(); + + // Executes entry function with the given buffer arguments. + Status Execute(const ServiceExecutableRunOptions* run_options, + const BufferAllocations& buffer_allocations, + const BufferAllocation* temp_alloc); + + private: + Gpu2RuntimeExecutable(std::string module_name, int32_t module_id, + std::unique_ptr device, + std::unique_ptr bytecode, + std::vector buffer_sizes, + DebugOptions debug_options, std::string_view asm_text, + absl::Span binary, + iree::vm::ref context, + iree::vm::ref instance, + std::unique_ptr> modules, + iree_vm_function_t function); + + // Module name and unique id of the corresponding HLO module. + std::string module_name_; + int32_t module_id_; + + // TODO(ezhulenev): Devices should be created lazily for each StreamExecutor + // and share underlying resources. For now we create a CUDA driver and CUDA + // HAL device for each executable. And we assume that we have just once GPU + // attached to the host, and always run on device with ordinal 0. + std::unique_ptr device_; + + std::unique_ptr bytecode_; + + std::vector buffer_sizes_; + const DebugOptions debug_options_; + + std::string_view asm_text_; + absl::Span binary_; + + // TODO(ezhulenev): VM context and instance should be shared between multiple + // executables. Also HAL module should be loaded just once. This has to be + // fixed together with efficient device sharing, because HAL VM module + // requires HAL device for loading. + iree::vm::ref context_; + iree::vm::ref instance_; + std::unique_ptr> modules_; + iree_vm_function_t function_; +}; + +} // namespace gpu +} // namespace xla + +#endif // !XLA_DISABLE_GPU2_RUNTIME +#endif // XLA_SERVICE_GPU_RUNTIME2_EXECUTABLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime3/cholesky_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime3/cholesky_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..f226a25f7e4885fd32462852c9015f697d09217c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime3/cholesky_thunk.h @@ -0,0 +1,83 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME3_CHOLESKY_THUNK_H_ +#define XLA_SERVICE_GPU_RUNTIME3_CHOLESKY_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/cusolver_context.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a Cholesky +// decomposition (LAPACK potrf). It is generated by IrEmitter. +// +// As an implementation detail, we may run potrf (potentially in a loop, if +// batch_size >1), or potrfBatched. +// +// Thread-compatible. +class CholeskyThunk : public Thunk { + public: + CholeskyThunk(ThunkInfo thunk_info, const CholeskyOptions& options, + se::GpuAsmOpts asm_opts, BufferAllocation::Slice a_buffer, + BufferAllocation::Slice workspace_buffer, + BufferAllocation::Slice info_buffer, PrimitiveType type, + int64_t batch_size, int64_t n); + + CholeskyThunk(const CholeskyThunk&) = delete; + CholeskyThunk& operator=(const CholeskyThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + se::GpuAsmOpts asm_opts_; + se::blas::UpperLower uplo_; + + const BufferAllocation::Slice a_buffer_; + const BufferAllocation::Slice workspace_buffer_; + const BufferAllocation::Slice info_buffer_; + + const PrimitiveType type_; + const int64_t batch_size_; + const int64_t n_; +}; + +struct CholeskyParams { + int64_t n; + int64_t batch_size; + se::blas::UpperLower uplo; + se::DeviceMemoryBase a_buffer; + se::DeviceMemoryBase workspace_buffer; + se::DeviceMemoryBase info_buffer; +}; +Status RunCholesky(const se::GpuAsmOpts& asm_opts, PrimitiveType type, + CholeskyParams* params, se::Stream* stream); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME3_CHOLESKY_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime_intrinsics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime_intrinsics.h new file mode 100644 index 0000000000000000000000000000000000000000..d73aced0e2a1fc58d7e83e7f82ab73ed2406d2c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/runtime_intrinsics.h @@ -0,0 +1,28 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_RUNTIME_INTRINSICS_H_ +#define XLA_SERVICE_GPU_RUNTIME_INTRINSICS_H_ + +#include "absl/strings/string_view.h" + +namespace xla { + +inline constexpr absl::string_view kXlaGpuAssertCustomCallTag = + "__xla_gpu_assert"; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_RUNTIME_INTRINSICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/scatter_slice_simplifier.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/scatter_slice_simplifier.h new file mode 100644 index 0000000000000000000000000000000000000000..374498fc31c5cd3d1067662c4db4f6c9432d03c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/scatter_slice_simplifier.h @@ -0,0 +1,53 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_SCATTER_SLICE_SIMPLIFIER_H_ +#define XLA_SERVICE_GPU_SCATTER_SLICE_SIMPLIFIER_H_ + +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// Replaces scatters followed by truncation slices with a new scatter using +// a different output shape, and the slices are eliminated. +// +// (a) Single output (b) Multiple outputs (c) Elementwise users +// +// T[N+1] scatter (T1, T2) scatter T scatter T constant +// v v v v v +// T[N] slice T1 gte T2 gte T maximum +// v v v +// T1 slice T2 slice T slice +// +// This pattern is used when the last element of the scatter output is intended +// to accumulate updates from the input elements that should be ignored. +// This is slow if there are many indices mapped to the last output index and +// the scatter is implemented using atomics, so everything collides on that one +// memory location. +// As OOB scatter indices are dropped by the GPU implementation, we can remove +// the slice step entirely and avoid the memory congestion in the scatter step. + +class ScatterSliceSimplifier : public HloModulePass { + public: + absl::string_view name() const override { return "scatter-slice-simplifier"; } + + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_GPU_SCATTER_SLICE_SIMPLIFIER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/sequential_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/sequential_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..b674a5e24e7035b3e96138bcde063782dd8785e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/sequential_thunk.h @@ -0,0 +1,54 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_SEQUENTIAL_THUNK_H_ +#define XLA_SERVICE_GPU_SEQUENTIAL_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// A thunk that wraps a list of sub-thunks. Executing this thunk executes all +// the sub-thunks sequentially. This is useful to implement instructions that +// require multiple kernel launches or library calls. +class SequentialThunk : public Thunk { + public: + SequentialThunk(ThunkInfo thunk_info, ThunkSequence thunks); + SequentialThunk(const SequentialThunk&) = delete; + SequentialThunk& operator=(const SequentialThunk&) = delete; + + ThunkSequence& thunks() { return thunks_; } + const ThunkSequence& thunks() const { return thunks_; } + std::string ToStringExtra(int indent) const override; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + // The list of sub-thunks. + ThunkSequence thunks_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_SEQUENTIAL_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/softmax_rewriter_triton.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/softmax_rewriter_triton.h new file mode 100644 index 0000000000000000000000000000000000000000..fd131f8336d75483bdcc1f0506c453db9681153b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/softmax_rewriter_triton.h @@ -0,0 +1,70 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_SOFTMAX_REWRITER_TRITON_H_ +#define XLA_SERVICE_GPU_SOFTMAX_REWRITER_TRITON_H_ + +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +struct DiamondChainDescriptor { + HloInstruction* root = nullptr; + HloInstruction* producer = nullptr; +}; + +// Rewrite compatible Softmax into a custom fusion region to be code-generated +// with the Triton-based Softmax emitter. +class SoftmaxRewriterTriton : public HloModulePass { + public: + explicit SoftmaxRewriterTriton(se::GpuComputeCapability gpu_version) + : gpu_version_(gpu_version) {} + absl::string_view name() const override { return "triton-softmax-rewriter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Finds and returns all the fusible diamond chains in the module. The + // resulting vector is sorted according to a post-order matching (i.e. within + // the same computation, producer diamonds appear before consumer diamonds). + std::vector FindAllFusibleDiamondChains( + HloModule& module, + const absl::flat_hash_set& execution_threads) const; + + // Constructs a Softmax fusion containing all the instructions between the + // root and the producer of a diamond chain. The producer is excluded from the + // fusion. + Status FuseDiamondChain(const DiamondChainDescriptor& diamond_chain); + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_SOFTMAX_REWRITER_TRITON_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/split_k_gemm_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/split_k_gemm_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..436247be2a4b0b76835829eb1b054e249e4d6a7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/split_k_gemm_rewriter.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_SPLIT_K_GEMM_REWRITER_H_ +#define XLA_SERVICE_GPU_SPLIT_K_GEMM_REWRITER_H_ + +#include + +#include "absl/types/span.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/status.h" + +namespace xla { +namespace gpu { + +// Is there a non-empty suffix "s" of span such that product(s) % divisor = 0 +// and for all t != s non-empty suffixes of s: d % product(t) = 0? +bool HasDivisibleSuffixAllowingSplit(absl::Span span, + int64_t divisor); + +// Apply split K configuration from the tiling to the fusion instruction: +// in addition to MakeDotComputationSplitKBatch on its computation add the +// necessary reduction after it. +Status MakeDotSplitKBatch(HloInstruction* dot_fusion, + const AutotuneResult::TritonGemmKey& tiling); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_SPLIT_K_GEMM_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/stream_executor_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/stream_executor_util.h new file mode 100644 index 0000000000000000000000000000000000000000..4e291b5e9a04cc7b4398a63f5e679e445feab2f6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/stream_executor_util.h @@ -0,0 +1,123 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_ +#define XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/autotuning.pb.h" +#include "xla/layout.h" +#include "xla/service/gpu/cublas_cudnn.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/hlo_module_config.h" +#include "xla/statusor.h" +#include "xla/stream_executor/kernel_spec.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +// Helper functions for interacting with StreamExecutor. + +namespace xla { +namespace gpu { + +// Returns (input, filter, output) XLA Layout protos given the StreamExecutor +// layouts. +StatusOr> +StreamExecutorConvLayoutsToXlaLayouts(const ConvolutionDimensionNumbers& dnums, + se::dnn::DataLayout input, + se::dnn::FilterLayout filter, + se::dnn::DataLayout output); + +// Returns (input, filter, output) StreamExecutor layouts given the XLA layouts. +StatusOr< + std::tuple> +XlaConvShapesToStreamExecutorLayouts(const ConvolutionDimensionNumbers& dnums, + const Shape& input, const Shape& filter, + const Shape& output); + +// Finds the VECT_C dimension in input/filter/output, if present. +// +// A cudnn convolution may have layout NCHW_VECT_C, which means instead of +// [N,C,H,W], the layout is [N,C/k,H,W,k] for some k (usually 4 or 32). +// +// ConvolutionDimensionNumbers doesn't explicitly store which is the `k` +// dimension, because only cudnn convolutions have this feature; it's not +// applicable elsewhere. We find it by finding a dimension in the +// input/filter/output shape that is *not* in dnums. +std::tuple, std::optional, + std::optional> +FindVectorizedFeatureDims(const ConvolutionDimensionNumbers& dnums, + const Shape& input, const Shape& filter, + const Shape& output); + +// Generates and returns a unique lock per the provided executor. +// Guarantees that blocks of code running for the same provided +// executor will not be running concurrently if they lock the returned mutex. +// +// This is used to prevent other XLA instances from trying to autotune on a +// device while another thread is using it. +absl::Mutex& GetGpuMutex(const se::StreamExecutor* stream_exec); + +// Creates a kernel with a provided name, based from provided PTX in ptx. +// The kernel should be executed using the provided executor. +// The argument cubin_data represents compiled PTX and may be left empty. +// +// The canonical storage for both ptx and cubin_data should outlive +// the lifetime of the kernel. +StatusOr> CreateKernel( + absl::string_view kernel_name, uint64_t num_args, absl::string_view ptx, + absl::Span cubin_data, se::StreamExecutor* stream_exec, + uint32_t shared_mem_bytes = 0); + +// Runs loaded kernel on the stream with the provided arguments. +Status ExecuteKernelOnStream(const se::KernelBase& kernel, + absl::Span args, + const LaunchDimensions& dims, se::Stream* stream); + +// Initializes `buffer` with random data on `stream`. +// `rng_state` is an inout parameter for the pseudorandom generator state. +// `buffer_type` determines what buffer would be filled out with. +// +// Precondition: `buffer_type` is a floating point type, `rng_state` needs to be +// initialized to zero on the first use. +void InitializeBuffer(se::Stream* stream, PrimitiveType buffer_type, + int64_t* rng_state, se::DeviceMemoryBase buffer); + +StatusOr GetDNNConvKindFromCudnnConvKind( + CudnnConvKind kind); + +StatusOr GetDNNFusedMHAKindFromCudnnfMHAKind( + CudnnfMHAKind kind); + +StatusOr GetDNNDataTypeFromPrimitiveType(PrimitiveType type); + +// Returns result with the smallest time which has not failed. +// If deterministic output is requested, returns first (not failing) result. +StatusOr PickBestResult( + absl::Span profile_results, + std::optional instr_str, + HloModuleConfig hlo_module_config); + +// Returns whether determinism is required. +bool RequireDeterminism(const HloModuleConfig& config); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_STREAM_EXECUTOR_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/target_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/target_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..92f31a6c13506806f9a11b60442ff238237e9ae1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/target_constants.h @@ -0,0 +1,60 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_TARGET_CONSTANTS_H_ +#define XLA_SERVICE_GPU_TARGET_CONSTANTS_H_ + +namespace xla { +namespace gpu { + +namespace nvptx { +// The triple that represents our target. +inline const char* TargetTriple() { + static constexpr char kTargetTriple[] = "nvptx64-nvidia-cuda"; + return kTargetTriple; +} + +// The data layout of the emitted module. Copied from computeDataLayout in +// NVPTXTargetMachine.cpp. +inline const char* DataLayout() { + static constexpr char kDataLayout[] = + "e-i64:64-i128:128-v16:16-v32:32-n16:32:64"; + return kDataLayout; +} +} // namespace nvptx + +namespace amdgpu { + +// The triple that represents our target on LLVM AMDGPU backend. +inline const char* TargetTriple() { + static constexpr char kTargetTriple[] = "amdgcn-amd-amdhsa"; + return kTargetTriple; +} + +// The data layout of the emitted module. +inline const char* DataLayout() { + static constexpr char kDataLayout[] = + "e-p:64:64-p1:64:64-p2:64:64-p3:32:32-p4:32:32-p5:32:32" + "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" + "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-A5"; + return kDataLayout; +} + +} // namespace amdgpu + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TARGET_CONSTANTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/target_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/target_util.h new file mode 100644 index 0000000000000000000000000000000000000000..19b00307b3fea1e68cce82acb5e72df0c16ec8d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/target_util.h @@ -0,0 +1,97 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_TARGET_UTIL_H_ +#define XLA_SERVICE_GPU_TARGET_UTIL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/Module.h" +#include "llvm/TargetParser/Triple.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace gpu { + +// Enumeration to get target specific intrinsics. +enum class TargetIntrinsicID { + kThreadIdx = 0, + kThreadIdy, + kThreadIdz, + kBlockIdx, + kBlockIdy, + kBlockIdz, + kBarrierId, + kBlockDimx, + kBlockDimy, + kBlockDimz, + kGroupBarrierId, +}; + +// Enumeration to get target specific device math function. +enum class TargetDeviceFunctionID { + kAtan2 = 0, + kCbrt, + kCos, + kExp, + kExpm1, + kFmod, + kHypot, + kLog, + kLog1p, + kPow, + kRsqrt, + kSin, + kSqrt, + kTan, + kTanh, +}; + +// HLO opcode -> TargetDeviceFunctionID mapping. +StatusOr GetTargetDeviceFunctionID(HloOpcode); + +// Emits IR to call a device function named "callee_name" on the given +// operand. Returns the IR value that represents the return value. +llvm::CallInst* EmitDeviceFunctionCall( + const std::string& callee_name, absl::Span operands, + absl::Span input_type, PrimitiveType output_type, + const llvm::AttrBuilder& attributes, llvm::IRBuilder<>* b, + absl::string_view name = ""); + +// Emits a call to the specified target intrinsic with the given operands. +// Overloaded intrinsics (for example, "minnum") must include a type +// in overloaded_types for each overloaded type. Typically, overloaded +// intrinsics have only a single overloaded type. +llvm::CallInst* EmitCallToTargetIntrinsic( + TargetIntrinsicID intrinsic_id, absl::Span operands, + absl::Span overloaded_types, llvm::IRBuilder<>* b); + +// Annotate the kernel as GPU kernel according to the GPU target. +void AnnotateFunctionAsGpuKernel(llvm::Module* module, llvm::Function* func, + llvm::IRBuilder<>* b); + +std::string ObtainDeviceFunctionName(TargetDeviceFunctionID func_id, + PrimitiveType output_type, + llvm::Triple target_triple); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TARGET_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..2bea9efc004b0058de09dfe1755bd69345e66094 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/thunk.h @@ -0,0 +1,200 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_THUNK_H_ +#define XLA_SERVICE_GPU_THUNK_H_ + +#include +#include +#include +#include +#include +#include + +#include "mlir/IR/Operation.h" // from @llvm-project +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/gpu_executable_run_options.h" +#include "xla/service/service_executable_run_options.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +class GpuExecutable; + +enum AsyncStreamKind { + kAsyncStreamCollective = 0, // Stream for asynchronous collective ops. + kAsyncStreamP2P = 1, // Stream for P2P Send and Recv ops. +}; +constexpr static int64_t kAsyncStreamTotal = kAsyncStreamP2P + 1; +// Assigns a unique ID to a stream for asynchronous or synchronous execution. +// These IDs can be used, for example, to look up the NCCL communicator. +inline uint64_t GetStreamId( + bool is_async, AsyncStreamKind stream_kind = kAsyncStreamCollective) { + return is_async ? stream_kind + 1 : 0; +} + +// Thunk acts as the bridge between IrEmitter and GpuExecutable. It stores the +// metadata IrEmitter generates for GpuExecutable to invoke an HloInstruction. +// +// Thunk provides the Initialize and ExecuteOnStream interface for GpuExecutable +// to initialize and execute the invocation respectively. Its subclasses are +// supposed to override these interfaces to launch a generated kernel or call an +// external library function (such as operations in cuBLAS). +// +// This is thread-compatible. +class Thunk { + public: + enum Kind { + kCholesky, + kConditional, + kConvolution, + kConvolutionReorder, + kCopy, + kCublasLtMatmul, + kCustomCall, + kFft, + kFor, + kGemm, + kInfeed, + kKernel, + kMemset32BitValue, + kMemzero, + kNcclAllGather, + kNcclAllGatherStart, + kNcclAllGatherDone, + kNcclAllReduce, + kNcclAllReduceStart, + kNcclAllReduceDone, + kNcclCollectivePermute, + kNcclCollectivePermuteStart, + kNcclCollectivePermuteDone, + kNcclReduceScatter, + kNcclReduceScatterStart, + kNcclReduceScatterDone, + kNcclAllToAll, + kNcclAllToAllStart, + kNcclAllToAllDone, + kNcclSend, + kNcclRecv, + kOutfeed, + kReplicaId, + kPartitionId, + kSequential, + kTriangularSolve, + kWhile, + kFusedMHA + }; + + struct ThunkInfo { + explicit ThunkInfo(mlir::Operation* op) : op(op) {} + std::optional profile_index; + std::string profile_annotation; + mlir::Operation* op; + + static ThunkInfo WithProfileAnnotation(mlir::Operation* op); + }; + + // The hlo_instruction argument is meant to be the instruction this thunk was + // generated from, but Thunk never uses this argument other than to save it + // to Thunk::hlo_instruction, so it can be null. + Thunk(Kind kind, ThunkInfo thunk_info) + : kind_(kind), + profile_index_(thunk_info.profile_index), + profile_annotation_(thunk_info.profile_annotation), + op_(thunk_info.op) {} + virtual ~Thunk() = default; + Thunk(const Thunk&) = delete; + Thunk& operator=(const Thunk&) = delete; + + virtual std::string ToStringExtra(int indent) const { return ""; } + Kind kind() const { return kind_; } + std::string profile_annotation() const { return profile_annotation_; } + // Only valid during compilation, i.e., lowering thunks to kernel-launch + // related XLA runtime custom calls). nullptr at runtime. MLIR codegen will + // cease the practice of lowering thunks to XLA runtime custom calls. + mlir::Operation* op() { return op_; } + + // Prepares the thunk for execution on the given StreamExecutor. + // + // This may be called multiple times. Its main purpose is to give us a chance + // to do initialization outside of ExecuteOnStream() so that the + // time spent initializing doesn't count towards our execution profile. + virtual Status Initialize(const GpuExecutable& /*executable*/, + se::StreamExecutor* /*executor*/) { + return OkStatus(); + } + + // Parameters passed to ExecuteOnStream. Encapsulated in a struct so that + // when we add something we don't have to change every subclass of Thunk. + struct ExecuteParams { + ExecuteParams(const ServiceExecutableRunOptions& run_options, + const BufferAllocations& buffer_allocations, + se::Stream* stream, + absl::Span async_streams); + + const BufferAllocations* buffer_allocations; // never null + se::Stream* stream; + absl::InlinedVector async_comms_streams; + NcclExecuteParams nccl_params; + }; + + // Execute the kernel for the thunk on the given stream. This method must be + // called after Initialize and can be called multiple times over Thunk's + // lifetime. + // + // Precondition: Initialize(stream->parent()) has been called. + virtual Status ExecuteOnStream(const ExecuteParams& params) = 0; + + // Clears metadata that is only valid during compile time. + virtual void ClearCompileTimeInfo() { op_ = nullptr; } + + static absl::string_view KindToString(Thunk::Kind kind); + + protected: + std::optional profile_index() const { return profile_index_; } + + private: + Kind kind_; + std::optional profile_index_; + std::string profile_annotation_; + mlir::Operation* op_; +}; + +// A sequence of thunks. +class ThunkSequence : public std::vector> { + public: + std::string ToString(int indent = 0, + std::function + get_thunk_annotation = nullptr) const; +}; + +std::ostream& operator<<(std::ostream& os, Thunk::Kind kind); + +// A struct that defines a shaped slice, i.e., a BufferAllocation::Slice and its +// shape. +struct ShapedSlice { + BufferAllocation::Slice slice; + Shape shape; +}; + +// Returns if the thunk implements a reduction collective (all-reduce or +// reduce-scatter). +bool IsReductionCollective(Thunk::Kind kind); +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_specializer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_specializer.h new file mode 100644 index 0000000000000000000000000000000000000000..c2c02cfe1864fee6bc6fff9449c818a122d4e9f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_specializer.h @@ -0,0 +1,43 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_TOPK_SPECIALIZER_H_ +#define XLA_SERVICE_GPU_TOPK_SPECIALIZER_H_ + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/executable_run_options.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "tsl/platform/statusor.h" + +namespace xla::gpu { + +// This pass transforms eligible TopK CustomCall into a call to be executed by +// runtime/topk.cc. +class TopkSpecializer : public HloModulePass { + public: + absl::string_view name() const override { return "topk-specializer"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla::gpu + +#endif // XLA_SERVICE_GPU_TOPK_SPECIALIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..ac177d10151ec94cce7e11dfbb9d4522cf2ddcd5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/topk_splitter.h @@ -0,0 +1,55 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_TOPK_SPLITTER_H_ +#define XLA_SERVICE_GPU_TOPK_SPLITTER_H_ + +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "tsl/platform/statusor.h" + +namespace xla { +namespace gpu { + +// Splits large TopK into batches of smaller TopKs, followed by sorting and +// slicing the results of those smaller topks. We consider TopKs to be 'large' +// the last dimension of the TopK is larger than `split_threshold`. +class TopKSplitter : public HloModulePass { + public: + explicit TopKSplitter(size_t split_threshold = 1024 * 1024) + : split_threshold_(split_threshold) {} + absl::string_view name() const override { return "topk-splitter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + const size_t split_threshold_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TOPK_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/tree_reduction_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/tree_reduction_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..5c3e8d9bf73116122e4d28dfd862d1fcc430e6de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/tree_reduction_rewriter.h @@ -0,0 +1,99 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_TREE_REDUCTION_REWRITER_H_ +#define XLA_SERVICE_GPU_TREE_REDUCTION_REWRITER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" + +namespace xla { +namespace gpu { + +// Rewrites reductions in a way they can be implemented without atomics. +// +// Rule application: rewrite a single HLO reduce operation into two. +// +// Case 1: Row reduction, batched dimension is present, larger than +// Z-tiling size. +// ----------------------------------------------------------------- +// +// Rewriting: +// +// f32[B] out = reduce(f32[A, B, C] input, dimensions={0, 2}) +// +// Into: +// +// f32[A, B] tmp = reduce(f32[A, B, C] input, dimensions={2}) +// f32[B] out = reduce(f32[A, B] tmp, dimensions={0}) +// +// Case 2: Row reduction +// ------------------------------------------------------------------ +// +// Let M be the thread tiling multiplied by the warp size. +// We go from (assuming C > M): +// +// f32[B] out = reduce(f32[A, B, C] input, dimensions={0, 2}) +// +// to: +// +// f32[A, B, P] padded = pad(input) // Let P = ceil(C/M) * M. +// f32[A, B, Q, M] reshaped = bitcast(padded) // Let Q = ceil(C/M) +// f32[B, Q] inner_reduce = reduce(reshaped, dimensions={0, 3}) +// f32[B] outer_reduce = reduce(inner_reduce, dimensions={1}) +// +// Case 3: Column reduction +// ------------------------------------------------------------------- +// +// Let T be the tiling size for the column reduction. +// +// We go from (assuming B > T): +// +// f32[A, C] out = reduce(f32[A, B, C] input, dimensions={1}) +// +// to: +// +// f32[A, P, C] padded = pad(input) // Let P = ceil(B/T) * T. +// f32[A, Q, T, C] reshaped = bitcast(padded) // Let Q = ceil(B/T) +// f32[A, Q, C] inner_reduce = reduce(reshaped, dimensions={2}) +// f32[A, C] outer_reduce = reduce(inner_reduce, dimensions={1}) +// +class GpuTreeReductionRewriter : public HloModulePass { + public: + explicit GpuTreeReductionRewriter(se::GpuComputeCapability gpu_version) + : gpu_version_(gpu_version) {} + + ~GpuTreeReductionRewriter() override = default; + absl::string_view name() const override { + return "gpu-tree-reduction-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + se::GpuComputeCapability gpu_version_; +}; + +} // end namespace gpu +} // end namespace xla + +#endif // XLA_SERVICE_GPU_TREE_REDUCTION_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_rewriter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_rewriter.h new file mode 100644 index 0000000000000000000000000000000000000000..7e1e2e0c69538f3f43373ca6cf92ac12eb9e33b4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_rewriter.h @@ -0,0 +1,59 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_TRIANGULAR_SOLVE_REWRITER_H_ +#define XLA_SERVICE_GPU_TRIANGULAR_SOLVE_REWRITER_H_ + +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Rewrites HLO TriangularSolve ops into a custom-call. +// +// The motivation for this is that we need to add temp memory to batched +// triangular-solve ops in order to call cublas trsmBatched. We rewrite batch 1 +// ops as well so that we have fewer codepaths to worry about in the backend. +// +// cublas trsmBatched takes arrays in GPU memory of pointers to the inputs and +// outputs, `a` and `b`. In XLA the inputs/outputs are always contiguous, but +// we still have to materialize out these arrays. +// +// We use the same trick as for cudnn convolutions: This custom-call returns a +// tuple (actual-result, temp-memory). In this our case the temp buffer always +// has size 2 * sizeof(void*) * batch_size, because we need two arrays of +// pointers. +// +// The custom-call has a backend-config equal to the TriangularSolveOptions +// object. +class TriangularSolveRewriter : public HloModulePass { + public: + absl::string_view name() const override { + return "triangular-solve-rewriter"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TRIANGULAR_SOLVE_REWRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..bb1a692ed83678a905a87778063d909687287bae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triangular_solve_thunk.h @@ -0,0 +1,88 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_TRIANGULAR_SOLVE_THUNK_H_ +#define XLA_SERVICE_GPU_TRIANGULAR_SOLVE_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace gpu { + +// This class stores everything that StreamExecutor needs to launch a triangular +// solve (BlasTrsm). It is generated by IrEmitter. +// +// Thread-compatible. +class TriangularSolveThunk : public Thunk { + public: + TriangularSolveThunk(ThunkInfo thunk_info, + const TriangularSolveOptions& options, + se::GpuAsmOpts asm_opts, + const BufferAllocation::Slice& a_buffer, + const BufferAllocation::Slice& b_buffer, + const BufferAllocation::Slice& temp_buffer, + PrimitiveType type, int64_t batch_size, int64_t m, + int64_t n, int64_t a_batch_stride, + int64_t b_batch_stride); + + TriangularSolveThunk(const TriangularSolveThunk&) = delete; + TriangularSolveThunk& operator=(const TriangularSolveThunk&) = delete; + + Status ExecuteOnStream(const ExecuteParams& params) override; + + private: + se::GpuAsmOpts asm_opts_; + const se::blas::UpperLower uplo_; + const se::blas::Side side_; + const se::blas::Diagonal unit_diagonal_; + se::blas::Transpose transpose_a_; + + const BufferAllocation::Slice a_buffer_; + const BufferAllocation::Slice b_buffer_; + const BufferAllocation::Slice temp_buffer_; + + const PrimitiveType type_; + const int64_t batch_size_; + const int64_t m_; + const int64_t n_; + const int64_t a_batch_stride_; + const int64_t b_batch_stride_; +}; + +Status RunTriangularSolve(se::DeviceMemoryBase a_data, + se::DeviceMemoryBase b_data, + se::DeviceMemoryBase temp_data, + se::GpuAsmOpts asm_opts, se::blas::UpperLower uplo, + se::blas::Side side, se::blas::Diagonal unit_diagonal, + se::blas::Transpose transpose_a, PrimitiveType type, + int64_t batch_size, int64_t m, int64_t n, + int64_t a_batch_stride, int64_t b_batch_stride, + se::Stream* stream); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TRIANGULAR_SOLVE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triton_autotuner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triton_autotuner.h new file mode 100644 index 0000000000000000000000000000000000000000..bff2f170e6e7b20c32a6aa4976503f5d927dd1e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/triton_autotuner.h @@ -0,0 +1,64 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_SERVICE_GPU_TRITON_AUTOTUNER_H_ +#define XLA_SERVICE_GPU_TRITON_AUTOTUNER_H_ + +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "xla/autotuning.pb.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/gpu/autotuner_util.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" +#include "tsl/platform/threadpool.h" + +namespace xla { +namespace gpu { + +// Find best tiling configuration for each triton fusion outlined. +class TritonAutotuner : public HloModulePass { + public: + explicit TritonAutotuner(const AutotuneConfig& config, + tsl::thread::ThreadPool* thread_pool) + : config_(config), thread_pool_(thread_pool) {} + + absl::string_view name() const override { return "triton-autotuner"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + private: + AutotuneConfig config_; + tsl::thread::ThreadPool* thread_pool_; +}; + +// TODO(b/266210099): have a way to generate/load these dynamically. +// Returns a list of possible tilings for a GEMM performed in Triton. +std::vector GetPossibleMatmulAutotuneConfigs( + const HloDotInstruction& dot, se::CudaComputeCapability compute_capability, + const DebugOptions& debug_options, bool exhaustive_tiling_search = false); + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_TRITON_AUTOTUNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/variadic_op_splitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/variadic_op_splitter.h new file mode 100644 index 0000000000000000000000000000000000000000..bba95c0ae179d15d213b316eb509dd4dbef4f283 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/variadic_op_splitter.h @@ -0,0 +1,41 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_VARIADIC_OP_SPLITTER_H_ +#define XLA_SERVICE_GPU_VARIADIC_OP_SPLITTER_H_ + +#include "absl/strings/string_view.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/statusor.h" + +namespace xla { +namespace gpu { + +// Splits variadic ops with many operands into pieces such that we don't exceed +// the parameter space on the GPU. Currently only concatenate ops are split up. +class VariadicOpSplitter : public HloModulePass { + public: + absl::string_view name() const override { return "variadic-op-splitter"; } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_VARIADIC_OP_SPLITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/while_thunk.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/while_thunk.h new file mode 100644 index 0000000000000000000000000000000000000000..a908885c1c33b4fc6b594dbbd4edb923f442c60e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/while_thunk.h @@ -0,0 +1,66 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_WHILE_THUNK_H_ +#define XLA_SERVICE_GPU_WHILE_THUNK_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/gpu/buffer_allocations.h" +#include "xla/service/gpu/sequential_thunk.h" +#include "xla/service/gpu/thunk.h" +#include "xla/stream_executor/stream_executor.h" + +namespace xla { +namespace gpu { + +// WhileThunk implements the while instruction on GPU by invoking a thunk +// sequence for the while 'condition' computation, and (conditionally) another +// thunk sequence for the while 'body' computation. WhileThunk assumes that +// buffers for the following set of while-related instructions share the same +// allocation: +// init, condition.parameter, body.parameter, body.root, while.result +// WhileThunk synchronizes the stream to test the result of the 'condition' +// computation. +class WhileThunk : public Thunk { + public: + // Constructs a WhileThunk to compute while instruction 'hlo'. + WhileThunk(ThunkInfo thunk_info, + const BufferAllocation::Slice& condition_result_buffer_index, + std::unique_ptr condition_thunk_sequence, + std::unique_ptr body_thunk_sequence); + WhileThunk(const WhileThunk&) = delete; + WhileThunk& operator=(const WhileThunk&) = delete; + + Status Initialize(const GpuExecutable& executable, + se::StreamExecutor* executor) override; + Status ExecuteOnStream(const ExecuteParams& params) override; + + SequentialThunk* condition_thunk_sequence() { + return condition_thunk_sequence_.get(); + } + SequentialThunk* body_thunk_sequence() { return body_thunk_sequence_.get(); } + + private: + const BufferAllocation::Slice condition_result_buffer_index_; + std::unique_ptr condition_thunk_sequence_; + std::unique_ptr body_thunk_sequence_; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_WHILE_THUNK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/xfeed_queue.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/xfeed_queue.h new file mode 100644 index 0000000000000000000000000000000000000000..1cb8dec6d5f91c21c1518d2c6632eb620d8f7738 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/xfeed_queue.h @@ -0,0 +1,160 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_XFEED_QUEUE_H_ +#define XLA_SERVICE_GPU_XFEED_QUEUE_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace gpu { + +// TODO(b/30467474) Once GPU outfeed implementation settles, consider +// folding back the cpu and gpu outfeed implementations into a generic +// one if possible. + +// Manages a thread-safe queue of buffers. +template +class XfeedQueue { + public: + // Adds a tree of buffers to the queue. The individual buffers correspond to + // the elements of a tuple and may be nullptr if the buffer is a tuple index + // buffer. + void EnqueueDestination(BufferType buffers) { + absl::MutexLock l(&mu_); + enqueued_buffers_.push_back(std::move(buffers)); + enqueue_cv_.Signal(); + + EnqueueHook(); + } + + // Blocks until the queue is non-empty, then returns the buffer at the head of + // the queue. + BufferType BlockingGetNextDestination() { + for (const auto& callback : before_get_next_dest_callbacks_) { + callback(); + } + + bool became_empty; + BufferType current_buffer; + { + absl::MutexLock l(&mu_); + while (enqueued_buffers_.empty()) { + enqueue_cv_.Wait(&mu_); + } + current_buffer = std::move(enqueued_buffers_.front()); + enqueued_buffers_.pop_front(); + DequeueHook(); + became_empty = enqueued_buffers_.empty(); + } + if (became_empty) { + for (const auto& callback : on_empty_callbacks_) { + callback(); + } + } + return current_buffer; + } + + void RegisterOnEmptyCallback(std::function callback) { + on_empty_callbacks_.push_back(std::move(callback)); + } + void RegisterBeforeGetNextDestinationCallback( + std::function callback) { + before_get_next_dest_callbacks_.push_back(std::move(callback)); + } + + virtual ~XfeedQueue() = default; + + protected: + virtual void DequeueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) {} + virtual void EnqueueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) {} + + absl::Mutex mu_; + + // The queue of trees of buffers. Buffer* queue contents are not owned. + std::deque enqueued_buffers_ ABSL_GUARDED_BY(mu_); + + private: + // Condition variable that is signaled every time a buffer is enqueued. + absl::CondVar enqueue_cv_; + + // List of callbacks which will be called when 'enqueued_buffers_' becomes + // empty. + std::vector> on_empty_callbacks_; + + // List of callbacks which will be called before BlockingGetNextDestination() + // is called. This lets you e.g. call EnqueueDestination() for each call to + // BlockingGetNextDestination(). + std::vector> before_get_next_dest_callbacks_; +}; + +// Like XfeedQueue but with a maximum capacity. Clients can call +// `BlockUntilEnqueueSlotAvailable` to block until there are fewer than +// `max_pending_xfeeds_` capacity pending infeed items. +// +// We introduce a separate `BlockUntilEnqueueSlotAvailable` (as opposed to +// overriding `EnqueueDestination` to block) because we want to block before we +// copy the buffer to GPU memory, in order to bound the memory consumption due +// to pending infeeds. +template +class BlockingXfeedQueue : public XfeedQueue { + public: + explicit BlockingXfeedQueue(int max_pending_xfeeds) + : max_pending_xfeeds_(max_pending_xfeeds) {} + + void BlockUntilEnqueueSlotAvailable() { + absl::MutexLock l{&this->mu_}; + while (pending_buffers_ + this->enqueued_buffers_.size() >= + max_pending_xfeeds_) { + VLOG(2) << "Capacity " + << (pending_buffers_ + this->enqueued_buffers_.size()) + << " >= max capacity " << max_pending_xfeeds_; + dequeue_cv_.Wait(&this->mu_); + } + + pending_buffers_++; + } + + protected: + void EnqueueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) override { + pending_buffers_--; + } + + void DequeueHook() ABSL_EXCLUSIVE_LOCKS_REQUIRED(this->mu_) override { + dequeue_cv_.Signal(); + } + + private: + const int max_pending_xfeeds_; + + // Condition variable that is signaled every time a buffer is dequeued. + absl::CondVar dequeue_cv_; + + // Keeps track of the number of buffers reserved but not added to + // enqueued_buffers_. + int pending_buffers_ ABSL_GUARDED_BY(this->mu_) = 0; +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_XFEED_QUEUE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/xla_executor_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/xla_executor_state.h new file mode 100644 index 0000000000000000000000000000000000000000..8714d0b24bb8125894795e7a50a77d14456007f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/gpu/xla_executor_state.h @@ -0,0 +1,64 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GPU_XLA_EXECUTOR_STATE_H_ +#define XLA_SERVICE_GPU_XLA_EXECUTOR_STATE_H_ + +#include + +#include "xla/service/gpu/infeed_manager.h" +#include "xla/service/gpu/outfeed_manager.h" + +// Defines XLA:GPU specific state that will be attached to the GpuExecutor. + +namespace xla { +namespace gpu { + +class GpuExecutorXLAState { + public: + explicit GpuExecutorXLAState(stream_executor::StreamExecutor *) {} + + InfeedManager *getOrCreateInfeedManager(stream_executor::StreamExecutor *se) { + absl::MutexLock l(&this->mu_); + if (!infeed_manager_) infeed_manager_ = std::make_unique(se); + return infeed_manager_.get(); + } + + OutfeedManager *getOrCreateOutfeedManager( + stream_executor::StreamExecutor *se) { + absl::MutexLock l(&this->mu_); + if (!outfeed_manager_) + outfeed_manager_ = std::make_unique(); + return outfeed_manager_.get(); + } + + private: + template + T *getOrCreate(stream_executor::StreamExecutor *se, std::unique_ptr &ptr) { + if (!ptr) { + ptr = std::make_unique(se); + } + return ptr.get(); + } + + absl::Mutex mu_; + std::unique_ptr infeed_manager_ ABSL_GUARDED_BY(mu_); + std::unique_ptr outfeed_manager_ ABSL_GUARDED_BY(mu_); +}; + +} // namespace gpu +} // namespace xla + +#endif // XLA_SERVICE_GPU_XLA_EXECUTOR_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/graphcycles/graphcycles.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/graphcycles/graphcycles.h new file mode 100644 index 0000000000000000000000000000000000000000..778ed446fba70fdf96b3a6c1aa4ecbdca4688f2e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/graphcycles/graphcycles.h @@ -0,0 +1,153 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GRAPHCYCLES_GRAPHCYCLES_H_ +#define XLA_SERVICE_GRAPHCYCLES_GRAPHCYCLES_H_ + +#include + +// GraphCycles detects the introduction of a cycle into a directed +// graph that is being built up incrementally. +// +// Nodes are identified by small integers. It is not possible to +// record multiple edges with the same (source, destination) pair; +// requests to add an edge where one already exists are silently +// ignored. +// +// It is also not possible to introduce a cycle; an attempt to insert +// an edge that would introduce a cycle fails and returns false. +// +// GraphCycles uses no internal locking; calls into it should be +// serialized externally. + +// Performance considerations: +// Works well on sparse graphs, poorly on dense graphs. +// Extra information is maintained incrementally to detect cycles quickly. +// InsertEdge() is very fast when the edge already exists, and reasonably fast +// otherwise. +// FindPath() is linear in the size of the graph. +// The current implementation uses O(|V|+|E|) space. + +#include + +#include "absl/types/span.h" + +namespace tensorflow { + +// NOTE!!! +// For now a copy of this is forked to net/plaque. If you +// find a bug or add a feature, please inform the owners of the +// net/plaque copy in case it should be integrated. +// NOTE!!! +class GraphCycles { + public: + GraphCycles(); + ~GraphCycles(); + + // Allocate an unused node id and return it. + // The new node has a null pointer for its node data. + // All node identifiers passed to other routines in this interface + // must have been allocated by NewNode() and not yet deallocated + // by RemoveNode(). + int32_t NewNode(); + + // Remove "node" from the graph, deleting all edges to and from it. + // After this call the identifier "node" it may no longer be used + // as an argument to any routine until it has been reallocated with + // NewNode(). + void RemoveNode(int32_t node); + + // Attempt to insert an edge from source_node to dest_node. If the + // edge would introduce a cycle, return false without making any + // changes. Otherwise add the edge and return true. + bool InsertEdge(int32_t source_node, int32_t dest_node); + + // Remove any edge that exists from source_node to dest_node. + void RemoveEdge(int32_t source_node, int32_t dest_node); + + // Return whether there is an edge directly from source_node to dest_node. + bool HasEdge(int32_t source_node, int32_t dest_node) const; + + // Contracts the edge from 'a' to node 'b', merging nodes 'a' and 'b'. One of + // the nodes is removed from the graph, and edges to/from it are added to + // the remaining one, which is returned. If contracting the edge would create + // a cycle, does nothing and return no value. + std::optional ContractEdge(int32_t a, int32_t b); + + // Return true if can contract edge, otherwise return false. + bool CanContractEdge(int32_t a, int32_t b); + + // Return whether dest_node is reachable from source_node + // by following edges. + bool IsReachable(int32_t source_node, int32_t dest_node) const; + + // A faster non-thread-safe version of IsReachable. + bool IsReachableNonConst(int32_t source_node, int32_t dest_node); + + // Return or set the node data for a node. This data is unused + // by the implementation. + void *GetNodeData(int32_t node) const; + void SetNodeData(int32_t node, void *data); + + // Find a path from "source" to "dest". If such a path exists, place the + // node IDs of the nodes on the path in the array path[], and return the + // number of nodes on the path. If the path is longer than max_path_len + // nodes, only the first max_path_len nodes are placed in path[]. The client + // should compare the return value with max_path_len" to see when this + // occurs. If no path exists, return 0. Any valid path stored in path[] + // will start with "source" and end with "dest". There is no guarantee that + // the path is the shortest, but no node will appear twice in the path, + // except the source and destination node if they are identical; therefore, + // the return value is at most one greater than the number of nodes in the + // graph. + int FindPath(int32_t source, int32_t dest, int max_path_len, + int32_t path[]) const; + + // Check internal invariants. Crashes on failure, returns true on success. + // Expensive: should only be called from graphcycles_test.cc. + bool CheckInvariants() const; + + // Warning: Do not use these if iterating over the span and modifying the + // GraphCycles at the same time. Instead use SuccessorsCopy/PredecessorsCopy. + absl::Span Successors(int32_t node) const; + absl::Span Predecessors(int32_t node) const; + + // Return a copy of the successors set. This is needed for code using the + // collection while modifying the GraphCycles. + std::vector SuccessorsCopy(int32_t node) const; + // Return a copy of the predecessors set. This is needed for code using the + // collection while modifying the GraphCycles. + std::vector PredecessorsCopy(int32_t node) const; + + // Returns all nodes in post order. + // + // If there is a path from X to Y then X appears after Y in the + // returned vector. + std::vector AllNodesInPostOrder() const; + + // Returns the graph in graphviz format. + std::string DebugString() const; + + // ---------------------------------------------------- + struct Rep; + + private: + Rep *rep_; // opaque representation + GraphCycles(const GraphCycles &) = delete; + GraphCycles &operator=(const GraphCycles &) = delete; +}; + +} // namespace tensorflow +#endif // XLA_SERVICE_GRAPHCYCLES_GRAPHCYCLES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/graphcycles/ordered_set.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/graphcycles/ordered_set.h new file mode 100644 index 0000000000000000000000000000000000000000..16258a395ae43028c06a73c94c56cb26926afaac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/graphcycles/ordered_set.h @@ -0,0 +1,85 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_GRAPHCYCLES_ORDERED_SET_H_ +#define XLA_SERVICE_GRAPHCYCLES_ORDERED_SET_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/types/span.h" +#include "tsl/platform/logging.h" + +namespace tensorflow { +// This is a set data structure that provides a deterministic iteration order. +// The iteration order of elements only depends on the sequence of +// inserts/deletes, so as long as the inserts/deletes happen in the same +// sequence, the set will have the same iteration order. +// +// Assumes that T can be cheaply copied for simplicity. +template +class OrderedSet { + public: + // Inserts `value` into the ordered set. Returns true if the value was not + // present in the set before the insertion. + bool Insert(T value) { + bool new_insertion = + value_to_index_.insert({value, value_sequence_.size()}).second; + if (new_insertion) { + value_sequence_.push_back(value); + } + return new_insertion; + } + + // Removes `value` from the set. Assumes `value` is already present in the + // set. + void Erase(T value) { + auto it = value_to_index_.find(value); + DCHECK(it != value_to_index_.end()); + + // Since we don't want to move values around in `value_sequence_` we swap + // the value in the last position and with value to be deleted and then + // pop_back. + value_to_index_[value_sequence_.back()] = it->second; + std::swap(value_sequence_[it->second], value_sequence_.back()); + value_sequence_.pop_back(); + value_to_index_.erase(it); + } + + void Reserve(size_t new_size) { + value_to_index_.reserve(new_size); + value_sequence_.reserve(new_size); + } + + void Clear() { + value_to_index_.clear(); + value_sequence_.clear(); + } + + bool Contains(T value) const { return value_to_index_.contains(value); } + size_t Size() const { return value_sequence_.size(); } + + absl::Span GetSequence() const { return value_sequence_; } + + private: + // The stable order that we maintain through insertions and deletions. + std::vector value_sequence_; + + // Maps values to their indices in `value_sequence_`. + absl::flat_hash_map value_to_index_; +}; +} // namespace tensorflow + +#endif // XLA_SERVICE_GRAPHCYCLES_ORDERED_SET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/alias_analysis.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/alias_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..9b55939679a6243bc31a7550fea11df5068bbeee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/alias_analysis.h @@ -0,0 +1,92 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_ALIAS_ANALYSIS_H_ +#define XLA_SERVICE_LLVM_IR_ALIAS_ANALYSIS_H_ + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/str_cat.h" +#include "llvm/IR/Module.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/types.h" + +namespace xla { +namespace llvm_ir { + +// Helper functionality used to augment the LLVM IR emitted with alias-scope +// metadata. +class AliasAnalysis { + public: + AliasAnalysis(const HloModule& module, const BufferAssignment& assignment, + llvm::LLVMContext* context) + : module_(module), assignment_(assignment), context_(context) {} + + // Augments IrArray with aliasing information. + void AddAliasingInformationToIrArray(const HloInstruction& hlo, + llvm_ir::IrArray* array, + const ShapeIndex& index = {}); + + private: + // Returns a unique alias domain for this emitter. + llvm::MDNode* GetAliasDomain(); + + // Returns an alias.scope metadata node corresponding to a given buffer slice. + llvm::MDNode* GetAliasScopeMetadataForBuffer( + const BufferAllocation::Slice& buffer_slice, llvm::MDNode* domain); + + // Returns a noalias metadata node corresponding to a given buffer slice. + // + // |buffer_slice| is the buffer slice. + // + // |domain| corresponds to the alias scope domain as documented at + // http://llvm.org/docs/LangRef.html#noalias-and-alias-scope-metadata + // + // |hlo| is the instruction we are computing a noalias set for. + llvm::MDNode* GetNoaliasMetadataForBuffer( + const BufferAllocation::Slice& buffer_slice, llvm::MDNode* domain, + const BufferAssignment& assignment, const HloInstruction& hlo); + + // The HLO module we are compiling for. + const HloModule& module_; + + // Assignment of the temporary buffers needed by the computation and their + // shape information. + const BufferAssignment& assignment_; + + // The LLVM context which we are using for IR emission. + llvm::LLVMContext* context_; + + // Holds the alias domain for this computation. + llvm::MDNode* alias_domain_ = nullptr; + + // A map from a buffer slice to metadata corresponding to its alias.scope + // metadata. The index kParameterAliasSet is used to hold aliasing + // information for parameters. + absl::flat_hash_map + alias_scope_metadata_; + + // A map from a buffer slice and producer to metadata corresponding to its + // noalias metadata. + absl::flat_hash_map, + llvm::MDNode*> + noalias_metadata_; +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_ALIAS_ANALYSIS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/buffer_assignment_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/buffer_assignment_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d8b80a58d20a91e3540c6f4a21a9fe2fdb3acc6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/buffer_assignment_util.h @@ -0,0 +1,44 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_BUFFER_ASSIGNMENT_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_BUFFER_ASSIGNMENT_UTIL_H_ + +#include "xla/service/buffer_assignment.h" + +namespace xla { +namespace llvm_ir { +// Sanitizes the HLO constant instruction name so that it can be used for the +// name of the corresponding constant buffer. In particular, it replaces . and +// - with _. +std::string SanitizeConstantName(const HloInstruction& instr); +std::string SanitizeConstantName(absl::string_view name); + +std::string ConstantHloToGlobalName(const HloInstruction& instr); +std::string ConstantNameToGlobalName(absl::string_view name); + +// In XLA:GPU we map constant buffer allocations to globals in the generated +// LLVM IR. This function gives us the name of the global variable a constant +// buffer is mapped to. Not used on XLA:CPU. +std::string ConstantBufferAllocationToGlobalName( + const BufferAllocation& allocation); + +// Returns the Literal corresponding to `allocation`, which must be a constant +// allocation. +const Literal& LiteralForConstantAllocation(const BufferAllocation& allocation); +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_BUFFER_ASSIGNMENT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/dynamic_update_slice_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/dynamic_update_slice_util.h new file mode 100644 index 0000000000000000000000000000000000000000..88c43e55416b5aedb2d85acab3eae2e80d6fb263 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/dynamic_update_slice_util.h @@ -0,0 +1,94 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_DYNAMIC_UPDATE_SLICE_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_DYNAMIC_UPDATE_SLICE_UTIL_H_ +#include + +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/buffer_assignment.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/llvm_ir/fused_ir_emitter.h" +#include "xla/service/llvm_ir/ir_array.h" + +// Utilities related to emitting LLVM IR for various HLO ops. + +namespace xla { +namespace llvm_ir { + +using GeneratorForOperandIrArrays = + std::function()>; + +// Determines whether the given instruction might be implemented as an +// in-place dynamic-update-slice after we have a buffer assignment. +// +// If this returns false, then CanUpdateDynamicSliceInPlace and +// CanEmitFusedDynamicUpdateSliceInPlace will also return false. +// +// This is useful if you want to check whether an instruction might be an +// in-place DUS during an HLO pass, at which point you don't have a buffer +// assignment. +// +// Note that simplifications to the HLO graph might change this function from +// returning false to returning true. Specifically, simplifying the contents of +// fusion nodes might cause a false->true transition. In general this isn't a +// problem by the time you're calling this function, but beware. +bool MayBeImplementedAsInPlaceDynamicUpdateSlice(const HloInstruction* instr); + +// Checks if we can emit code for the given DynamicUpdateSlice node that updates +// its input in place. Returns true if the dynamic-update-slice's +// array-to-be-updated and output share the same BufferAllocation::Slice. +// +// dynamic_update_slice must be a DynamicUpdateSlice op. +bool CanUpdateDynamicSliceInPlace(HloInstruction* dynamic_update_slice, + const BufferAssignment& assignment); + +// Checks if the given fusion node is amenable to being implemented by +// EmitFusedDynamicUpdateSliceInPlace. +bool CanEmitFusedDynamicUpdateSliceInPlace(HloInstruction* fusion, + const BufferAssignment& assignment); + +// Emits IR for running the given dynamic-update-slice op in-place -- that is, +// where the input and output buffers share the same slice, so we can simply +// modify the input/output buffer without touching any of the other elements. +Status EmitDynamicUpdateSliceInPlace(absl::Span operand_arrays, + const IrArray& output_array, + absl::string_view name, + llvm::IRBuilder<>* b); + +// Given a loop-fusion node whose root is a dynamic-update-slice op whose +// array-to-be-updated and output share the same buffer slice, emits +// (sequential) code for a fusion node that does the dynamic-update-slice in +// place. +Status EmitFusedDynamicUpdateSliceInPlace(HloInstruction* fusion, + const IrArray& fusion_output_array, + FusedIrEmitter* fused_emitter, + llvm::IRBuilder<>* b); + +// Same as EmitFusedDynamicUpdateSliceInPlace, except emits a parallel loop with +// the given launch dimensions for arbitrarily many independent dynamic slice +// updates. +Status EmitParallelFusedDynamicUpdateSliceInPlace( + const HloComputation* fusion, + const std::vector>& + dus_and_output_array, + FusedIrEmitter* fused_emitter, + const gpu::LaunchDimensions& launch_dimensions, llvm::IRBuilder<>* b); + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_DYNAMIC_UPDATE_SLICE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..ec958615ab67ee00e3cb9461a71568bd1fe370fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h @@ -0,0 +1,85 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_FUSED_IR_EMITTER_H_ +#define XLA_SERVICE_LLVM_IR_FUSED_IR_EMITTER_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "llvm/IR/Value.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/elemental_ir_emitter.h" +#include "xla/statusor.h" + +namespace xla { + +// FusedIrEmitter is used to generate code for fusion nodes. +// +// Unlike IrEmitter and its ilk, which directly create LLVM IR in an LLVM +// Module, FusedIrEmitter is better understood as "IR generator generator". +// FusedIrEmitter recursively creates a generator (a host function) which the +// compiler can invoke at a later time. Invoking the generator emits LLVM IR +// that, when run, produces the value at a particular index of the output. +// +// After building this generator, the compiler creates a loop (or its moral +// equivalent, e.g. a GPU kernel) and calls the generator from within the loop. +// This generates code that produces each element of the output. +// +// This class handles both vanilla fusion and multi-output fusion. In the MOF +// case, the fusion node ends with a kTuple instruction, and the generator +// created produces an LLVM struct with N elements, one for each element of the +// arrays in the tuple. It follows that the arrays in the tuple must have the +// same length. +class FusedIrEmitter { + public: + using IndexedGenerator = llvm_ir::ElementGenerator; + + explicit FusedIrEmitter(ElementalIrEmitter& elemental_emitter) + : elemental_emitter_(elemental_emitter) {} + + void BindGenerator(const HloInstruction& instruction, + llvm_ir::ElementGenerator generator) { + indexed_generators_[&instruction] = std::move(generator); + } + + // Returns the generator function for the given instruction. + StatusOr GetGenerator(const HloInstruction& instruction); + + private: + StatusOr CreateGenerator(const HloInstruction& instruction); + StatusOr DefaultAction(const HloInstruction& instruction); + IndexedGenerator HandleConstant(const HloInstruction& constant); + StatusOr HandleTuple(const HloInstruction& tuple); + + ElementalIrEmitter& elemental_emitter_; + + // Map from instructions to functions that generate code for the output + // elements. If an instruction is a GetTupleElement instruction, the + // instruction produces non-tuple result. + absl::flat_hash_map + indexed_generators_; + + // Cache of generated values, lest we regenerate an element of a node with + // multiple outgoing edges. + // Use instruction and index values as the key. + using ValueCacheKey = + std::pair>; + absl::flat_hash_map value_cache_; +}; + +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_FUSED_IR_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_array.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_array.h new file mode 100644 index 0000000000000000000000000000000000000000..cfd55362215cc9553ff51b2a762205ee9cb0cf50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_array.h @@ -0,0 +1,378 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_IR_ARRAY_H_ +#define XLA_SERVICE_LLVM_IR_IR_ARRAY_H_ + +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/map_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace llvm_ir { + +// IrArray represents an XLA array at the LLVM IR level. This class +// encapsulates a base pointer to the buffer holding the array (as an LLVM +// Value) and the shape of the array. The class includes methods for emitting +// LLVM IR sequences which access elements of the array at a multidimensional +// index (eg, [x, y, z] in a 3-dimensional array). Arbitrary shape and layouts +// are supported. +class IrArray { + public: + // A multidimensional index into an IrArray. The order of the runtime indices + // (multidim) corresponds to the order of dimensions in the Shape passed to + // the constructor. + // + // This may also keep a linear index and the layout and dimensions it was + // emitted for; if the shape where this `Index` is used matches, the linear + // index may be used, potentially sparing the cost of computing the + // multidimensional index, which LLVM DCE can delete. + class Index { + public: + // Constructs an index for a scalar shape. + explicit Index(llvm::Type* index_ty) : index_type_(index_ty) { + CHECK(index_ty->isIntegerTy()); + } + + // Constructs an index from linear index "linear" and computes the + // multi-dimensional index from "linear" and "shape". "b" is the IR + // builder to emit the index of each dimension in the multi-dimensional + // index. + // + // Precondition: "shape" has a layout. + Index(llvm::Value* linear, const Shape& shape, llvm::IRBuilder<>* b); + + // As before, but also take a multidim to reuse. multidim.size() + // == shape.rank() must be true. If some of the multidim element + // are null we will use the value that would be used if + // deliearized from linear. + Index(llvm::Value* linear, absl::Span multidim, + const Shape& shape, llvm::IRBuilder<>* b); + + // Similar to the above constructor except using "dynamic_dims" instead of + // shape's static dimension to constructs the index. + Index(llvm::Value* linear, const Shape& shape, + absl::Span dynamic_dims, llvm::IRBuilder<>* b); + + // Constructs an index from a multi-dimensional index. 'shape' is the shape + // for which the multi-dimensional index is used. 'index_type' is the type + // of the index. + // + // Precondition: "shape" has a layout. + Index(absl::Span multidim, const Shape& shape, + llvm::Type* index_type); + + // Same as above, but only the dimensions of the shape without layout is + // passed. The layout is assumed to be the default (descending + // minor-to-major) layout. + Index(absl::Span multidim, + absl::Span dimensions, llvm::Type* index_type); + + // Returns an index that adds `addend` to the given `dim` of the object. + Index AddOffsetToDim(llvm::Value* addend, int64_t dim, + llvm::IRBuilder<>* b) const { + Index with_offset = *this; + with_offset.linear_ = nullptr; + with_offset.multidim_[dim] = + b->CreateAdd(with_offset.multidim_[dim], addend); + return with_offset; + } + + const std::vector& multidim() const { return multidim_; } + const std::vector& dims() const { return dims_; } + llvm::Value* linear() const { return linear_; } + + size_t size() const { return multidim().size(); } + + llvm::Value* operator[](size_t i) const { return multidim()[i]; } + + using const_iterator = std::vector::const_iterator; + + const_iterator begin() const { return multidim().begin(); } + const_iterator end() const { return multidim().end(); } + + bool LinearValidOnShape(const Shape& a) const; + + static bool ShapeIsCompatible(const Shape& a, const Shape& b); + + bool ShapeIsCompatible(const Shape& a) const { + return ShapeIsCompatible(a, AsShapeWithType(a.element_type())); + } + + Shape AsShapeWithType(PrimitiveType element_type) const { + return ShapeUtil::MakeShapeWithDenseLayout(element_type, dims_, + layout_.minor_to_major()); + } + + // Given that "this" is the target index of a reshape from `input_shape` + // to `output_shape`, returns the source index. + Index SourceIndexOfReshape(const Shape& output_shape, + const Shape& input_shape, + llvm::IRBuilder<>* builder) const; + + // Returns the index into the source operand from which a slice operation + // selects a value to be placed into index "this". The slice is described + // by starting indices `starts` and stride values `strides`. + // + // Precondition: "this" is an index into a slice whose operand shape is + // `operand_shape`. + Index SourceIndexOfSlice(const Shape& operand_shape, + absl::Span starts, + absl::Span strides, + llvm::IRBuilder<>* builder) const; + + // Given that "this" is the target index of a transpose from `operand_shape` + // to `shape` with the given dimension mapping, returns the source index. + Index SourceIndexOfTranspose( + const Shape& shape, const Shape& operand_shape, + absl::Span dimension_mapping) const; + + // Given that "this" is the target index of a bitcast from `operand_shape` + // to `shape`, returns the source index. + Index SourceIndexOfBitcast(const Shape& shape, const Shape& operand_shape, + llvm::IRBuilder<>* builder) const; + + // Given that "this" is the target index of a broadcast from `operand_shape` + // to `shape` with the given dimension mapping, returns the source index. + Index SourceIndexOfBroadcast(const Shape& shape, const Shape& operand_shape, + absl::Span dimension_mapping, + llvm::IRBuilder<>* builder) const; + + // Linearizes the index into the given shape, i.e. reshapes it to rank-1 and + // returns the index into the sole dimension 0 of the new shape. + llvm::Value* Linearize(absl::Span dimensions, + llvm::IRBuilder<>* builder) const; + + // Linearizes the index into the given dynamic dimensions. + llvm::Value* Linearize(const std::vector& dynamic_dims, + llvm::IRBuilder<>* builder) const; + + llvm::Type* GetType() const { return index_type_; } + + llvm::Constant* GetConstantWithIndexType(int64_t c) const { + // The LLVM function makes sure that the value can be represented by the + // specified type, see ConstantInt::ConstantInt(IntegerType *Ty, const + // APInt &V). + return llvm::ConstantInt::get(index_type_, c); + } + + private: + // Constructs an index from both a multi-dimensional index and a linear + // index. 'shape' is the shape on which the index is used. 'index_type' is + // the type of the index. + // + // Precondition: "shape" has a layout. + Index(absl::Span multidim, llvm::Value* linear, + const Shape& shape, llvm::Type* index_type); + + void Delinearize(std::vector* multidim, llvm::Value* linear, + const Shape& shape, llvm::IRBuilder<>* b) const; + + // Delinearize the linear index with the dynamic dimensions. + void Delinearize(std::vector* multidim, llvm::Value* linear, + const Shape& shape, absl::Span dynamic_dims, + llvm::IRBuilder<>* b) const; + + std::vector multidim_; + + // These values are purely for efficiency; `multidim_` is enough to find the + // element at a given `Index`, but if a loop is emitted with a linear index + // space, that linear index can be saved in `linear_`, and the layout and + // dimensions of the shape the loop was emitted for in `layout_` and + // `dims_`, and if the `Index` is used in another array, and its layout and + // dimensions match, the linear index can be used, sparing the cost of + // computing `multidim_`, which LLVM DCE could potentially so delete. + // Modifying `multidim_` after construction nullifies `linear_`, lest it + // be used wrongly, as it would be valid no more. + // If a loop is emitted with a multidimensional index space, `linear_` would + // be null and `layout_` and `dims_` would be ignored. + llvm::Value* linear_ = nullptr; + Layout layout_; + std::vector dims_; + + llvm::Type* index_type_; + }; + + // Default constructor. Constructs an IrArray in a null status. + IrArray() : base_ptr_(nullptr) {} + + // Construct an IrArray with the given base pointer, pointee type, and shape. + // base_ptr is a pointer type pointing to the first element(lowest address) + // of the array. + // + // For int4 arrays, pointee_type should be i8, not i4, as int4 + // IrArrays are represented as i8 arrays where each i8 value stores two 4-bit + // values. Additionally, reads and write return or take in i8 values which + // hold a value representable by i4, instead of directly returning or taking + // in i4 values. Specifically, the i8 values returned or passed in are between + // 0 and 15 for U4 arrays and between -8 and 7 for S4 arrays. + IrArray(llvm::Value* base_ptr, llvm::Type* pointee_type, Shape shape); + + // Default implementations of copying and moving. + IrArray(IrArray&& other) = default; + IrArray(const IrArray& other) = default; + IrArray& operator=(IrArray&& other) = default; + IrArray& operator=(const IrArray& other) = default; + + llvm::Value* GetBasePointer() const { return base_ptr_; } + llvm::Type* GetBasePointeeType() const { return pointee_type_; } + llvm::Type* GetElementLlvmType() const { return element_type_; } + + const Shape& GetShape() const { return shape_; } + + // Emit a sequence of instructions to compute the address of the element in + // the given array at the given index. Returns the address of the element as + // an LLVM Value. + // + // The optional name is useful for debugging when looking at + // the emitted LLVM IR. + // + // For int4 values, 'is_high_order_bits' must be non-null and this function + // sets '*is_high_order_bits' to a boolean value indicating whether the 4-bit + // value resides in the high-order or low- order bits of the byte that the + // address points to. + llvm::Value* EmitArrayElementAddress( + const Index& index, llvm::IRBuilder<>* b, absl::string_view name = "", + bool use_linear_index = true, + llvm::Value** is_high_order_bits = nullptr) const; + + // Attach metadata this IrArray instance knows about to "instruction". + void AnnotateLoadStoreInstructionWithMetadata( + llvm::Instruction* instruction) const; + + // Emit IR to read an array element at the given index. Returns the read + // result (effectively, a Value loaded from memory). This method seamlessly + // handles scalar shapes by broadcasting their value to all indices (index is + // ignored). + // + // The optional name is useful for debugging when looking at + // the emitted LLVM IR. + // 'use_linear_index' can be used to specify whether the linear index (if + // available) or the multi-dimensional index should be used. + // + // For int4 arrays, returns an i8 value that is representable by i4. The + // returned i8 value will be between 0 and 15 for U4 arrays and between -8 and + // 7 for S4 arrays. + llvm::Value* EmitReadArrayElement(const Index& index, llvm::IRBuilder<>* b, + absl::string_view name = "", + bool use_linear_index = true) const; + + // Emit IR to write the given value to the array element at the given index. + // 'use_linear_index' can be used to specify whether the linear index (if + // available) or the multi-dimensional index should be used. + // + // For int4 arrays, the given value must be an i8 value representable by i4. + // Only 4 bits of a byte in the array are written. First the appropriate byte + // is read from the array, then 4 bits are modified and written back. To avoid + // race conditions, the caller must ensure that the two different 4-bit values + // within a byte are not written to in parallel. + void EmitWriteArrayElement(const Index& index, llvm::Value* value, + llvm::IRBuilder<>* b, + bool use_linear_index = true) const; + + // Returns a new IrArray whose shape is "new_shape" and base pointer is a + // bitcast of the base pointer of "this" IrArray. + // 'use_linear_index' can be used to specify whether the linear index (if + // available) or the multi-dimensional index should be used. + IrArray CastToShape(const Shape& new_shape, llvm::IRBuilder<>* b) const; + + void AddAliasScopeMetadata(llvm::MDNode* alias_scope) { + CHECK_NE(alias_scope, nullptr); + AddMetadata(llvm::LLVMContext::MD_alias_scope, alias_scope); + } + + void AddNoaliasMetadata(llvm::MDNode* noalias) { + CHECK_NE(noalias, nullptr); + AddMetadata(llvm::LLVMContext::MD_noalias, noalias); + } + + // Promises LLVM that the data pointed to by this IrArray never changes after + // it's first loaded. + // + // The temporal scope of this promise is the "whole program" from LLVM's point + // of view, but how this translates to HLOs differs between backends. + // + // In the single-threaded CPU backend, we emit one function that + // runs all the HLOs in sequence, so the whole program is the whole HLO + // module. + // + // In the GPU backend, we emit one GPU kernel per top-level HLO (i.e. per HLO + // in the entry computation). From LLVM's perspective, launching a new kernel + // is like launching a new program, and so the whole program is one top-level + // HLO. Since the scope of the promise is smaller than in the CPU backend, we + // can mark more things as invariant in the GPU backend. + // + // Marking loads as invariant is particularly helpful on GPUs because + // invariant loads can be lowered to PTX ld.global.nc (equivalent to CUDA's + // __ldg intrinsic). These loads use a special cache, and can be + // significantly faster than regular loads. + void MarkInvariantOverWholeProgram(llvm::LLVMContext* context) { + if (is_invariant_) { + return; + } + is_invariant_ = true; + AddMetadata(llvm::LLVMContext::MD_invariant_load, + llvm::MDNode::get(*context, {})); + } + + const std::map& metadata() const { return metadata_; } + + private: + // Add the specified LLVM IR metadata to loads/stores associated with this + // IrArray. + void AddMetadata(int kind, llvm::MDNode* md) { + InsertOrDie(&metadata_, kind, md); + } + + // Like EmitArrayElementAddress, but always uses a linear index. + llvm::Value* EmitLinearArrayElementAddress( + const Index& index, llvm::IRBuilder<>* b, absl::string_view name = "", + llvm::Value** is_high_order_bits = nullptr) const; + + // Address of the base of the array as an LLVM Value. + llvm::Value* base_ptr_; + + // The pointee type of base_ptr_; + llvm::Type* pointee_type_; + + // The LLVM type of the elements in the array. + llvm::Type* element_type_; + + // Shape of the XLA array. + Shape shape_; + + // The list of key/value pairs used when attaching metadata to emitted + // loads/stores for this array. They keys are the metadata kinds and the + // values are the metadata nodes. + std::map metadata_; + + bool is_invariant_ = false; +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_IR_ARRAY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_builder_mixin.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_builder_mixin.h new file mode 100644 index 0000000000000000000000000000000000000000..6f5f6a3f615c30596b2f27475b23bff95a1825a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/ir_builder_mixin.h @@ -0,0 +1,446 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_IR_BUILDER_MIXIN_H_ +#define XLA_SERVICE_LLVM_IR_IR_BUILDER_MIXIN_H_ + +#include + +#include "llvm/IR/IRBuilder.h" + +namespace xla { + +// Mixin class that injects more ergonomic versions of llvm::IRBuilder methods +// into a class. Intended to be used as a CRTP base class, like: +// +// class MyIrEmitter : public IrBuilderMixin { +// llvm::IRBuilder<>* builder() { return builder_; } +// +// void EmitFoo(HloInstruction* foo) { +// Add(Mul(...), FPToUI(...)); +// } +// }; + +template +class IrBuilderMixin { + protected: + template + llvm::Value* Add(Args&&... args) { + return mixin_builder()->CreateAdd(std::forward(args)...); + } + + template + llvm::LoadInst* AlignedLoad(Args&&... args) { + return mixin_builder()->CreateAlignedLoad(std::forward(args)...); + } + + template + llvm::StoreInst* AlignedStore(Args&&... args) { + return mixin_builder()->CreateAlignedStore(std::forward(args)...); + } + + template + llvm::AllocaInst* Alloca(Args&&... args) { + return mixin_builder()->CreateAlloca(std::forward(args)...); + } + + template + llvm::Value* And(Args&&... args) { + return mixin_builder()->CreateAnd(std::forward(args)...); + } + + template + llvm::Value* AtomicCmpXchg(Args&&... args) { + return mixin_builder()->CreateAtomicCmpXchg(std::forward(args)...); + } + + template + llvm::Value* AtomicRMW(Args&&... args) { + return mixin_builder()->CreateAtomicRMW(std::forward(args)...); + } + + template + llvm::Value* BitCast(Args&&... args) { + return mixin_builder()->CreateBitCast(std::forward(args)...); + } + + template + llvm::Value* Br(Args&&... args) { + return mixin_builder()->CreateBr(std::forward(args)...); + } + + llvm::CallInst* Call(llvm::FunctionCallee func_callee, + llvm::ArrayRef args = std::nullopt, + const llvm::Twine& name = "", + llvm::MDNode* fp_math_tag = nullptr) { + return mixin_builder()->CreateCall(func_callee, args, name, fp_math_tag); + } + + llvm::CallInst* Call(llvm::FunctionType* func_type, llvm::Value* callee, + llvm::ArrayRef args = std::nullopt, + const llvm::Twine& name = "", + llvm::MDNode* fp_math_tag = nullptr) { + return mixin_builder()->CreateCall(func_type, callee, args, name, + fp_math_tag); + } + + template + llvm::BranchInst* CondBr(Args&&... args) { + return mixin_builder()->CreateCondBr(std::forward(args)...); + } + + template + llvm::Value* ConstInBoundsGEP1_32(Args&&... args) { + return mixin_builder()->CreateConstInBoundsGEP1_32( + std::forward(args)...); + } + + template + llvm::Value* FAdd(Args&&... args) { + return mixin_builder()->CreateFAdd(std::forward(args)...); + } + + template + llvm::Value* FMul(Args&&... args) { + return mixin_builder()->CreateFMul(std::forward(args)...); + } + + llvm::Value* GEP(llvm::Type* type, llvm::Value* ptr, + llvm::ArrayRef idx_list, + const llvm::Twine& name = "") { + return mixin_builder()->CreateGEP(type, ptr, idx_list, name); + } + + template + llvm::Value* ICmpEQ(Args&&... args) { + return mixin_builder()->CreateICmpEQ(std::forward(args)...); + } + + template + llvm::Value* ICmpNE(Args&&... args) { + return mixin_builder()->CreateICmpNE(std::forward(args)...); + } + + template + llvm::Value* ICmpULE(Args&&... args) { + return mixin_builder()->CreateICmpULE(std::forward(args)...); + } + + template + llvm::Value* ICmpULT(Args&&... args) { + return mixin_builder()->CreateICmpULT(std::forward(args)...); + } + + llvm::Value* InBoundsGEP(llvm::Type* type, llvm::Value* ptr, + llvm::ArrayRef idx_list, + const llvm::Twine& name = "") { + return mixin_builder()->CreateInBoundsGEP(type, ptr, idx_list, name); + } + + llvm::Value* ExtractValue(llvm::Value* agg, llvm::ArrayRef idxs, + const llvm::Twine& name = "") { + return mixin_builder()->CreateExtractValue(agg, idxs, name); + } + + llvm::Value* InsertValue(llvm::Value* agg, llvm::Value* val, + llvm::ArrayRef idxs, + const llvm::Twine& name = "") { + return mixin_builder()->CreateInsertValue(agg, val, idxs, name); + } + + template + llvm::Value* IntToPtr(Args&&... args) { + return mixin_builder()->CreateIntToPtr(std::forward(args)...); + } + + template + llvm::LoadInst* Load(Args&&... args) { + return mixin_builder()->CreateLoad(std::forward(args)...); + } + + template + llvm::CallInst* MemCpy(Args&&... args) { + return mixin_builder()->CreateMemCpy(std::forward(args)...); + } + + template + llvm::Value* Mul(Args&&... args) { + return mixin_builder()->CreateMul(std::forward(args)...); + } + + template + llvm::Value* NSWAdd(Args&&... args) { + return mixin_builder()->CreateNSWAdd(std::forward(args)...); + } + + template + llvm::Value* NSWMul(Args&&... args) { + return mixin_builder()->CreateNSWMul(std::forward(args)...); + } + + template + llvm::Value* NSWSub(Args&&... args) { + return mixin_builder()->CreateNSWSub(std::forward(args)...); + } + + template + llvm::Value* Or(Args&&... args) { + return mixin_builder()->CreateOr(std::forward(args)...); + } + + template + llvm::Value* PointerCast(Args&&... args) { + return mixin_builder()->CreatePointerCast(std::forward(args)...); + } + + template + llvm::Value* PtrToInt(Args&&... args) { + return mixin_builder()->CreatePtrToInt(std::forward(args)...); + } + + template + llvm::Value* SDiv(Args&&... args) { + return mixin_builder()->CreateSDiv(std::forward(args)...); + } + + template + llvm::Value* Select(Args&&... args) { + return mixin_builder()->CreateSelect(std::forward(args)...); + } + + template + llvm::Value* SRem(Args&&... args) { + return mixin_builder()->CreateSRem(std::forward(args)...); + } + + template + llvm::StoreInst* Store(Args&&... args) { + return mixin_builder()->CreateStore(std::forward(args)...); + } + + template + llvm::Value* UDiv(Args&&... args) { + return mixin_builder()->CreateUDiv(std::forward(args)...); + } + + template + llvm::Value* URem(Args&&... args) { + return mixin_builder()->CreateURem(std::forward(args)...); + } + + template + llvm::Value* VectorSplat(Args&&... args) { + return mixin_builder()->CreateVectorSplat(std::forward(args)...); + } + + template + llvm::Value* ZExtOrTrunc(Args&&... args) { + return mixin_builder()->CreateZExtOrTrunc(std::forward(args)...); + } + + template + llvm::Value* AShr(Args&&... args) { + return mixin_builder()->CreateAShr(std::forward(args)...); + } + + template + llvm::Value* FCmpOEQ(Args&&... args) { + return mixin_builder()->CreateFCmpOEQ(std::forward(args)...); + } + + template + llvm::Value* FCmpOGT(Args&&... args) { + return mixin_builder()->CreateFCmpOGT(std::forward(args)...); + } + + template + llvm::Value* FCmpOGE(Args&&... args) { + return mixin_builder()->CreateFCmpOGE(std::forward(args)...); + } + + template + llvm::Value* FCmpOLT(Args&&... args) { + return mixin_builder()->CreateFCmpOLT(std::forward(args)...); + } + + template + llvm::Value* FCmpULT(Args&&... args) { + return mixin_builder()->CreateFCmpULT(std::forward(args)...); + } + + template + llvm::Value* FCmpULE(Args&&... args) { + return mixin_builder()->CreateFCmpULE(std::forward(args)...); + } + + template + llvm::Value* FCmpOLE(Args&&... args) { + return mixin_builder()->CreateFCmpOLE(std::forward(args)...); + } + + template + llvm::Value* FCmpONE(Args&&... args) { + return mixin_builder()->CreateFCmpONE(std::forward(args)...); + } + + template + llvm::Value* FCmpUNE(Args&&... args) { + return mixin_builder()->CreateFCmpUNE(std::forward(args)...); + } + + template + llvm::Value* FCmpUNO(Args&&... args) { + return mixin_builder()->CreateFCmpUNO(std::forward(args)...); + } + + template + llvm::Value* FCmpUGE(Args&&... args) { + return mixin_builder()->CreateFCmpUGE(std::forward(args)...); + } + + template + llvm::Value* FDiv(Args&&... args) { + return mixin_builder()->CreateFDiv(std::forward(args)...); + } + + template + llvm::Value* FNeg(Args&&... args) { + return mixin_builder()->CreateFNeg(std::forward(args)...); + } + + template + llvm::Value* FPCast(Args&&... args) { + return mixin_builder()->CreateFPCast(std::forward(args)...); + } + + template + llvm::Value* FPToSI(Args&&... args) { + return mixin_builder()->CreateFPToSI(std::forward(args)...); + } + + template + llvm::Value* FPToUI(Args&&... args) { + return mixin_builder()->CreateFPToUI(std::forward(args)...); + } + + template + llvm::Value* FPTrunc(Args&&... args) { + return mixin_builder()->CreateFPTrunc(std::forward(args)...); + } + + template + llvm::Value* FRem(Args&&... args) { + return mixin_builder()->CreateFRem(std::forward(args)...); + } + + template + llvm::Value* FSub(Args&&... args) { + return mixin_builder()->CreateFSub(std::forward(args)...); + } + + template + llvm::Value* ICmpSGE(Args&&... args) { + return mixin_builder()->CreateICmpSGE(std::forward(args)...); + } + + template + llvm::Value* ICmpSLT(Args&&... args) { + return mixin_builder()->CreateICmpSLT(std::forward(args)...); + } + + template + llvm::Value* IntCast(Args&&... args) { + return mixin_builder()->CreateIntCast(std::forward(args)...); + } + + template + llvm::Value* LShr(Args&&... args) { + return mixin_builder()->CreateLShr(std::forward(args)...); + } + + template + llvm::Value* MemSet(Args&&... args) { + return mixin_builder()->CreateMemSet(std::forward(args)...); + } + + template + llvm::Value* Neg(Args&&... args) { + return mixin_builder()->CreateNeg(std::forward(args)...); + } + + template + llvm::Value* Not(Args&&... args) { + return mixin_builder()->CreateNot(std::forward(args)...); + } + + template + llvm::PHINode* PHI(Args&&... args) { + return mixin_builder()->CreatePHI(std::forward(args)...); + } + + template + llvm::Value* RetVoid(Args&&... args) { + return mixin_builder()->CreateRetVoid(std::forward(args)...); + } + + template + llvm::Value* SExtOrTrunc(Args&&... args) { + return mixin_builder()->CreateSExtOrTrunc(std::forward(args)...); + } + + template + llvm::Value* Shl(Args&&... args) { + return mixin_builder()->CreateShl(std::forward(args)...); + } + + template + llvm::Value* SIToFP(Args&&... args) { + return mixin_builder()->CreateSIToFP(std::forward(args)...); + } + + template + llvm::Value* Sub(Args&&... args) { + return mixin_builder()->CreateSub(std::forward(args)...); + } + + template + llvm::Value* Trunc(Args&&... args) { + return mixin_builder()->CreateTrunc(std::forward(args)...); + } + + template + llvm::Value* UIToFP(Args&&... args) { + return mixin_builder()->CreateUIToFP(std::forward(args)...); + } + + template + llvm::Value* Unreachable(Args&&... args) { + return mixin_builder()->CreateUnreachable(std::forward(args)...); + } + + template + llvm::Value* Xor(Args&&... args) { + return mixin_builder()->CreateXor(std::forward(args)...); + } + + private: + llvm::IRBuilder<>* mixin_builder() { + return static_cast(this)->builder(); + } +}; + +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_IR_BUILDER_MIXIN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h new file mode 100644 index 0000000000000000000000000000000000000000..6f8600f42b105c86f501c5f42075f6734bf833c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h @@ -0,0 +1,311 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_KERNEL_SUPPORT_LIBRARY_H_ +#define XLA_SERVICE_LLVM_IR_KERNEL_SUPPORT_LIBRARY_H_ + +#include + +#include "absl/strings/string_view.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/llvm_loop.h" +#include "xla/service/llvm_ir/llvm_util.h" + +namespace xla { +// A thin wrapper around llvm_loop.h to make code generating structured control +// flow more readable. +class KernelSupportLibrary { + public: + // `b` is the llvm::IRBuilder instance used to generate LLVM IR. + // `unroll_mode` specifies the desired LLVM unrolling behavior for every loop + // generated by this instance of KernelSupportLibrary. + explicit KernelSupportLibrary( + llvm::IRBuilder<>* b, + llvm_ir::UnrollMode unroll_mode = llvm_ir::UnrollMode::kNoUnroll, + bool prevent_vectorization = true) + : b_(b), + unroll_mode_(unroll_mode), + prevent_vectorization_(prevent_vectorization) {} + + // Generates the following control flow structure: + // + // if (`start` < `end`) { + // `for_body_generator(/*ind_var=*/start, /*is_first_iteration=*/true)`; + // for (i64 i = `start` + `step`; i s< `end`; i += `step`) + // `for_body_generator(/*ind_var=*/,i, /*is_first_iteration=*/false)`; + // } + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& for_body_generator); + + void For( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& + for_body_generator) { + CHECK_EQ(OkStatus(), + ForWithStatus( + name, start, end, step, + [&](llvm::Value* ind_var, bool is_first_iteration) -> Status { + for_body_generator(ind_var, is_first_iteration); + return OkStatus(); + })); + } + + Status ForWithStatus( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& for_body_generator) { + return ForWithStatus(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + void For( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& + for_body_generator) { + For(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + // Generates the following control flow structure if `peel_first_iteration` is + // true: + // + // if (`start` < `end`) { + // `for_body_generator(/*ind_var=*/start, /*is_first_iteration=*/,true)`; + // for (i64 i = `start` + `step`; i s< `end`; i += `step`) + // `for_body_generator(/*ind_var=*/,i, /*is_first_iteration=*/,false)`; + // } + // + // and the following if `peel_first_iteration` is false: + // + // for (i64 i = `start`; i s< `end`; i += `step`) + // `for_body_generator(/*ind_var=*/,i, + // /*is_first_iteration=*/,(i != `start`))`; + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, bool peel_first_iteration, + const std::function& + for_body_generator); + + void For(absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, bool peel_first_iteration, + const std::function& + for_body_generator) { + TF_CHECK_OK(ForWithStatus( + name, start, end, step, peel_first_iteration, + [&](llvm::Value* ind_var, llvm::Value* is_first_iteration) -> Status { + for_body_generator(ind_var, is_first_iteration); + return OkStatus(); + })); + } + + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, bool peel_first_iteration, + const std::function& + for_body_generator) { + return ForWithStatus( + name, /*start=*/start, /*end=*/end, + /*step=*/llvm::ConstantInt::get(start->getType(), step), + peel_first_iteration, for_body_generator); + } + + void For(absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, bool peel_first_iteration, + const std::function& + for_body_generator) { + For(name, /*start=*/start, /*end=*/end, + /*step=*/llvm::ConstantInt::get(start->getType(), step), + peel_first_iteration, for_body_generator); + } + + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& for_body_generator) { + return ForWithStatus(name, start, end, step, + /*peel_first_iteration=*/false, + [&](llvm::Value* indvar, llvm::Value*) -> Status { + return for_body_generator(indvar); + }); + } + + void For( + absl::string_view name, llvm::Value* start, llvm::Value* end, + llvm::Value* step, + const std::function& for_body_generator) { + For(name, start, end, step, + /*peel_first_iteration=*/false, [&](llvm::Value* indvar, llvm::Value*) { + return for_body_generator(indvar); + }); + } + + Status ForWithStatus( + absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, + const std::function& for_body_generator) { + return ForWithStatus(name, start, end, + llvm::ConstantInt::get(start->getType(), step), + /*peel_first_iteration=*/false, + [&](llvm::Value* indvar, llvm::Value*) -> Status { + return for_body_generator(indvar); + }); + } + + void For( + absl::string_view name, llvm::Value* start, llvm::Value* end, + int64_t step, + const std::function& for_body_generator) { + For(name, start, end, llvm::ConstantInt::get(start->getType(), step), + for_body_generator); + } + + Status ForWithStatus( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& for_body_generator) { + return ForWithStatus(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + void For( + absl::string_view name, int64_t start, int64_t end, int64_t step, + const std::function& for_body_generator) { + For(name, /*start=*/b_->getInt64(start), + /*end=*/b_->getInt64(end), + /*step=*/b_->getInt64(step), for_body_generator); + } + + // Generates the following control flow structure: + // + // if (`condition`) + // `true_block_generator()`; + // else + // `false_block_generator()`; + // The else is skipped if false_block_generator is null. + Status IfWithStatus( + absl::string_view name, llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = nullptr); + + Status IfWithStatus( + llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = []() -> Status { + return OkStatus(); + }) { + return IfWithStatus("", condition, true_block_generator, + false_block_generator); + } + + void If(llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = nullptr) { + If("", condition, true_block_generator, false_block_generator); + } + + void If(absl::string_view name, llvm::Value* condition, + const std::function& true_block_generator, + const std::function& false_block_generator = nullptr) { + if (false_block_generator != nullptr) { + TF_CHECK_OK(IfWithStatus( + name, condition, + [&]() { + true_block_generator(); + return OkStatus(); + }, + [&]() { + false_block_generator(); + return OkStatus(); + })); + } else { + TF_CHECK_OK(IfWithStatus(name, condition, [&]() { + true_block_generator(); + return OkStatus(); + })); + } + } + + using ArgumentVector = absl::Span; + + // Generates the following control flow structure: + // + // define @`kernel_name`(arg0, arg1, ... arg`arguments.size()`) { + // kernel_body_generator({arg0, arg1, ... arg`arguments.size()`}); + // } + // + // ... + // call @`kernel_name`(arguments[0], arguments[1] ...) + // ... + // + // If a function called `kernel_name` is already present in the module then + // that function is re-used. In that sense we're using the llvm::Module as a + // cache of outlined kernels, keyed by function name. + // + // If any of the values in `arguments` is nullptr (i.e. a nullptr + // llvm::Value*) then we ignore it when generating LLVM IR, and instead pass + // in a nullptr llvm::Value* in its position to `kernel_body_generator`. + // Currently we only support at most one nullptr value in `arguments`. + static void EmitAndCallOutlinedKernel( + const HloModuleConfig& module_config, llvm::IRBuilder<>* b, + absl::string_view kernel_name, ArgumentVector arguments, + const std::function& kernel_body_generator); + + // Thin wrappers around the more general EmitAndCallOutlinedKernel above. + static void EmitAndCallOutlinedKernel( + const HloModuleConfig& module_config, llvm::IRBuilder<>* b, + absl::string_view kernel_name, llvm::Value* arg0, llvm::Value* arg1, + llvm::Value* arg2, + const std::function& + kernel_body_generator) { + EmitAndCallOutlinedKernel(module_config, b, kernel_name, {arg0, arg1, arg2}, + [&](ArgumentVector args) { + kernel_body_generator(args[0], args[1], + args[2]); + }); + } + + static void EmitAndCallOutlinedKernel( + const HloModuleConfig& module_config, llvm::IRBuilder<>* b, + absl::string_view kernel_name, llvm::Value* arg0, llvm::Value* arg1, + llvm::Value* arg2, llvm::Value* arg3, + const std::function& kernel_body_generator) { + EmitAndCallOutlinedKernel( + module_config, b, kernel_name, {arg0, arg1, arg2, arg3}, + [&](ArgumentVector args) { + kernel_body_generator(args[0], args[1], args[2], args[3]); + }); + } + + private: + llvm::IRBuilder<>* b_; + llvm_ir::UnrollMode unroll_mode_; + bool prevent_vectorization_; +}; +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_KERNEL_SUPPORT_LIBRARY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_command_line_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_command_line_options.h new file mode 100644 index 0000000000000000000000000000000000000000..aa55982ff03949e946ec7ae418ae37492a1a52f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_command_line_options.h @@ -0,0 +1,61 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_LLVM_COMMAND_LINE_OPTIONS_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_COMMAND_LINE_OPTIONS_H_ + +#include +#include + +#include "absl/strings/match.h" +#include "llvm/Support/CommandLine.h" +#include "tsl/platform/logging.h" + +namespace xla { +namespace llvm_ir { + +// Given a map with options (e.g. originating from xla_backend_extra_options()) +// pass those that don't start with xla_ to LLVM. +template +void InitializeLLVMCommandLineOptions(const T& options) { + if (!options.empty()) { + std::vector fake_argv_storage; + fake_argv_storage.push_back(""); + for (const auto& it : options) { + // Skip options the XLA backend itself consumes. + if (!absl::StartsWith(it.first, "xla_")) { + if (it.second.empty()) { + fake_argv_storage.push_back(it.first); + } else { + fake_argv_storage.push_back(it.first + "=" + it.second); + } + } + } + + VLOG(2) << "Passing argv to LLVM:"; + std::vector fake_argv; + for (const auto& s : fake_argv_storage) { + fake_argv.push_back(s.c_str()); + VLOG(2) << s; + } + llvm::cl::ParseCommandLineOptions(static_cast(fake_argv.size()), + &fake_argv[0]); + } +} + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_COMMAND_LINE_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h new file mode 100644 index 0000000000000000000000000000000000000000..a30ec8c8bea92a9072e56efa1fcd6ee8834c750b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h @@ -0,0 +1,293 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_LLVM_LOOP_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_LOOP_H_ + +#include +#include + +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace llvm_ir { + +enum class UnrollMode { + kDefaultUnroll, + kFullyUnroll, + kNoUnroll, +}; + +// A class for constructing a for-loop in LLVM IR. +class ForLoop { + public: + ForLoop(const ForLoop&) = delete; + ForLoop& operator=(const ForLoop&) = delete; + + // Emit a for-loop at the current insert point of the given IRBuilder. + // + // start_index and end_index are the loop bounds (end_index is not inclusive). + // `step` is the increment of the loop index after each iteration. + // + // The current insert basic block of the builder is the preheader to the loop + // (see below for definition of basic block names). All instructions (if any) + // at or after the insert point in the insert basic block are moved to a newly + // created exit basic block. Instructions before the insert point remain in + // the insert BB: + // + // +--------------+ +----------------+ + // | insert BB | | insert BB | + // | ... | | (preheader BB) | + // | %foo = ... | | ... | + // insert point ->| %bar = ... | ===> | %foo = ... | + // | ... | +----------------+ + // +--------------+ | + // V + // [[ LOOP BBs ]] + // | + // V + // +--------------+ + // | exit BB | + // | %bar = ... | + // | ... | + // +--------------+ + // + // `prefix` is used to disambiguate variable and basic block names emitted in + // LLVM IR. If non-empty, it is prepended to the name of the induction + // variable value and each basic block created for the loop. + // + // `unroll_mode` specifies the desired LLVM unrolling behavior for generated + // loop. + static std::unique_ptr EmitForLoop( + absl::string_view prefix, llvm::Value* start_index, + llvm::Value* end_index, llvm::Value* step, llvm::IRBuilder<>* b, + UnrollMode unroll_mode = llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // The names of the blocks follow LLVM's conventions. Control flow amongst the + // blocks for the example C code looks like: + // + // for (int i = 0; i < n; ++i) { + // do_stuff(i); + // } + // + // +--------------+ + // | preheader BB | + // | i = 0 | + // +--------------+ + // | + // V + // +-------------+ + // | header BB |<-+ + // | if i < n: | | + // | goto body | | + // | else: | | + // | goto exit | | + // +-------------+ | + // | | | + // +--------+ | | + // | V | + // | +-------------+ | + // | | body BB | | + // | | dostuff(i) |--+ + // | | ++i | + // | +-------------+ + // | + // | +-------------+ + // +->| exit BB | + // +-------------+ + // + // Caller-emitted code to execute within the loop should be placed within the + // "body" basic block. + // + // Return pointers to various blocks in the loop. + llvm::BasicBlock* GetPreheaderBasicBlock() const { return preheader_bb_; } + llvm::BasicBlock* GetHeaderBasicBlock() const { return header_bb_; } + llvm::BasicBlock* GetBodyBasicBlock() const { return body_bb_; } + llvm::BasicBlock* GetExitBasicBlock() const { return exit_bb_; } + + // Return the Value representing the induction variable in the body basic + // block of the loop. + llvm::Value* GetIndVarValue() const { return indvar_; } + + private: + // Allow ForLoopNest to call this private constructor. + friend class ForLoopNest; + + ForLoop(absl::string_view prefix, absl::string_view suffix, + llvm::Value* start_index, llvm::Value* end_index, llvm::Value* step, + UnrollMode unroll_mode, bool prevent_vectorization); + + // Emit the loop at the insert point of the builder. + void Emit(llvm::IRBuilder<>* b); + + llvm::BasicBlock* CreateLoopBB(absl::string_view name, llvm::IRBuilder<>* b); + + // Creates a name for an LLVM construct, appending prefix_ and suffix_, if + // they are set. + std::string GetQualifiedName(absl::string_view name); + + // Return a list of metadata nodes that should be associated with the + // llvm::Loop for this `ForLoop`. + std::vector GetLoopMetadata(llvm::IRBuilder<>* b); + + std::string prefix_; + std::string suffix_; + llvm::Value* start_index_; + llvm::Value* end_index_; + llvm::Value* step_; + + // To improve readability of the IR, we want the basic blocks to appear + // consecutively in the following order: preheader, header, body, loop, + // exit. The member insert_before_bb_ points to where the next basic block + // should be created to ensure this ordering. + llvm::BasicBlock* insert_before_bb_; + + llvm::BasicBlock* preheader_bb_; + llvm::BasicBlock* header_bb_; + llvm::BasicBlock* body_bb_; + llvm::BasicBlock* exit_bb_; + llvm::Value* indvar_; + UnrollMode unroll_mode_; + bool prevent_vectorization_; +}; + +// A simple class for constructing nested for-loops. +class ForLoopNest { + public: + ForLoopNest(absl::string_view name, llvm::IRBuilder<>* b, + llvm::Type* index_ty = nullptr) + : name_(name), + outer_loop_preheader_bb_(nullptr), + outer_loop_exit_bb_(nullptr), + inner_loop_body_bb_(nullptr), + b_(b) { + SetIndexType(index_ty); + } + ForLoopNest(const ForLoopNest&) = delete; + ForLoopNest& operator=(const ForLoopNest&) = delete; + + // Adds a loop to the nest. If no loop has been added yet then emit a loop at + // the current insert point of the given builder. If one or more loops have + // been added then emit loop inside the body of the last added loop. + // unroll_mode is used to emit metadata that controls LLVM unrolling. + std::unique_ptr AddLoop( + absl::string_view suffix, llvm::Value* start_index, + llvm::Value* end_index, llvm::Value* stride, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // Like the above, except that it defaults to a stride of one. + std::unique_ptr AddLoop( + absl::string_view suffix, llvm::Value* start_index, + llvm::Value* end_index, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // A convenient wrapper of the other flavor of AddLoop. The given start and + // end index are constant. + std::unique_ptr AddLoop( + int64_t start_index, int64_t end_index, int64_t stride, + absl::string_view suffix, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // Like the above, except that it defaults to a stride of one. + std::unique_ptr AddLoop( + int64_t start_index, int64_t end_index, absl::string_view suffix, + UnrollMode unroll_mode = xla::llvm_ir::UnrollMode::kDefaultUnroll, + bool prevent_vectorization = false); + + // Add loops to iterate through the indices within the specified + // shape. The returned index collects the induction variables of the + // loops so that it will iterate through all coordinates within the + // specified shape. + // + // E.g. if you pass in a 2x3 shape, you will get back an index with + // two entries that are induction variables of the two loops that + // will be added. That index will iterate through the 6 coordinates + // within the shape. One possible order for that sequence would be: + // + // (0,0), (0,1), (0,2), (1,0), (1,1), (1,2) + IrArray::Index AddLoopsForShape(const Shape& shape, absl::string_view suffix); + + // Add a loop for each dimension in "dimensions". "suffix" is the + // name suffix of the indvar and basic blocks in this new loop nest. + // + // The return value is an index with the induction variables. The + // size equals the rank of shape and there is a null for each + // dimension that is not in "dimensions". + std::vector AddLoopsForShapeOnDimensions( + const Shape& shape, absl::Span dimensions, + absl::string_view suffix); + + // Emits a series of nested loops for iterating over an operand array. Loops + // are constructed in major to minor dimension layout order. No loop is + // emitted for the given 'dimension_to_skip'. The function returns an IrArray + // index for the given operand_array containing the indvars of the loops. All + // dimensions of the index are filled except for 'dimension_to_skip'. + // name_suffix is the string to append to the names of LLVM constructs (eg, + // basic blocks) constructed by this method. + std::vector EmitOperandArrayLoopNest( + const llvm_ir::IrArray& operand_array, int64_t dimension_to_skip, + absl::string_view name_suffix); + + // Convenience methods which return particular basic blocks of the outermost + // or innermost loops. These methods return nullptr if no loops have been + // added yet. + llvm::BasicBlock* GetOuterLoopPreheaderBasicBlock() { + return outer_loop_preheader_bb_; + } + llvm::BasicBlock* GetOuterLoopExitBasicBlock() { return outer_loop_exit_bb_; } + llvm::BasicBlock* GetInnerLoopBodyBasicBlock() { return inner_loop_body_bb_; } + + private: + void SetIndexType(llvm::Type* index_ty) { + index_type_ = index_ty == nullptr ? b_->getInt64Ty() : index_ty; + } + + llvm::Constant* GetConstantWithIndexType(int64_t c) const { + return llvm::ConstantInt::get(index_type_, c); + } + + // Human-friendly name of the loop nest. + std::string name_; + + // The preheader and exit basic block of the outermost loop, or nullptr if no + // loop has been added yet. + llvm::BasicBlock* outer_loop_preheader_bb_; + llvm::BasicBlock* outer_loop_exit_bb_; + + // The body basic block of the most-recently added loop, or nullptr if no loop + // has been added yet. + llvm::BasicBlock* inner_loop_body_bb_; + + llvm::IRBuilder<>* b_; + + llvm::Type* index_type_; +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_LOOP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_type_conversion_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_type_conversion_util.h new file mode 100644 index 0000000000000000000000000000000000000000..033c933deb1577a724518b56be83a132b6a99ce3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_type_conversion_util.h @@ -0,0 +1,55 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_LLVM_TYPE_CONVERSION_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_TYPE_CONVERSION_UTIL_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" + +namespace xla { +namespace llvm_ir { + +// Convert a absl::string_view to a llvm::StringRef. Note: both +// absl::string_view and llvm::StringRef are non-owning pointers into a +// string in memory. This method is used to feed strings to LLVM +// & Clang APIs that expect llvm::StringRef. +inline llvm::StringRef AsStringRef(absl::string_view str) { + return llvm::StringRef(str.data(), str.size()); +} + +inline absl::string_view AsStringView(llvm::StringRef str) { + return absl::string_view(str.data(), str.size()); +} + +template +llvm::ArrayRef AsArrayRef(const std::vector& vec) { + return llvm::ArrayRef(vec.data(), vec.size()); +} + +template +llvm::ArrayRef AsArrayRef(const absl::Span slice) { + return llvm::ArrayRef(slice.data(), slice.size()); +} + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_TYPE_CONVERSION_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_util.h new file mode 100644 index 0000000000000000000000000000000000000000..10f710309781e4f18666a9e7ff05d85d0322db85 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/llvm_util.h @@ -0,0 +1,326 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_LLVM_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_LLVM_UTIL_H_ + +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/FPEnv.h" +#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/InstrTypes.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Value.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/literal.h" +#include "xla/service/hlo_module_config.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace llvm { +class FastMathFlags; +class TargetOptions; +}; // namespace llvm + +namespace xla { +namespace llvm_ir { + +// We have different DumpToString functions for each type for findability. We +// use pointers / values based on the usual semantics of the parameter type. + +std::string DumpToString(const llvm::Module* module); +std::string DumpToString(const llvm::Type* type); +std::string DumpToString(const llvm::Value* value); + +// This also works for mlir::Op<...> descendants, such as mlir::ModuleOp and +// mlir::lmhlo::FusionOp. +// +// For findability: +// std::string DumpToString(mlir::Op<...>& op); +// std::string DumpToString(mlir::ModuleOp& module_op); +// std::string DumpToString(mlir::lmhlo::FusionOp& fusion_op); +// +// The `operation` parameter is not const, because the used print() method is +// not const. +std::string DumpToString(mlir::Operation* operation); +std::string DumpToString(mlir::Type type); +std::string DumpToString(mlir::Value value); + +// Constructs a human-friendly name from the given inputs. The result is +// suitable for use as an llvm::Value's name. +// +// This is equivalent to +// +// - changing the HloInstruction* to its name() (if we called that overload), +// - joining all of the nonempty inputs by '.', and then +// - removing all '%'s. +// +std::string IrName(absl::string_view a); +std::string IrName(absl::string_view a, absl::string_view b); +std::string IrName(const HloInstruction* a, absl::string_view b = ""); + +// Construct a module from the given location with an optional name. +// +// The underlying "create" method is unsafe, because it leaks the new module by +// default. This function avoids this by always returning an OwningOpRef. +mlir::OwningOpRef CreateMlirModuleOp( + mlir::Location loc, std::optional name = std::nullopt); + +// Removes special characters from a function name. +// +// Note that this can cause different inputs to map to the same output, so after +// sanitizing a function name, you must run it through a uniquer. +std::string SanitizeFunctionName(std::string function_name); + +// Emits a call to the specified intrinsic with the given operands. Overloaded +// intrinsics (for example, "minnum") must include a type in overloaded_types +// for each overloaded type. Typically, overloaded intrinsics have only a single +// overloaded type. +llvm::CallInst* EmitCallToIntrinsic( + llvm::Intrinsic::ID intrinsic_id, absl::Span operands, + absl::Span overloaded_types, llvm::IRBuilder<>* b, + absl::string_view name = ""); + +// Emit float max. Emit maxnum intrinsic is fast math is disabled, or +// fcmp+select otherwise +llvm::Value* EmitFloatMax(llvm::Value* lhs_value, llvm::Value* rhs_value, + llvm::IRBuilder<>* b, bool enable_fast_min_max, + absl::string_view name = ""); + +// Emit float min. Emit minnum intrinsic is fast math is disabled, or +// fcmp+select otherwise +llvm::Value* EmitFloatMin(llvm::Value* lhs_value, llvm::Value* rhs_value, + llvm::IRBuilder<>* b, bool enable_fast_min_max, + absl::string_view name = ""); + +// Convenience methods for emitting a GEP instruction that indexes into a buffer +// (1-dimensional array), equivalent to array[index]. The element type of the +// array must be explicitly passed in. The int64_t index overload +// wraps the index in a i64 llvm::Value. +llvm::Value* EmitBufferIndexingGEP(llvm::Value* array, llvm::Type* element_type, + llvm::Value* index, llvm::IRBuilder<>* b); +llvm::Value* EmitBufferIndexingGEP(llvm::Value* array, llvm::Type* element_type, + int64_t index, llvm::IRBuilder<>* b); + +// Returns the LLVM type which represents the given XLA primitive type. +llvm::Type* PrimitiveTypeToIrType(PrimitiveType element_type, + llvm::Module* module); + +// Returns the type size in bits. If "type" is a struct, it must be packed. +int GetSizeInBits(llvm::Type* type); + +// Returns the LLVM type which represents the given XLA shape. For example, +// if "shape" is [5 x [10 x f32]], the function returns [5 x [10 x float]]. +llvm::Type* ShapeToIrType(const Shape& shape, llvm::Module* module); + +// Returns a value that represents a pointer to a global string constant that +// encodes the shape as a serialized protobuf. +StatusOr EncodeSelfDescribingShapeConstant(const Shape& shape, + int32_t* shape_size, + llvm::IRBuilder<>* b); + +// Converts a given literal to an IR Constant. Literals have known constant +// values at IR emission time. +llvm::Constant* ConvertLiteralToIrConstant(const Literal& literal, + llvm::Module* module); + +// Allocates a tile of shared memory. +llvm::GlobalVariable* AllocateSharedMemoryTile(llvm::Module* module, + llvm::Type* tile_type, + absl::string_view name); + +// Inserts an allocate of the requested type at the entry point of the +// function that the builder is currently building. The insert point +// of the builder is set to the same place after calling this function +// as before. +// +// This can be useful to avoid e.g. executing an alloca every time +// through a loop. +llvm::AllocaInst* EmitAllocaAtFunctionEntry(llvm::Type* type, + absl::string_view name, + llvm::IRBuilder<>* b, + int alignment = 0); + +// As EmitAllocaAtFunctionEntry, but allocates element_count entries +// instead of a single element. +llvm::AllocaInst* EmitAllocaAtFunctionEntryWithCount(llvm::Type* type, + llvm::Value* element_count, + absl::string_view name, + llvm::IRBuilder<>* b, + int alignment = 0); + +// Creates a basic block with the same context and function as for the +// builder. Inserts at the end of the function if insert_before is +// null. +llvm::BasicBlock* CreateBasicBlock(llvm::BasicBlock* insert_before, + absl::string_view name, + llvm::IRBuilder<>* b); + +// Struct with data on a conditional branch in a diamond shape created +// via EmitIfThenElse. +struct LlvmIfData { + // The block that has the conditional branch. + llvm::BasicBlock* if_block; + + // The block that is executed if the condition is true. + llvm::BasicBlock* true_block; + + // The block that is executed if the condition is false. + llvm::BasicBlock* false_block; + + // The block that follows after both the true_block and the + // false_block. + llvm::BasicBlock* after_block; +}; + +// Inserts a diamond-shaped if-then-else construct at the current +// insertion point of the builder. This involves splitting the current +// block into two blocks, at the insertion point, and introducing a +// true-block and a false-block that connect the two split pieces. The +// true-block is executed if the condition parameter evaluates to true +// and otherwise the false-block is executed. If `emit_else` is false, +// it jumps to the after-block rather than the false-block if the +// condition is false, and the returned `false_block` is null. +// +// Currently the insertion point of the builder must be a well-formed +// block with a terminator. If you need to use this for a +// non-terminated block, just make the function able to do that too. +LlvmIfData EmitIfThenElse(llvm::Value* condition, absl::string_view name, + llvm::IRBuilder<>* b, bool emit_else = true); + +// Emits a compare operation between "lhs" and "rhs" with the given predicate, +// and then converts the result to i8 so that it is addressable. +llvm::Value* EmitComparison(llvm::CmpInst::Predicate predicate, + llvm::Value* lhs, llvm::Value* rhs, + llvm::IRBuilder<>* b, absl::string_view name = ""); + +// Emits a call that logs the given value with the given tag as a prefix. +// The provided tag and value are passed to a runtime logging call that is +// embedded in this translation unit when the emitted code is executed. +// +// This can be very useful for debugging generated programs in short order when +// developing new generated routines. +// +// Precondition: value must be an int64_t. +// Precondition: tag must be a stable pointer for the lifetime of the generated +// program (the constant pointer is burned in to the program). +void EmitLogging(const char* tag, llvm::Value* value, llvm::IRBuilder<>* b); + +// Adds alignment metadata to a load instruction using the given alignment. +// The alignment refers to the result of the load, not the load itself. +void SetAlignmentMetadataForLoad(llvm::LoadInst* load, uint64_t alignment); + +// Adds dereferenceable metadata to a load instruction using the given +// the number of dereferenceable bytes. +// Dereferenceable refers to the result of the load, not the load itself. +void SetDereferenceableMetadataForLoad(llvm::LoadInst* load, + uint64_t dereferenceable_bytes); + +// Tells LLVM `inst >= lower && inst < upper`. Returns `inst` for convenience. +llvm::Instruction* AddRangeMetadata(int32_t lower, int32_t upper, + llvm::Instruction* inst); + +void SetToFirstInsertPoint(llvm::BasicBlock* blk, llvm::IRBuilder<>* builder); + +void SetToLastInsertPoint(llvm::BasicBlock* blk, llvm::IRBuilder<>* builder); + +// Create a bitwise rotation of `rotand` by `rotor`. +llvm::Value* CreateRor(llvm::Value* rotand, llvm::Value* rotor, + llvm::IRBuilder<>* builder); + +// Returns the number of bytes within the shape. +int64_t ByteSizeOf(const Shape& shape, const llvm::DataLayout& data_layout); + +// Gets an llvm::FastMathFlags that reflects the settings in the given +// module config. +llvm::FastMathFlags GetCpuFastMathFlags(const HloModuleConfig& module_config); + +// Computes a conservative union of the metadata in "a" and "b". For +// aliasing-related metadata, this means the result can be applied to +// instructions whose aliasing relationship can be described either by "a" *or* +// by "b". +std::map MergeMetadata( + llvm::LLVMContext* context, const std::map& a, + const std::map& b); + +// Dumps out `llvm_module` to the path specified in DebugOptions, if dumping is +// enabled for the given HLO module. +// +// A sanitized version of `hlo_module_name` is incorporated into the file name. +// If `optimized` is true then a suffix of "-with-opt.ll" is used, else a suffix +// of "-no-opt.ll" is used. +void DumpIrIfEnabled(const HloModule& hlo_module, + const llvm::Module& llvm_module, bool optimized, + absl::string_view filename_suffix = ""); + +llvm::Function* CreateCpuFunction(llvm::FunctionType* function_type, + llvm::GlobalValue::LinkageTypes linkage, + const HloModuleConfig& module_config, + absl::string_view name, llvm::Module* module); + +// Zero-extends two 32-bit values to 64 bits, multiplies them, and returns the +// result as a pair of (low 32 bits, high 32 bits). +std::pair UMulLowHigh32(llvm::IRBuilder<>* b, + llvm::Value* src0, + llvm::Value* src1); +// Splits the 64-bit integer value into its high and low 32 bits. +std::pair SplitInt64ToInt32s( + llvm::IRBuilder<>* b, llvm::Value* value_64bits); + +// Checks whether a global variable is already created to represent the state +// of a random number generator. If not, creates such a variable. Returns the +// global variable. +llvm::GlobalVariable* GetOrCreateVariableRngState(llvm::Module* module, + llvm::IRBuilder<>* b); + +// Adds a delta value to the global state variable and return the old value of +// the variable. +llvm::Value* RngGetAndUpdateState(uint64_t delta, llvm::Module* module, + llvm::IRBuilder<>* b); + +// Gets the LLVM address space that should be used for global variables (e.g. +// XLA's rng state). +unsigned GetGlobalMemoryAddressSpace(); + +// Emits a block which does "return void". Leaves the insert point as is. +llvm::BasicBlock* EmitReturnBlock(llvm::IRBuilder<>* b); + +// Emits `if (condition) return`. Assumes that the current function returns +// void. +// +// Can either use a supplied `return_block`, or generate a new one. +void EmitEarlyReturn(llvm::Value* condition, llvm::IRBuilder<>* b, + llvm::BasicBlock* return_block = nullptr); + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LLVM_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/loop_emitter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/loop_emitter.h new file mode 100644 index 0000000000000000000000000000000000000000..c5f3c2322db059e036b8a105eba6e20f57f46ee2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/loop_emitter.h @@ -0,0 +1,112 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_LOOP_EMITTER_H_ +#define XLA_SERVICE_LLVM_IR_LOOP_EMITTER_H_ + +#include + +#include "llvm/IR/BasicBlock.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "xla/service/llvm_ir/llvm_loop.h" +#include "xla/statusor.h" + +namespace xla { +namespace llvm_ir { + +// A function type for emitting code that generates an element in the target +// array. The function gets a multi-dimensional index as its only input. This +// index specifies the target element for which a value needs to be computed. +// The function has to emit code to compute this value and return the resulting +// llvm::Value*. +using ElementGenerator = + std::function(const IrArray::Index& index)>; +using BodyEmitter = std::function; + +// Creates the body emitter from target arrays. +BodyEmitter MakeBodyEmitter(const ElementGenerator& target_element_generator, + absl::Span target_arrays, + llvm::IRBuilder<>* b, bool is_tuple); + +// Emits a loop for every element in the given shape. +class LoopEmitter { + public: + LoopEmitter(const BodyEmitter& body_emitter, const Shape& shape, + llvm::IRBuilder<>* b); + + // Constructs a LoopEmitter from an body_emitter that generates + // element of the given target array in the dynamic dimension. + LoopEmitter(const BodyEmitter& body_emitter, const Shape& shape, + std::vector dynamic_dims, llvm::IRBuilder<>* b); + + // Constructs a LoopEmitter from an element generator that generates each + // element of the given target array. + LoopEmitter(const ElementGenerator& target_element_generator, + const IrArray& target_array, llvm::IRBuilder<>* b); + + // Constructs a LoopEmitter that emits one element into each of N separate + // arrays on each iteration of the loop. + // + // This is used for multi-output fusion. target_element_generator must + // produce an LLVM struct with N elements. + LoopEmitter(const ElementGenerator& target_element_generator, + absl::Span target_arrays, llvm::IRBuilder<>* b); + + LoopEmitter(const LoopEmitter&) = delete; + LoopEmitter& operator=(const LoopEmitter&) = delete; + virtual ~LoopEmitter() = default; + + // Emits a loop nest (with a yet-to-be-filled loop body) that iterates through + // every element in the given shape. Returns the multi-dimensional index that + // specifies the element, will return multiple indices if the loop is + // unrolled. + virtual std::vector EmitIndexAndSetExitBasicBlock( + absl::string_view loop_name, llvm::Type* index_type, + llvm::Value* base_index); + + // Emits a complete loop nest for every element in the given shape. + Status EmitLoop(absl::string_view loop_name = "", + llvm::Type* index_type = nullptr); + + protected: + // An IR emitter that generates the loop body. + BodyEmitter body_emitter_; + + // The shape that the emitted loop iterates through. + Shape shape_; + + // Dynamic dimensions that emitted loop iterates through. Generate the + // loop based on the dynamic dimensions if this vector is not empty. + std::vector dynamic_dims_; + + // Points to the exit block of the emitted loop. If the given shape is + // scalar, no loops are emitted and exit_bb_ is nullptr in that case. + llvm::BasicBlock* exit_bb_; + + llvm::IRBuilder<>* b_; + + private: + IrArray::Index EmitStaticIndex(ForLoopNest* loop_nest, + llvm::Type* index_type); + IrArray::Index EmitDynamicIndex(ForLoopNest* loop_nest, + llvm::Type* index_type); +}; + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_LOOP_EMITTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/math_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/math_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..bc16d4cc593d647847106dd0b134beb9d7e48619 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/math_ops.h @@ -0,0 +1,32 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_MATH_OPS_H_ +#define XLA_SERVICE_LLVM_IR_MATH_OPS_H_ + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" + +namespace xla { +namespace llvm_ir { + +// Emits an approximation of tanh. The implementation uses the same rational +// interpolant as implemented in Eigen3. +llvm::Value* EmitFastTanh(llvm::IRBuilder<>* b, llvm::Value* input); + +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_MATH_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/sort_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/sort_util.h new file mode 100644 index 0000000000000000000000000000000000000000..92cfa679ae284700f8c648376338d3615d54cc0b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/sort_util.h @@ -0,0 +1,45 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_SORT_UTIL_H_ +#define XLA_SERVICE_LLVM_IR_SORT_UTIL_H_ + +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/IR/Value.h" +#include "xla/service/gpu/launch_dimensions.h" +#include "xla/service/llvm_ir/ir_array.h" +#include "tsl/platform/status.h" + +namespace xla { +namespace llvm_ir { +using EmitCallToNestedComputationCallback = + std::function, llvm::Value*)>; +// Emits llvm IR to do pairwise comparisons/swaps in the 'dimension_to_sort' +// dimension of each array in 'values_arrays'. All other dimensions are kept +// as-is. This implements the inner loop of BitonicSort. It is assumed that +// 'xor_masks' contains only powers of 2, or values 2^k - 1 (k > 0). +Status EmitSortInPlace( + int64_t dimension_to_sort, const std::vector& values_arrays, + absl::string_view name, absl::Span xor_masks, + llvm::IRBuilder<>* b, const gpu::LaunchDimensions& launch_dimensions, + int64_t num_iterations_in_sort_dim, int64_t tile_size, + const EmitCallToNestedComputationCallback& emit_compare_callback); +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_SORT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/tuple_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/tuple_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0ce8249caa9f1e6dc600a63fd82bd6384f5a7304 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/llvm_ir/tuple_ops.h @@ -0,0 +1,56 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_LLVM_IR_TUPLE_OPS_H_ +#define XLA_SERVICE_LLVM_IR_TUPLE_OPS_H_ + +#include "absl/types/span.h" +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Value.h" +#include "xla/service/llvm_ir/ir_array.h" + +// Utilities for emitting LLVM IR related to HLO tuples. + +namespace xla { +namespace llvm_ir { + +// A tuple is an array of pointers, one for each operand. Each pointer points to +// the output buffer of its corresponding operand. +void EmitTuple(const IrArray& tuple, absl::Span operands, + llvm::IRBuilder<>* b); + +// Emits one alloca for each element in the tuple of shape tuple_shape, +// returns the emitted allocas. +// Precondition: tuple_shape should be a tuple of scalars. +std::vector EmitTupleAllocasAtFunctionEntry( + const Shape& tuple_shape, llvm::IRBuilder<>* b); + +// Similar to EmitTuple above, except that the output buffers are provided in +// the form of IrArray. +void EmitTuple(const IrArray& tuple, absl::Span buffers, + llvm::IRBuilder<>* b); + +// A tuple is an array of pointers, one for each operand. Each pointer points to +// the output buffer of its corresponding operand. A GetTupleElement instruction +// forwards the pointer to underlying tuple element buffer at the given index. +// Returns an llvm value representing a pointer to the tuple element buffer. +llvm::Value* EmitGetTupleElement(const Shape& target_shape, int64_t index, + int alignment, llvm::Value* operand, + llvm::Type* operand_pointee_type, + llvm::IRBuilder<>* b); +} // namespace llvm_ir +} // namespace xla + +#endif // XLA_SERVICE_LLVM_IR_TUPLE_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.h new file mode 100644 index 0000000000000000000000000000000000000000..384c5bc46d985bf293aaa57080e94561c9fdc397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.h @@ -0,0 +1,2670 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_MEMORY_SPACE_ASSIGNMENT_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_MEMORY_SPACE_ASSIGNMENT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// TODO(b/210891274): Use btree_map after build issue in Windows is resolved. +#if defined(__GNUC__) || defined(__clang__) +#include "absl/container/btree_map.h" +#endif +#include "absl/container/flat_hash_map.h" +#include "absl/functional/function_ref.h" +#include "absl/types/span.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/service/heap_simulator.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_cost_analysis.h" +#include "xla/service/hlo_value.h" +#include "xla/service/memory_space_assignment/memory_space_assignment.pb.h" +#include "xla/service/memory_space_assignment/repacking.h" +#include "xla/shape.h" +#include "xla/statusor.h" + +namespace xla { + +namespace memory_space_assignment { +// Forward Declaration of Options. +class Options; + +inline constexpr char kConcatBitcastCustomCall[] = "ConcatBitcast"; + +// This class contains pre-set assignments determined by memory space +// assignment. It contains two data structures: (1) a chunks vector that maps a +// defining HloPosition to a Chunk (offset and size), and (2) an assignment_info +// vector that maps the memory space to information like its allocated size and +// heap memory trace. If there is only one alternate memory space like there is +// currently, there will be one entry in assignment_info. +class PresetAssignments { + public: + // Contains per-memory-space information like the allocated size and heap + // simulator trace. + struct AssignmentInformation { + int64_t size; + HeapSimulatorTrace heap_simulator_trace; + }; + + PresetAssignments() = default; + + void add_chunk(const HloPosition& position, + const HeapSimulator::Chunk& chunk) { + chunks_.emplace_back(position, chunk); + } + + void add_scoped_allocation_chunk(HloInstruction* instruction, + const HeapSimulator::Chunk& chunk) { + scoped_allocation_chunks_.emplace_back(instruction, chunk); + } + + AssignmentInformation* assignment_information_for_space( + int64_t memory_space) { + for (auto& space_and_info : assignment_info_) { + if (space_and_info.first == memory_space) { + return &space_and_info.second; + } + } + assignment_info_.emplace_back(memory_space, AssignmentInformation()); + return &assignment_info_.back().second; + } + + absl::Span> chunks() + const { + return chunks_; + } + + absl::Span> + scoped_allocation_chunks() const { + return scoped_allocation_chunks_; + } + + absl::Span> + assignment_informations() const { + return assignment_info_; + } + + // Get debugging information. + std::string buffer_info_str() const { return buffer_info_str_; } + std::string allocation_info_str() const { return allocation_info_str_; } + std::string instruction_schedule_str() const { + return instruction_schedule_str_; + } + + private: + std::vector> chunks_; + std::vector> + scoped_allocation_chunks_; + std::vector> assignment_info_; + std::string buffer_info_str_; + std::string allocation_info_str_; + std::string instruction_schedule_str_; +}; + +// A wrapper class around HloCostAnalysis with additional knowledge about the +// bandwidths of different memory spaces. +class MemorySpaceAssignmentCostAnalysis { + public: + // An optional Cache object may be provided to some of the methods below to + // speed up the lookup. + struct Cache { + absl::flat_hash_map while_nest_multiplier; + absl::flat_hash_map memory_boundedness; + }; + + // Function type that can be used to indicate which input/output values are in + // the alternate memory. + using IsInAlternateMemoryFun = absl::FunctionRef /*operand_num*/, const ShapeIndex& /*index*/, + const Shape& /*shape*/)>; + + virtual ~MemorySpaceAssignmentCostAnalysis() = default; + + static StatusOr> Create( + const HloCostAnalysis& cost_analysis, const Options& options, + const HloModule& module); + + const HloCostAnalysis& cost_analysis() const { return cost_analysis_; } + + // Returns a heuristic value that captures how much putting this tensor to the + // alternate memory would help if the op is memory bound, or otherwise how far + // off is the op to memory boundedness. The larger this number, the higher + // priority it will be placed in the alternate memory. + float GetAlternateMemoryBenefit(const HloInstruction& instruction, + float elapsed_time_due_to_alternate_mem, + Cache* cache = nullptr) const; + // Like above, return the benefit of putting the output tensor in the + // alternate memory. + float GetAlternateMemoryBenefit(const HloPosition& position, + Cache* cache = nullptr) const; + // Like above, return the benefit of putting the input tensor in the alternate + // memory. + float GetAlternateMemoryBenefit(const HloUse& use, + Cache* cache = nullptr) const; + + // Returns a heuristic value of memory boundedness for the given + // BufferInterval. The larger this number, the higher priority it will be + // placed in the alternate memory. + float GetMemoryBoundedness( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& interval, + Cache* cache = nullptr) const; + + // If enabled in Options::pipeline_overhead_window_size_mib, returns the + // overhead of accessing the default memory, in seconds. The source of the + // overhead is the software pipelining ovehead. The lowering of the operations + // typically use tiling to copy one window at a time from default memory, and + // perform compute: + // + // Pipeline overhead: <-> + // +----+----+----+----+ + // Copy from default mem: | | | | | + // +----+----+----+----+ + // \ \ \ \ + // \ \ \ \ + // V V V V + // +--+ +--+ +--+ +--+ + // Compute: | | | | | | | | + // +--+ +--+ +--+ +--+ + float GetDefaultMemoryAccessOverhead( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Returns the amount of time the default memory bandwidth is idle, while + // executing this instruction, in seconds. This value can be multiplied with + // the default memory bandwidth to get the amount of bytes that are available + // to be copied to/from default memory during the execution of this + // instruction. + float GetDefaultMemoryBandwidthIdleTime( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Returns the bytes accessed from alternate memory. + float GetBytesAccessedFromAlternateMemory( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Returns the elapsed time in seconds due to compute only. + float GetInstructionElapsedDueToCompute( + const HloInstruction& instruction) const; + + // Returns the elapsed time in seconds due to memory only. If + // operands_in_alternate_mem or outputs_in_alternate_mem is provided, it will + // assume that the corresponding operands or output will be in the alternate + // memory space. This is useful for calculating the benefit of placing the + // buffer in alternate memory. + float GetInstructionElapsedDueToMemory( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem = {}, + absl::Span outputs_in_alternate_mem = {}) const; + + // Like above, only the inputs/outputs indicated by is_in_alternate_mem are in + // the alternate memory. + float GetInstructionElapsedDueToMemory( + const HloInstruction& instruction, + IsInAlternateMemoryFun is_in_alternate_mem) const; + + // Returns the estimated elapsed duration of the instruction in seconds. It + // assumes all operands and outputs of the instruction are in the default + // memory. + virtual float GetInstructionElapsed(const HloInstruction& instruction) const; + + // Returns the estimated elapsed duration of the instruction in seconds. It + // assumes all operands and outputs of the instruction are in the default + // memory, except for the operands and outputs specified to be in the + // alternate memory. + virtual float GetInstructionElapsedInAlternateMemory( + const HloInstruction& instruction, + absl::Span> + operands_in_alternate_mem, + absl::Span outputs_in_alternate_mem) const; + + // Like above, only the inputs/outputs indicated by is_in_alternate_mem are in + // the alternate memory. + float GetInstructionElapsedInAlternateMemory( + const HloInstruction& instruction, + IsInAlternateMemoryFun is_in_alternate_mem) const; + + // Returns the elapsed time it would take to asynchronously copy the shape + // from default to alternate memory space (or vice versa). + virtual float GetAsyncCopyElapsed(const Shape& shape) const; + + int64_t GetScheduleEndTime() const; + + // Returns the number of nested computation levels this instruction resides + // in. If while_only is true, it returns the while loop nest level and 0 + // means the instruction is not in a while loop. + int CalculateComputationNestLevel(const HloInstruction* instruction, + bool while_only) const; + + const HloLiveRange& hlo_live_range() const { return *hlo_live_range_; } + const Options& options() const { return options_; } + + protected: + MemorySpaceAssignmentCostAnalysis( + const HloCostAnalysis& cost_analysis, const Options& options, + std::unique_ptr alias_analysis, + std::unique_ptr hlo_live_range, + std::unique_ptr call_graph) + : cost_analysis_(cost_analysis), + options_(options), + alias_analysis_(std::move(alias_analysis)), + hlo_live_range_(std::move(hlo_live_range)), + call_graph_(std::move(call_graph)) {} + + private: + const HloCostAnalysis& cost_analysis_; + const Options& options_; + std::unique_ptr alias_analysis_; + std::unique_ptr hlo_live_range_; + std::unique_ptr call_graph_; +}; + +// Abstract base class that memory space assignment uses to pick prefetch +// intervals. +class PrefetchIntervalPicker { + public: + PrefetchIntervalPicker() = default; + virtual ~PrefetchIntervalPicker() = default; + + // Returns true if the buffer can be allocated in alternate memory space + // without any copies (prefetches). + virtual bool CanAllocateInAlternateMemoryNoCopy(const Shape& shape, + int64_t start_time, + int64_t end_time) const = 0; + + // Returns the preferred end time for an eviction that starts at a given time + // and must end by the given end time. + virtual int64_t PreferredEvictionEndTime(const Shape& shape, + int64_t start_time, + int64_t latest_end_time) const = 0; + + // Returns the latest time that a prefetch can start. + virtual int64_t LatestPrefetchStartTime(const Shape& shape, + int64_t start_time, int64_t end_time, + const HloUse* use) const = 0; + + // Returns the preferred time that a prefetch can start. + virtual int64_t PreferredPrefetchStartTime( + const Shape& shape, int64_t earliest_prefetch_start_time, + int64_t latest_prefetch_start_time, int64_t prefetch_end_time) const = 0; + + // Returns the latest time that a prefetch can end that is less than or equal + // to proposed_prefetch_end_time. + virtual int64_t LatestPrefetchEndTime( + int64_t original_prefetch_end_time, + int64_t proposed_prefetch_end_time) const { + return proposed_prefetch_end_time; + } + + // Returns the estimated end time of a prefetch that starts at the given time. + virtual int64_t EstimatedPrefetchEndTime(const Shape& shape, + int64_t start_time, + int64_t end_time) const = 0; + + // Returns the elapsed time in seconds between the logical interval that + // corresponds to the instruction schedule. + virtual float GetLogicalIntervalElapsed(int64_t start_time, + int64_t end_time) const = 0; + + // Begins the iterator for the first start time of the prefetch. + virtual void Begin(const HloUse& use, int64_t start_time, int64_t end_time, + std::optional preferred_time) = 0; + + // Advances the start time of the prefetch and returns that value. + virtual int64_t Next() = 0; + + // Returns true if the available prefetch intervals have been exhausted. + virtual bool Done() const = 0; + + // Returns the latest time the prefetch interval picker will have pick. + virtual int64_t latest_time() const = 0; + + // The retry number can be used to modify the interval picking policies. The + // first attempt will have a retry_number of 0, then 1, etc. + virtual void SetRetryNumber(int retry_number) { + retry_number_ = retry_number; + } + int retry_number() const { return retry_number_; } + + // Returns a debug string for the current state of the prefetch interval + // picker. + virtual std::string ToDebugString() const = 0; + + // Returns a debug string for no-copy allocation. + virtual std::string ToNoCopyDebugString(const Shape& shape, + int64_t start_time, + int64_t end_time) const = 0; + + // Prefetch interval pickers may return a value corresponding to the benefit + // of placing the BufferInterval in the alternate memory. The larger value, + // the more beneficial. + virtual std::optional BufferIntervalAlternateMemoryBenefit( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& interval) + const { + return std::nullopt; + } + + protected: + const absl::flat_hash_map* + instruction_schedule_ = nullptr; + int retry_number_ = 0; +}; + +// Prefetch interval picker that uses instruction count to overlap asynchronous +// copies with independent computation. The min and max overlap counts describe +// the number of independent HLOs overlapped while a value is being prefetched +// into the alternate memory (between CopyStart and CopyDone HLO instructions). +// max_overlap_count attempts to prevent bringing tensors into the alternate +// memory too eagerly and hence occupying the space for other tensors which +// might use it. min_overlap_count attempts to prevent cases where tensors are +// prefetched into the alternate memory without sufficient time for the copy to +// take place. In those cases, it's just better to keep the tensor in the +// default memory instead of hurting the critical path with this copy that +// likely won't finish in time. +class InstructionCountPrefetchIntervalPicker : public PrefetchIntervalPicker { + public: + InstructionCountPrefetchIntervalPicker(int64_t min_overlap_count, + int64_t max_overlap_count) + : min_overlap_count_(min_overlap_count), + max_overlap_count_(max_overlap_count) {} + + bool CanAllocateInAlternateMemoryNoCopy(const Shape& shape, + int64_t start_time, + int64_t end_time) const override; + + int64_t PreferredEvictionEndTime(const Shape& shape, int64_t start_time, + int64_t latest_end_time) const override; + + int64_t LatestPrefetchStartTime(const Shape& shape, int64_t start_time, + int64_t end_time, + const HloUse* use) const override; + + int64_t PreferredPrefetchStartTime(const Shape& shape, + int64_t earliest_prefetch_start_time, + int64_t latest_prefetch_start_time, + int64_t prefetch_end_time) const override; + + int64_t EstimatedPrefetchEndTime(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + float GetLogicalIntervalElapsed(int64_t start_time, + int64_t end_time) const override; + + void Begin(const HloUse& use, int64_t start_time, int64_t end_time, + std::optional preferred_time) override; + + int64_t Next() override; + bool Done() const override; + + int64_t latest_time() const override; + + std::string ToDebugString() const override; + std::string ToNoCopyDebugString(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + + private: + int64_t min_overlap_count_; + int64_t max_overlap_count_; + int64_t end_time_; + int64_t current_prefetch_time_; +}; + +// Forward Declaration of MemorySpaceAssignmentCostAnalysis +class MemorySpaceAssignmentCostAnalysis; +// Prefetch interval picker that uses cost analysis to overlap asynchronous +// copies with independent computation. It uses min (independent computation +// duration) / (asynchronous copy duration) ratio to guide whether the prefetch +// is within the lower bound. For the upper bound, it restricts the maximum +// duration that a buffer may occupy the alternate memory space as a multiple of +// the time it would take to copy a buffer that is the size of the alternate +// memory. It starts with the preferred ratio in Begin() and works its way for +// alternately earlier and later prefetches until hitting min and max ratios. +// The value for buffer size for max async copy is a mechanism to prevent +// copying small buffers between the two memories unnecessarily. For calculating +// the max time that the buffer can reside in alternate memory, we use the +// larger of this value and the actual size of the buffer. A shape override can +// also be provided which causes the interval picker to use that shape for async +// copy durations instead of the actual shape of the copy. +class CostAnalysisPrefetchIntervalPicker : public PrefetchIntervalPicker { + public: + CostAnalysisPrefetchIntervalPicker( + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + float min_overlap_to_async_copy_ratio, + float preferred_overlap_to_async_copy_ratio, + float max_overlap_to_mem_size_async_copy_ratio, int64_t mem_size_bytes, + const Shape* shape_override = nullptr); + + bool CanAllocateInAlternateMemoryNoCopy(const Shape& shape, + int64_t start_time, + int64_t end_time) const override; + + int64_t PreferredEvictionEndTime(const Shape& shape, int64_t start_time, + int64_t latest_end_time) const override; + + int64_t LatestPrefetchEndTime( + int64_t original_prefetch_end_time, + int64_t proposed_prefetch_end_time) const override; + + int64_t LatestPrefetchStartTime(const Shape& shape, int64_t start_time, + int64_t end_time, + const HloUse* use) const override; + + int64_t PreferredPrefetchStartTime(const Shape& shape, + int64_t earliest_prefetch_start_time, + int64_t latest_prefetch_start_time, + int64_t prefetch_end_time) const override; + + int64_t EstimatedPrefetchEndTime(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + float GetLogicalIntervalElapsed(int64_t start_time, + int64_t end_time) const override; + + void Begin(const HloUse& use, int64_t start_time, int64_t end_time, + std::optional preferred_time) override; + + int64_t Next() override; + bool Done() const override; + + int64_t latest_time() const override; + + void SetRetryNumber(int retry_number) override; + + std::string ToDebugString() const override; + std::string ToNoCopyDebugString(const Shape& shape, int64_t start_time, + int64_t end_time) const override; + + std::optional BufferIntervalAlternateMemoryBenefit( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& interval) + const override; + + private: + // Finds the minimum nest level in the given interval. + int GetMinWhileNestLevel(int64_t start_time, int64_t end_time) const; + + // Given the elapsed time to copy this buffer to the alternate memory, returns + // the longest time that this buffer may reside in the alternate memory space. + float GetMaxElapsedInAlternateMemory(float async_copy_elapsed) const; + + // For each instruction in the flattened schedule, maintain their elapsed time + // (in cumulative sum) and while nesting level. + std::vector elapsed_time_cumsum_; + std::vector while_nest_level_; + std::vector computation_nest_level_; + // Maintain the index of the most recent (before this instruction) nest level + // change in order to efficiently determine the minimum nest level in an + // interval. + std::vector while_nest_level_change_; + + const MemorySpaceAssignmentCostAnalysis& cost_analysis_; + float min_overlap_to_async_copy_ratio_; + float preferred_overlap_to_async_copy_ratio_; + float max_async_copy_elapsed_; + float max_overlap_multiplier_ = 1.0; + + float async_copy_elapsed_; + float inst_elapsed_reduction_; + int64_t end_logical_time_; + int64_t earliest_prefetch_time_; + int64_t latest_prefetch_time_; + bool using_increasing_prefetch_time_iterator_ = true; + int64_t increasing_prefetch_time_iterator_; + int64_t decreasing_prefetch_time_iterator_; + + std::vector while_execution_counts_; + // Shape override is used to override the shape of the shape of the async copy + // to treat all async copies the same duration. Having an override forces + // prefetches to be scheduled roughly in FIFO order. + std::optional shape_override_; +}; + +// MemorySpaceAssignment assigns memory spaces (default or alternate) to each +// instruction in the module. It will greedily try placing as as many values in +// the alternate memory space as possible. It uses the heap simulator to +// determine the actual allocation offsets of values in the alternate memory +// space to account for fragmentation. The default memory space is assumed to be +// large enough to hold the values that could not be placed in the alternate +// memory space. +class MemorySpaceAssignment { + public: + using Chunk = HeapSimulator::Chunk; + using BufferInterval = + GlobalDecreasingSizeBestFitHeap::BufferInterval; + using BufferIntervalCompare = + GlobalDecreasingSizeBestFitHeap::BufferIntervalCompare; + using IsAllowedInAlternateMemoryFunction = + std::function; + using IsUseAllowedInAlternateMemoryFunction = + std::function; + using IsPositionAllowedInAlternateMemoryFunction = + std::function; + using ReservedScopedMemoryFunction = std::function>& /*operands_in_alternate_memory*/, + const absl::flat_hash_set& /*outputs_in_alternate_memory*/)>; + using UpdateLayoutFunction = std::function; + + // MemorySpaceAssignment uses a notion of a slow and large default memory + // space and a fast and small alternate memory space. + enum class MemorySpace { kDefault, kAlternate }; + + // Forward declaration for Allocation. + class Allocation; + class ParentAllocation; + + // This class represents an allocation that might either be in the default or + // alternate memory. An HloValue might live in multiple different allocations + // over its lifetime. The lifetimes of the allocations are defined using + // start_time and end_time, which corresponds to the instruction indexes in + // the flattened schedule. Each of these allocations might partially overlap + // with each other. CopyAllocation defined below represents asynchronous + // copies between Allocations. + // + // Consider an instruction Foo, and its users Bar and Baz, and the times given + // in terms of the flattened schedule of the entire module: + // + // Foo:10 + // / \ + // Bar:14 \ + // Baz:25 + // + // A valid memory space assignment could be like the following: + // + // Time: 10 ... 14 ... 25 + // Foo Bar Baz + // Alternate +-------+ +-----+ + // Default +---------------------+ + // ^ ^ ^ ^ + // | | | | + // evict evict prefetch prefetch + // start end start end + // + // This would be represented with: + // - Allocation(memory_space=kAlternate, start_time=10, end_time=14) + // - CopyAllocation(memory_space=kDefault, start_time=12, end_time=25) + // - CopyAllocation(memory_space=kAlternate, start_time=22, end_time=25) + class Allocation { + friend class ParentAllocation; + + public: + Allocation(HloPosition defining_position, MemorySpace memory_space, + std::optional chunk, int64_t start_time, int64_t end_time, + bool is_scoped_allocation) + : defining_position_(defining_position), + memory_space_(memory_space), + chunk_(chunk), + start_time_(start_time), + end_time_(end_time), + is_scoped_allocation_(is_scoped_allocation) { + CHECK(!is_scoped_allocation || defining_position.index == ShapeIndex({})); + } + virtual ~Allocation() = default; + + // True if the allocation is for a copy or a sliced-copy. + bool is_copy_like_allocation() const; + + virtual bool is_copy_allocation() const { return false; } + virtual bool is_sliced_copy_allocation() const { return false; } + + // Adds a use to this allocation. + void AddUse(HloUse use); + + // Extends the end time of this allocation. + void Extend(int64_t end_time) { end_time_ = std::max(end_time_, end_time); } + + // After all of the time ranges for the allocations have been assigned, + // Process morphs the instructions affected to assign the memory spaces and + // insert asynchronous copy instructions if necessary. + virtual Status Process(); + + // An optional post-process step that will be called after all allocations + // have been processed. + virtual Status PostProcess() { return OkStatus(); } + + // Marks (adds this allocation to needed_allocations) if this allocation is + // needed. Allocation and CopyAllocations are always needed and + // ParentAllocations are needed if they have any uses or if other + // CopyAllocation or ParentAllocations depend on them. + virtual void MarkIfNeeded( + absl::flat_hash_set& needed_allocations) const; + + // Marks this allocation as needed. + virtual void MarkNeeded( + absl::flat_hash_set& needed_allocations) const; + + // Returns the defining position for this allocation. + virtual HloPosition defining_position() const { return defining_position_; } + + // Returns the time the buffer is first available to be used. For + // Allocation, this is start_time. + virtual int64_t earliest_available_time() const { return start_time_; } + + const std::vector& uses() const { return uses_; } + void clear_uses() { uses_.clear(); } + MemorySpace memory_space() const { return memory_space_; } + // Returns the associated chunk that may be a nullopt if the allocation is + // in the default memory space. + std::optional maybe_chunk() const { return chunk_; } + // Returns the associated chunk. The caller should ensure that the chunk is + // defined (the allocation should be in the alternate memory space). + Chunk chunk() const { + CHECK(chunk_.has_value()); + return *chunk_; + } + Chunk* mutable_chunk() { return &*chunk_; } + void set_offset(int64_t offset); + void set_start_time(int64_t start_time) { start_time_ = start_time; } + void set_end_time(int64_t end_time) { end_time_ = end_time; } + int64_t start_time() const { return start_time_; } + int64_t end_time() const { return end_time_; } + bool is_scoped_allocation() const { return is_scoped_allocation_; } + virtual std::optional cross_program_prefetch_index() const { + return std::nullopt; + } + + bool operator==(const Allocation& other) const; + virtual std::string ToString() const; + + bool is_in_alternate_mem() const { + return memory_space_ == MemorySpace::kAlternate; + } + bool is_in_default_mem() const { + return memory_space_ == MemorySpace::kDefault; + } + + protected: + // Recursively create kGetTupleElement instructions if the defining position + // shape is not an array. Returns the new instruction that has array shape. + HloInstruction* AddGetTupleElements() const; + + HloPosition defining_position_; + std::vector uses_; + MemorySpace memory_space_; + std::optional chunk_; + int64_t start_time_; + int64_t end_time_; + const bool is_scoped_allocation_; + }; + + // This class represents an allocation as a result of an asynchronous copy. + // Note: CopyStart instructions are inserted after `start_time` or later, + // while CopyDone instructions are inserted before + // `copy_done_schedule_before_time` or earlier. + class CopyAllocation : public Allocation { + public: + CopyAllocation( + Allocation& prev_allocation, MemorySpace memory_space, + std::optional chunk, int64_t start_time, int64_t end_time, + int64_t copy_done_schedule_before_time, + std::optional cross_program_prefetch_index = std::nullopt) + : Allocation(/*defining_position=*/{nullptr, {}}, memory_space, chunk, + start_time, end_time, /*is_scoped_allocation=*/false), + prev_allocation_(prev_allocation), + copy_start_schedule_after_(start_time), + copy_done_schedule_before_(copy_done_schedule_before_time), + cross_program_prefetch_index_(cross_program_prefetch_index) {} + + bool is_copy_allocation() const override { return true; } + + Status Process() override; + + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + HloPosition defining_position() const override { + // Unless explicitly set, the defining position of a copy allocation in + // retrieved from the previous allocation. This is because we don't create + // new CopyStart/CopyDone instructions until later and the position should + // point to the previous (copy or otherwise) allocation's position for the + // original defining position. + if (defining_position_.instruction == nullptr) { + return prev_allocation_.defining_position(); + } + return defining_position_; + } + + HloInstruction* copy_start() const { return copy_start_; } + HloInstruction* copy_done() const { return copy_done_; } + + // Returns the time the buffer is first available to be used. For + // CopyAllocation, this is when the copy ends, which is + // copy_done_schedule_before. + int64_t earliest_available_time() const override { + return copy_done_schedule_before_; + } + + int64_t copy_start_schedule_after() const { + return copy_start_schedule_after_; + } + int64_t copy_done_schedule_before() const { + return copy_done_schedule_before_; + } + + void set_copy_start_schedule_after(int64_t copy_start_schedule_after) { + copy_start_schedule_after_ = copy_start_schedule_after; + } + + void set_copy_done_schedule_before(int64_t copy_done_schedule_before) { + copy_done_schedule_before_ = copy_done_schedule_before; + } + + std::optional cross_program_prefetch_index() const override { + return cross_program_prefetch_index_; + } + + bool operator==(const CopyAllocation& other) const; + std::string ToString() const override; + + const Allocation& prev_allocation() { return prev_allocation_; } + Allocation& mutable_prev_allocation() { return prev_allocation_; } + + private: + Allocation& prev_allocation_; + // These variables define the scheduling boundaries where CopyStart and + // CopyDone can be scheduled. The earliest CopyStart can be scheduled is + // after copy_start_schedule_after_ and the latest CopyDone can be scheduled + // is before copy_done_schedule_before_. + int64_t copy_start_schedule_after_; + int64_t copy_done_schedule_before_; + HloInstruction* copy_start_; + HloInstruction* copy_done_; + std::optional cross_program_prefetch_index_; + }; + + // The parameters for slicing a single dimension of a tensor. + struct SliceParam { + std::string ToString() const; + bool operator==(const SliceParam& other) const; + + int64_t start_inclusive; + int64_t end_exclusive; + }; + + // A proposed way to slice a buffer. + struct SliceProposal { + std::string ToString() const; + friend std::ostream& operator<<(std::ostream& os, + const SliceProposal& proposal); + std::tuple&, int64_t> + ToTuple() const; + bool operator==(const SliceProposal& other) const; + + // Shape resulting from the slice. + Shape slice_shape; + + // slice_params map to the parameters that would be passed to a slice + // instruction. Thus: + // * There should be a slice parameter for every dimension in the shape of + // the tensor being sliced. + // * The ith slice_param applies to the ith logical dimension in the shape + // being sliced. + // * If a dimension is not being sliced, it should have a SliceParam of + // {0, dim size}. + std::vector slice_params; + + // The size to be allocated for the slice. Note, this may be > the size of + // the slice shape, due to additional padding that may occur when the slices + // are concatenated back together. + int64_t slice_size; + }; + + // A SliceProposalCollection proposes a way to to slice an AllocationRequest. + // A SliceProposalCollection is generated from a SliceProposalFunction and is + // used when we want to slice a prefetch. + using SliceProposalCollection = std::vector; + using SliceProposalFunction = std::function( + const Shape& shape, const SlicedPrefetchOptions& options)>; + + // A SliceDecision is a SliceProposal that we've determined where and when to + // allocate. + struct SliceDecision { + std::string ToString() const; + bool operator==(const SliceDecision& other) const; + + Chunk chunk; + int64_t start_time; + SliceProposal sizing; + float copy_resource_consumed; + }; + + // This class represents an allocation resulting from asynchronous sliced + // copies. + // + // Let the sliced allocation be represented as follows, and imagine that t3 + // is the time when the entire buffer [p0, p3) is available for use + // + // space + // ^ + // p3 | +-----------+ + // | | | + // p2 | +---+ | + // | | | + // p1 | +-------+ | + // | | | + // p0 | +-------+ + // +---|---|---|---|---|----> time + // t0 t1 t2 t3 t4 + // + // The Allocation underlying the SlicedCopyAllocation will use the following + // dimensions: + // - chunk = [p0, p3) + // - start time = t2 + // - earliest_available_time = t3 + // - end_time = t4 + class SlicedCopyAllocation : public Allocation { + public: + // Full details about a slice in the sliced allocation. + struct SliceDetail { + std::string ToString() const; + std::tuple + ToTuple() const; + bool operator==(const SliceDetail& other) const; + + // Create the instructions to copy the slice. This method updates + // copy_start and copy_done. Given a Shape, the hardware may have + // constraints on how the shape is physically laid out in memory. + // update_layout_fn updates a Shape's layout in accordance with those + // constraints. + Status CreateAsyncSlice(const Shape& original_shape, + HloInstruction& producer, HloComputation& parent, + absl::FunctionRef update_layout_fn); + + SliceDecision slice_decision; + int64_t copy_start_after_time = -1; + int64_t copy_done_before_time = -1; + HloInstruction* copy_start = nullptr; + HloInstruction* copy_done = nullptr; + }; + + // REQUIRES: + // - slice_decisions_sorted_by_start_time.size() >= 2, otherwise, + // CopyAllocation should be used. + SlicedCopyAllocation( + const Allocation& prev_allocation, MemorySpace memory_space, + std::vector slice_decisions_sorted_by_start_time, + int64_t end_time, int64_t copy_done_schedule_before_time, + absl::FunctionRef update_layout_fn); + + bool is_sliced_copy_allocation() const override { return true; } + + // MemorySpaceAssignment::Process() calls Process() to create asynchronous + // slice copies, and a bitcast-concat call to glue the slices back together. + Status Process() override; + + // Marks the allocation as needed. + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + // Returns the defining position for this allocation. + HloPosition defining_position() const override; + + // Returns the time the buffer is first available to be used. For + // SlicedCopyAllocation, this is when all copies have ended. + int64_t earliest_available_time() const override; + + std::vector SliceOffsetsSortedByStartTime() const; + void AddDiffToAllSliceOffsets(int64_t diff); + + // Used to update offsets and start times after repacking. + void ImportRepackedSliceData( + const MemorySpaceAssignmentRepacker::SlicedAllocationData& data); + + const std::vector& slice_details_sorted_by_start_time() const; + std::vector& mutable_slice_details_sorted_by_start_time(); + HloInstruction* concat() const { return concat_; } + + std::tuple&, + const HloInstruction*> + ToTuple() const; + bool operator==(const SlicedCopyAllocation& other) const; + std::string ToString() const override; + + private: + SlicedCopyAllocation() = delete; + + // Create an instruction to concatenate the slices. Populates concat_. + Status CreateBitcastConcat(const Shape& shape, + absl::Span slices); + + Shape original_shape_to_slice_; + const Allocation& prev_allocation_; + // REQUIRES: + // - sorted_segments_[i].copy_start_after_time <= + // sorted_segments_[i+j].copy.start_after_time + // - sorted_segments_[i].copy_done_before_time <= + // sorted_segments_[i+j].copy.start_before_time + std::vector slice_details_sorted_by_start_time_; + HloInstruction* concat_ = nullptr; + absl::FunctionRef update_layout_fn_; + }; + + // An allocation in the default memory space that mirrors another Allocation + // object. This is useful to model an eviction that happens before a while op + // so that we don't need to redundantly evict the buffer after the while op as + // well. + class MirroredAllocation : public Allocation { + public: + MirroredAllocation(const Allocation& original_allocation, int64_t time) + : Allocation(original_allocation.defining_position(), + MemorySpace::kDefault, original_allocation.maybe_chunk(), + /*start_time=*/time, + /*end_time=*/time, /*is_scoped_allocation=*/false), + original_allocation_(original_allocation) {} + + Status Process() override; + + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + std::string ToString() const override; + + private: + const Allocation& original_allocation_; + }; + + // An allocation in default memory space that is defined in the parent + // computation. If a value has a copy in the default memory space in the + // parent computation, we don't need to evict this buffer in a while loop. + class ParentAllocation : public Allocation { + public: + ParentAllocation(const Allocation& original_allocation, + HloInstruction* calling_instruction, HloPosition position, + int64_t time) + : Allocation(position, MemorySpace::kDefault, + original_allocation.maybe_chunk(), /*start_time=*/time, + /*end_time=*/time, /*is_scoped_allocation=*/false), + original_allocation_(original_allocation), + calling_instruction_(calling_instruction) {} + + Status Process() override; + Status PostProcess() override; + + void MarkIfNeeded(absl::flat_hash_set& + needed_allocations) const override; + void MarkNeeded(absl::flat_hash_set& needed_allocations) + const override; + + std::string ToString() const override; + + private: + const Allocation& original_allocation_; + HloInstruction* calling_instruction_; + }; + + using AllocationSequence = std::vector>; + // AllocationValue is used to break up HloValues for each non-trivial position + // (trivial positions are considered Tuple, GetTupleElement, and Bitcast). An + // HloValue may include positions and uses that alias with each other across + // multiple computations. We use this class to break these HloValues such that + // every AllocationValue has one defining position (that may alias with other + // AllocationValues). The uses field of the AllocationValue contains only the + // direct uses of the AllocationValue's defining position. + // + // For example, consider the following HLO snippet: + // + // Body { + // body_param = (f32[4,3]{1,0}, f32[]) parameter(0) + // get-tuple-element.3 = f32[4,3]{1,0} get-tuple-element(body_param), + // index=0 + // ... + // ROOT tuple = (f32[4,3]{1,0}, f32[]) tuple(get-tuple-element.3, ...) + // } + // + // Cond { + // cond_param = (f32[4,3]{1,0}, f32[]) parameter(0) + // ... + // } + // + // add.4 = f32[4,3]{1,0} add(...) + // tuple.1 = (f32[4,3]{1,0}, f32[]) tuple(add.4, ...) + // while = (f32[4,3]{1,0}, f32[]) while(tuple.1), body=Body, condition=Cond + // get-tuple-element.5 = f32[4,3]{1,0} get-tuple-element(while), index=0 + // add.5 = f32[4,3]{1,0} add(get-tuple-element.5, ...) + // + // This contains an HloValue that looks like the following: + // positions: + // add.4 + // body_param {0} + // get-tuple-element.3 + // tuple {0} + // cond_param {0} + // tuple.1 {0} + // while {0} + // get-tuple-element.5 + // uses: + // add.1, operand 0 + // tuple, operand 0 + // while, operand 0 {0} + // add.5, operand 0 + // + // We break this HloValue up into the following AllocationValues for each + // non-trivial position: + // AllocationValue1: computation = Entry + // position: + // add.4 + // uses: + // while, operand 0 {0} + // AllocationValue2: computation = Cond + // position: + // cond_param {0} + // uses: + // AllocationValue3: computation = Body + // position: + // body_param {0} + // uses: + // add.1, operand 0 + // tuple, operand 0 + // AllocationValue4: computation = Entry + // position: + // while {0} + // uses: + // add.5, operand 0 + class AllocationValue { + public: + // This data structure wraps an HloUse and adds additional metadata that are + // useful for allocation. + struct Use { + // The wrapped HloUse object. + HloUse hlo_use; + // The logical time this use is scheduled. + int64_t time; + // All the positions where this use aliases with. The aliased positions + // must get the same allocation. + std::vector aliases; + + bool operator==(const Use& other) const { + return hlo_use == other.hlo_use && time == other.time && + aliases == other.aliases; + } + + template + friend H AbslHashValue(H h, const Use& s) { + return H::combine(std::move(h), s.hlo_use, s.time, s.aliases); + } + }; + + AllocationValue(const HloValue* value, const HloPosition& position, + int64_t size) + : value_(value), + defining_position_(position), + size_(size), + requires_contiguous_allocation_(false) {} + + const HloPosition& defining_position() const { return defining_position_; } + const HloInstruction* defining_instruction() const { + return defining_position().instruction; + } + int64_t size() const { return size_; } + const std::vector& uses() const { return uses_; } + std::vector& uses() { return uses_; } + const HloValue* value() const { return value_; } + const HloComputation* computation() const { + return defining_instruction()->parent(); + } + AllocationSequence* mutable_allocation_sequence() { + return &allocation_sequence_; + } + const AllocationSequence* allocation_sequence() const { + return &allocation_sequence_; + } + + // Sets/gets whether this AllocationValue requires allocating it + // contiguously throughout its live range (without any copies). + bool requires_contiguous_allocation() const { + return requires_contiguous_allocation_; + } + void set_requires_contiguous_allocation( + bool requires_contiguous_allocation) { + requires_contiguous_allocation_ = requires_contiguous_allocation; + } + + void AddUse(const HloUse& use, int64_t use_time) { + uses_.push_back({use, use_time, {}}); + } + + std::string ToString() const; + std::string ToShortString() const; + + private: + const HloValue* value_; + HloPosition defining_position_; + int64_t size_; + // If true, there must be a contiguous allocation for this buffer without + // any copies. + bool requires_contiguous_allocation_; + std::vector uses_; + AllocationSequence allocation_sequence_; + }; + + // Statistics of asynchronous copies. + struct AsyncCopyStats { + // Includes both async copies and async sliced copies. + int64_t max_outstanding_async_copies = 0; + // Includes both async copies and async sliced copies. + int64_t num_prefetches = 0; + int64_t num_sliced_prefetches = 0; + int64_t num_sliced_prefetch_slices = 0; + int64_t prefetch_bytes = 0; + int64_t num_evictions = 0; + int64_t eviction_bytes = 0; + }; + + virtual ~MemorySpaceAssignment() = default; + + // Runs the MemorySpaceAssignment pass. + static StatusOr> Run( + HloModule* module, const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis, const Options& options); + + // Calculates asynchronous copy statistics. + StatusOr CalculateAsyncCopyStats() const; + + static BufferIntervalCompare GetMemoryBoundednessBufferIntervalCompare( + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + MemorySpaceAssignmentCostAnalysis::Cache* cache = nullptr); + + // Verify that the memory space assignment is free of overlapping buffers and + // export heap simulator trace to be used by buffer_assignment. + Status VerifyAndExportHeapSimulatorTrace(); + + protected: + // Main driver of the memory space assignment pass. + virtual StatusOr> RunMemorySpaceAssignment( + const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis); + + // Finds an AllocationSequence for placing buffers in alternate memory using + // the AlternateMemoryBestFitHeap algorithm. Must be set before Process() is + // called. + virtual Status FindAllocationSequence(const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis); + + const Options& options() const { return options_; } + + MemorySpaceAssignment(HloModule* module, const Options& options, + const HloLiveRange& hlo_live_range) + : module_(module), + options_(options), + flattened_instructions_(hlo_live_range.flattened_instruction_sequence() + .instructions() + .begin(), + hlo_live_range.flattened_instruction_sequence() + .instructions() + .end()), + computations_in_schedule_(), + preset_assignments_(std::make_unique()) { + for (const auto& computation_and_bound : + hlo_live_range.computation_span_times()) { + computations_in_schedule_.insert(computation_and_bound.first); + } + } + + AllocationSequence allocations_; + + HloModule* module() { return module_; } + + private: + // Process calls Process methods of the allocations after the allocations have + // been finalized. + Status Process(const HloLiveRange& hlo_live_range); + + // Process() might have altered the computation graph by inserting kTuple and + // kGetTupleElement instructions. SimplifyGraph performs a simple DCE and + // tuple simplification operation (e.g., given GetTupleElement(Tuple(a, b), + // 1), simply forwards b). Runs to fixed point. + Status SimplifyGraph(); + + // FixSchedule inserts asynchronous copies in the schedule. + Status FixSchedule(); + + // Export the alternate memory assignments to the PresetAssignments and color + // the HLO graph with the determined memory spaces. + Status ExportAndColorBuffers(); + + // Schedules asynchronous copies and ensures that the CopyStarts and their + // corresponding CopyDones follow the same order. + void ScheduleAsynchronousCopies(); + + // Remove the positions and chunks associated with the instruction from + // alternate_memory_assignments_. + void RemoveAssignmentForInstruction(const HloInstruction* instruction); + + // Returns the estimated elapsed duration of the hlo module in seconds. It + // uses the 'allocations' argument to determine the location (default memory + // or alternate memory) of each operand and output of an instruction. + float ComputeEstimatedElapsedTime(const HloLiveRange& hlo_live_range, + const AllocationSequence& allocations); + + HloModule* module_; + const Options& options_; + std::vector flattened_instructions_; + absl::flat_hash_set computations_in_schedule_; + std::unique_ptr preset_assignments_; + std::vector> alternate_memory_assignments_; + std::vector> scoped_memory_assignments_; + int64_t alternate_memory_size_ = 0; + + // These maps hold vectors of new instructions that need to be scheduled after + // (or before) the instruction index in the key. FixSchedule uses these maps + // to modify and fix the schedule. + absl::flat_hash_map> schedule_after_; + absl::flat_hash_map> schedule_before_; +}; + +// Filters prefetches by matching against multiple filters and overrides the +// preferred prefetch time for matching prefetches by the provided override +// strategy. +class FilterUpdatePreferredPrefetch { + public: + // Supported filters for prefetch filtering by operand size, instruction name, + // operand number and operand index matching. + enum class FilterType { + OP_SIZE_LTE, // sting value: op_size_lte, filter value type: integer + OP_SIZE_GTE, // sting value: op_size_gte, filter value type: integer + INSTRUCTION_NAME_EXACT, // sting value: instruction_name_exact, + // filter value type: string + OP_NUMBER_EXACT, // sting value: op_number_exact, + // filter value type: integer + OP_INDEX_EXACT // sting value: op_index_exact, filter value type: string + // (empty string for {}, 1 for {1} and 1#2 for {1,2}) + }; + // Strategies to compute new perferred prefetch time. Prefetch eagerness + // sets prefetch time to a time within the live-range depending on a value, + // e.g. 0.5 sets it exactly in the middle of the live-range. Put after + // instruction or put before instruction finds an instruction in the schedule + // and puts the preferred prefetch time before or after the found instruction. + enum class OverrideType { + PREFETCH_EAGERNESS, // sting value: prefetch_eagerness, + // override value type : float + PUT_AFTER_INSTRUCTION, // sting value: put_after_instruction, + // override value type: string + PUT_BEFORE_INSTRUCTION // sting value: put_before_instruction, + // override value type: string + }; + std::vector> filter_list_; + OverrideType override_type_; + std::string override_value_; + + std::string ToString() const { return config_string_; } + + static StatusOr> + ParseFilterUpdatePreferredPrefetches(std::string config); + + static StatusOr IsOpSizeGte(int64_t operand_size, std::string config); + + static StatusOr IsOpSizeLte(int64_t operand_size, std::string config); + + static StatusOr IsInstructionNameExact( + absl::string_view instruction_name, std::string config); + + static StatusOr IsOpNumberExact(int64_t operand_number, + std::string config); + + static StatusOr IsOpIndexExact(const ShapeIndex& operand_index, + std::string config); + + StatusOr> GetPrefetchByEagerness( + int64_t earliest_prefetch_time, int64_t latest_prefetch_time) const; + + StatusOr> GetPrefetchTimeAfterInstruction( + const absl::flat_hash_map& schedule) + const; + + StatusOr> GetPrefetchTimeBeforeInstruction( + const absl::flat_hash_map& schedule) + const; + + private: + std::string config_string_; + StatusOr GetScheduleTimeFromInstructionName( + const absl::flat_hash_map& schedule) + const; + + static StatusOr ParseFilterType(std::string config); + + static StatusOr ParseOverrideType(std::string config); + + static StatusOr ParseOperandIndex(std::string config); + + static StatusOr + ParseFilterUpdatePreferredPrefetch(std::string config); +}; + +// The different options to be passed to the Run() API. +struct Options { + // Backend-specific integer value that describes the alternate memory. + int64_t alternate_memory_space = 0; + + // Maximum size of the alternate memory space. + int64_t max_size_in_bytes = 0; + + // Memory alignment of the alternate memory space. + int64_t alignment_in_bytes = 1; + + // If provided, we sort the buffers using this comparison function + // otherwise, we use GlobalDecreasingSizeBestFitHeap::kSpatial. + std::optional + buffer_interval_compare = std::nullopt; + + // This object determines how early and how late prefetches can occur. + PrefetchIntervalPicker* prefetch_interval_picker = nullptr; + + // This object is used to determine the benefit of a particular allocation. + MemorySpaceAssignmentCostAnalysis* cost_analysis = nullptr; + + // Size function for buffer values. + BufferValue::SizeFunction size_fn; + + // This function can be used to prevent certain HloValues (e.g., based on + // the opcode) to be placed on the alternate memory. + MemorySpaceAssignment::IsAllowedInAlternateMemoryFunction + is_allowed_in_alternate_mem_fn; + + // This function can be used to prevent certain HloUses (e.g., based on + // the opcode) to be placed on the alternate memory. + MemorySpaceAssignment::IsUseAllowedInAlternateMemoryFunction + is_use_allowed_in_alternate_mem_fn = [](const HloUse&) { return true; }; + + // Specifies if the given position is allowed in the alternate memory. + MemorySpaceAssignment::IsPositionAllowedInAlternateMemoryFunction + is_position_allowed_in_alternate_mem_fn = + [](const HloPosition&) { return true; }; + + // This function returns the amount of scoped memory in bytes that should be + // reserved during the execution of this instruction. + MemorySpaceAssignment::ReservedScopedMemoryFunction + reserved_scoped_memory_fn = + [](const HloInstruction*, + const absl::flat_hash_set< + std::pair>& /*operands_in_alternate_memory*/, + const absl::flat_hash_set< + ShapeIndex>& /*outputs_in_alternate_memory*/) { return 0; }; + + // If true, we will try to reduce scoped allocation buffer size for all + // instructions if their operand/output has been allocated in alternate + // memory. + bool reduce_scoped_memory_limit = false; + + // If true, we allocate the reserved scoped memory at the same offset. This + // is useful to enable more deduplication between HLOs that have reserved + // scoped memories, but may result in less efficient memory packing. + bool allocate_reserved_scoped_memory_at_same_offset = true; + + // Specifies the upper bound for number of outstanding prefetches and + // evictions, -1 for unlimited. + int64_t max_outstanding_prefetches = -1; + int64_t max_outstanding_evictions = -1; + + // Extra outstanding prefetch limit for while uses (in addition to + // max_outstanding_prefetches). + int64_t while_use_extra_outstanding_prefetch_limit = 0; + + // Specifies the maximum number of retries that will be performed for each + // value in case prefetching failed due to running out of asynchronous + // copies or asynchronous copy resource. + int64_t max_retries = 1; + + // The maximum number of repacks that we are willing to perform in case we + // can't allocate a buffer due to running out of memory. If this value is + // greater than 0, repacker must be non-nullptr. + int64_t max_repacks = 0; + + // This variable is used by the cost analysis in estimating how many times + // each while loop will execute. Nested loops will be assumed to have + // executed pow(while_execution_count, nesting_level) times. + uint64_t xla_tpu_memory_space_assignment_while_execution_count = 5ULL; + + // This variable is used to scale the alternate memory benefit factor for + // large buffers. The default scaling function is sqrt. + std::string + xla_tpu_alternate_memory_benefit_scaling_factor_for_large_buffers = + "SQRT"; + + float async_copy_bandwidth_bytes_per_second = 0.0f; + + float alternate_mem_bandwidth_bytes_per_second = 0.0f; + + // The repacking algorithm to reduce fragmentation. Must be non-null if + // max_repacks is greater than 0. + MemorySpaceAssignmentRepacker* repacker = nullptr; + + // This is only useful for testing, repack after every allocation. + bool repack_after_every_allocation = false; + + // If true, tries allocating buffers across (e.g., before and inside a while + // loop body) sequential calls (kWhile, kCall, and kConditional). + bool allocate_across_sequential_calls = false; + + // If true, verifies the memory space assignment against overlapping + // buffers. + bool verify = false; + + // If not nullptr, this function is called to dump debugging information. + // The first argument is appended to the file name and the second argument + // is the contents of the file. + std::function dump_fn = nullptr; + + // Enable prefetching buffers into preferred memory across program + // boundaries + bool enable_cross_program_prefetch = true; + + // If true, use buffer_interval_compare to determine which buffers to + // prefetch across program boundaries. + bool default_cross_program_prefetch_heuristic = false; + + // Enable cross-program prefetch freeing optimization where the + // cross-program-prefetched buffer can be reused. + bool enable_cross_program_prefetch_freeing = true; + + // The maximum number of cross program prefetches. + // TODO(tjablin): Use a heuristic to determine this automatically. + int max_cross_program_prefetches = 1; + + // Enable redundant eviction optimization in/around while loops. If enabled, + // this optimization would keep a copy of the buffer in the default memory in + // addition to alternate memory to eliminate redundant evictions. + bool enable_while_redundant_eviction_elimination = true; + + // An optional memory space assignment autotuning config, which is used + // to sort allocated buffers. + std::optional> autotuning_config = std::nullopt; + + // Scales effective bandwidth for async copies. Valid range is (0, 1]. + float async_copy_bandwidth_scaling_factor = 1.0; + + // If true, uses the earlier instance of the same instruction to use as + // preferred prefetch start time. + bool use_repeated_instance_for_preferred_prefetch_time = false; + + // If true, enforces the FIFO order for prefetches. + bool enforce_prefetch_fifo_order = false; + + // The ratio of use bytes to copy bytes for a given allocation site below + // which we consider the site to be inefficient. A value of 0 would treat all + // sites as efficient and a value of 1 would require the amount of bytes used + // at the site to be at least as much as the async copy bytes. There are two + // factors that determine the copy and use bytes: + // - Some uses don't actually access the entire tensor, e.g. in + // dynamic-update-slice. + // - copy_bytes may be larger than the size of the tensor as well. An + // example is a tensor may be prefetched, used, and then evicted. In that + // case copy_bytes would be twice the size of the tensor. + float inefficient_use_to_copy_ratio = 0.0; + + // This is mostly used for testing, it allows a test case to inject its own + // logic for AlternateMemoryBestFitHeap::GetInefficientAllocationSites. + std::function>( + absl::Span)> + get_inefficient_allocation_sites_fn = nullptr; + + // The window size used to calculate the pipeline overhead when HLO accesses + // the default memory, in MiB. + float pipeline_overhead_window_size_mib = 0; + + // Config to filter prefetches and update preferred prefetch times for the + // filtered prefetches according to an update config. + std::vector filter_update_preferred_prefetches; + + // Options for slicing prefetches into smaller asynchronously copied pieces. + SlicedPrefetchOptions sliced_prefetch_options; + + // Options for the memory-bound loop optimizer feature. + MemoryBoundLoopOptimizerOptions memory_bound_loop_optimizer_options; + + // A function for updating shape layouts. + MemorySpaceAssignment::UpdateLayoutFunction update_layout_fn = [](Shape*) {}; + + MemorySpaceAssignment::SliceProposalFunction propose_slice_fn = + [](const Shape&, const SlicedPrefetchOptions&) + -> xla::StatusOr { + return UnimplementedStrCat("Generation of SliceProposals unimplemented"); + }; + + // Option to always spill buffers from alternate memory to default memory + // and prefetching back to alternate memory(if needed) just in time for use. + bool always_spill_to_default_memory = false; +}; + +// A struct representing an asynchronous copy with its logical start and end +// time (time that copy done is scheduled), the resource this copy would use, +// its destination memory space, and a unique ID. +struct AsynchronousCopy { + int64_t start_time; + int64_t end_time; + float resource; + MemorySpaceAssignment::MemorySpace destination; + int64_t id; + + std::tuple + AsTuple() const { + return std::make_tuple(start_time, end_time, resource, destination, id); + } +}; + +// Compare asynchronous copies such that an earlier start time has the same or +// earlier end time and an earlier end time has the same or earlier start time. +bool operator<(const AsynchronousCopy& a, const AsynchronousCopy& b); + +bool operator==(const AsynchronousCopy& a, const AsynchronousCopy& b); +bool operator!=(const AsynchronousCopy& a, const AsynchronousCopy& b); + +// Helper class to enforce asynchronous copy ordering. If the appropriate option +// is enabled, we only allow asynchronous copies that are pipelined: if an +// asynchronous copy ends earlier than another asynchronous copy, it must start +// the same time or earlier than the other asynchronous copy; and if an +// asynchronous copy starts earlier than another asynchronous copy, it must end +// the same time or earlier than the other asynchronous copy. +class AsynchronousCopyOrdering { + public: + AsynchronousCopyOrdering() = default; + + // Adds an asynchronous copy. + void AddCopy(const AsynchronousCopy& copy); + + // Removes an asynchronous copy. CHECKs that it is removed. + void RemoveCopy(const AsynchronousCopy& copy); + + // Returns true if the addition of an asynchronous copy in the given time + // interval would violate the asynchronous copy ordering. E.g., consider the + // following scenario: + // CS CD + // already committed async copy: +-----------+ + // new async copy: +--------+ + // + // The new asynchronous copy would violate the ordering guarantee because the + // copy start is after an already committed asynchronous copy while its copy + // done is before the committed copy. + bool ViolatesOrdering(int64_t start_time, int64_t end_time) const; + + private: + // We use this data structure for keys into the map that has a custom + // comparator for the ordering guarantees. + struct Interval { + int64_t start_time; + int64_t end_time; + + // We allow multiple prefetches that have one or both of the same start and + // end times. std::map considers two values as equal if neither are less + // than the other. Using this comparator, we can ensure that the only + // intervals that evaluate to be equal are those with the same start and end + // times or those with intervals that violate the FIFO order. + bool operator<(const Interval& other) const { + return (start_time < other.start_time && end_time <= other.end_time) || + (start_time <= other.start_time && end_time < other.end_time); + } + }; + // Stores asynchronous copies in a tree set respecting the pipelining order. + std::map> ranges_; +}; + +// Helper class to enforce asynchronous copy resources by keeping track of +// available copy bandwidth and elapsed times of overlapped operations. It +// maintains a list of initial resources that correspond to the elapsed times of +// overlapped operations. As asynchronous copies are added, the available +// resource is subtracted to keep track of the current state. +class AsynchronousCopyResource { + public: + // A specification of needed asynchronous copy resources. + struct ResourceSpec { + int64_t start_time; + int64_t end_time; + float resource; + }; + + AsynchronousCopyResource() = default; + + // The constructor needs the initial resources. + explicit AsynchronousCopyResource(absl::Span initial_resources) + : initial_resources_(initial_resources.begin(), initial_resources.end()), + delay_(initial_resources.size(), 0) {} + + // Adds the given asynchronous copy and updates the current resources. CHECK + // fails if there aren't enough resources to satisfy this copy (the caller + // should use HasEnoughResource first to ensure there is enough resource). + void AddCopy(const AsynchronousCopy& copy); + + // Removes the given copy and frees the resource. + void RemoveCopy(const AsynchronousCopy& copy); + + // Returns true if a copy with the given start and end times and resource can + // be satisfied. + bool HasEnoughResource(int64_t start_time, int64_t end_time, float resource); + + // Returns true if a set of copy specifications can be satisfied in the + // order specified. + bool HasEnoughResourceMultiCheck(const std::vector& specs); + + // This is only used for debugging and testing purposes, it returns the + // currently available resource at each logical time. + std::vector GetCurrentResources() const { + std::vector current_resources(initial_resources_.begin(), + initial_resources_.end()); + for (int i = 0; i < current_resources.size(); ++i) { + current_resources[i] -= std::min(current_resources[i], delay_[i]); + } + return current_resources; + } + + // A useful debugging tool for printing several pieces of information about + // AsynchronousCopyResource. + std::string Dump( + int64_t start_time, int64_t end_time, + MemorySpaceAssignment::MemorySpace memory_space_filter) const; + + private: + // Internal helper method to implement adding/removing/checking resources. + // ConsumeResource() may modify delay_. If delay_change_map is not null, + // for any change to delay_[i], {i, delay_[i]} will be added to + // delay_change_map, allowing callers to undo any modifications. + bool ConsumeResource( + int64_t start_time, int64_t end_time, float resource, + absl::flat_hash_map* delay_change_map = nullptr, + float resource_to_free = 0.0); + + // Same as the public RemoveCopy except it works on the async_copies_ + // iterator. Assumes copy_it points to the last copy for its start time; + // otherwise the public RemoveCopy method is supposed to temporarily remove + // these later copies that share the same start time before removing the + // requested copy. + void RemoveCopy(std::list::iterator& copy_it); + + // We maintain a linked list of asynchronous copies sorted by the start times. + // This allows us to efficiently find the copy that starts right after another + // one because adding a copy might push a copy further into the future. + std::list async_copies_; +// To make the lookups into async_copies_ more efficient, we also maintain a +// binary tree that is indexed by the start time, containing iterators into +// async_copies_. +// TODO(b/210891274): Use btree_map after build issue in Windows is resolved. +#if defined(__GNUC__) || defined(__clang__) + absl::btree_map::iterator> + async_copy_time_map_; +#else + std::map::iterator> async_copy_time_map_; +#endif + std::vector initial_resources_; + std::vector delay_; +}; + +// TODO(b/280618622): Refactor this class out of this file. +// +// An optimizer for unrolled memory-bound loops. It keeps track of alternate +// memory capacity and default memory bandwidth to decide the allocations of +// each tensor within a loop iteration. The assumption is that all of the +// unrolled loop iterations will use the same allocation decisions, so we can +// spend more time to optimize this one iteration as optimally as possible. +// +// To represent instructions, we keep track of three iterations (previous, +// current, and next), as well as the header and footer regions that are before +// and after the loop, respectively. +// +// We classify each tensor used in the current iteration as one of the following +// allocations based on its positions and uses: +// +// Temporary Allocations: These are produced by a producer in the current +// iteration and consumed either in this or the next iteration. For these, we +// try to give them alternate memory allocations for their entire live range. +// +// Case 1: producer and consumer all in the current iteration. +// p-----c--c +// Case 2: producer is in the current iter, consumer is in the next iter. +// p-----c +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +// +// Loop Carried Dependences: This is where the last use is at a larger index +// than the producer. This would require 2X peak buffer consumption because both +// this and next iteration's buffer is alive at the same time. This case is +// currently not supported. +// +// Case 3: producer is in the current iter, consumer is in the next iter +// (consumer idx >= producer idx). +// p-----------------c +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +// +// Pinned Allocations: These are values produced at the header and are used in +// every iteration at the same indices. For these, we just allocate the buffer +// for the duration of the loop: +// +// Case 4: producer: kHead, consumer: kCurrent +// p---------------c--------------c--------------c-------- +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +// +// Prefetch Allocations: These are values produced at the header and are used in +// the current (and possibly next) iteration. We will try to prefetch these +// values into the alternate memory: +// +// Case 5: producer: kHead, consumer: kCurrent +// p---------------------------------c--------c +// idx: |...| 0 1 2 3 4| 0 1 2 3 4| 0 1 2 3 4|...| +// iter: head |...| prev | current | next |...| foot +class MemoryBoundLoopOptimizer { + public: + // We represent each tensor used in the current iteration as a LoopValue, + // wrapping the relevant information such as its HLO value, indices and + // pointers to its use and position sites in different iterations. + struct LoopValue { + // An enum that encodes the allocation type that is suitable for this + // LoopValue. See the comment above on what each of these mean. + enum class AllocationType { + kTemporary, + kLoopCarriedDependence, + kPinned, + kPrefetch, + kUnsupported + }; + + // ToString methods for logging/debugging. + static std::string AllocationTypeToString(AllocationType allocation_type); + std::string ToString() const; + + // The HloValues that correspond to this LoopValue. + std::vector hlo_values; + // The position in the header, if any. + std::optional header_position; + // The loop index and position in the previous and current iterations. + std::vector> prev_iteration_positions; + std::vector> loop_positions; + // The loop index and use in the current and next iterations. + std::vector> loop_uses; + std::vector> next_iteration_uses; + // The allocation type. + AllocationType allocation_type; + // Size of this tensor. + int64_t size; + // The default memory bandwidth savings were we to successfully put this in + // the alternate memory using the allocation type, in bytes. + float savings; + // The savings divided by the size. This is typically 2 for temporary + // allocations (skip a write and a read to the default memory). More complex + // production/consumption patterns may result in higher or lower values. We + // use this value to sort LoopValues so that the algorithm can prioritize + // allocating the buffers with the highest savings per byte to the alternate + // memory. + float savings_per_byte; + // The optimized AllocationSequence. + MemorySpaceAssignment::AllocationSequence allocations; + }; + + // Factory method to create and initialize a MemoryBoundLoopOptimizer. + static StatusOr> Create( + int loop_start, int loop_end, uint64_t alternate_memory_size, + const MemoryBoundLoopOptimizerOptions& options, + const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis_, + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + const BufferValue::SizeFunction& size_function); + + // Optimize the loop. Initialize must be called first. + void Optimize(); + + // Calculate the steady-state execution time of one loop iteration using the + // allocation decisions so far. + float CalculateExecutionTime() const; + + // Return the LoopValues. + const std::vector& loop_values() const { return loop_values_; } + std::vector& loop_values() { return loop_values_; } + + // Return the remaining memory vector for each point in time in the loop using + // the allocation decisions so far. + const std::vector& remaining_memory() const { + return remaining_memory_; + } + + // The loop start, end, and size accessors. + int loop_start() const { return loop_start_; } + int loop_end() const { return loop_end_; } + int loop_size() const { return loop_size_; } + + private: + // Temporary data structures used by the AllocatePrefetch function. + struct AllocatePrefetchesContext { + // The values that are requested to be prefetched. + absl::Span values; + + // A list of indices into values array, sorted by the start time of the + // first use. + std::vector value_indices; + + // Default memory remaining bandwidths assuming all prefetches succeeded. + std::vector bandwidth_idle_times; + + // Additional memory used while performing prefetching. + std::vector additional_memory_used; + }; + + MemoryBoundLoopOptimizer( + int loop_start, int loop_end, uint64_t alternate_memory_size, + const MemoryBoundLoopOptimizerOptions& options, + const HloLiveRange& hlo_live_range, + const HloAliasAnalysis& alias_analysis_, + const MemorySpaceAssignmentCostAnalysis& cost_analysis, + const BufferValue::SizeFunction& size_function); + + // Initializes the data structures used by the optimizer. + Status Initialize(); + + // Given an HloBuffer object, determines if this buffer represents a LoopValue + // that can be optimized by the optimizer, and if so it adds a LoopValue to + // the back of loop_values_ that represents the HloBuffer. Otherwise, no new + // LoopValue is added to loop_values_. + void MaybeCreateLoopValue(const HloBuffer& buffer, + const HloComputation* loop_computation); + + // Sort LoopValues by savings_per_byte. + void SortLoopValues(); + + // After allocation finishes, we fix up by creating Allocation objects to any + // LoopValues that didn't get alternate memory allocations. + void PostProcess(); + + // Allocate LoopValues by dispatching to the correct Allocate method. + void AllocateLoopValues(); + + // Allocate and reserve memory between the given indices. + bool AllocateBetween(int64_t begin_idx, int64_t end_idx, int64_t size); + + // Perform allocation type kTemporary. Return true if successful. + bool AllocateTemporary(LoopValue& value); + + // Perform allocation type kPinned. Return true if successful. + bool AllocatePinned(LoopValue& value); + + // Perform allocation type kPrefetch. Unlike the other Allocate methods, this + // performs allocation of multiple LoopValues in order to consider the effect + // of remaining bandwidth assuming the other prefetches were successful. + // Return true if successful. + bool AllocatePrefetches(absl::Span values); + + // Allocate one prefetch for the loop value index that corresponds to + // context.context.values. Returns true if successful. + bool AllocatePrefetch(int value_index, AllocatePrefetchesContext& context); + + // Keeps track of successful allocation of all uses and positions of this + // LoopValue. + void AddAllLoopPositionsAndUses(LoopValue& value, + bool allocate_next_iteration_uses); + + // Returns the default memory bandwidth idle time at the index. + float GetBandwidthIdleTime(int idx) const; + + // Returns the default memory bandwidth idle time at the index assuming the + // given uses and positions got alternate memory allocations. + float GetBandwidthIdleTime( + int idx, + const absl::flat_hash_map>>& + additional_uses_in_alternate_mem, + const absl::flat_hash_map>& + additional_positions_in_alternate_mem) const; + + // Returns the instruction elapsed at the index. + float GetInstructionElapsed(int idx) const; + + int loop_start_; + int loop_end_; + int loop_size_; + uint64_t alternate_memory_size_; + MemoryBoundLoopOptimizerOptions options_; + const HloLiveRange& hlo_live_range_; + const HloAliasAnalysis& alias_analysis_; + const MemorySpaceAssignmentCostAnalysis& cost_analysis_; + BufferValue::SizeFunction size_function_; + + absl::flat_hash_map instructions_in_loop_; + absl::flat_hash_map + instructions_in_prev_iteration_; + absl::flat_hash_map + instructions_in_next_iteration_; + std::vector loop_values_; + std::vector remaining_memory_; + absl::flat_hash_map>> + uses_in_alternate_mem_; + absl::flat_hash_map> + positions_in_alternate_mem_; +}; + +// This class inherits from GlobalDecreasingSizeBestFitHeap with a notion of +// maximum size. +class AlternateMemoryBestFitHeap + : public GlobalDecreasingSizeBestFitHeap { + public: + using MemorySpace = MemorySpaceAssignment::MemorySpace; + using AllocationValue = MemorySpaceAssignment::AllocationValue; + using HloPositionOrUse = std::variant; + + AlternateMemoryBestFitHeap( + MemorySpaceAssignment::AllocationSequence* allocations, + const Options& options, const HloAliasAnalysis& alias_analysis, + const HloLiveRange& hlo_live_range); + + // Allocates a buffer in preferred memory with whole program lifetime and + // enables prefetching prefetch_candidate from default memory across program + // boundaries. + void AllocateCrossProgramPrefetchBuffer( + HloModule* module, const BufferInterval& prefetch_candidate); + + HeapSimulator::Result Finish() override; + + protected: + // Given a buffer interval, returns the colocated intervals. Unlike the + // similar GlobalDecreasingSizeBestFitHeap::GetTransitiveColocations, it + // returns the colocated intervals sorted by scheduled time. + std::vector GetSortedColocatedIntervals( + const BufferInterval& interval) const; + + // Given a BufferInterval, creates AllocationValue objects and corresponding + // AllocationSequences and appends them into allocation_sequence_list_. + void CreateAllocationValues( + const BufferInterval& buffer_interval, + std::vector& allocation_values) const; + + // Given colocated intervals, populates allocation_values with the + // corresponding AllocationValue objects. + virtual void CreateAllocationValuesFromColocatedIntervals( + absl::Span + colocated_intervals, + std::vector& allocation_values); + + // Go through all the uses in the AllocationValues and find the aliasing + // positions. + void FindAliases(std::vector* allocation_values) const; + + MemorySpaceAssignment::AllocationSequence* allocations() { + return allocations_; + } + const Options& options() const { return options_; } + const HloAliasAnalysis& alias_analysis() { return alias_analysis_; } + const HloLiveRange& hlo_live_range() { return hlo_live_range_; } + + private: + // We inherit AllocationBlock struct to attach the Allocation information to + // make importing repacked offsets easier. + struct RepackAllocationBlock + : MemorySpaceAssignmentRepacker::AllocationBlock { + MemorySpaceAssignment::Allocation* allocation; + }; + + // A data structure we use to associate Allocation objects that are aliased + // and must get the same offset. + struct AliasedOffset { + int64_t offset; + absl::flat_hash_set allocations; + }; + + // An allocation request for a use segment. A use segment is the time segment + // between the definition and the first use, and the time segment between the + // uses of a buffer. For example, the time between the definition and Use1, is + // the first segment, and the time between Use1 and Use2 is the second segment + // and so on: + // + // +------+----------+-------+ + // / \ \ \ + // / v v v + // Def Use1 Use2 Use3 + // <----------> <--------> <-----> + // Segment Segment Segment + // + // start_time and end_time are the start and end logical times of the segment. + // use_times is a sorted sequence of the times of all uses. + // latest_prefetch_time is the latest time we can schedule the CopyDone for a + // prefetch. + // If allow_no_copy_alternate_mem_allocation is false, an eviction is forced. + // If earliest_prefetch_time is set, prefetches cannot start before this + // value. + struct AllocationRequest { + int64_t start_time; + int64_t end_time; + int64_t latest_prefetch_time; + int64_t size; + bool prefer_no_copy_alternate_mem_allocation; + bool allow_no_copy_alternate_mem_allocation; + bool allow_prefetch; + std::optional earliest_prefetch_time; + std::optional preferred_prefetch_time; + AliasedOffset* preferred_offset; + const MemorySpaceAssignment::AllocationValue::Use* use; + MemorySpaceAssignment::AllocationValue* allocation_value; + absl::Span all_use_times; + }; + + // This struct contains mandatory memory assignments at a given time. E.g., an + // input's required memory assignment time would correspond to the definition + // time of the parameter instruction, and an output's time would correspond to + // the time of last use. + struct RequiredMemoryAssignment { + MemorySpaceAssignment::MemorySpace memory_space; + int64_t time; + AliasedOffset* offset; + + bool equals_ignoring_time(const RequiredMemoryAssignment& other) const { + return memory_space == other.memory_space && offset == other.offset; + } + + bool operator==(const RequiredMemoryAssignment& other) const { + return memory_space == other.memory_space && time == other.time && + offset == other.offset; + } + + bool operator!=(const RequiredMemoryAssignment& other) const { + return !(*this == other); + } + }; + + // A struct that contains a pointer to loop-optimized allocation along with + // essential data about the loop itself. + struct LoopOptimizedAllocationInfo { + // The use_idx is the instruction index of the use within the loop. + int64_t use_index; + // The number of instructions in one iteration of the loop. We use use_index + // and loop_size to calculate when exactly to schedule a prefetch + // instruction. + int64_t loop_size; + // A pointer into an Allocation in loop_optimized_allocations_. + const MemorySpaceAssignment::Allocation* loop_optimized_allocation; + }; + + // A context object that is used to share state amongst the methods that + // implement Prefetch(). Prefetch tries to find both a sliced solution and an + // unsliced solution at the same time. We store both in this structure. + struct PrefetchContext { + // Prefetching is designed to operate on a SlicedBufferInterval that is + // backed by a standard BufferInterval, even if the number of slices == 1. + // WorkingIntervals is used to store a SlicedBufferInterval and its backing + // BufferInterval. + struct WorkingIntervals { + BufferInterval full; + // sliced is a unique_ptr because it won't necessarily be initialized + // when the WorkingBufferIntervals are created, and there is no way to + // create an empty SlicedBufferInterval. + std::unique_ptr sliced; + }; + + struct SlicedSolution { + // When we talk about a slice, we think of spatial slices, where each + // slice is allocated at different times. The following example shows + // 3 slices that are used to form a contiguous buffer from [p0, p3] + // + // space + // ^ + // p3 | +-----------+ + // | | s2 | + // p2 | +---+-----------+ + // | | s1 | + // p1 | +-------+-------+ + // | | s0 | + // p0 | +-------+ + // +---|---|---|---|---|----> time + // t0 t1 t2 t3 t4 + std::vector + slice_decisions_sorted_by_start_time; + + // In order to support colocated buffer calculations, we need to add a + // BufferInterval-Chunk pair to pending_chunks_, such that: + // - The duration of the BufferInterval is non-zero. + // - All slices have been allocated by the start of the BufferInterval. + // - The BufferInterval ends at the end time for all slices. + // - The Chunk covers the space allocated for all slices. + // + // In order to meet that requirement, + // we create BufferInterval-Chunk pairs from + // slice_decisions_sorted_by_start_time that meet those requirement but do + // not cause any memory to be allocated in more than one Chunk at a time. + // The result is stored in slices_for_pending_chunks. + // + // The illustration below demonstrates how we would construct such + // BufferInterval-Chunk pairs from the + // slice_decisions_sorted_by_start_time example above. + // + // space + // ^ + // p3 | +---+---+---+ + // | |c2 | | + // p2 | +---+---+ | + // | | c0 | c2 | + // p1 | +-------+ | + // | | | + // p0 | +-------+ + // +---|---|---|---|---|----> time + // t0 t1 t2 t3 t4 + std::vector> slices_for_pending_chunks; + + // The prefetch_picker_debug_string will only be set with the appropriate + // VLOG level. + std::string prefetch_picker_debug_string; + }; + + struct UnslicedSolution { + Chunk chunk_candidate; // The chunk chosen for the solution. + float prefetch_resource; // The amount of required prefetch resource. + // The prefetch_picker_debug_string will only be set with the appropriate + // VLOG level. + std::string prefetch_picker_debug_string; + }; + + WorkingIntervals& GetMutableWorkingIntervals(bool for_sliced_solution) { + if (for_sliced_solution) { + return sliced_solution_intervals; + } + return unsliced_solution_intervals; + } + + const WorkingIntervals& GetWorkingIntervals( + bool for_sliced_solution) const { + if (for_sliced_solution) { + return sliced_solution_intervals; + } + return unsliced_solution_intervals; + } + + // Parameters to Prefetch(). + const AllocationRequest* request; + MemorySpaceAssignment::Allocation* prev_allocation_in_default_mem; + + // Intermediate calculations common to both the sliced and unsliced + // solutions. + int64_t prefetch_start_time = -1; + int64_t prefetch_end_time = -1; + const Shape* full_shape; + int64_t extra_async_copy_limit = 0; + // As a compilation time optimization, store the prefetch start time where + // we have first seen out of memory. There is no point of exploring prefetch + // start times earlier than this point. + std::optional out_of_mem_start = std::nullopt; + + // Data structures used to compute and store the sliced solution. + std::optional + slice_proposal_collection = std::nullopt; + WorkingIntervals sliced_solution_intervals; + std::optional sliced_solution; + + // Data structures used to compute and store the unsliced solution. + WorkingIntervals unsliced_solution_intervals; + std::optional unsliced_solution; + }; + + // Result of an allocation, prefetch, eviction etc. request. The result is + // either kSuccess or a bitwise OR of one or more failures. The values are + // unique powers of two. To check if a result contains a particular failure, + // use the result_is method. To add a new failure to a result, use the + // result_mark method. + enum class Result { + // Successful allocation. + kSuccess = 0, + // Allocation failed because we ran out of alternate memory. + kFailOutOfMemory = 1, + // A no-copy allocation couldn't be performed because the previous + // allocation wasn't in the alternate memory space. + kFailPrevAllocationNotInAlternateMem = 2, + // A no-copy allocation couldn't be performed because the live range was too + // long. + kFailLiveRangeTooLong = 4, + // A prefetching couldn't be performed because the live range was too short. + kFailLiveRangeTooShort = 8, + // Ran out of outstanding asynchronous copy limit either during prefetching + // or eviction. + kFailOutOfAsyncCopies = 16, + // A prefetching couldn't be performed because the asynchronous copy + // resource was violated. + kFailViolatesAsyncCopyResource = 32, + // An allocation failure happened that requires uncommitting all the pending + // allocations. Usually this is due to a situation requiring an eviction but + // the eviction couldn't be performed. + kFailRequiresUncommit = 64, + // For prefetching, indicates that all slices have the same start time, in + // which case, we fallback to an unsliced solution. + kAllSlicesHaveTheSameStartTime = 128 + }; + + // Return true if the result belongs to a failure. + static bool result_is(Result result, Result failure) { + return static_cast(result) & static_cast(failure); + } + + // Mark (bitwise OR) a failure to the result. + static Result result_mark(Result failure, Result& result) { + result = static_cast(static_cast(result) | + static_cast(failure)); + return result; + } + + // Return true if the result is a failure that requires us to uncommit pending + // chunks. + static bool result_requires_uncommit(Result result) { + return result_is(result, Result::kFailRequiresUncommit); + } + + // Return true if the result is a failure either due to running out of + // outstanding asynchronous copies or due to violating asynchronous copy + // ordering. + static bool result_failed_because_of_async_copy(Result result) { + return result_is(result, Result::kFailOutOfAsyncCopies) || + result_is(result, Result::kFailViolatesAsyncCopyResource); + } + + // For the given loop with the start and end index and loop size, run the + // MemoryBoundLoopOptimizer and record its outputs into + // optimized_allocations_map_. + Status OptimizeMemoryBoundLoop(int loop_start_idx, int loop_end_idx, + int loop_size); + + // Identify memory-bound loops in the graph and call OptimizeMemoryBoundLoop + // for the found loops. + void IdentifyAndOptimizeMemoryBoundLoops(); + + // Allocates buffers for instructions that need reserved scoped allocations in + // the alternate memory space. + void AllocateReservedScopedAllocations(); + + // Returns the AliasedOffset object associated with the allocation. + AliasedOffset* GetAliasedOffset( + const MemorySpaceAssignment::Allocation& allocation); + + // If aliased_offset is non-null, this method adds the allocation to + // aliased_offset. Otherwise, it creates a new AliasedOffset object and adds + // the allocation to this new AliasedOffset. + void CreateOrAddToAliasedOffset( + const MemorySpaceAssignment::Allocation& allocation, + AliasedOffset* aliased_offset); + + // Given an allocation sequence, returns the live allocation at time with a + // preference towards allocations in alternate memory. Returns nullptr if no + // allocation is alive at that time. + static MemorySpaceAssignment::Allocation* GetLiveAllocationAt( + const MemorySpaceAssignment::AllocationSequence& allocations, + int64_t time); + + // Returns true if the use is allowed in the alternate memory. + bool IsUseAllowedInAlternateMemory(const AllocationValue& value, + const HloUse& use) const; + + // Finds allocations for allocation values generated from colocated intervals. + // All of the allocation values have a must-alias relationship with each + // other. Returns either kSuccess if all of the sites could be placed in the + // alternate memory or a bitwise OR of failure reasons why they couldn't + Result AllocateAllocationValues( + absl::Span allocation_values); + + // Finds an allocation for an allocation request for a segment (see the + // documentation for AllocationRequest above how a segment is defined). + // + // It performs three things in the following order: + // 1- Allocate the allocation request entirely in the alternate memory, if + // there is enough space and if the prefetch interval picker allows. + // 2- If (1) was unsuccessful, and the only allocation for + // this buffer was in the alternate memory, we try to perform a prefetch. + // 3- If (1) was unsuccessful, prefetch the buffer into the alternate memory, + // if there is enough space and if the prefetch interval picker allows. + // + // If an eviction (2) was requested and was unsuccessful, this method returns + // Result::kFailRequiresUncommit. This means we could not find a suitable + // allocation, so all previous allocations for this buffer must be removed and + // allocated in the default memory. Otherwise, this method may return + // Result::kSuccess if the buffer could be placed in alternate memory or some + // other Result with an OR of reasons why the buffer couldn't be placed in + // alternate memory. + Result AllocateSegment(const AllocationRequest& request); + + // Try allocating in alternate memory without any copies. + Result AllocateInAlternateMemoryNoCopy(const AllocationRequest& request); + + // Try evicting to default memory space. + Result Evict(const AllocationRequest& request); + + // Returns the time a copy done of a prefetch should be scheduled. + int64_t FindPrefetchEndTime(const AllocationRequest& request, + int64_t earliest_prefetch_time) const; + + // Try prefetching to alternate memory space. + Result Prefetch( + const AllocationRequest& request, + MemorySpaceAssignment::Allocation& prev_allocation_in_default_mem); + + // Helper methods used to implement Prefetch(). + // + // Generates a SliceProposal in context, if options dictate and one can be + // constructed. + void GenerateSliceProposal(PrefetchContext& context) const; + // Calls GenerateSliceProposal to potentially create a SliceProposal, and + // sets up WorkingIntervals for a sliced and unsliced solution. Updates + // context. + void SetupPrefetchWorkingIntervalsAndSliceProposal( + PrefetchContext& context) const; + // Initializes the PrefetchIntervalPicker and associated data structures in + // context. + Result InitializePrefetchIntervalPicker(PrefetchContext& context); + // As a compile time optimization, try a prefetch allocation that is as late + // as possible. If this is not able to find a solution, none of the + // earlier tries will succeed either. + Result EnsureSomeSpatialPrefetchFitExists(PrefetchContext& context) const; + // Check if for the specified type of solution, using the parameters in + // context. If we find a solution, it will be stored in context. + Result CheckPrefetchFit(bool for_sliced_solution, PrefetchContext& context); + // Given a specified number of slices, start times, and end times, pick times + // to start each slice. + std::vector PickSliceStartTimes(int64_t num_slices, + int64_t prefetch_start_time, + int64_t prefetch_end_time) const; + // Creates a debugging string describing the timing of the prefetch solution + // we are currently attempting (as dictated by for_sliced_solution and + // context). + std::string AlternateMemoryAllocationAttemptToString( + bool for_sliced_solution, const PrefetchContext& context) const; + + // Find the best possible chunk candidate, where it has the longest possible + // availability if no preferred offset is given, or at the preferred_offset if + // it is given. + std::optional FindBestChunkCandidate( + const AllocationRequest& request, const AliasedOffset* preferred_offset, + BufferInterval* alternate_mem_interval) const; + // The same as FindBestChunkCandidate() but allocates the request in slices. + // The ith returned chunk should be allocated at slice time i. + std::vector FindBestChunkCandidates( + const AllocationRequest& request, const AliasedOffset* preferred_offset, + SlicedBufferInterval* alternate_mem_interval) const; + + // Returns the required assignment at a particular time, if available. + std::optional RequiredMemoryAssignmentAt( + const HloValue* buffer, int64_t time) const; + + // Searches for aliases in the use for a required assignment, and returns it + // if found. + std::optional AliasedRequiredAssignmentForUse( + const AllocationValue::Use& use) const; + + // Goes through the colocated intervals and adds any required assignment. + void AddRequiredAssignmentsForColocatedIntervals( + absl::Span + colocated_intervals); + + // Propagates aliased required assignment for a given position. + void AddAliasedRequiredAssignment( + const HloInstruction* instruction, ShapeIndex index, + const MemorySpaceAssignment::Allocation* aliased_allocation); + + // This sets a required assignment. CHECK fails if there is a conflicting + // required assignment at the same time. + void AddRequiredAssignment(const HloValue* value, + const HloInstruction* instruction, + MemorySpace memory_space, int64_t time, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + void AddRequiredAssignment(const HloInstruction* instruction, + ShapeIndex index, MemorySpace memory_space, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + void AddRequiredAssignment(const HloPosition& position, + MemorySpace memory_space, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + void AddRequiredAssignment(const HloUse& use, MemorySpace memory_space, + AliasedOffset* offset = nullptr, + bool add_to_pending = true); + + // Adds input and outputs as required assignments. + void AddInputAndOutputRequiredAssignments(); + + // Returns a list of "linked" allocations in the alternate memory. Linked + // allocations all share a common allocation site (a use or position) with + // each other. This can be used to determine if a group of linked allocations + // are considered efficient or not. + std::vector> + GetLinkedAllocationsInAlternateMemory( + absl::Span allocation_values) const; + + // Returns allocation sites (use or position) that are allocated in the + // alternate memory, but is considered inefficient. These arise in the + // context of in-place operation like dynamic-update-slice. We will typically + // have an allocation that has the DUS as a use, and another allocation that + // has the DUS as a defining position. These two allocation will be part of + // the same linked allocation group. + // + // One reason why an allocation site could be inefficient is because the + // amount of data that is asynchronously copied (prefetch and eviction) is + // much larger than the amount of data that is used by the HLOs. If we find + // inefficient allocation sites, we can require these sites default memory + // allocations and allocate them again. + std::vector GetInefficientAllocationSites( + absl::Span allocation_values) const; + + // Returns true if the colocated intervals in the argument are in a parameter + // or root instruction of the entry computation and are reserved by the user + // to be in the alternate memory space. + bool AreIntervalsReservedInAlternateMemory( + absl::Span colocated_intervals) const; + + // Since the allocations are recorded to the AllocationSequence, we don't + // maintain result_ in GlobalDecreasingSizeBestFitHeap. Override AddToChunkMap + // to avoid unnecessarily adding the chunk to the chunk map. + // + // Sliced prefetching requires that we override this method because we + // associate more than one chunk with a buffer (i.e., 1 chunk per slice), + // which would cause the original implementation of this method to CHECK fail. + void AddToChunkMap(const HloValue* buffer, Chunk chunk) override {} + + // Returns true if the addition of num_additional_copies asynchronous copies + // in the given time interval would violate the maximum number of asynchronous + // copies. An extra async copy limit can be provided to increase the limit of + // asynchronous copies for this instance. + bool ViolatesMaximumOutstandingAsyncCopies( + int64_t start_time, int64_t end_time, bool is_prefetch, + int64_t extra_async_copy_limit = 0, + int64_t num_additional_copies = 1) const; + + // Exports the allocations for repacking and puts them into the vector in the + // parameter. + void ExportAllocationsForRepacking( + std::vector& + allocations); + + // Update reserved scoped allocation size for instructions when their + // operand/output has been allocated in alternate memory by invoking + // reserved_scoped_memory_fn + void UpdateReservedScopedAllocationSize(); + + // Imports repacked allocations and updates the internal data structures + // consistent with the new packing. + void ImportRepackedAllocations(); + // Helper functions to implement ImportRepackedAllocations. + void ImportRepackedNonSlicedAllocation(RepackAllocationBlock& block); + void ImportRepackedSlicedAllocation(RepackAllocationBlock& block); + + // Adds an asynchronous copy to allocations. + void AddAsyncCopy( + MemorySpaceAssignment::Allocation& prev_allocation, + MemorySpace memory_space, std::optional chunk, int64_t start_time, + int64_t end_time, int64_t copy_done_schedule_before_time, + MemorySpaceAssignment::AllocationSequence* allocations, + AliasedOffset* aliased_offset, float resource, + std::optional cross_program_prefetch_index = std::nullopt); + + // For prefetching, adds a SlicedCopyAllocation to allocations. Also updates + // asynchronous copy data structures, prefetch_interval_tree_, and aliasing + // data structures + void AddAsyncSlicesForPrefetch( + const MemorySpaceAssignment::Allocation& prev_allocation, + MemorySpaceAssignment::AllocationSequence* allocations, + AliasedOffset* aliased_offset, + const std::vector& + slice_decisions_sorted_by_start_time, + int64_t prefetch_end_time, int64_t allocation_end_time); + + // This method is used for committing the chunk candidate but adding it to + // pending_chunks_ so that we can "uncommit" them in case we need to roll back + // this allocation sequence. + void AddToPendingChunks(const BufferInterval& buffer_interval, + const Chunk& chunk); + // If we need to remove the allocations for this allocation sequence, this + // removes pending chunks and asynchronous copies in the respective pending + // buffers from the interval trees. If an allocation request returns + // kFailRequiresUncommit, this method must be called. + void UncommitPendingChunks(absl::Span allocation_values); + + // Finalizes the allocations where they can no longer be uncommitted. + void FinalizeAllocations(absl::Span allocation_values); + + // Clears all pending chunks and asynchronous copies. + void ClearPendingChunks(); + + // Append buffer and allocation infos for debugging and dump it into a file, + // if enabled. + void AppendBufferInfoDebugString(const BufferInterval& interval, + std::string* debug_str) const; + void AppendScopedAllocationBufferInfoDebugString( + const HloInstruction* instruction, int64_t time, int64_t size, + std::string& debug_str) const; + void AppendAllocationInfoDebugString( + const MemorySpaceAssignment::Allocation& allocation, + std::string& debug_str) const; + void DumpDebugStringsIfEnabled() const; + + // Returns the available heap size in the alternate memory. + int64_t available_heap_size() const { + return options_.max_size_in_bytes - reserved_in_bytes_; + } + + // Returns the earliest time in the [start_time, end_time] range that a new + // allocation with the given size would fit in the alternate memory. If it + // doesn't fit, it returns nullopt. + std::optional FindEarliestTimeToSatisfyPeakMemory(int start_time, + int end_time, + int64_t size) const; + + // Creates and returns a RepackAllocationBlock. + static RepackAllocationBlock MakeRepackAllocationBlock( + int64_t start_time, int64_t end_time, int64_t size, + int64_t initial_offset, int64_t id, + MemorySpaceAssignment::Allocation* allocation) { + RepackAllocationBlock allocation_block; + allocation_block.start_time = start_time; + allocation_block.end_time = end_time; + allocation_block.size = size; + allocation_block.offset = -1; + allocation_block.initial_offset = initial_offset; + allocation_block.id = id; + allocation_block.colocations = {}; + allocation_block.allocation = allocation; + return allocation_block; + } + + // Returns a vector of instructions that have the same fingerprint as this + // instruction. + const std::vector* GetRepeatedInstructionList( + const HloInstruction* instruction) const; + + MemorySpaceAssignment::AllocationSequence* allocations_; + const Options& options_; + const HloAliasAnalysis& alias_analysis_; + const HloLiveRange& hlo_live_range_; + std::unique_ptr call_graph_; + // We use a interval tree to keep track of the number of outstanding + // prefetches and evictions. + BufferIntervalTree prefetch_interval_tree_; + BufferIntervalTree eviction_interval_tree_; + AsynchronousCopyOrdering async_copy_ordering_; + AsynchronousCopyResource prefetch_async_copy_resource_; + AsynchronousCopyResource eviction_async_copy_resource_; + // A list of RepackAllocationBlock objects that mirrors allocation sequences, + // used for repacking. We use a list here because we need pointer stability + // for aliased allocations. + std::list repack_allocation_blocks_; + int64_t num_repacks_ = 0; + std::vector> pending_chunks_; + std::vector pending_async_copies_; + std::vector> + pending_required_assignments_; + // A cache to keep the peak memory usage at each point in the graph. We use + // this to see if the proposed allocation in the alternate memory would fit + // ignoring fragmentation, and if not, we can skip the more expensive lookup + // in the BufferIntervalTree, which also considers fragmentation. + std::vector peak_memory_usage_; + // The data structure that contains AliasedOffset objects and Allocation to + // AliasedOffset map for efficient lookup. + std::list aliased_offsets_; + absl::flat_hash_map + aliased_offset_map_; + // This map contains required memory assignments for HloValues (e.g., input + // and outputs). + absl::flat_hash_map> + required_assignments_; + // Number of bytes reserved in alternate memory space. + int64_t reserved_in_bytes_ = 0; + // A rough measure of the memory pressure of the model, in bytes. Note that + // this is pressure for memory capacity (and not accessed bytes), and for + // alternate memory (not default memory). + int64_t memory_pressure_ = 0; + int64_t next_async_copy_id_ = 0; + // Fingerprint cache. + absl::flat_hash_map fingerprint_map_; + // Vector of repeated instructions (that have the same fingerprint) indexed by + // fingerprint. + absl::flat_hash_map> + repeated_inst_map_; + + // Loop-optimized allocations found by MemoryBoundLoopOptimizer. These + // allocation objects describe the allocations for one iteration of the loop, + // so we translate them into the program-level Allocation objects in + // allocations_. + std::vector + loop_optimized_allocations_; + // A map to look up the loop-optimized allocation info by use. + absl::flat_hash_map + loop_optimized_allocations_map_; + // A map to look the operands of each instruction that are assigned in + // alternate memory. + absl::flat_hash_map>> + operands_in_alternate_memory_map_; + // A map to look the outputs of each instruction that are assigned in + // alternate memory. + absl::flat_hash_map> + outputs_in_alternate_memory_map_; + // Debug strings. + std::string buffer_info_str_; + std::string allocation_info_str_; + std::string instruction_schedule_str_; +}; +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_MEMORY_SPACE_ASSIGNMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..7d4d597a213719076e19ba910ccac3ef46a49144 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/memory_space_assignment.pb.h @@ -0,0 +1,590 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/service/memory_space_assignment/memory_space_assignment.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto; +namespace xla { +namespace memory_space_assignment { +class MemoryBoundLoopOptimizerOptions; +struct MemoryBoundLoopOptimizerOptionsDefaultTypeInternal; +extern MemoryBoundLoopOptimizerOptionsDefaultTypeInternal _MemoryBoundLoopOptimizerOptions_default_instance_; +class SlicedPrefetchOptions; +struct SlicedPrefetchOptionsDefaultTypeInternal; +extern SlicedPrefetchOptionsDefaultTypeInternal _SlicedPrefetchOptions_default_instance_; +} // namespace memory_space_assignment +} // namespace xla +PROTOBUF_NAMESPACE_OPEN +template<> ::xla::memory_space_assignment::MemoryBoundLoopOptimizerOptions* Arena::CreateMaybeMessage<::xla::memory_space_assignment::MemoryBoundLoopOptimizerOptions>(Arena*); +template<> ::xla::memory_space_assignment::SlicedPrefetchOptions* Arena::CreateMaybeMessage<::xla::memory_space_assignment::SlicedPrefetchOptions>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace xla { +namespace memory_space_assignment { + +// =================================================================== + +class SlicedPrefetchOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.memory_space_assignment.SlicedPrefetchOptions) */ { + public: + inline SlicedPrefetchOptions() : SlicedPrefetchOptions(nullptr) {} + ~SlicedPrefetchOptions() override; + explicit PROTOBUF_CONSTEXPR SlicedPrefetchOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + SlicedPrefetchOptions(const SlicedPrefetchOptions& from); + SlicedPrefetchOptions(SlicedPrefetchOptions&& from) noexcept + : SlicedPrefetchOptions() { + *this = ::std::move(from); + } + + inline SlicedPrefetchOptions& operator=(const SlicedPrefetchOptions& from) { + CopyFrom(from); + return *this; + } + inline SlicedPrefetchOptions& operator=(SlicedPrefetchOptions&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const SlicedPrefetchOptions& default_instance() { + return *internal_default_instance(); + } + static inline const SlicedPrefetchOptions* internal_default_instance() { + return reinterpret_cast( + &_SlicedPrefetchOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(SlicedPrefetchOptions& a, SlicedPrefetchOptions& b) { + a.Swap(&b); + } + inline void Swap(SlicedPrefetchOptions* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(SlicedPrefetchOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + SlicedPrefetchOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const SlicedPrefetchOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const SlicedPrefetchOptions& from) { + SlicedPrefetchOptions::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(SlicedPrefetchOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.memory_space_assignment.SlicedPrefetchOptions"; + } + protected: + explicit SlicedPrefetchOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMinBytesFieldNumber = 2, + kMaxSlicesFieldNumber = 1, + kFailOnNonAlignmentBoundarySliceProposalFieldNumber = 3, + }; + // uint64 min_bytes = 2; + void clear_min_bytes(); + uint64_t min_bytes() const; + void set_min_bytes(uint64_t value); + private: + uint64_t _internal_min_bytes() const; + void _internal_set_min_bytes(uint64_t value); + public: + + // uint32 max_slices = 1; + void clear_max_slices(); + uint32_t max_slices() const; + void set_max_slices(uint32_t value); + private: + uint32_t _internal_max_slices() const; + void _internal_set_max_slices(uint32_t value); + public: + + // bool fail_on_non_alignment_boundary_slice_proposal = 3; + void clear_fail_on_non_alignment_boundary_slice_proposal(); + bool fail_on_non_alignment_boundary_slice_proposal() const; + void set_fail_on_non_alignment_boundary_slice_proposal(bool value); + private: + bool _internal_fail_on_non_alignment_boundary_slice_proposal() const; + void _internal_set_fail_on_non_alignment_boundary_slice_proposal(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.memory_space_assignment.SlicedPrefetchOptions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + uint64_t min_bytes_; + uint32_t max_slices_; + bool fail_on_non_alignment_boundary_slice_proposal_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto; +}; +// ------------------------------------------------------------------- + +class MemoryBoundLoopOptimizerOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions) */ { + public: + inline MemoryBoundLoopOptimizerOptions() : MemoryBoundLoopOptimizerOptions(nullptr) {} + ~MemoryBoundLoopOptimizerOptions() override; + explicit PROTOBUF_CONSTEXPR MemoryBoundLoopOptimizerOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + MemoryBoundLoopOptimizerOptions(const MemoryBoundLoopOptimizerOptions& from); + MemoryBoundLoopOptimizerOptions(MemoryBoundLoopOptimizerOptions&& from) noexcept + : MemoryBoundLoopOptimizerOptions() { + *this = ::std::move(from); + } + + inline MemoryBoundLoopOptimizerOptions& operator=(const MemoryBoundLoopOptimizerOptions& from) { + CopyFrom(from); + return *this; + } + inline MemoryBoundLoopOptimizerOptions& operator=(MemoryBoundLoopOptimizerOptions&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const MemoryBoundLoopOptimizerOptions& default_instance() { + return *internal_default_instance(); + } + static inline const MemoryBoundLoopOptimizerOptions* internal_default_instance() { + return reinterpret_cast( + &_MemoryBoundLoopOptimizerOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(MemoryBoundLoopOptimizerOptions& a, MemoryBoundLoopOptimizerOptions& b) { + a.Swap(&b); + } + inline void Swap(MemoryBoundLoopOptimizerOptions* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(MemoryBoundLoopOptimizerOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + MemoryBoundLoopOptimizerOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const MemoryBoundLoopOptimizerOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const MemoryBoundLoopOptimizerOptions& from) { + MemoryBoundLoopOptimizerOptions::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(MemoryBoundLoopOptimizerOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions"; + } + protected: + explicit MemoryBoundLoopOptimizerOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kDesiredCopyRatioFieldNumber = 2, + kEnabledFieldNumber = 1, + kAllowUnsatisfiedFullyPipelinedPrefetchFieldNumber = 3, + }; + // optional float desired_copy_ratio = 2; + bool has_desired_copy_ratio() const; + private: + bool _internal_has_desired_copy_ratio() const; + public: + void clear_desired_copy_ratio(); + float desired_copy_ratio() const; + void set_desired_copy_ratio(float value); + private: + float _internal_desired_copy_ratio() const; + void _internal_set_desired_copy_ratio(float value); + public: + + // optional bool enabled = 1; + bool has_enabled() const; + private: + bool _internal_has_enabled() const; + public: + void clear_enabled(); + bool enabled() const; + void set_enabled(bool value); + private: + bool _internal_enabled() const; + void _internal_set_enabled(bool value); + public: + + // optional bool allow_unsatisfied_fully_pipelined_prefetch = 3; + bool has_allow_unsatisfied_fully_pipelined_prefetch() const; + private: + bool _internal_has_allow_unsatisfied_fully_pipelined_prefetch() const; + public: + void clear_allow_unsatisfied_fully_pipelined_prefetch(); + bool allow_unsatisfied_fully_pipelined_prefetch() const; + void set_allow_unsatisfied_fully_pipelined_prefetch(bool value); + private: + bool _internal_allow_unsatisfied_fully_pipelined_prefetch() const; + void _internal_set_allow_unsatisfied_fully_pipelined_prefetch(bool value); + public: + + // @@protoc_insertion_point(class_scope:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + float desired_copy_ratio_; + bool enabled_; + bool allow_unsatisfied_fully_pipelined_prefetch_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// SlicedPrefetchOptions + +// uint32 max_slices = 1; +inline void SlicedPrefetchOptions::clear_max_slices() { + _impl_.max_slices_ = 0u; +} +inline uint32_t SlicedPrefetchOptions::_internal_max_slices() const { + return _impl_.max_slices_; +} +inline uint32_t SlicedPrefetchOptions::max_slices() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.SlicedPrefetchOptions.max_slices) + return _internal_max_slices(); +} +inline void SlicedPrefetchOptions::_internal_set_max_slices(uint32_t value) { + + _impl_.max_slices_ = value; +} +inline void SlicedPrefetchOptions::set_max_slices(uint32_t value) { + _internal_set_max_slices(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.SlicedPrefetchOptions.max_slices) +} + +// uint64 min_bytes = 2; +inline void SlicedPrefetchOptions::clear_min_bytes() { + _impl_.min_bytes_ = uint64_t{0u}; +} +inline uint64_t SlicedPrefetchOptions::_internal_min_bytes() const { + return _impl_.min_bytes_; +} +inline uint64_t SlicedPrefetchOptions::min_bytes() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.SlicedPrefetchOptions.min_bytes) + return _internal_min_bytes(); +} +inline void SlicedPrefetchOptions::_internal_set_min_bytes(uint64_t value) { + + _impl_.min_bytes_ = value; +} +inline void SlicedPrefetchOptions::set_min_bytes(uint64_t value) { + _internal_set_min_bytes(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.SlicedPrefetchOptions.min_bytes) +} + +// bool fail_on_non_alignment_boundary_slice_proposal = 3; +inline void SlicedPrefetchOptions::clear_fail_on_non_alignment_boundary_slice_proposal() { + _impl_.fail_on_non_alignment_boundary_slice_proposal_ = false; +} +inline bool SlicedPrefetchOptions::_internal_fail_on_non_alignment_boundary_slice_proposal() const { + return _impl_.fail_on_non_alignment_boundary_slice_proposal_; +} +inline bool SlicedPrefetchOptions::fail_on_non_alignment_boundary_slice_proposal() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.SlicedPrefetchOptions.fail_on_non_alignment_boundary_slice_proposal) + return _internal_fail_on_non_alignment_boundary_slice_proposal(); +} +inline void SlicedPrefetchOptions::_internal_set_fail_on_non_alignment_boundary_slice_proposal(bool value) { + + _impl_.fail_on_non_alignment_boundary_slice_proposal_ = value; +} +inline void SlicedPrefetchOptions::set_fail_on_non_alignment_boundary_slice_proposal(bool value) { + _internal_set_fail_on_non_alignment_boundary_slice_proposal(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.SlicedPrefetchOptions.fail_on_non_alignment_boundary_slice_proposal) +} + +// ------------------------------------------------------------------- + +// MemoryBoundLoopOptimizerOptions + +// optional bool enabled = 1; +inline bool MemoryBoundLoopOptimizerOptions::_internal_has_enabled() const { + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + return value; +} +inline bool MemoryBoundLoopOptimizerOptions::has_enabled() const { + return _internal_has_enabled(); +} +inline void MemoryBoundLoopOptimizerOptions::clear_enabled() { + _impl_.enabled_ = false; + _impl_._has_bits_[0] &= ~0x00000002u; +} +inline bool MemoryBoundLoopOptimizerOptions::_internal_enabled() const { + return _impl_.enabled_; +} +inline bool MemoryBoundLoopOptimizerOptions::enabled() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.enabled) + return _internal_enabled(); +} +inline void MemoryBoundLoopOptimizerOptions::_internal_set_enabled(bool value) { + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.enabled_ = value; +} +inline void MemoryBoundLoopOptimizerOptions::set_enabled(bool value) { + _internal_set_enabled(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.enabled) +} + +// optional float desired_copy_ratio = 2; +inline bool MemoryBoundLoopOptimizerOptions::_internal_has_desired_copy_ratio() const { + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; + return value; +} +inline bool MemoryBoundLoopOptimizerOptions::has_desired_copy_ratio() const { + return _internal_has_desired_copy_ratio(); +} +inline void MemoryBoundLoopOptimizerOptions::clear_desired_copy_ratio() { + _impl_.desired_copy_ratio_ = 0; + _impl_._has_bits_[0] &= ~0x00000001u; +} +inline float MemoryBoundLoopOptimizerOptions::_internal_desired_copy_ratio() const { + return _impl_.desired_copy_ratio_; +} +inline float MemoryBoundLoopOptimizerOptions::desired_copy_ratio() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.desired_copy_ratio) + return _internal_desired_copy_ratio(); +} +inline void MemoryBoundLoopOptimizerOptions::_internal_set_desired_copy_ratio(float value) { + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.desired_copy_ratio_ = value; +} +inline void MemoryBoundLoopOptimizerOptions::set_desired_copy_ratio(float value) { + _internal_set_desired_copy_ratio(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.desired_copy_ratio) +} + +// optional bool allow_unsatisfied_fully_pipelined_prefetch = 3; +inline bool MemoryBoundLoopOptimizerOptions::_internal_has_allow_unsatisfied_fully_pipelined_prefetch() const { + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; + return value; +} +inline bool MemoryBoundLoopOptimizerOptions::has_allow_unsatisfied_fully_pipelined_prefetch() const { + return _internal_has_allow_unsatisfied_fully_pipelined_prefetch(); +} +inline void MemoryBoundLoopOptimizerOptions::clear_allow_unsatisfied_fully_pipelined_prefetch() { + _impl_.allow_unsatisfied_fully_pipelined_prefetch_ = false; + _impl_._has_bits_[0] &= ~0x00000004u; +} +inline bool MemoryBoundLoopOptimizerOptions::_internal_allow_unsatisfied_fully_pipelined_prefetch() const { + return _impl_.allow_unsatisfied_fully_pipelined_prefetch_; +} +inline bool MemoryBoundLoopOptimizerOptions::allow_unsatisfied_fully_pipelined_prefetch() const { + // @@protoc_insertion_point(field_get:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.allow_unsatisfied_fully_pipelined_prefetch) + return _internal_allow_unsatisfied_fully_pipelined_prefetch(); +} +inline void MemoryBoundLoopOptimizerOptions::_internal_set_allow_unsatisfied_fully_pipelined_prefetch(bool value) { + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.allow_unsatisfied_fully_pipelined_prefetch_ = value; +} +inline void MemoryBoundLoopOptimizerOptions::set_allow_unsatisfied_fully_pipelined_prefetch(bool value) { + _internal_set_allow_unsatisfied_fully_pipelined_prefetch(value); + // @@protoc_insertion_point(field_set:xla.memory_space_assignment.MemoryBoundLoopOptimizerOptions.allow_unsatisfied_fully_pipelined_prefetch) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace memory_space_assignment +} // namespace xla + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fmemory_5fspace_5fassignment_2fmemory_5fspace_5fassignment_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/repacking.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/repacking.h new file mode 100644 index 0000000000000000000000000000000000000000..0379fc794832303147b4532219711141f4b1a603 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/repacking.h @@ -0,0 +1,165 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_REPACKING_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_REPACKING_H_ + +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/types/span.h" +#include "xla/statusor.h" +#include "xla/types.h" + +namespace xla { +namespace memory_space_assignment { + +// An interface to define allocation repacking algorithms. +class MemorySpaceAssignmentRepacker { + public: + MemorySpaceAssignmentRepacker(int64_t max_size, int64_t alignment) + : max_size_(max_size), alignment_(alignment) {} + virtual ~MemorySpaceAssignmentRepacker() = default; + + // Data about a slice in a sliced allocation. + struct Slice { + int64_t size; + int64_t offset; + int64_t start_time; + + std::string ToString() const { + return absl::StrCat("{ size: ", size, ", offset: ", offset, + ", start_time: ", start_time, " }"); + } + + std::tuple ToTuple() const { + return std::make_tuple(size, offset, start_time); + } + + bool operator==(const Slice& rhs) const { + return ToTuple() == rhs.ToTuple(); + } + }; + + // Slice data about a sliced allocation. + struct SlicedAllocationData { + std::vector slices_sorted_by_offset; + + std::vector SizesSortedByOffset() const { + std::vector sizes_sorted_by_offset; + sizes_sorted_by_offset.reserve(slices_sorted_by_offset.size()); + absl::c_for_each(slices_sorted_by_offset, + [&sizes_sorted_by_offset](const Slice& slice) { + sizes_sorted_by_offset.push_back(slice.size); + }); + return sizes_sorted_by_offset; + } + + std::vector SortedStartTimes() const { + std::vector sorted_start_times; + sorted_start_times.reserve(slices_sorted_by_offset.size()); + absl::c_for_each(slices_sorted_by_offset, + [&sorted_start_times](const Slice& slice) { + sorted_start_times.push_back(slice.start_time); + }); + absl::c_sort(sorted_start_times); + return sorted_start_times; + } + + std::string ToString() const { + return absl::StrCat( + "{ slices_sorted_by_offset: [ ", + absl::StrJoin(slices_sorted_by_offset, ", ", + [](std::string* out, const Slice& slice) { + absl::StrAppend(out, slice.ToString()); + }), + " ] }"); + } + + bool operator==(const SlicedAllocationData& rhs) const { + return slices_sorted_by_offset == rhs.slices_sorted_by_offset; + } + }; + + // A contiguous block of allocation consisting of start and end (logical) + // times, size, and the initial offset. After repacking, if the repacking was + // successful and the allocations were modified, the offset field holds the + // new offset. To support aliased allocations, AllocationBlock also includes a + // vector of AllocationBlock pointers, called colocations. All AllocationBlock + // objects within the colocations must get the same offset. The id should be + // unique and is used to ensure determinism for comparison tie-breaker. + // + // Each AllocationBlock can be treated as an allocation that requires size + // space from start_time to end_time. However, some allocations are really + // composed of slices. In such cases, the repacker can utilize + // the information in the original_slice_data field to achieve an even more + // efficient repacking. + struct AllocationBlock { + int64_t start_time; + int64_t end_time; + int64_t size; + int64_t offset; + int64_t initial_offset; + int64_t id; + std::vector colocations; + + // Optional data structures that are used to improve repacking, when an + // allocation is sliced, e.g., from a sliced prefetch. + std::optional original_slice_data; + std::optional repacked_slice_data; + + std::string ToString() const { + std::string original_slicing_str; + if (original_slice_data.has_value()) { + original_slicing_str = absl::StrCat("; original_slice_data: ", + original_slice_data->ToString()); + } + std::string repacked_slicing_str; + if (repacked_slice_data.has_value()) { + repacked_slicing_str = absl::StrCat("; repacked_slice_data: ", + repacked_slice_data->ToString()); + } + return absl::StrCat("[", start_time, ", ", end_time, "]; size: ", size, + "; offset: ", offset, + "; initial offset: ", initial_offset, + "; # colocations: ", colocations.size(), + original_slicing_str, repacked_slicing_str); + } + + // This is required by BufferIntervalCompare as a tie breaker. Use a unique + // and deterministic id. + bool operator<(const AllocationBlock& other) const { return id < other.id; } + }; + + // Repack the AllocationBlocks provided in the parameter. Returns true if + // allocations have been modified and false if not. Returns a non-ok status if + // there was an error. + virtual StatusOr Repack(absl::Span allocations) = 0; + + protected: + int64_t max_size_; + int64_t alignment_; +}; + +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_REPACKING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/tuning_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/tuning_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..749b4445e4be9afbd187115e3ee16711e4155b39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/tuning_utils.h @@ -0,0 +1,38 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_TUNING_UTILS_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_TUNING_UTILS_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/heap_simulator.h" + +namespace xla { + +namespace memory_space_assignment { + +using BufferInterval = + GlobalDecreasingSizeBestFitHeap::BufferInterval; + +// This function converts sorted_buffer_intervals to order-customized buffer +// intervals respecting a given memory space assignment autotuning config. +void CustomizeSortedBufferInterval( + std::optional> memory_space_assignment_config, + std::vector& sorted_buffer_intervals); + +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_TUNING_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..c2d76208a28e188c222031fd2e15031aaef9f392 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/memory_space_assignment/utils.h @@ -0,0 +1,40 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_UTILS_H_ +#define XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_UTILS_H_ + +#include "xla/service/heap_simulator.h" + +namespace xla { +namespace memory_space_assignment { + +// Encapsulates common utility methods for memory space assignment. +class MemorySpaceAssignmentUtils { + public: + // Returns true if this buffer is allowed to be placed in the alternate + // memory. + static bool IsIntervalAllowedInAlternateMemory( + const GlobalDecreasingSizeBestFitHeap::BufferInterval& + interval); + + // Returns true if the HloValue is allowed to be placed in alternate memory. + static bool IsValueAllowedInAlternateMemory(const HloValue* value); +}; + +} // namespace memory_space_assignment +} // namespace xla + +#endif // XLA_SERVICE_MEMORY_SPACE_ASSIGNMENT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/collective_permute_motion.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/collective_permute_motion.h new file mode 100644 index 0000000000000000000000000000000000000000..8b35b90b90a257d0017381a0d802fe44900b7cc9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/collective_permute_motion.h @@ -0,0 +1,41 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_SPMD_COLLECTIVE_PERMUTE_MOTION_H_ +#define XLA_SERVICE_SPMD_COLLECTIVE_PERMUTE_MOTION_H_ + +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" + +namespace xla { + +// This pass moves collective permutes at the end of a loop to the beginning, +// which makes overlapping possible for megascale decomposed ops. +class CollectivePermuteMotion : public HloModulePass { + public: + CollectivePermuteMotion() = default; + absl::string_view name() const override { + return "collective-permute-motion"; + } + + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; +}; + +} // namespace xla + +#endif // XLA_SERVICE_SPMD_COLLECTIVE_PERMUTE_MOTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/convolution_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/convolution_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..617dbb8aeac6c03552417e78672970a95bade0a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/convolution_handler.h @@ -0,0 +1,43 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_SPMD_CONVOLUTION_HANDLER_H_ +#define XLA_SERVICE_SPMD_CONVOLUTION_HANDLER_H_ + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/service/dot_as_convolution_util.h" +#include "xla/service/spmd/spmd_partitioner.h" + +namespace xla { +namespace spmd { + +// Partition convolution. +StatusOr PartitionConvolution( + PartitionedHlo lhs, PartitionedHlo rhs, const Shape& output_base_shape, + const HloSharding& output_sharding, const DotConvDimsMapping& dims_mapping, + absl::FunctionRef(HloInstruction*, + HloInstruction*, SpmdBuilder*, + const Window& conv_window)> + create_sharded_conv, + const Window& conv_window, HloInstruction* original_hlo, + int64_t num_partitions, const SpmdPartitionerOptions& options, + HloInstruction* partition_id, HloModule* module, SpmdBuilder* b); + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_CONVOLUTION_HANDLER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/custom_call_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/custom_call_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..93c777626301c1bcc003b696d9387ca351615476 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/custom_call_handler.h @@ -0,0 +1,35 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_SPMD_CUSTOM_CALL_HANDLER_H_ +#define XLA_SERVICE_SPMD_CUSTOM_CALL_HANDLER_H_ + +#include + +#include "xla/hlo/ir/hlo_instruction.h" + +namespace xla { +namespace spmd { + +// Creators of custom ops defined by the partitioner itself. + +// Creates a custom op that rotates data along `dim` with the given amount. +std::unique_ptr CreateCustomCallSPMDInternal_RotateRight( + HloInstruction* input, int64_t dim, int64_t amount); + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_CUSTOM_CALL_HANDLER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner.h new file mode 100644 index 0000000000000000000000000000000000000000..26d7a5e6b43cbf33ed79abacd5c86af737dd9f1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner.h @@ -0,0 +1,670 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_SPMD_SPMD_PARTITIONER_H_ +#define XLA_SERVICE_SPMD_SPMD_PARTITIONER_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/container/node_hash_map.h" +#include "absl/functional/function_ref.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_opcode.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/service/call_graph.h" +#include "xla/service/custom_call_sharding_helper.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace spmd { + +struct SpmdPartitionerOptions { + // Always exchange halo on LHS for all convolutions. If false, backprop filter + // convolution exchanges halo on RHS. + bool conv_halo_exchange_always_on_lhs = true; + + // The number of instructions to be reported for the highest memory profile + // instructions. + int64_t report_instruction_count = 5; + + // The minimum size in MiB of an einsum operand to be considered using + // windowed implementation in an HLO loop. + int64_t threshold_for_windowed_einsum_mib = 256; + + // Whether unroll windowed einsum loop by degree of two. + bool unroll_windowed_einsum = false; + + // Whether doing bidirectional collective permute in windowed einsum loop. + bool bidirectional_windowed_einsum = false; + + // Whether the entry computations' signature could change after partitioning. + bool allow_module_signature_change = false; + + // Whether to use cached all-gather to avoid repeatedly replicate a tiled + // tensor. If it is set to false, the result tends to be more + // memory-efficient, and the compiler can use the ScheduleAwareAllGatherCSE + // pass to CSE some all-gathers which are relatively close to each other. + bool cache_all_gather = true; + + // When making a compromise between windowed einsum speed and memory usage + // prefer the former if true. + bool choose_faster_windowed_einsum_over_mem = false; + + // Whether doing bidirectional communication when decomposing independent + // all-gathers. + bool bidirectional_decomposed_all_gather = false; + + // Whether to skip checking the numbers and shardings of windowed einsum's + // users. + bool skip_checking_windowed_einsum_users = false; +}; + +// Class to wrap the computation builder to capture information during SPMD +// transformation. +class SpmdBuilder : public HloComputation::Builder { + public: + SpmdBuilder(const std::string& name, HloInstruction* hlo) + : HloComputation::Builder(name) { + visiting_hlo_ = hlo; + } + + HloInstruction* AddInstruction( + std::unique_ptr instruction) override; + + const std::vector& derived_instructions( + HloInstruction* hlo) { + return instructions_.at(hlo); + } + + void set_visiting_hlo(HloInstruction* hlo) { + visiting_hlo_ = hlo; + instructions_[hlo]; + } + + HloInstruction* visiting_hlo() const { return visiting_hlo_; } + + // Wrapper of queries to broadcast_dims_. + std::optional*> BroadcastDimsForCreatedHlo( + const HloInstruction* hlo) { + auto it = broadcast_dims_.find(hlo); + if (it == broadcast_dims_.end()) { + return std::nullopt; + } + return &it->second; + } + + private: + // Currently visiting instruction. + HloInstruction* visiting_hlo_; + + // Map from the currently visiting (old) instruction to new instructions + // created during SPMD partitioning. + HloInstructionMap> instructions_; + + // Maps from each created instruction to a set of dimensions that are from + // broadcasts or elementwise ops over broadcasts. This means elements along + // these dimensions have the same value. + absl::flat_hash_map> + broadcast_dims_; +}; + +// A set of functions that create the cross-partition collective ops. +struct SPMDCollectiveOpsCreator { + // Function used to create a partition ID HLO. + std::function create_partition_id; + + // Function used to create a cross-partition all-reduce HLO. + std::function>& partition_subgroups, + int64_t channel_id)> + create_cross_partition_all_reduce; + + // Function used to create a cross-partition collective-permute HLO. + std::function>& src_dst_pairs, + int64_t next_channel_id)> + create_cross_partition_collective_permute; + + // Function used to create a cross-partition all-to-all HLO. + std::function operands, + const std::vector>& partition_subgroups, + int64_t channel_id, std::optional split_dimension)> + create_cross_partition_all_to_all; + + // Function used to create a cross-partition all-gather HLO. This is optional: + // if it is nullptr, the partitioner will use all-reduce instead. + std::function>& partition_subgroups, + int64_t channel_id, int64_t all_gather_dimension)> + create_cross_partition_all_gather; +}; + +// Create a default SPMDCollectiveOpsCreator. +SPMDCollectiveOpsCreator GetDefaultCollectiveOpsCreator(int64_t num_partitions, + int64_t num_replicas); + +// Logger to report memory usage during SPMD partitioning. +class SpmdLogger { + public: + SpmdLogger(int64_t report_instruction_count, bool disabled) + : report_instruction_count_(report_instruction_count), + disabled_(disabled) {} + static std::string ReportBeforePartition(const HloModule& module, + int64_t report_instruction_count); + static std::string ReportAfterPartition(const HloModule& module, + int64_t report_instruction_count); + + // Registers the logging for the groups of instructions created to transform + // the given hlo. + void RegisterLogEntry(HloInstruction* hlo, + const std::vector& group); + + std::string MakeReport(); + + private: + template + static std::string ReportMemoryUsage(const HloModule& module, const F& filter, + int64_t report_instruction_count); + + // A vector of logging messages (one for each original HLO instruction), where + // the first integer of the pair represents the size of the HBM used. + std::vector> entries_; + + int64_t report_instruction_count_; + + // Note that we allow creating a *disabled* logger when logging is not + // enabled, in which case it is supposed to avoid doing any potentially + // expensive work. The logger is still created in this case and passed to the + // users to help avoid changing current call sites. + const bool disabled_; +}; + +class SpmdPartitioningVisitor; + +class SpmdPartitioner : public HloModulePass { + public: + SpmdPartitioner(int64_t num_partitions, int64_t num_replicas, + SpmdPartitionerOptions options); + SpmdPartitioner(int64_t num_partitions, int64_t num_replicas, + SpmdPartitionerOptions options, + SPMDCollectiveOpsCreator collective_ops_creator) + : num_partitions_(num_partitions), + num_replicas_(num_replicas), + options_(std::move(options)), + collective_ops_creator_(std::move(collective_ops_creator)) {} + absl::string_view name() const override { return "spmd-partitioning"; } + using HloPassInterface::Run; + StatusOr Run( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + + // Transforms the given computation with SPMD instructions, replacing it with + // a new computation. + StatusOr PartitionComputation(HloComputation* computation, + const HloSharding& root_sharding, + int64_t* next_channel_id, + SpmdLogger* logger, + const CallGraph& call_graph); + + // Creates all-gather(s) based on HloSharding. Can be overridden to customize. + // The default uses a single all-gather even if there are multiple sharded + // dimensions, and adds potential reshapes and transposes to achieve that. + // If it returns false, the partitioner will fall back to all-reduce. + // `selected_dims` specifies the dimensions along which the all-gather happens + // in the tiled sharding, which allows potentially creating a subgroup + // all-gather. + virtual HloInstruction* AllGatherShards( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator); + + // Creates all-reduce(s) across devices along selected_dims in sharding. Can + // be overridden to customize. + virtual HloInstruction* AllReduceAlongShardingDims( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator, + HloComputation* reduction); + + const SpmdPartitionerOptions& options() { return options_; } + + protected: + virtual std::unique_ptr CreateVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdLogger* logger, + SpmdPartitionerOptions options, const CallGraph& call_graph); + + // This is the internal implementation for AllGatherShards(), returns a pair + // of hlo instructions whose first element is the result of the all-gather + // shard(which might not be the all-gather itself and it could go through + // some other formatting instructions), and the second element is the + // all-gather being generated or nullptr is no all-gather is generated. + std::pair AllGatherShardsInternal( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator, bool per_dim_ag); + + HloInstruction* AllReduceAlongShardingDimsInternal( + SpmdBuilder* b, HloInstruction* operand, const HloSharding& sharding, + int64_t* next_channel_id, absl::Span selected_dims, + const SPMDCollectiveOpsCreator& collectives_creator, + HloComputation* reduction, bool per_dim_ar); + + // Verifies that the sharding of instructions in the module are valid, and + // also fill in missing sharding information. + virtual Status PreprocessSharding( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + // Returns if the given side-effecting instruction is allowed to have + // replicated sharding. + virtual bool CanSideEffectingHaveReplicatedSharding( + const HloInstruction* hlo) { + if (hlo->opcode() == HloOpcode::kCustomCall) { + if (auto* partitioner = + GetCustomCallPartitioner(hlo->custom_call_target())) { + return partitioner->CanSideEffectingHaveReplicatedSharding(); + } + } + return hlo->opcode() == HloOpcode::kInfeed || + hlo->opcode() == HloOpcode::kOutfeed; + } + + // Preprocesses the graph to simplify some communication patterns. E.g., merge + // pad->slice into a single pad with potentially negative padding to avoid + // multiple halo exchanges. + Status PreprocessHlos( + HloModule* module, + const absl::flat_hash_set& execution_threads); + + const int64_t num_partitions_; + const int64_t num_replicas_; + + SpmdPartitionerOptions options_; + SPMDCollectiveOpsCreator collective_ops_creator_; + std::vector> device_groups_; +}; + +// Class describes partition state of the data represented by an HLO created +// during SPMD partitioning pass. +// +// Data on some devices may include padding region, if the base (full) shape +// could not be evenly partitioned. +class PartitionedHlo { + public: + // Return value for ReshardAsWindowedInput which describes the resharded HLO, + // the window for the user on the shard, and if necessary, the dynamic slice + // offsets to be applied to the output of the op being sharded. + struct WindowedInputShardReturnValue { + HloInstruction* sharded_input; + Window shard_window; + std::optional> dynamic_slice_index_on_output; + }; + // A cache for resharding each partitioned HLO. + struct ReshardCache { + struct PerHloCache { + absl::flat_hash_map reshard_cache; + std::vector< + std::tuple> + window_reshard_cache; + }; + // Use absl::node_hash_map for pointer stability. + absl::node_hash_map per_hlo_cache; + // Caches for nested partitioning of grouped sharding. Each string key + // represents a unique way of grouping devices. + absl::flat_hash_map> + groupd_caches; + }; + struct PartitioningState { + SpmdBuilder* b; + HloModule* module; + int64_t num_replicas; + HloInstruction* partition_id; + SPMDCollectiveOpsCreator collective_ops_creator; + int64_t* next_channel_id; + ReshardCache* reshard_cache; + SpmdPartitioner* partitioner; + }; + PartitionedHlo(HloInstruction* hlo, Shape base_shape, PartitioningState state) + : hlo_(hlo), base_shape_(base_shape), state_(std::move(state)) { + CHECK(hlo->has_sharding()) + << "PartitionedHlo is missing sharding:" << hlo->ToString(); + } + + PartitionedHlo CloneWithNewHlo(HloInstruction* hlo) const { + PartitionedHlo new_phlo = *this; + new_phlo.hlo_ = hlo; + if (!hlo->has_sharding() && hlo_->has_sharding()) { + hlo->copy_sharding(hlo_); + } + return new_phlo; + } + + // Reshards the current SPMD instruction to a new sharding with optional + // specified pad value used during resharding. Could only modify the reshard + // cache. + PartitionedHlo Reshard(const HloSharding& target, + std::optional pad_value = std::nullopt); + + // Pads the garbage area of the output with the provided value. Normally, + // unevenly partitioned dimensions are padded on the right, but this function + // allows specifying left-padded dimensions, which can be used during the + // handling of kReverse, etc. + PartitionedHlo PadWithValue( + HloInstruction* pad_value, + absl::Span left_padded_dims = {}, + absl::Span skipped_dims = {}) const; + + // Same as PadWithValue but does not create a new PartitionedHlo. + HloInstruction* PadWithValueHlo( + HloInstruction* pad_value, + absl::Span left_padded_dims = {}, + absl::Span skipped_dims = {}) const; + + PartitionedHlo PadWithZero(absl::Span left_padded_dims = {}, + absl::Span skipped_dims = {}) const; + + // Returns the SPMD instruction. + HloInstruction* hlo() const { return hlo_; } + + // Returns the sharding of the SPMD instruction. + const HloSharding& sharding() const { return hlo_->sharding(); } + + // Returns the rank of the SPMD instruction. + const int64_t rank() const { return base_shape_.rank(); } + + // Original full shape of the data. + const Shape& base_shape() const { return base_shape_; } + + int64_t NewChannel() const { return (*state_.next_channel_id)++; } + + // Reshards the HLO to a usable partitioned input for a windowed user. Could + // only modify the reshard cache. + std::optional ReshardAsWindowedInput( + const Window& window, const HloSharding& target, + HloInstruction* pad_value, bool mask_invalid_region = true, + bool force_mask_in_compact = false); + + const PartitioningState& state() const { return state_; } + + // Helper function to replicate the data on all devices. Could only modify + // the reshard cache. + PartitionedHlo Replicate(); + + // Helper function to replicate the data for partitions along the given dims. + HloInstruction* ReplicatePartial(absl::Span dims); + + // Set state of the partitoned HLO. + void set_state(PartitioningState state) { state_ = std::move(state); } + + private: + // Same as Reshard except that it does not explicitly modify the reshard + // cache, although it would indirectly modify by calling Replicate(). + PartitionedHlo ReshardNoCache(const HloSharding& target, + std::optional pad_value = std::nullopt, + bool allow_full_replication = true); + + // Helper function to broadcast data from a single device to all devices. + PartitionedHlo Broadcast() const; + + // Try to perform complicated reshard handling by splitting a big reshard into + // multiple reshards using that can be handled directly. + std::optional TryComplexReshardHandling( + const HloSharding& target); + + // Helper function to reshard the tensor using AllToAll (instead of the + // default of Replicate followed by Slice). + PartitionedHlo ReshardWithAllToAll( + const HloSharding& target, + absl::Span> source_target_dims) const; + + // Helper function to reshard the tensor using CollectivePermute. + PartitionedHlo ReshardWithCollectivePermute(const HloSharding& target) const; + + // Helper function to reshard to partial replicate using AllGather. + std::optional ReshardToPartialReplicateWithAllGather( + const HloSharding& target); + + // Helper function to reshard from partial replicate using DynamicSlice. + std::optional ReshardFromPartialReplicateWithDynamicSlice( + const HloSharding& target); + + // Helper function to reshard from partial replicate using AllToAll. + std::optional ReshardPartialReplicateWithAllToAll( + const HloSharding& target); + + // SPMD instruction. + HloInstruction* hlo_; + + // The original shape of the data before SPMD transformation is applied. + Shape base_shape_; + + PartitioningState state_; +}; + +struct DotConvDimsMapping { + // The dimension numbers for the operands and output corresponding to a + // logical dimension (e.g., batch, contracting, non-contracting). If an + // operand or the output doesn't have the logical dimension, it is set to + // -1. + struct DimsMapping { + int64_t lhs; + int64_t rhs; + int64_t output; + // input mapped to index in input_spatial_dimensions(). + int64_t spatial; + }; + std::vector batch_dims; + std::vector contracting_dims; + std::vector lhs_non_contracting_dims; + std::vector rhs_non_contracting_dims; + std::vector conv_spatial_dims; +}; + +class SpmdPartitioningVisitor : public DfsHloVisitorWithDefault { + public: + SpmdPartitioningVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdLogger* logger, + SpmdPartitionerOptions options, SpmdPartitioner* partitioner, + const CallGraph& call_graph); + + Status DefaultAction(HloInstruction* hlo) override; + Status HandleAllReduce(HloInstruction* hlo) override; + Status HandleBroadcast(HloInstruction* hlo) override; + Status HandleConstant(HloInstruction* hlo) override; + Status HandleCustomCall(HloInstruction* hlo) override; + Status HandleDot(HloInstruction* hlo) override; + Status HandleDynamicSlice(HloInstruction* hlo) override; + Status HandleDynamicUpdateSlice(HloInstruction* hlo) override; + Status HandleFft(HloInstruction* hlo) override; + Status HandleGather(HloInstruction* hlo) override; + Status HandleGetTupleElement(HloInstruction* hlo) override; + Status HandleInfeed(HloInstruction* hlo) override; + Status HandleOptimizationBarrier(HloInstruction* hlo) override; + Status HandleOutfeed(HloInstruction* hlo) override; + Status HandlePad(HloInstruction* hlo) override; + Status HandleParameter(HloInstruction* hlo) override; + Status HandleReduce(HloInstruction* hlo) override; + Status HandleReverse(HloInstruction* hlo) override; + Status HandleWhile(HloInstruction* hlo) override; + Status HandleConditional(HloInstruction* hlo) override; + Status HandleReduceWindow(HloInstruction* hlo) override; + Status HandleSelectAndScatter(HloInstruction* hlo) override; + Status HandleTuple(HloInstruction* hlo) override; + Status HandleRng(HloInstruction* hlo) override; + Status HandleConvolution(HloInstruction* hlo) override; + Status HandleConcatenate(HloInstruction* hlo) override; + Status HandleScatter(HloInstruction* hlo) override; + Status HandleSlice(HloInstruction* hlo) override; + Status HandleSort(HloInstruction* hlo) override; + Status HandleTranspose(HloInstruction* hlo) override; + Status HandleReshape(HloInstruction* hlo) override; + Status HandleIota(HloInstruction* hlo) override; + Status HandlePartitionId(HloInstruction* hlo) override; + + // Implementation of dot partitioning given DotGeneralDimsMapping. + Status HandleDotHelper(HloInstruction* hlo, + const DotConvDimsMapping& dims_mapping, + absl::FunctionRef( + HloInstruction*, HloInstruction*, SpmdBuilder*, + const Window& conv_window)> + create_sharded_dot); + + // Common handle for elementwise HLOs. + Status HandleElementwise(HloInstruction* hlo); + + // Common handle for HLOs that runs on a single device. + Status HandleSingleDevice(const HloInstruction* hlo); + + // CustomCall handlers per call target. + Status HandleCustomCallTopK(HloInstruction* hlo); + // Convenient custom ops defined by the partitioner itself. + Status HandleCustomCallSPMDInternal_RotateRight(HloInstruction* hlo); + + // Returns the PartitionedHlo that corresponds to the original hlo. + PartitionedHlo& GetPartitionedHlo(const HloInstruction* hlo) { + CHECK_EQ(partitioned_instructions_.count(hlo), 1); + return partitioned_instructions_.find(hlo)->second; + } + + // Sets the PartitionedHlo for the original hlo. + void SetPartitionedHlo(const HloInstruction* hlo, + const PartitionedHlo& partitioned_hlo) { + CHECK_EQ(partitioned_instructions_.count(hlo), 0); + partitioned_instructions_.emplace(hlo, partitioned_hlo); + changed_ = true; + } + + // Convenient wrapper that creates PartitionedHlo from the result of the func + // and maps it to the given original hlo. + void SetPartitionedHlo(const HloInstruction* hlo, + absl::FunctionRef func) { + HloInstruction* new_hlo = func(); + new_hlo->set_sharding(hlo->sharding()); + SetPartitionedHlo( + hlo, PartitionedHlo(new_hlo, hlo->shape(), MakePartitioningState())); + changed_ = true; + } + + int64_t NewChannel() { return (*next_channel_id_)++; } + + PartitionedHlo::PartitioningState MakePartitioningState(); + + SpmdBuilder* builder() { return &b_; } + + virtual StatusOr DoPartition(HloComputation* computation, + const HloSharding& root_sharding, + const SpmdPartitionerOptions& options); + + virtual double GetComputationTimeInMilliSec(HloInstruction* hlo) { + return 0.0; + } + + virtual double GetCommunicationTimeInMilliSec( + int64_t bytes, absl::Span device_groups) { + return 0.0; + } + + virtual int GetCommunicationMultiplier( + absl::Span device_groups) { + return 1; + } + + std::vector CreateReplicaGroups( + std::vector>& groups); + + const CallGraph& call_graph() { return call_graph_; } + + // Information about a loop created for windowed dot-general. Used when + // DoCodeMotionForWindowedDotGeneralLoops() executes after the visitor + // finishes traversing the graph. + struct WindowedDotGeneralLoop { + HloInstruction* while_loop; + int64_t windowed_operand; + bool windowed_in_contracting_dims; + bool windowed_in_batch_dims; + bool operands_sharded_at_contracting_dims; + int64_t num_partitions; + std::vector loop_replica_groups; + }; + + protected: + Status Preprocess(HloInstruction* hlo) override; + Status Postprocess(HloInstruction* hlo) override; + + // Performs code motion for windowed dot-general loops in + // windowed_dot_general_loops_. Invoked after the visitor finishes traversing + // the graph. + Status DoCodeMotionForWindowedDotGeneralLoops( + HloComputation* computation, const SpmdPartitionerOptions& options); + + bool changed_; + HloModule* module_; + int64_t num_partitions_; + int64_t num_replicas_; + + SPMDCollectiveOpsCreator collective_ops_creator_; + + // Tracks the next channel id to use for cross-partition all-reduce. + int64_t* next_channel_id_; + SpmdBuilder b_; + + std::vector windowed_dot_general_loops_; + + HloInstruction* partition_id_; + + private: + PartitionedHlo::ReshardCache reshard_cache_; + + // Mapping from the instruction in the original computation to the new SPMD + // partitioned instruction. + ConstHloInstructionMap partitioned_instructions_; + + HloInstruction* visiting_hlo_; + SpmdLogger* logger_; + const SpmdPartitionerOptions options_; + SpmdPartitioner* partitioner_; + std::vector visiting_hlo_operand_shardings_; + std::optional visiting_hlo_sharding_; + std::optional visiting_num_partitions_; + std::optional visiting_collective_ops_creator_; + std::optional visiting_partition_id_; + std::vector visiting_state_; + std::vector> device_groups_; + const CallGraph& call_graph_; +}; + +} // namespace spmd +} // namespace xla +#endif // XLA_SERVICE_SPMD_SPMD_PARTITIONER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0bb05c96577394322d134e169da15751ab1e5f4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/spmd_partitioner_util.h @@ -0,0 +1,568 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_SPMD_SPMD_PARTITIONER_UTIL_H_ +#define XLA_SERVICE_SPMD_SPMD_PARTITIONER_UTIL_H_ + +#include +#include +#include +#include +#include +#include + +#include "xla/hlo/ir/hlo_casting_utils.h" +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/hlo/utils/hlo_sharding_util.h" +#include "xla/literal_util.h" +#include "xla/service/spmd/spmd_partitioner.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" + +namespace xla { +namespace spmd { + +template +using IsCompOrCompBuilder = + typename std::enable_if_t::value || + std::is_same::value || + std::is_same::value>; + +struct GatherScatterParallelDimSharding { + HloSharding indices_sharding; + HloSharding operand_sharding; +}; + +// Returns true if the given sharding contains any replicated sharding. +bool HasReplicatedSharding(const HloSharding& sharding); + +// Base for creating constants. +template > +HloInstruction* CreateConstantBase(const Shape& shape, Literal value, T* b, + Literal (*literal_creator)(Literal, + PrimitiveType)) { + if (shape.IsTuple()) { + std::vector elements; + for (int64_t i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) { + elements.push_back( + CreateConstantBase(ShapeUtil::GetTupleElementShape(shape, i), + value.Clone(), b, literal_creator)); + } + return b->AddInstruction(HloInstruction::CreateTuple(elements)); + } + + if (shape.IsToken()) { + return b->AddInstruction(HloInstruction::CreateToken()); + } + auto c = b->AddInstruction(HloInstruction::CreateConstant( + literal_creator(std::move(value), shape.element_type()))); + if (shape.rank() == 0) { + return c; + } + return b->AddInstruction(HloInstruction::CreateBroadcast(shape, c, {})); +} + +// Creates constant value instructions of the given shape. The literal must be a +// scalar shape and is broadcast to the given shape. +template > +HloInstruction* CreateConstant(const Shape& shape, Literal value, T* b) { + auto identity = [](Literal value, PrimitiveType primitive_type) { + CHECK(ShapeUtil::IsScalarWithElementType(value.shape(), primitive_type)); + return value; + }; + return CreateConstantBase(shape, std::move(value), b, identity); +} + +// Creates zero value instructions of the given shape. +template > +HloInstruction* CreateZero(const Shape& shape, T* b) { + auto zero = [](Literal /*unused*/, PrimitiveType primitive_type) { + return LiteralUtil::Zero(primitive_type); + }; + return CreateConstantBase(shape, /*unused*/ Literal(), b, zero); +} + +// Creates one value instructions of the given shape. +template > +HloInstruction* CreateOne(const Shape& shape, T* b) { + auto one = [](Literal /*unused*/, PrimitiveType primitive_type) { + return LiteralUtil::One(primitive_type); + }; + return CreateConstantBase(shape, /*unused*/ Literal(), b, one); +} + +template > +HloInstruction* CreateR0WithType(PrimitiveType type, NativeT value, T* b) { + auto literal = LiteralUtil::CreateR0(value) + .ConvertToShape(ShapeUtil::MakeShape(type, {})) + .value(); + return b->AddInstruction(HloInstruction::CreateConstant(std::move(literal))); +} + +template > +inline HloInstruction* CreateFirstWithType(PrimitiveType type, T* b) { + if (type == F32) { + auto float_pad_value = std::numeric_limits::quiet_NaN(); + return CreateR0WithType(type, -float_pad_value, b); + } + auto literal = LiteralUtil::MinValue(type); + return b->AddInstruction(HloInstruction::CreateConstant(std::move(literal))); +} + +template > +inline HloInstruction* CreateLastWithType(PrimitiveType type, T* b) { + if (type == F32) { + auto float_pad_value = std::numeric_limits::quiet_NaN(); + return CreateR0WithType(type, float_pad_value, b); + } + auto literal = LiteralUtil::MaxValue(type); + return b->AddInstruction(HloInstruction::CreateConstant(std::move(literal))); +} + +// Create a binary add computation of the given type and add to the module. +HloComputation* MakeBinaryAdd(PrimitiveType type, HloModule* module); + +// Returns true if the shape can be evenly partitioned for the given sharding. +// All tile sharded dimensions should be evenly divisible and there should be no +// single-device sharding. Replicate sharding is considered even partition. +bool EvenlyPartitions(const Shape& shape, const HloSharding& sharding); + +// Returns the shard shape of the given shape when it is partitioned for the +// target sharding. +Shape MakePartitionedShape(const Shape& shape, const HloSharding& sharding); + +// Similar to ShapeUtil::ByteSizeOf(), but does not check it has dense layout +// since this can be before layout assignment. +int64_t ShapeSizeInBytes(const Shape& shape); + +// Creates a table lookup HLO using the ordinal as the offset. +template +HloInstruction* TableLookup(absl::Span table, PrimitiveType type, + HloInstruction* ordinal, SpmdBuilder* b) { + HloInstruction* table_hlo = b->AddInstruction( + HloInstruction::CreateConstant(LiteralUtil::CreateR1(table))); + HloInstruction* value = b->AddInstruction(HloInstruction::CreateDynamicSlice( + ShapeUtil::MakeShape(type, {1}), table_hlo, {ordinal}, {1})); + return b->AddInstruction( + HloInstruction::CreateReshape(ShapeUtil::MakeShape(type, {}), value)); +} + +// Returns the shard shape for a partition without padding due to uneven +// sharding. +Shape MakeNonPaddedShapeForGivenPartition(const Shape& shape, + const HloSharding& sharding, + int64_t partition_id); + +// Generates the HLO instructions that represent the dimension offsets on any +// device. The size of the returned vector is the rank of the given shape. +// If `dims` is non-empty, the generated offsets will only be non-zero for those +// dimensions. +std::vector MakePartitionOffsets( + const Shape& shape, const HloSharding& sharding, + HloInstruction* partition_id, SpmdBuilder* b, + absl::Span dims = {}); + +// Returns the offsets of the partition in the tile assignment. +std::vector MakeTiledPartitionOrdinals( + const HloSharding& sharding, HloInstruction* partition_id, SpmdBuilder* b); + +// Pads hlo to the desired shape using high padding. Either a builder or a +// computation needs to be supplied, but not both. +template > +HloInstruction* PadToShape(HloInstruction* hlo, const Shape& padded_shape, T* b, + std::optional value = std::nullopt) { + if (ShapeUtil::Compatible(hlo->shape(), padded_shape)) { + return hlo; + } + PaddingConfig padding_config; + for (int64_t i = 0; i < padded_shape.rank(); ++i) { + auto padding_config_dim = padding_config.add_dimensions(); + padding_config_dim->set_edge_padding_low(0); + padding_config_dim->set_interior_padding(0); + padding_config_dim->set_edge_padding_high(padded_shape.dimensions(i) - + hlo->shape().dimensions(i)); + } + const Shape padding_shape = + ShapeUtil::MakeScalarShape(hlo->shape().element_type()); + HloInstruction* padding = + value.has_value() ? CreateConstant(padding_shape, std::move(*value), b) + : CreateZero(padding_shape, b); + return b->AddInstruction( + HloInstruction::CreatePad(padded_shape, hlo, padding, padding_config)); +} + +// Returns the padded shape when combining all partitions. +Shape GetPaddedShapeForUnevenPartitioning(const Shape& base_shape, + const HloSharding& sharding); + +// Pads the HLO (with base shape) for uneven tiled partition to make it evenly +// partitionable. +template > +HloInstruction* PadBaseShapeBeforeUnevenTiledSharding( + HloInstruction* hlo, const HloSharding& sharding, T* b, + std::optional value = std::nullopt) { + auto padded_base_shape = + GetPaddedShapeForUnevenPartitioning(hlo->shape(), sharding); + if (ShapeUtil::Compatible(padded_base_shape, hlo->shape())) { + return hlo; + } + return PadToShape(hlo, padded_base_shape, b, std::move(value)); +} + +// Returns the index of the unique tile dimension. Returns std::nullopt if the +// given sharding is not tiled or tiled along multiple dimensions. +std::optional UniqueTiledDim(const HloSharding& sharding); + +// Utilities for symbolic offset calculation and halo exchange. +class OffsetCalculation; + +// Represents a calculation over integers: +// (shard_ordinal * multiplier + offset) / divisor +class MultiplyAddDivideOffsetCalculation { + public: + MultiplyAddDivideOffsetCalculation() + : multiplier_(0), offset_(0), divisor_(1) {} + MultiplyAddDivideOffsetCalculation(int64_t multiplier, int64_t offset, + int64_t divisor); + + OffsetCalculation operator-( + const MultiplyAddDivideOffsetCalculation& other) const; + OffsetCalculation operator+( + const MultiplyAddDivideOffsetCalculation& other) const; + + bool operator==(const MultiplyAddDivideOffsetCalculation& other) const { + return multiplier_ == other.multiplier_ && offset_ == other.offset_ && + divisor_ == other.divisor_; + } + + bool IsConstant() const { return multiplier_ == 0; } + void Simplify(); + int64_t Calculate(int64_t shard_ordinal) const; + HloInstruction* Calculate(HloInstruction* shard_ordinal, + SpmdBuilder* b) const; + + // Returns the maximum result for shard ordinals in the range + // [start_ordinal, limit_ordinal). + int64_t MaxInRange(int64_t start_ordinal, int64_t limit_ordinal) const; + + private: + int64_t multiplier_; + int64_t offset_; + int64_t divisor_; +}; + +// Represents a calculation over integers based on results of other calculations +// defined by an opcode. If the opcode is kCopy, it simply wraps an +// MultiplyAddDivideOffsetCalculation. +class OffsetCalculation { + public: + OffsetCalculation() : opcode_(HloOpcode::kCopy), copy_from_() {} + explicit OffsetCalculation( + const MultiplyAddDivideOffsetCalculation& copy_from) + : opcode_(HloOpcode::kCopy), copy_from_(copy_from) {} + OffsetCalculation(const OffsetCalculation& copy_from) { *this = copy_from; } + OffsetCalculation(HloOpcode opcode, + const MultiplyAddDivideOffsetCalculation& lhs, + const MultiplyAddDivideOffsetCalculation& rhs) + : opcode_(opcode), + lhs_(std::make_unique(lhs)), + rhs_(std::make_unique(rhs)) {} + OffsetCalculation(HloOpcode opcode, const OffsetCalculation& lhs, + const OffsetCalculation& rhs) + : opcode_(opcode), + lhs_(std::make_unique(lhs)), + rhs_(std::make_unique(rhs)) {} + + OffsetCalculation& operator=(const OffsetCalculation& other); + + // Returns whether the calculation returns the same value for all shards. This + // is conservative and could return false even if it is actually constant. + bool IsConstant() const; + + OffsetCalculation operator-(const OffsetCalculation& other) const; + OffsetCalculation operator+(const OffsetCalculation& other) const; + bool operator==(const OffsetCalculation& other) const; + int64_t Calculate(int64_t shard_ordinal) const; + HloInstruction* Calculate(HloInstruction* shard_ordinal, + SpmdBuilder* b) const; + + // Returns the maximum result for shard ordinals in the range + // [start_ordinal, limit_ordinal). + int64_t MaxInRange(int64_t start_ordinal, int64_t limit_ordinal) const; + + private: + HloOpcode opcode_; + std::unique_ptr lhs_; + std::unique_ptr rhs_; + MultiplyAddDivideOffsetCalculation copy_from_; +}; + +// Performs halo exchange on the given dimension based on the provided +// left/right halo size functions. Returns nullopt if the halo is beyond the +// direct neighbor of the shard. +std::optional ExchangeHalo( + HloInstruction* hlo, const OffsetCalculation& left_halo_size_function, + const OffsetCalculation& right_halo_size_function, int64_t dim, + const HloSharding& target, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b); + +// Exchange halo on all dimensions of the HLO. Returns nullopt if any one of the +// dimensions fails to exchange halo (halo is beyond the neighbor shard). +std::optional ExchangeHalo( + HloInstruction* hlo, + std::vector left_halo_size_functions, + std::vector right_halo_size_functions, + const HloSharding& target, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b); + +// A compact version of halo exchange, which generates fewer collective permutes +// when the halo ranges are far from the current shard while the final result +// size is small. It tries to reuse the same collective permute to do as many +// disjoint communications as possible. It also includes data masking. pad_value +// can be nullptr, which means the value in padding regions doesn't matter. +HloInstruction* ExchangeHaloCompact( + HloInstruction* hlo, const Shape& base_shape, + const OffsetCalculation& left_halo_size_function, + const OffsetCalculation& right_halo_size_function, + HloInstruction* pad_value, int64_t dim, const HloSharding& sharding, + HloInstruction* shard_ordinal, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b); + +// Exchanges halos and performs pad/dynamic-slice on the concatenated data such +// that the result starts with the first needed element on each shard. It also +// masks off invalid data due to padding. +// Arguments: +// hlo: the HLO op before halo exchange +// explicit_left_padding_on_full_shape: the amount of left padding to be added +// explicitly by this function on the base shape before partitioning. Without +// base dilation, this is usually set to the window's padding_low so that the +// sharded op do not need to add padding_low on the window; however, with base +// dilation, this could only be set to a custom size. +// padded_full_shape_size: the size of the padded full shape on the given +// dimension, which includes explicit_left_padding_on_full_shape and required +// right padding to make the shape evenly shardable. +// shard_size_with_halo: the shard size on the dimension after halo exchange. +// If different shards have different sizes, use the maximum size. +// offset_on_padded_shape: the offset HLO (S32) that represents the start of +// each shard on the padded full shape. +// pad_value: the padding value used on the full shape. +// force_mask_in_compact: If true, masking is always applied if it uses +// ExchangeHaloCompact. An example is that certain cases in pad can skip +// masking in non-compact halo exchange, but not in compact ones. +std::optional ExchangeHaloAndGetValidData( + HloInstruction* hlo, const Shape& base_shape, + const OffsetCalculation& left_halo_size_function, + const OffsetCalculation& right_halo_size_function, + int64_t explicit_left_padding_on_full_shape, int64_t padded_full_shape_size, + int64_t shard_size_with_halo, int64_t dim, const HloSharding& target, + HloInstruction* offset_on_padded_shape, HloInstruction* pad_value, + HloInstruction* partition_ordinal, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, SpmdBuilder* b, bool mask_invalid_region = true, + bool force_mask_in_compact = false); + +// Uses halo exchange to change from right-padding to left-padding for uneven +// tiled sharding on the given dimensions. Tiled sharding always pads uneven +// partitioned data on the right, but we need to swap it to the left for +// kReverse or kConvolution with window reversal. +HloInstruction* HaloExchangeToPadOnLeft(PartitionedHlo& original, + absl::Span dims); + +// Check if the computation is GT comparison and safe for NaNs. +bool IsNanSafeGt(HloComputation* computation); + +// Return k in TopK when input value is parttioned in the sort dimension. +std::optional GetKValueInTopKWhenPartitionSortDim(HloInstruction* hlo); + +// Slices the first k elements at slice dimension. +HloInstruction* SliceFirstK(HloInstruction* hlo, SpmdBuilder* builder, + int64_t slice_dim, int64_t k); + +// Check if a dimension is sharded. +int64_t ShardCountAtDim(const HloSharding& sharding, int64_t dim); + +// Returns the list of source-target pairs of dimensions to swap during +// resharding via all-to-all. Reshard can be done by swapping each pair at a +// time. +std::optional>> +GetReshardAllToAllSourceTargetDims(const HloSharding& source, + const HloSharding& target); + +// Returns whether the resharding can be done via collective-permute. +bool CanReshardWithCollectivePermute(const HloSharding& source, + const HloSharding& target); + +// Returns a new GroupedSharding that has the same group definition of +// `reference`. +hlo_sharding_util::GroupedSharding AlignGroupsWith( + hlo_sharding_util::GroupedSharding grouped_sharding, + const hlo_sharding_util::GroupedSharding& reference, + bool ignore_group_order = false); + +// Align device groups between the two shardings. Equivalent in calling +// GroupShardingOnDims on the two sharding AlignGroupsWith and then +// UngroupSharding +HloSharding AlignShardingOnDims(const HloSharding& sharding, + absl::Span sharding_dims, + const HloSharding& reference, + absl::Span reference_dims); + +// AlignShardingOnDims only if it doesn't change the sharding when ungrouped. +std::optional AlignGroupsWithIfCompatible( + hlo_sharding_util::GroupedSharding grouped_sharding, + const hlo_sharding_util::GroupedSharding& reference); + +// Returns the per-group base shape, i.e., before applying the in-group +// sharding. +Shape GetPerGroupBaseShape( + const hlo_sharding_util::GroupedSharding& grouped_sharding, + const Shape& original_base_shape); + +// Returns the partition id within a group. +HloInstruction* GetInGroupPartitionId( + HloInstruction* partition_id, + const std::vector>& device_groups, SpmdBuilder* b); + +// Creates the nested partitioner state for in-group partitioning. +PartitionedHlo::PartitioningState CreatePerGroupPartitioningState( + const PartitionedHlo::PartitioningState& state, + const std::vector>& device_groups, SpmdBuilder* b); + +// Partially shards a replicated HLO into groups along the group dimensions, and +// within each group data is still replicated. +HloInstruction* PerGroupSliceFromReplicated( + HloInstruction* replicated, HloInstruction* partition_id, + const std::vector>& device_groups, + absl::Span group_dims, + absl::Span group_dim_sizes, SpmdBuilder* b); + +// Pad the shape from partial replicate shape for `dst_sharding`. +// If dst_sharding needs more padding and per_shard_size increased in +// dst_sharding, halo exchange on the right side is needed. +std::optional PadFromPartialReplicateShape( + HloInstruction* hlo, const Shape& base_shape, + const HloSharding& src_sharding, const HloSharding& dst_sharding, + const std::vector& expand_tile_dims, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, HloInstruction* partition_id, SpmdBuilder* b); + +// Get the compatible sharding from a partial replicate sharding to a desired +// target tiled sharding. +// Compatible means replicate sharding can transform to the target tile +// dimensions by dynamic slice. +// For example, if partial_sharding is +// {devices=[1,2,2]0,1,2,3 last_tile_dim_replicate} +// Target sharding is {devices=[2,2]0,1,2,3}, the returned compatible sharding +// will be sharding={devices=[2,2]0,2,1,3}. +// If patial replicate sharding is not partial replicate or can't reshard to +// target_tile_dims by dynamic slice, return std::nullopt. +// If target_sharding is already compatible, returns it. +std::optional PartialReplicateReshardCompatibleSharding( + const HloSharding& partial_sharding, const HloSharding& target_sharding); + +// Do left halo exchange if all-reduce directly from tile sharding to partial +// replicate sharding will remove useful data from the source. +std::optional TileToPartialReplicateHaloExchange( + HloInstruction* hlo, const Shape& base_shape, + const HloSharding& src_sharding, const HloSharding& dst_sharding, + const std::vector& replicate_dims, + const SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, HloInstruction* partition_id, SpmdBuilder* b); + +// Finds a list of dimensions that can be grouped on such that it will have the +// specified device groups. Group order and dimension order are ignored. +std::optional> FindMatchingPartitionedDimsForGrouping( + const HloSharding& sharding, + const std::vector>& device_groups); + +// Create a sharding that matches the provided source sharding on the +// specified dimensions. 'target_dims' and 'source_dims' represent the +// dimensions for which the sharding should match in their respective shape. +// If some devices from the source sharding are left over (because not all the +// devices are allocated to 'source_dims' dimensions) then partial replication +// is employed to make sure the number of devices for the two sharding match. +HloSharding CreateMatchingShardingOnDims(const Shape& target_shape, + const HloSharding& source_sharding, + absl::Span target_dims, + absl::Span source_dims); + +// Returns if the sharding across operand and indices of a gather/scatter is +// across parallel dimensions and matches what SPMD partitioner supports. +std::optional +GatherScatterOperandsShardedAcrossParallelDims( + const HloInstruction& operand, const HloInstruction& indices, + const hlo_sharding_util::GatherScatterParallelDims& parallel_dims); + +// Pattern rewrite preprocessing utilities. + +// Returns rotate_amount if the concat(lhs, rhs) is equivalent to rotating the +// elements along the concat dimension to the right by rotate_amount, where the +// input of rotation is the shard operand of lhs and rhs. Returns -1 if the +// pattern is not found. +int64_t FindRotateRightPattern(const HloInstruction* concat, + const HloInstruction* lhs, + const HloInstruction* rhs); + +// Describes the pad with wrap pattern. +struct PadWithWrapPattern { + int64_t lhs_slice_start; + int64_t rhs_slice_start; + std::vector lhs_modifiers; + std::vector rhs_modifiers; +}; + +// Returns the `PadWithWrapPattern` if the concat(lhs,mid,rhs) is equivalent to +// padding mid with wrapping (i.e., padding mid with slices of itself). Return +// std::nullopt if the pattern is not found. +std::optional FindPadWithWrapPattern( + const HloInstruction* concat, const HloInstruction* lhs, + const HloInstruction* mid, const HloInstruction* rhs); + +// Reshards data for a slice to be happening on such data with the passed +// parameters. +std::optional +ReshardDataForSlicing(absl::Span strides, + absl::Span starts, + absl::Span limits, + PartitionedHlo to_reshard, + const HloSharding& target_sharding, SpmdBuilder* b); + +// Performs slicing of data based on the windowed sharding passed as input. +HloInstruction* SliceDataFromWindowReshard( + const PartitionedHlo::WindowedInputShardReturnValue& reshard_operand, + absl::Span strides, const Shape& base_shape, + const HloSharding& target_sharding, SpmdBuilder* b); + +// Reshards data for a pad to be happening on such data with the passed +// parameters. +std::optional ReshardDataForPad( + HloInstruction* pad_value, PaddingConfig pc, PartitionedHlo to_reshard, + const HloSharding& target_sharding, SpmdBuilder* b); + +// Performs padding of data based on the windowed sharding passed as input. +HloInstruction* PadDataFromWindowReshard( + const PartitionedHlo::WindowedInputShardReturnValue& reshard_operand, + HloInstruction* pad_value, SpmdBuilder* b); + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_SPMD_PARTITIONER_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/stateful_rng_spmd_partitioner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/stateful_rng_spmd_partitioner.h new file mode 100644 index 0000000000000000000000000000000000000000..76ef60a3c3178a689a07c40299a28364a88e616f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/service/spmd/stateful_rng_spmd_partitioner.h @@ -0,0 +1,80 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_SERVICE_SPMD_STATEFUL_RNG_SPMD_PARTITIONER_H_ +#define XLA_SERVICE_SPMD_STATEFUL_RNG_SPMD_PARTITIONER_H_ + +#include + +#include "xla/hlo/ir/hlo_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo_pass_interface.h" +#include "xla/service/spmd/spmd_partitioner.h" + +namespace xla { +namespace spmd { + +class StatefulRngSpmdPartitioningVisitor + : public spmd::SpmdPartitioningVisitor { + public: + StatefulRngSpmdPartitioningVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const spmd::SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, spmd::SpmdLogger* logger, + spmd::SpmdPartitionerOptions options, spmd::SpmdPartitioner* partitioner, + const CallGraph& call_graph) + : spmd::SpmdPartitioningVisitor(computation, num_partitions, num_replicas, + collective_ops_creator, next_channel_id, + logger, std::move(options), partitioner, + call_graph) {} + Status HandleRngGetAndUpdateState(HloInstruction* hlo) override; +}; + +class StatefulRngSpmdPartitioner : public spmd::SpmdPartitioner { + public: + StatefulRngSpmdPartitioner(int64_t num_partitions, int64_t num_replicas) + : spmd::SpmdPartitioner(num_partitions, num_replicas, + GetSpmdPartitionerOptions()) {} + + protected: + std::unique_ptr CreateVisitor( + HloComputation* computation, int64_t num_partitions, int64_t num_replicas, + const spmd::SPMDCollectiveOpsCreator& collective_ops_creator, + int64_t* next_channel_id, spmd::SpmdLogger* logger, + spmd::SpmdPartitionerOptions options, + const CallGraph& call_graph) override; + + Status PreprocessSharding( + HloModule* module, + const absl::flat_hash_set& execution_threads) override; + bool CanSideEffectingHaveReplicatedSharding( + const HloInstruction* hlo) override; + + private: + static spmd::SpmdPartitionerOptions GetSpmdPartitionerOptions() { + spmd::SpmdPartitionerOptions options; + options.allow_module_signature_change = true; + // Setting windowed einsum threshold to be large to disable it for GPU by + // default. + options.threshold_for_windowed_einsum_mib = 100000; + return options; + } +}; + +} // namespace spmd +} // namespace xla + +#endif // XLA_SERVICE_SPMD_STATEFUL_RNG_SPMD_PARTITIONER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/allocator_stats.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/allocator_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..d073d08cb92d5b327e77c7d609cae5a7554740ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/allocator_stats.h @@ -0,0 +1,63 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_ALLOCATOR_STATS_H_ +#define XLA_STREAM_EXECUTOR_ALLOCATOR_STATS_H_ + +#include + +#include "absl/types/optional.h" +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +// Runtime statistics collected by an allocator. Exactly the same as +// tsl::AllocatorStats, but independently defined to preserve the mutual +// independence of StreamExecutor and TensorFlow. +struct AllocatorStats { + int64_t num_allocs; // Number of allocations. + int64_t bytes_in_use; // Number of bytes in use. + int64_t peak_bytes_in_use; // The peak bytes in use. + int64_t largest_alloc_size; // The largest single allocation seen. + + // The upper limit of bytes of user allocatable device memory, if such a limit + // is known. + std::optional bytes_limit; + + // Stack related memory usage. + int64_t bytes_reserved; // Number of bytes reserved on the stack. + int64_t + peak_bytes_reserved; // The peak number of bytes reserved on the stack. + // The upper limit on the number bytes of reservable memory on the stack, + // if such a limit is known. + std::optional bytes_reservable_limit; + + int64_t largest_free_block_bytes; // Largest free block's size in heap. + + AllocatorStats() + : num_allocs(0), + bytes_in_use(0), + peak_bytes_in_use(0), + largest_alloc_size(0), + bytes_reserved(0), + peak_bytes_reserved(0), + largest_free_block_bytes(0) {} + + std::string DebugString() const; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_ALLOCATOR_STATS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/blas.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/blas.h new file mode 100644 index 0000000000000000000000000000000000000000..a85ea3b460d6ed659dbabc4a533a570df30ad218 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/blas.h @@ -0,0 +1,696 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Exposes the family of BLAS routines as pre-canned high performance calls for +// use in conjunction with the StreamExecutor abstraction. +// +// Note that this interface is optionally supported by platforms. +// +// This abstraction makes it simple to entrain BLAS operations on GPU data into +// a Stream -- users typically will not use this API directly, but will use the +// Stream builder methods to entrain these operations "under the hood". For +// example: +// +// DeviceMemory x = stream_exec->AllocateArray(1024); +// DeviceMemory y = stream_exec->AllocateArray(1024); +// // ... populate x and y ... +// Stream stream{stream_exec}; +// stream +// .Init() +// .ThenBlasAxpy(1024, 5.5, x, 1, &y, 1); +// TF_CHECK_OK(stream.BlockHostUntilDone()); +// +// By using stream operations in this manner the user can easily intermix custom +// kernel launches (via StreamExecutor::ThenLaunch()) with these pre-canned BLAS +// routines. + +#ifndef XLA_STREAM_EXECUTOR_BLAS_H_ +#define XLA_STREAM_EXECUTOR_BLAS_H_ + +#include +#include +#include +#include +#include + +#include "absl/types/span.h" +#include "xla/stream_executor/data_type.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/statusor.h" +#include "tsl/protobuf/dnn.pb.h" + +namespace Eigen { +struct half; +} // namespace Eigen + +namespace stream_executor { + +class Stream; +class ScratchAllocator; + +template +class DeviceMemory; + +template +class HostOrDeviceScalar; + +template +using DeviceMemorySlice = absl::Span *const>; + +namespace blas { + +// Specifies whether the input matrix will be transposed or +// transposed+conjugated before any BLAS operations. +enum class Transpose { kNoTranspose, kTranspose, kConjugateTranspose }; + +// Returns a name for t. +std::string TransposeString(Transpose t); + +// Specifies whether the upper or lower triangular part of a +// symmetric/Hermitian matrix is used. +enum class UpperLower { kUpper, kLower }; + +// Returns a name for ul. +std::string UpperLowerString(UpperLower ul); + +// Specifies whether a matrix is unit triangular. +enum class Diagonal { kUnit, kNonUnit }; + +// Returns a name for d. +std::string DiagonalString(Diagonal d); + +// Specifies whether a Hermitian matrix appears on the left or right in +// operation. +enum class Side { kLeft, kRight }; + +// Returns a name for s. +std::string SideString(Side s); + +// Type with which intermediate computations of a blas routine are performed. +// +// Some blas calls can perform computations with a type that's different than +// the type of their inputs/outputs. This lets you e.g. multiply two matrices +// of int8s using float32s to store the matmul's intermediate values. +enum class ComputationType { + kF16, // 16-bit floating-point + kF32, // 32-bit floating-point + kF64, // 64-bit floating-point + kI32, // 32-bit integer + // The below values use float32 for accumulation, but allow the inputs and + // outputs to be downcast to a lower precision: + kF16AsF32, // Allow downcast to F16 precision. + kBF16AsF32, // Allow downcast to BF16 precision. + kTF32AsF32, // Allow downcast to TF32 precision. +}; + +// Converts a ComputationType to a string. +std::string ComputationTypeString(ComputationType ty); + +std::ostream &operator<<(std::ostream &os, ComputationType ty); + +using dnn::DataType; +using dnn::ToDataType; + +// Converts a ComputationType to a string. +std::string DataTypeString(DataType ty); + +std::ostream &operator<<(std::ostream &os, DataType ty); + +// Opaque identifier for an "algorithm" used by a blas routine. This functions +// as a hint to the blas library. +typedef int64_t AlgorithmType; +constexpr AlgorithmType kDefaultAlgorithm = -1; +constexpr AlgorithmType kDefaultBlasGemm = -2; +constexpr AlgorithmType kDefaultBlasGemv = -3; +constexpr AlgorithmType kNoAlgorithm = -4; +constexpr AlgorithmType kRuntimeAutotuning = -5; + +// blas uses -1 to represent the default algorithm. This happens to match up +// with the CUBLAS_GEMM_DFALT constant, so cuda_blas.cc is using static_cast +// to convert from AlgorithmType to cublasGemmAlgo_t, and uses a static_assert +// to ensure that this assumption does not break. +// If another blas implementation uses a different value for the default +// algorithm, then it needs to convert kDefaultGemmAlgo to that value +// (e.g. via a function called ToWhateverGemmAlgo). +constexpr AlgorithmType kDefaultGemmAlgo = -1; + +// Describes the result of a performance experiment, usually timing the speed of +// a particular AlgorithmType. +// +// If the call we were benchmarking failed (a common occurrence; not all +// algorithms are valid for all calls), is_valid() will be false. +class ProfileResult { + public: + bool is_valid() const { return is_valid_; } + void set_is_valid(bool val) { is_valid_ = val; } + AlgorithmType algorithm() const { return algorithm_; } + void set_algorithm(AlgorithmType val) { algorithm_ = val; } + float elapsed_time_in_ms() const { return elapsed_time_in_ms_; } + void set_elapsed_time_in_ms(float val) { elapsed_time_in_ms_ = val; } + + private: + bool is_valid_ = false; + AlgorithmType algorithm_ = kDefaultAlgorithm; + float elapsed_time_in_ms_ = std::numeric_limits::max(); +}; + +class AlgorithmConfig { + public: + AlgorithmConfig() : algorithm_(kDefaultAlgorithm) {} + explicit AlgorithmConfig(AlgorithmType algorithm) : algorithm_(algorithm) {} + AlgorithmType algorithm() const { return algorithm_; } + void set_algorithm(AlgorithmType val) { algorithm_ = val; } + bool operator==(const AlgorithmConfig &other) const { + return this->algorithm_ == other.algorithm_; + } + bool operator!=(const AlgorithmConfig &other) const { + return !(*this == other); + } + std::string ToString() const; + + private: + AlgorithmType algorithm_; +}; + +// Opaque identifier specifying the precision to use in gemm calls. +typedef int64_t ComputePrecision; +constexpr ComputePrecision kDefaultComputePrecision = 0; + +// BLAS support interface -- this can be derived from a GPU executor when the +// underlying platform has an BLAS library implementation available. See +// StreamExecutor::AsBlas(). +// +// Thread-hostile: CUDA associates a CUDA-context with a particular thread in +// the system. Any operation that a user attempts to perform by enqueueing BLAS +// operations on a thread not-associated with the CUDA-context has unknown +// behavior at the current time; see b/13176597 +class BlasSupport { + public: + virtual ~BlasSupport() {} + + // Performs a BLAS y <- ax+y operation. + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, float alpha, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, double alpha, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, + std::complex alpha, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + virtual bool DoBlasAxpy(Stream *stream, uint64_t elem_count, + std::complex alpha, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + + // Copies vector to another vector: y <- x. + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + virtual bool DoBlasCopy(Stream *stream, uint64_t elem_count, + const DeviceMemory> &x, int incx, + DeviceMemory> *y, int incy) = 0; + + // Computes the product of a vector by a scalar: x <- a*x. + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, + DeviceMemory *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, + DeviceMemory *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, + DeviceMemory> *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, + DeviceMemory> *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, + std::complex alpha, + DeviceMemory> *x, int incx) = 0; + virtual bool DoBlasScal(Stream *stream, uint64_t elem_count, + std::complex alpha, + DeviceMemory> *x, int incx) = 0; + + // Computes a matrix-vector product using a general matrix. + // + // y <- alpha * a * x + beta * y, + // or + // y <- alpha * a' * x + beta * y, + // or + // y <- alpha * conj(a') * x + beta * y, + // + // alpha and beta are scalars; a is an m-by-n general matrix; x is a vector + // with n(trans==kNoTranspose)/m(otherwise) elements; + // y is a vector with m(trans==kNoTranspose)/n(otherwise) elements. + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, float alpha, const DeviceMemory &a, + int lda, const DeviceMemory &x, int incx, + float beta, DeviceMemory *y, int incy) = 0; + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, double alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, double beta, + DeviceMemory *y, int incy) = 0; + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy) = 0; + virtual bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy) = 0; + + // Computes a matrix-vector product using a symmetric band matrix. + // + // y <- alpha * a * x + beta * y, + // + // alpha and beta are scalars; a is an n-by-n symmetric band matrix, with k + // super-diagonals; x and y are n-element vectors. + virtual bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, + uint64_t k, float alpha, const DeviceMemory &a, + int lda, const DeviceMemory &x, int incx, + float beta, DeviceMemory *y, int incy) = 0; + virtual bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, + uint64_t k, double alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, double beta, + DeviceMemory *y, int incy) = 0; + + // Computes a matrix-matrix product with general matrices: + // + // c <- alpha * op(a) * op(b) + beta * c, + // + // op(X) is one of op(X) = X, or op(X) = X', or op(X) = conj(X'); alpha and + // beta are scalars; a, b, and c are matrices; op(a) is an m-by-k matrix; + // op(b) is a k-by-n matrix; c is an m-by-n matrix. + // + // Note: The half interface uses float precision internally; the version + // that uses half precision internally is not yet supported. There is no + // batched version of the half-precision interface. + // + // Alpha/beta type matches `dtype`, unless `dtype` is `Eigen::half`, in that + // case the expected alpha/beta type is `float`. + virtual tsl::Status DoBlasGemm(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, DataType dtype, const void *alpha, + const DeviceMemoryBase &a, int lda, + const DeviceMemoryBase &b, int ldb, + const void *beta, DeviceMemoryBase *c, int ldc, + const NumericOptions &numeric_options) = 0; + + // Gets a list of supported algorithms for DoBlasGemmWithAlgorithm. + virtual bool GetBlasGemmAlgorithms( + Stream *stream, std::vector *out_algorithms) = 0; + + // Like DoBlasGemm, but accepts an algorithm and an compute type. + // + // The compute type lets you say (e.g.) that the inputs and outputs are + // Eigen::halfs, but you want the internal computations to be done with + // float32 precision. + // + // If output_profile_result is not null, a failure here does not put the + // stream in a failure state. Instead, success/failure is indicated by + // output_profile_result->is_valid(). This lets you use this function for + // choosing the best algorithm among many (some of which may fail) without + // creating a new Stream for each attempt. + virtual tsl::Status DoBlasGemmWithAlgorithm( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, const void *alpha, + const DeviceMemoryBase &a, DataType type_a, int lda, + const DeviceMemoryBase &b, DataType type_b, int ldb, const void *beta, + DeviceMemoryBase *c, DataType type_c, int ldc, + ComputationType computation_type, AlgorithmType algorithm, + const NumericOptions &numeric_options, + ProfileResult *output_profile_result) = 0; + + virtual tsl::Status DoBlasGemmStridedBatchedWithAlgorithm( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, const void *alpha, + const DeviceMemoryBase &a, DataType type_a, int lda, int64_t stride_a, + const DeviceMemoryBase &b, DataType type_b, int ldb, int64_t stride_b, + const void *beta, DeviceMemoryBase *c, DataType type_c, int ldc, + int64_t stride_c, int batch_count, ComputationType computation_type, + AlgorithmType algorithm, const NumericOptions &numeric_options, + ProfileResult *output_profile_result) = 0; + + // Computes a batch of matrix-matrix product with general matrices. + // This is a batched version of DoBlasGemm. + // The batched GEMM computes matrix product for each input/output in a, b, + // and c, which contain batch_count DeviceMemory objects. + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, + DeviceMemorySlice c, int ldc, + int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched(Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64_t n, + uint64 k, double alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + double beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + virtual bool DoBlasGemmBatched( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator) = 0; + + // Batched gemm with strides instead of pointer arrays. + virtual tsl::Status DoBlasGemmStridedBatched( + Stream *stream, blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64_t n, uint64 k, DataType dtype, const void *alpha, + const DeviceMemoryBase &a, int lda, int64_t stride_a, + const DeviceMemoryBase &b, int ldb, int64_t stride_b, const void *beta, + DeviceMemoryBase *c, int ldc, int64_t stride_c, int batch_count, + const NumericOptions &numeric_options) = 0; + + // Solves a triangular matrix equation. + // + // op(a) * x = alpha * b, + // or + // x * op(a) = alpha * b + // + // alpha is a scalar; x and b are m-by-n matrices; a is a unit, or non-unit, + // upper or lower triangular matrix; op(a) is one of op(a) = a, or op(a) = a', + // or op(a) = conj(a'). + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + float alpha, const DeviceMemory &a, int lda, + DeviceMemory *b, int ldb) = 0; + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + double alpha, const DeviceMemory &a, int lda, + DeviceMemory *b, int ldb) = 0; + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb) = 0; + virtual bool DoBlasTrsm(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb) = 0; + + // Same as DoBlasTrsm, but operates over a list of a's and b's. The lists + // `as` and `bs` must have the same length. + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + float alpha, const DeviceMemory &as, + int lda, DeviceMemory *bs, int ldb, + int batch_count) = 0; + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + double alpha, const DeviceMemory &as, + int lda, DeviceMemory *bs, int ldb, + int batch_count) = 0; + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory *> &as, + int lda, + DeviceMemory *> *bs, + int ldb, int batch_count) = 0; + virtual bool DoBlasTrsmBatched(Stream *stream, blas::Side side, + blas::UpperLower uplo, blas::Transpose transa, + blas::Diagonal diag, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory *> &as, + int lda, + DeviceMemory *> *bs, + int ldb, int batch_count) = 0; + + virtual tsl::Status GetVersion(std::string *version) = 0; + + protected: + BlasSupport() {} + + private: + BlasSupport(const BlasSupport &) = delete; + void operator=(const BlasSupport &) = delete; +}; + +// Macro used to quickly declare overrides for abstract virtuals in the +// BlasSupport base class. +#define TENSORFLOW_STREAM_EXECUTOR_GPU_BLAS_SUPPORT_OVERRIDES \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, float alpha, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, double alpha, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasAxpy(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory &x, int incx, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasCopy(Stream *stream, uint64_t elem_count, \ + const DeviceMemory> &x, int incx, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, \ + DeviceMemory *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, \ + DeviceMemory *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, float alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, double alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasScal(Stream *stream, uint64_t elem_count, \ + std::complex alpha, \ + DeviceMemory> *x, int incx) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + float alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, float beta, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + double alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, double beta, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + const DeviceMemory> &x, int incx, \ + std::complex beta, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasGemv(Stream *stream, blas::Transpose trans, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + const DeviceMemory> &x, int incx, \ + std::complex beta, \ + DeviceMemory> *y, int incy) override; \ + bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, uint64 k, \ + float alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, float beta, \ + DeviceMemory *y, int incy) override; \ + bool DoBlasSbmv(Stream *stream, blas::UpperLower uplo, uint64_t n, uint64 k, \ + double alpha, const DeviceMemory &a, int lda, \ + const DeviceMemory &x, int incx, double beta, \ + DeviceMemory *y, int incy) override; \ + tsl::Status DoBlasGemm( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, blas::DataType dtype, const void *alpha, \ + const DeviceMemoryBase &a, int lda, const DeviceMemoryBase &b, int ldb, \ + const void *beta, DeviceMemoryBase *c, int ldc, \ + const NumericOptions &numeric_options) override; \ + bool GetBlasGemmAlgorithms(Stream *stream, \ + std::vector *out_algorithms) \ + override; \ + tsl::Status DoBlasGemmWithAlgorithm( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, const void *alpha, \ + const DeviceMemoryBase &a, blas::DataType type_a, int lda, \ + const DeviceMemoryBase &b, blas::DataType type_b, int ldb, \ + const void *beta, DeviceMemoryBase *c, blas::DataType type_c, int ldc, \ + blas::ComputationType computation_type, blas::AlgorithmType algorithm, \ + const NumericOptions &numeric_options, \ + blas::ProfileResult *output_profile_result) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, float alpha, \ + DeviceMemorySlice a, int lda, \ + DeviceMemorySlice b, int ldb, float beta, \ + DeviceMemorySlice c, int ldc, int batch_count, \ + const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, float alpha, \ + DeviceMemorySlice a, int lda, \ + DeviceMemorySlice b, int ldb, float beta, \ + DeviceMemorySlice c, int ldc, int batch_count, \ + const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, float alpha, DeviceMemorySlice a, \ + int lda, DeviceMemorySlice b, int ldb, float beta, \ + DeviceMemorySlice c, int ldc, int batch_count, \ + const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, double alpha, \ + DeviceMemorySlice a, int lda, DeviceMemorySlice b, \ + int ldb, double beta, DeviceMemorySlice c, int ldc, \ + int batch_count, const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, std::complex alpha, \ + DeviceMemorySlice> a, int lda, \ + DeviceMemorySlice> b, int ldb, \ + std::complex beta, DeviceMemorySlice> c, \ + int ldc, int batch_count, const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + bool DoBlasGemmBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, std::complex alpha, \ + DeviceMemorySlice> a, int lda, \ + DeviceMemorySlice> b, int ldb, \ + std::complex beta, DeviceMemorySlice> c, \ + int ldc, int batch_count, const NumericOptions &numeric_options, \ + ScratchAllocator *scratch_allocator) override; \ + tsl::Status DoBlasGemmStridedBatched( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, blas::DataType dtype, const void *alpha, \ + const DeviceMemoryBase &a, int lda, int64_t stride_a, \ + const DeviceMemoryBase &b, int ldb, int64_t stride_b, const void *beta, \ + DeviceMemoryBase *c, int ldc, int64_t stride_c, int batch_count, \ + const NumericOptions &numeric_options) override; \ + tsl::Status DoBlasGemmStridedBatchedWithAlgorithm( \ + Stream *stream, blas::Transpose transa, blas::Transpose transb, \ + uint64_t m, uint64 n, uint64 k, const void *alpha, \ + const DeviceMemoryBase &a, blas::DataType type_a, int lda, \ + int64_t stride_a, const DeviceMemoryBase &b, blas::DataType type_b, \ + int ldb, int64_t stride_b, const void *beta, DeviceMemoryBase *c, \ + blas::DataType type_c, int ldc, int64_t stride_c, int batch_count, \ + blas::ComputationType computation_type, blas::AlgorithmType algorithm, \ + const NumericOptions &numeric_options, \ + blas::ProfileResult *output_profile_result) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, float alpha, const DeviceMemory &a, \ + int lda, DeviceMemory *b, int ldb) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, double alpha, const DeviceMemory &a, \ + int lda, DeviceMemory *b, int ldb) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + DeviceMemory> *b, int ldb) override; \ + bool DoBlasTrsm(Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, \ + uint64_t n, std::complex alpha, \ + const DeviceMemory> &a, int lda, \ + DeviceMemory> *b, int ldb) override; \ + bool DoBlasTrsmBatched( \ + Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, uint64 n, \ + float alpha, const DeviceMemory &as, int lda, \ + DeviceMemory *bs, int ldb, int batch_count) override; \ + bool DoBlasTrsmBatched( \ + Stream *stream, blas::Side side, blas::UpperLower uplo, \ + blas::Transpose transa, blas::Diagonal diag, uint64_t m, uint64 n, \ + double alpha, const DeviceMemory &as, int lda, \ + DeviceMemory *bs, int ldb, int batch_count) override; \ + bool DoBlasTrsmBatched(Stream *stream, blas::Side side, \ + blas::UpperLower uplo, blas::Transpose transa, \ + blas::Diagonal diag, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory *> &as, \ + int lda, DeviceMemory *> *bs, \ + int ldb, int batch_count) override; \ + bool DoBlasTrsmBatched(Stream *stream, blas::Side side, \ + blas::UpperLower uplo, blas::Transpose transa, \ + blas::Diagonal diag, uint64_t m, uint64 n, \ + std::complex alpha, \ + const DeviceMemory *> &as, \ + int lda, DeviceMemory *> *bs, \ + int ldb, int batch_count) override; \ + tsl::Status GetVersion(std::string *version) override; + +} // namespace blas +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_BLAS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/command_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/command_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..2587872d27e5438ff733391d47a4f3aec43db17f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/command_buffer.h @@ -0,0 +1,163 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_COMMAND_BUFFER_H_ +#define XLA_STREAM_EXECUTOR_COMMAND_BUFFER_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; +class StreamExecutor; + +namespace internal { +class CommandBufferInterface; +} + +//===----------------------------------------------------------------------===// +// CommandBuffer +//===----------------------------------------------------------------------===// + +// Command buffer represent a "bundle of work items" for StreamExecutor device +// that can be submitted with one API call, e.g. command buffer might have +// multiple device kernels and synchronization barriers between them. Command +// buffers allow to amortize the cost of launching "work" on device by building +// it on the host ahead of time without expensive interaction with underlying +// device. +class CommandBuffer { + public: + // Command buffer state: + // + // (1) kCreate: a new command buffer under construction + // (2) kUpdate: updating a previously finalized command buffer + // (3) kFinalized: command buffer ready for execution + // + // Supported state transitions: + // + // (1) Finalize: (kCreate|kUpdate) -> kFinalized + // (2) Update: kFinalized -> kUpdate + // + enum class State { kCreate, kUpdate, kFinalized }; + + // Command buffers have two modes of execution: + // + // (1) kPrimary: command buffer can be submitted for execution via + // StreamExecutor APIs + // (2) kNested: command buffer can be executed only within a primary + // command buffer + // + enum class Mode { kPrimary, kNested }; + + //===--------------------------------------------------------------------===// + // Command buffer constructors + //===--------------------------------------------------------------------===// + + // Creates a new empty command buffer on the given executor. + static tsl::StatusOr Create(StreamExecutor* executor, + Mode mode = Mode::kPrimary); + + // Creates a new command buffer on the given executor by tracing `function` + // invocation. All StreamExecutor operations on a Stream argument will be + // recorded into the command buffer. Returned command buffer is finalized, and + // can't be updated. + // + // Command buffer tracing should be used only when it is impossible to use + // explicit construction APIs, e.g. when calling external libraries. + static tsl::StatusOr Trace( + StreamExecutor* executor, + absl::AnyInvocable function, + Mode mode = Mode::kPrimary); + + //===--------------------------------------------------------------------===// + // Command buffer API + //===--------------------------------------------------------------------===// + + // Adds a kernel launch command to the command buffer. + tsl::Status Launch(const ThreadDim& threads, const BlockDim& blocks, + const KernelBase& kernel, const KernelArgsArrayBase& args); + + // Adds a device-to-device memory copy to the command buffer. + tsl::Status MemcpyDeviceToDevice(DeviceMemoryBase* dst, + const DeviceMemoryBase& src, uint64_t size); + + // Finalizes command buffer and makes it executable. Once command buffer is + // finalized no commands can be added to it. + tsl::Status Finalize(); + + // Begins command buffer update. Command buffer update should be finalized + // before it can be executed. + tsl::Status Update(); + + // Type-safe wrapper for launching typed kernels. Notice that the order of + // arguments is different do disambiguate from the regular launch API. + template + tsl::Status Launch(const TypedKernel& kernel, + const ThreadDim& threads, const BlockDim& blocks, + Args... args); + + // Returns command buffer execution mode. + Mode mode() const; + + internal::CommandBufferInterface* implementation() { + return implementation_.get(); + } + + const internal::CommandBufferInterface* implementation() const { + return implementation_.get(); + } + + CommandBuffer(CommandBuffer&&) = default; + CommandBuffer& operator=(CommandBuffer&&) = default; + + private: + explicit CommandBuffer( + std::unique_ptr implementation); + + std::unique_ptr implementation_; + + CommandBuffer(const CommandBuffer&) = delete; + void operator=(const CommandBuffer&) = delete; +}; + +//===----------------------------------------------------------------------===// +// CommandBuffer templates implementation below +//===----------------------------------------------------------------------===// + +template +inline tsl::Status CommandBuffer::Launch(const TypedKernel& kernel, + const ThreadDim& threads, + const BlockDim& blocks, Args... args) { + KernelInvocationChecker, + std::tuple>::CheckAllStaticAssert(); + + KernelArgsArray kernel_args; + kernel.PackParams(&kernel_args, args...); + TF_RETURN_IF_ERROR(Launch(threads, blocks, kernel, kernel_args)); + return tsl::OkStatus(); +} + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_COMMAND_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_activation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_activation.h new file mode 100644 index 0000000000000000000000000000000000000000..bcdc8f5e178efec265331e3c3d551f09f231b8e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_activation.h @@ -0,0 +1,39 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file contains APIs that assume a StreamExecutor is backed by CUDA. +// It reaches into the CUDA implementation to activate an underlying CUDA +// context. +// +// Having this file separate from cuda/cuda_executor.h means that dependent +// code does not also have to depend on cuda.h. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_ACTIVATION_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_ACTIVATION_H_ + +#include "xla/stream_executor/gpu/gpu_activation.h" + +namespace stream_executor { + +class StreamExecutor; + +namespace cuda { + +using ScopedActivateExecutorContext = gpu::ScopedActivateExecutorContext; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_ACTIVATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.h new file mode 100644 index 0000000000000000000000000000000000000000..a23fb616181e4261f4879604d59dfa81b9783118 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.h @@ -0,0 +1,131 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// CUDA-specific support for BLAS functionality -- this wraps the cuBLAS library +// capabilities, and is only included into CUDA implementation code -- it will +// not introduce cuda headers into other code. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_H_ + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "third_party/gpus/cuda/include/cublas_v2.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/cuda/cuda_blas_lt.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/plugin_registry.h" + +namespace stream_executor { + +class Stream; + +namespace gpu { +class GpuExecutor; +} // namespace gpu + +namespace cuda { + +// BLAS plugin for CUDA platform via cuBLAS library. +// +// This satisfies the platform-agnostic BlasSupport interface. +// +// Note that the cuBLAS handle that this encapsulates is implicitly tied to the +// context (and, as a result, the device) that the parent GpuExecutor is tied +// to. This simply happens as an artifact of creating the cuBLAS handle when a +// CUDA context is active. +// +// Thread-safe post-initialization. +class CUDABlas : public blas::BlasSupport { + public: + explicit CUDABlas(gpu::GpuExecutor *parent); + + // Allocates a cuBLAS handle. + bool Init(); + + // Releases the cuBLAS handle, if present. + ~CUDABlas() override; + + TENSORFLOW_STREAM_EXECUTOR_GPU_BLAS_SUPPORT_OVERRIDES + + BlasLt &blas_lt() { return blas_lt_; } + + private: + // Tells cuBLAS to enqueue the BLAS operation onto a particular Stream. + // + // cuBLAS is stateful, and only be associated with one stream (in order to + // enqueue dispatch) at a given time. As a result, this generally must be + // invoked before calling into cuBLAS. + bool SetStream(Stream *stream) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + // Returns the underlying CUDA stream. + cudaStream_t CUDAStream(Stream *stream); + + // A helper function that calls the real cuBLAS function together with error + // handling. + // + // cublas_func: cuBLAS function pointer. + // cublas_name: cuBLAS function name. + // stream: Stream to enqueue the BLAS operation onto. + // pointer_mode_host: Indicate if the pointer to a scalar value is from host + // (true) or device (false). + // args: Arguments of cuBLAS function. + template + tsl::Status DoBlasInternalImpl(FuncT cublas_func, Stream *stream, + bool pointer_mode_host, cublasMath_t math_type, + Args... args); + + // Convenience functions that call DoBlasInternalImpl with err_on_failure=true + // and math_type=CUBLAS_DEFAULT_MATH. + template + bool DoBlasInternal(FuncT cublas_func, Stream *stream, bool pointer_mode_host, + Args... args) { + return DoBlasInternalImpl(cublas_func, stream, pointer_mode_host, + CUBLAS_DEFAULT_MATH, args...) + .ok(); + } + + // A helper function to implement DoBlasGemmBatched interfaces for generic + // types. + template + tsl::Status DoBlasGemmBatchedInternal( + FuncT cublas_func, Stream *stream, blas::Transpose transa, + blas::Transpose transb, uint64_t m, uint64 n, uint64 k, Scalar alpha, + const DeviceMemorySlice &a_array, int lda, + const DeviceMemorySlice &b_array, int ldb, Scalar beta, + const DeviceMemorySlice &c_array, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + + // Guards the cuBLAS handle for this device. + absl::Mutex mu_; + + // GpuExecutor which instantiated this CUDABlas. + // Immutable post-initialization. + gpu::GpuExecutor *parent_; + + // cuBLAS library handle on the device. + cublasHandle_t blas_ ABSL_GUARDED_BY(mu_); + + BlasLt blas_lt_; + + CUDABlas(const CUDABlas &) = delete; + void operator=(const CUDABlas &) = delete; +}; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_lt.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_lt.h new file mode 100644 index 0000000000000000000000000000000000000000..44e11206925f8baea84ca7ca54e6c3acaf8c58e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_lt.h @@ -0,0 +1,250 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_LT_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_LT_H_ + +#include +#include +#include +#include +#include + +#include "third_party/gpus/cuda/include/cublasLt.h" +#include "third_party/gpus/cuda/include/cublas_v2.h" +#include "third_party/gpus/cuda/include/cuda.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/cuda/cuda_blas_utils.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/host_or_device_scalar.h" +#include "tsl/platform/status.h" + +namespace stream_executor { +namespace gpu { +class GpuExecutor; +} // namespace gpu + +namespace cuda { + +class BlasLt { + template + using Owned = + std::unique_ptr, cublasStatus_t (*)(T)>; + + public: + class MatrixLayout { + public: + enum class Order { kRowMajor, kColumnMajor }; + + // If `leading_dim_stride` is not specified, it defaults to: + // - `num_cols` if `order == kRowMajor`, + // - `num_rows` if `order == kColumnMajor`. + // If `batch_stride` is not specified, it defaults to `num_rows * num_cols` + // if `batch_size > 1`, otherwise `0`. + static tsl::StatusOr Create( + blas::DataType type, size_t num_rows, size_t num_cols, Order order, + size_t batch_size = 1, + std::optional leading_dim_stride = std::nullopt, + std::optional batch_stride = std::nullopt); + + cudaDataType_t type() const; + + cublasLtMatrixLayout_t get() const { return handle_.get(); } + + private: + explicit MatrixLayout(cublasLtMatrixLayout_t handle) + : handle_(handle, cublasLtMatrixLayoutDestroy) {} + + Owned handle_; + }; + + enum class Epilogue { + kDefault = 1, // No special postprocessing + kReLU = 2, // Apply point-wise ReLU function + kBias = 4, // Add broadcasted bias vector + kBiasThenReLU = kBias | kReLU, // Apply bias and then ReLU transform + kGELU = 32, // Apply GELU point-wise transform to the results + kGELUWithAux = 32 | 1024, // Apply GELU with auxiliary output. + kBiasThenGELU = kBias | kGELU, // Apply bias and then approximate GELU. + kBiasThenGELUWithAux = kBiasThenGELU | 1024, + }; + + // Describes the location of pointers for the scaling factors alpha and beta. + enum class PointerMode { + kHost, + kDevice, + }; + + class MatmulDesc { + public: + static tsl::StatusOr Create( + blas::ComputationType compute_type, blas::DataType scale_type, + blas::Transpose trans_a = blas::Transpose::kNoTranspose, + blas::Transpose trans_b = blas::Transpose::kNoTranspose, + Epilogue epilogue = Epilogue::kDefault, + PointerMode pointer_mode = PointerMode::kHost); + + cublasComputeType_t compute_type() const; + cudaDataType_t scale_type() const; + cublasLtPointerMode_t pointer_mode() const; + + cublasLtMatmulDesc_t get() const { return handle_.get(); } + + private: + explicit MatmulDesc(cublasLtMatmulDesc_t handle) + : handle_(handle, cublasLtMatmulDescDestroy) {} + + Owned handle_; + }; + + // TODO(cjfj): Add consistency checks for types, shapes, etc.? + struct MatmulPlan { + MatmulDesc op_desc; + MatrixLayout a_desc; + MatrixLayout b_desc; + MatrixLayout c_desc; + MatrixLayout d_desc; + }; + + class MatmulPreference { + public: + static tsl::StatusOr Create(size_t max_workspace_size); + + cublasLtMatmulPreference_t get() const { return handle_.get(); } + + private: + explicit MatmulPreference(cublasLtMatmulPreference_t handle) + : handle_(handle, cublasLtMatmulPreferenceDestroy) {} + + Owned handle_; + }; + + struct MatmulAlgorithm { + cublasLtMatmulAlgo_t algo; + size_t workspace_size; + }; + + explicit BlasLt(gpu::GpuExecutor* parent) + : parent_(parent), blas_lt_(nullptr, cublasLtDestroy) {} + + tsl::Status Init(); + + // Returns a list of supported algorithms for DoMatmul. The algorithms are + // returned in the order of increasing estimated compute time according to an + // internal heuristic. + tsl::StatusOr> GetMatmulAlgorithms( + const MatmulPlan& plan, const MatmulPreference& preference, + size_t max_algorithm_count = 128); + + template + tsl::Status DoMatmul(Stream* stream, const MatmulPlan& plan, + const HostOrDeviceScalar& alpha, + const DeviceMemory& a, const DeviceMemory& b, + const HostOrDeviceScalar& beta, + const DeviceMemory& c, DeviceMemory& d, + const MatmulAlgorithm& algorithm, + ScratchAllocator& scratch_allocator, + const DeviceMemory& bias = {}, + const DeviceMemoryBase& aux = DeviceMemory{}, + const DeviceMemory& a_scale = {}, + const DeviceMemory& b_scale = {}, + const DeviceMemory& c_scale = {}, + const DeviceMemory& d_scale = {}, + const DeviceMemory& d_amax = {}, + blas::ProfileResult* profile_result = nullptr) { + if (AsCudaDataType(blas::ToDataType::value) != + plan.op_desc.scale_type()) { + return tsl::errors::InvalidArgument("mismatched scale types"); + } + + bool expect_scale_factor_on_device = + (plan.op_desc.pointer_mode() == CUBLASLT_POINTER_MODE_DEVICE); + + if (alpha.on_device() != expect_scale_factor_on_device) { + return tsl::errors::InvalidArgument("wrong location for alpha"); + } + + if (beta.on_device() != expect_scale_factor_on_device) { + return tsl::errors::InvalidArgument("wrong location for beta"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.a_desc.type()) { + return tsl::errors::InvalidArgument("mismatched A matrix types"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.b_desc.type()) { + return tsl::errors::InvalidArgument("mismatched B matrix types"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.c_desc.type()) { + return tsl::errors::InvalidArgument("mismatched C matrix types"); + } + + if (AsCudaDataType(blas::ToDataType::value) != plan.d_desc.type()) { + return tsl::errors::InvalidArgument("mismatched D matrix types"); + } + + return DoMatmul(stream, plan, alpha.opaque(), a, b, beta.opaque(), c, d, + algorithm, scratch_allocator, bias, aux, a_scale, b_scale, + c_scale, d_scale, d_amax, profile_result); + } + + template + tsl::Status DoMatmul(Stream* stream, const MatmulPlan& plan, + const HostOrDeviceScalar& alpha, + const DeviceMemory& a, const DeviceMemory& b, + const HostOrDeviceScalar& beta, + const DeviceMemory& c, DeviceMemory& d, + const MatmulAlgorithm& algorithm, + ScratchAllocator& scratch_allocator, + const DeviceMemory& bias = {}, + const DeviceMemoryBase& aux = DeviceMemory{}, + blas::ProfileResult* profile_result = nullptr) { + return DoMatmul(stream, plan, alpha, a, b, beta, c, d, algorithm, + scratch_allocator, bias, aux, {}, {}, {}, {}, {}, + profile_result); + } + + private: + tsl::Status DoMatmul(Stream* stream, const MatmulPlan& plan, + const void* alpha, DeviceMemoryBase a, + DeviceMemoryBase b, const void* beta, DeviceMemoryBase c, + DeviceMemoryBase d, const MatmulAlgorithm& algorithm, + ScratchAllocator& scratch_allocator, + DeviceMemoryBase bias, DeviceMemoryBase aux, + DeviceMemoryBase a_scale, DeviceMemoryBase b_scale, + DeviceMemoryBase c_scale, DeviceMemoryBase d_scale, + DeviceMemoryBase d_amax, + blas::ProfileResult* profile_result); + + gpu::GpuExecutor* parent_; + + absl::Mutex mu_; + Owned blas_lt_ ABSL_GUARDED_BY(mu_); +}; + +// Returns `BlasLt` implementation for a stream if available, or `nullptr`. +BlasLt* GetBlasLt(Stream* stream); + +} // namespace cuda + +namespace gpu { +using BlasLt = ::stream_executor::cuda::BlasLt; +inline BlasLt* GetBlasLt(Stream* stream) { return cuda::GetBlasLt(stream); } +} // namespace gpu + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_LT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..2e8789b1f1bcde7d87cf5ace2356a9f08d58e109 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_blas_utils.h @@ -0,0 +1,41 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_UTILS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_UTILS_H_ + +#include + +#include "third_party/gpus/cuda/include/cublas_v2.h" +#include "xla/stream_executor/blas.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" + +#define SE_CUBLAS_RETURN_IF_ERROR(expr) \ + TF_RETURN_IF_ERROR(::stream_executor::cuda::ToStatus(expr, #expr)) + +namespace stream_executor { +namespace cuda { + +const char* ToString(cublasStatus_t status); +tsl::Status ToStatus(cublasStatus_t status, const char* prefix = "cublasLt"); +cudaDataType_t AsCudaDataType(blas::DataType type); +cublasComputeType_t AsCublasComputeType(blas::ComputationType type); +cublasOperation_t AsCublasOperation(blas::Transpose trans); + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_BLAS_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_diagnostics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_diagnostics.h new file mode 100644 index 0000000000000000000000000000000000000000..46d1a001051c658bdca8efeec990b2b51c177b48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_diagnostics.h @@ -0,0 +1,41 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_DIAGNOSTICS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_DIAGNOSTICS_H_ + +#include "xla/stream_executor/gpu/gpu_diagnostics.h" + +namespace stream_executor { +namespace cuda { + +// e.g. DriverVersion{346, 3, 4} +using DriverVersion = gpu::DriverVersion; + +// Converts a parsed driver version to string form. +std::string DriverVersionToString(DriverVersion version); + +// Converts a parsed driver version or status value to natural string form. +std::string DriverVersionStatusToString(tsl::StatusOr version); + +// Converts a string of a form like "331.79" to a DriverVersion{331, 79}. +tsl::StatusOr StringToDriverVersion(const std::string& value); + +using Diagnostician = gpu::Diagnostician; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_DIAGNOSTICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.h new file mode 100644 index 0000000000000000000000000000000000000000..1157093b53bedcd891ab9301de6ae48228b3fd7a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.h @@ -0,0 +1,777 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The CUDA-specific DNN library support, implementing the general DnnSupport +// interface. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_DNN_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_DNN_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/types/span.h" +#include "xla/stream_executor/cuda/cuda_activation.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/plugin_registry.h" +#include "xla/stream_executor/temporary_device_memory.h" +#include "tsl/platform/status.h" + +namespace stream_executor { +namespace gpu { + +class GpuExecutor; +class CudnnRnnDescriptor; +class CudnnRnnSequenceTensorDescriptor; +class CudnnRnnStateTensorDescriptor; +class CudnnCtcLossDescriptor; + +using BatchDescriptorSlice = absl::Span; + +template +using DeviceMemorySlice = absl::Span* const>; + +// cudnn-library based DNN support. For details on overridden interface +// functions, see dnn.h. +class CudnnSupport : public dnn::DnnSupport { + public: + explicit CudnnSupport(GpuExecutor* parent); + + tsl::Status Init() override; + tsl::StatusOr GetVersion() override; + + tsl::StatusOr> createRnnDescriptor( + int num_layers, int hidden_size, int input_size, int cell_size, + int batch_size, dnn::RnnInputMode input_mode, + dnn::RnnDirectionMode direction_mode, dnn::RnnMode rnn_mode, + dnn::DataType data_type, const dnn::AlgorithmConfig& algorithm_config, + const NumericOptions& numeric_options, float dropout, uint64_t seed, + ScratchAllocator* state_allocator, bool use_padded_io) override; + + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + dnn::DataType data_type) override; + + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + const absl::Span& seq_lengths, + bool time_major, + dnn::DataType data_type) override; + + tsl::StatusOr> + createRnnStateTensorDescriptor(int num_layer, int batch_size, int data_size, + dnn::DataType data_type) override; + + bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnBackward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnBackward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + bool DoRnnBackward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) override; + + tsl::Status GetConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, ScratchAllocator* scratch_allocator, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans) + override; + + tsl::StatusOr> ConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor) override; + + tsl::Status GetGraphConvolveRunners( + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, const NumericOptions& numeric_options, + std::vector>* out_exec_plans, + std::string serialized_graph) override; + + tsl::StatusOr> + GraphConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + std::string serialized_graph) override; + + tsl::Status GetFusedConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_scale, double side_input_scale, + double leakyrelu_alpha, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, dnn::ActivationMode activation_mode, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans) + override; + + tsl::Status GetFusedMatmulRunners( + bool use_cudnn_frontend, dnn::DataType input_type, + dnn::DataType bias_type, dnn::DataType output_type, Stream* stream, + bool trans_a, bool trans_b, uint64_t m, uint64_t n, uint64_t k, + int64_t lda, int64_t ldb, int64_t ldc, + dnn::ActivationMode activation_mode, bool use_fallback, + const NumericOptions& numeric_options, + std::vector>* + out_exec_plans) override; + + tsl::StatusOr> + FusedConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType bias_type, dnn::DataType output_type, double conv_scale, + double side_input_scale, double leakyrelu_alpha, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::ActivationMode activation_mode) override; + + tsl::StatusOr> + FusedMHARunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor& bmm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& intermediate_bmm2_lhs_descriptor, + const dnn::TensorDescriptor& output_descriptor, + std::optional activation_descriptor, + std::optional mask_descriptor, + std::optional bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) override; + + tsl::StatusOr> + FusedMHABackwardRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor& bmm1_grad_gemm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm1_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_grad_gemm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& d_output_descriptor, + const dnn::TensorDescriptor& d_bmm1_lhs_descriptor, + const dnn::TensorDescriptor& d_bmm1_rhs_descriptor, + const dnn::TensorDescriptor& d_bmm2_rhs_descriptor, + const dnn::TensorDescriptor& d_s_descriptor, + std::optional mask_descriptor, + std::optional d_bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) override; + bool GetRnnAlgorithms( + std::vector* out_algorithms) override; + + bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_var_iance, + const DeviceMemory& side_input, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) override; + + bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, + const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoConvolve( + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::AlgorithmDesc algorithm_desc, DeviceMemory scratch_memory, + dnn::ProfileResult* output_profile_result) override; + + tsl::Status DoFusedConvolve( + Stream* stream, dnn::DataType input_type, dnn::DataType side_input_type, + dnn::DataType bias_type, dnn::DataType output_type, + const dnn::BatchDescriptor& conv_input_descriptor, + DeviceMemoryBase conv_input_data, double conv_input_scale, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + DeviceMemoryBase side_input_data, double side_input_scale, + const dnn::BatchDescriptor& bias_descriptor, DeviceMemoryBase biases, + dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, ScratchAllocator* scratch_allocator, + const dnn::AlgorithmConfig& algorithm_config, + dnn::ProfileResult* output_profile_result) override; + + tsl::Status CudnnReorderConvolutionFilterAndBias( + Stream* stream, const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_input, + DeviceMemory* filter_output, + std::optional> bias_input, + std::optional> bias_output) override; + + bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) override { + LOG(ERROR) << "DoConvolveQuantized not supported by cuDNN"; + return false; + } + + bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) override { + LOG(ERROR) << "DoConvolveQuantized not supported by cuDNN"; + return false; + } + + bool DoSeparableConvolve( + Stream* stream, const dnn::BatchDescriptor& batch_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, int depth_multiplier, + const DeviceMemory& first_weights, + const DeviceMemory& second_weights, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) override { + LOG(ERROR) << "separable convolution not supported by CUDNN"; + return false; + } + + bool DoMatMul(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& weights, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override; + + bool DoMatMulQuantized(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override { + LOG(ERROR) << "DNN MatMulQuantized not supported by CUDNN"; + return false; + } + + bool DoMatMulQuantized(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override { + LOG(ERROR) << "DNN MatMulQuantized not supported by CUDNN"; + return false; + } + + bool DoBiasAdd(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& biases, + const dnn::BatchDescriptor& dimensions, + DeviceMemory* output_data) override; + + bool DoActivate(Stream* stream, dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + DeviceMemory* output_data, uint64_t options) override; + + tsl::Status DoPoolForward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoPoolForward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoPoolBackward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, + ScratchAllocator* workspace_allocator) override; + + tsl::Status DoPoolBackward(dnn::DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, + DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, + DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, + ScratchAllocator* workspace_allocator) override; + + bool DoNormalizeWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + DeviceMemory* output_data) override; + + bool DoNormalizeBackwardWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& raw_data, + const DeviceMemory& normalized_data, + const DeviceMemory& normalized_variable_gradient, + DeviceMemory* raw_variable_gradient, + ScratchAllocator* workspace_allocator) override; + + bool DoDepthConcatenate(Stream* stream, BatchDescriptorSlice input_dimensions, + DeviceMemorySlice input_data, + DeviceMemory* output_data) override; + + bool DoElementwiseOperate(Stream* stream, dnn::ElementwiseOperation operation, + BatchDescriptorSlice input_dimensions, + DeviceMemorySlice input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) override; + + bool DoXYPad(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, int64_t left_pad, + int64_t right_pad, int64_t top_pad, int64_t bottom_pad, + DeviceMemory* output_data) override; + + bool DoXYSlice(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, int64_t left_trim, + int64_t right_trim, int64_t top_trim, int64_t bottom_trim, + DeviceMemory* output_data) override; + + bool DoMemcpyD2HQuantized(Stream* stream, + const DeviceMemory& device_unquantized_src, + dnn::QuantizedActivationMode mode, void* host_dst, + int64_t size) override; + + bool DoMemcpyH2DQuantized( + Stream* stream, const void* host_src, int64_t size, + dnn::QuantizedActivationMode mode, + DeviceMemory* device_unquantized_dst) override; + + // Derives an output batch descriptor from an input batch and convolution + // descriptors. + bool DeriveOutputBatchDescriptor( + const dnn::BatchDescriptor& batch_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::BatchDescriptor* output_batch_descriptor); + + tsl::Status DoCtcLoss(Stream* stream, dnn::DataType element_type, + const dnn::RnnStateTensorDescriptor& probs_desc, + const DeviceMemoryBase probs_data, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + DeviceMemoryBase costs_data, + const dnn::RnnStateTensorDescriptor& grads_desc, + DeviceMemoryBase grads_data, + DeviceMemory scratch_memory, + int ctc_loss_algo_id) override; + + bool DoTransformTensor(Stream* stream, const dnn::BatchDescriptor& input_desc, + dnn::DataType input_type, + const DeviceMemoryBase& input_data, + const dnn::BatchDescriptor& output_desc, + dnn::DataType output_type, float scale, + DeviceMemoryBase* output_data) override; + + void NotifyStreamDestroyed(Stream* stream) override; + + private: + GpuExecutor* parent_; // Parent executor object. Not owned. + + // Provides access to the cuDNN handle. + std::unique_ptr cudnn_; + + bool GetConvolveAlgorithms(CudaComputeCapability cuda_compute_capability, + dnn::DataType input_type, + const NumericOptions& numeric_options, + std::vector* out_algorithms); + + bool GetConvolveBackwardDataAlgorithms( + CudaComputeCapability cuda_compute_capability, dnn::DataType input_type, + const NumericOptions& numeric_options, + std::vector* out_algorithms); + + bool GetConvolveBackwardFilterAlgorithms( + CudaComputeCapability cuda_compute_capability, dnn::DataType input_type, + const NumericOptions& numeric_options, + std::vector* out_algorithms); + + template + tsl::Status DoBatchNormalizationForwardImpl( + Stream* stream, dnn::DataType input_data_type, + dnn::DataType scale_data_type, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* saved_mean, DeviceMemory* saved_inv_var, + bool is_training, ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator); + + template + tsl::Status DoBatchNormalizationBackwardImpl( + Stream* stream, int cudnn_input_type, int cudnn_scale_type, + const DeviceMemory& y_backprop, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& mean, const DeviceMemory& inv_var, + const DeviceMemory& y, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator); + + template + tsl::Status DoRnnForwardImpl( + Stream* stream, const CudnnRnnDescriptor& rnn_desc, + const CudnnRnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const CudnnRnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const CudnnRnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, const DeviceMemory& params, + const CudnnRnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const CudnnRnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const CudnnRnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result); + + template + tsl::Status DoRnnBackwardImpl( + Stream* stream, const CudnnRnnDescriptor& rnn_desc, + const CudnnRnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const CudnnRnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const CudnnRnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, const DeviceMemory& params, + const CudnnRnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const CudnnRnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const CudnnRnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result); + + tsl::Status DoCtcLossImpl( + Stream* stream, const CudnnRnnStateTensorDescriptor& probs_desc, + const DeviceMemoryBase probs_data, absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, DeviceMemoryBase costs_data, + const CudnnRnnStateTensorDescriptor& grads_desc, + DeviceMemoryBase grads_data, const CudnnCtcLossDescriptor& ctc_loss_desc, + DeviceMemory scratch_memory, int ctc_loss_algo_id); + + private: + tsl::Status DoPrepareForConvolution( + dnn::ConvolutionKind kind, dnn::DataType element_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::AlgorithmConfig& algorithm_config, + ScratchAllocator* scratch_allocator, dnn::AlgorithmDesc* algorithm_desc, + DeviceMemory* scratch_memory) override; + + tsl::Status DoPrepareForCtcLoss( + Stream* stream, dnn::DataType element_type, + const dnn::RnnStateTensorDescriptor& probs_desc, + const dnn::RnnStateTensorDescriptor& grads_desc, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions& numeric_options, + ScratchAllocator* scratch_allocator, + DeviceMemory* scratch_memory, int* ctc_loss_algo_id) override; + + CudnnSupport(const CudnnSupport&) = delete; + void operator=(const CudnnSupport&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_DNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_driver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_driver.h new file mode 100644 index 0000000000000000000000000000000000000000..7f3314fbff585c8868badeedc7ae478dd5ffadcf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_driver.h @@ -0,0 +1,165 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// CUDA userspace driver library wrapper functionality. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ + +#include "absl/container/node_hash_map.h" +#include "absl/memory/memory.h" +#include "absl/strings/str_cat.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/gpu/gpu_driver.h" + +namespace stream_executor { +namespace gpu { +// Formats CUresult to output prettified values into a log stream. +static std::string ToString(CUresult result) { + const char* error_name; + if (cuGetErrorName(result, &error_name)) { + return absl::StrCat("UNKNOWN ERROR (", static_cast(result), ")"); + } + const char* error_string; + if (cuGetErrorString(result, &error_string)) { + return error_name; + } + return absl::StrCat(error_name, ": ", error_string); +} + +// CUDAContext wraps a cuda CUcontext handle, and includes a unique id. The +// unique id is positive, and ids are not repeated within the process. +class GpuContext { + public: + GpuContext(CUcontext context, int64_t id) : context_(context), id_(id) {} + + CUcontext context() const { return context_; } + int64_t id() const { return id_; } + + // Disallow copying and moving. + GpuContext(GpuContext&&) = delete; + GpuContext(const GpuContext&) = delete; + GpuContext& operator=(GpuContext&&) = delete; + GpuContext& operator=(const GpuContext&) = delete; + + private: + CUcontext const context_; + const int64_t id_; +}; + +// Manages the singleton map of contexts that we've created, mapping +// from the CUcontext to the GpuContext* that we pass around internally. +// This also manages assignment of unique ids to GpuContexts, to allow +// for fast comparison of a context against the current context. +// +// CUDA-runtime-created contexts are avoided, if triple angle +// brace launches are required, by using the scoped activations in +// gpu/gpu_activation.h. +class CreatedContexts { + public: + // Returns whether context is a member of the live set. + static bool Has(CUcontext context) { + absl::ReaderMutexLock lock(&mu_); + return Live()->find(context) != Live()->end(); + } + + // Adds context to the live set, or returns it if it's already present. + static GpuContext* Add(CUcontext context, int device_ordinal) { + CHECK(context != nullptr); + absl::MutexLock lock(&mu_); + + auto insert_result = Live()->insert(std::make_pair(context, nullptr)); + auto it = insert_result.first; + if (insert_result.second) { + // context was not present in the map. Add it. + it->second = std::make_unique(context, next_id_++); + (*LiveOrdinal())[device_ordinal].push_back(context); + } + return it->second.get(); + } + + // Removes context from the live set. + static void Remove(CUcontext context) { + CHECK(context != nullptr); + absl::MutexLock lock(&mu_); + auto it = Live()->find(context); + CHECK(it != Live()->end()) << context; + Live()->erase(it); + for (auto p : (*LiveOrdinal())) { + auto it2 = std::find(p.second.begin(), p.second.end(), context); + if (it2 != p.second.end()) { + p.second.erase(it2, it2++); + if (p.second.empty()) { + LiveOrdinal()->erase(p.first); + } + break; + } + } + } + + // Return the context associated to that ptr. + static CUcontext GetAnyContext(void* ptr) { + absl::ReaderMutexLock lock(&mu_); + int device_ordinal; + CUresult result = cuPointerGetAttribute(static_cast(&device_ordinal), + CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL, + reinterpret_cast(ptr)); + if (result != CUDA_SUCCESS) { + LOG(FATAL) << "Not able to get the device_ordinal for ptr: " << ptr + << ". Error: " << ToString(result); + } + CHECK_EQ(LiveOrdinal()->count(device_ordinal), 1); + CHECK(!LiveOrdinal()->at(device_ordinal).empty()) + << "Need at least one context."; + return LiveOrdinal()->at(device_ordinal)[0]; + } + + private: + // Returns the live map singleton. + static absl::node_hash_map>* Live() { + static auto singleton = + new absl::node_hash_map>; + return singleton; + } + static absl::node_hash_map>* LiveOrdinal() { + static auto singleton = + new absl::node_hash_map>; + return singleton; + } + + // Lock that guards access-to/mutation-of the live set. + static absl::Mutex mu_; + static int64_t next_id_; +}; +} // namespace gpu + +namespace cuda { + +using MemorySpace = gpu::MemorySpace; + +using CUDADriver = gpu::GpuDriver; + +using ScopedActivateContext = gpu::ScopedActivateContext; + +using CudaContext = gpu::GpuContext; + +// Returns the current context set in CUDA. This is done by calling the cuda +// driver (e.g., this value is not our cached view of the current context). +CUcontext CurrentContextOrDie(); + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_DRIVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_event.h new file mode 100644 index 0000000000000000000000000000000000000000..b4aa70392a46ccf05fa70eb4fae2363794f80283 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_event.h @@ -0,0 +1,29 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_EVENT_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_EVENT_H_ + +#include "xla/stream_executor/gpu/gpu_event.h" + +namespace stream_executor { +namespace cuda { + +using CUDAEvent = gpu::GpuEvent; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.h new file mode 100644 index 0000000000000000000000000000000000000000..e5ce88163e4bbca8b3018474da4b561020a3a54a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.h @@ -0,0 +1,141 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// CUDA-specific support for FFT functionality -- this wraps the cuFFT library +// capabilities, and is only included into CUDA implementation code -- it will +// not introduce cuda headers into other code. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_ + +#include + +#include "third_party/gpus/cuda/include/cufft.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/plugin_registry.h" +#include "xla/stream_executor/scratch_allocator.h" + +namespace stream_executor { + +class Stream; + +namespace gpu { + +class GpuExecutor; + +// CUDAFftPlan uses deferred initialization. Only a single call of +// Initialize() is allowed to properly create cufft plan and set member +// variable is_initialized_ to true. Newly added interface that uses member +// variables should first check is_initialized_ to make sure that the values of +// member variables are valid. +class CUDAFftPlan : public fft::Plan { + public: + CUDAFftPlan() + : parent_(nullptr), + plan_(-1), + fft_type_(fft::Type::kInvalid), + scratch_(nullptr), + scratch_size_bytes_(0), + is_initialized_(false), + scratch_allocator_(nullptr) {} + ~CUDAFftPlan() override; + + // Get FFT direction in cuFFT based on FFT type. + int GetFftDirection() const; + cufftHandle GetPlan() const { + if (IsInitialized()) { + return plan_; + } else { + LOG(FATAL) << "Try to get cufftHandle value before initialization."; + } + } + + // Initialize function for batched plan + tsl::Status Initialize(GpuExecutor* parent, Stream* stream, int rank, + uint64_t* elem_count, uint64_t* input_embed, + uint64_t input_stride, uint64 input_distance, + uint64_t* output_embed, uint64_t output_stride, + uint64_t output_distance, fft::Type type, + int batch_count, ScratchAllocator* scratch_allocator); + + // Initialize function for 1d,2d, and 3d plan + tsl::Status Initialize(GpuExecutor* parent, Stream* stream, int rank, + uint64_t* elem_count, fft::Type type, + ScratchAllocator* scratch_allocator); + + tsl::Status UpdateScratchAllocator(Stream* stream, + ScratchAllocator* scratch_allocator); + + ScratchAllocator* GetScratchAllocator() const { return scratch_allocator_; } + + protected: + bool IsInitialized() const { return is_initialized_; } + + private: + GpuExecutor* parent_; + cufftHandle plan_; + fft::Type fft_type_; + DeviceMemory scratch_; + size_t scratch_size_bytes_; + bool is_initialized_; + ScratchAllocator* scratch_allocator_; +}; + +// FFT support for CUDA platform via cuFFT library. +// +// This satisfies the platform-agnostic FftSupport interface. +// +// Note that the cuFFT handle that this encapsulates is implicitly tied to the +// context (and, as a result, the device) that the parent GpuExecutor is tied +// to. This simply happens as an artifact of creating the cuFFT handle when a +// CUDA context is active. +// +// Thread-safe. The CUDA context associated with all operations is the CUDA +// context of parent_, so all context is explicit. +class CUDAFft : public fft::FftSupport { + public: + explicit CUDAFft(GpuExecutor* parent) : parent_(parent) {} + ~CUDAFft() override {} + + TENSORFLOW_STREAM_EXECUTOR_GPU_FFT_SUPPORT_OVERRIDES + + private: + GpuExecutor* parent_; + + // Two helper functions that execute dynload::cufftExec?2?. + + // This is for complex to complex FFT, when the direction is required. + template + bool DoFftWithDirectionInternal(Stream *stream, fft::Plan *plan, + FuncT cufft_exec, + const DeviceMemory &input, + DeviceMemory *output); + + // This is for complex to real or real to complex FFT, when the direction + // is implied. + template + bool DoFftInternal(Stream *stream, fft::Plan *plan, FuncT cufft_exec, + const DeviceMemory &input, + DeviceMemory *output); + + CUDAFft(const CUDAFft&) = delete; + void operator=(const CUDAFft&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_helpers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..5ff0ed0d2af5db9c360bd69f12d7b8e07ef8b679 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_helpers.h @@ -0,0 +1,25 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Common helper functions used for dealing with CUDA API datatypes. +// +// These are typically placed here for use by multiple source components (for +// example, BLAS and executor components). +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_HELPERS_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_HELPERS_H_ + +#include "xla/stream_executor/gpu/gpu_helpers.h" + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_HELPERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..7077ee952ec9e2f270816070a29895cc93f2236b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_kernel.h @@ -0,0 +1,35 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The CUDA implementation of the StreamExecutorInterface functionality. +// CUDA inclusions are ideally confined to this implementation file. +// +// The notions from the StreamExecutor basically correspond to the CUDA streams +// programming model provided by the libcuda.so driver APIs, so we don't have +// to do much more than wrap the calls to the libraries appropriately. +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_KERNEL_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_KERNEL_H_ + +#include "xla/stream_executor/gpu/gpu_kernel.h" + +namespace stream_executor { +namespace cuda { + +using CUDAKernel = gpu::GpuKernel; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_platform_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_platform_id.h new file mode 100644 index 0000000000000000000000000000000000000000..83af581d6f209492a5ec45ac7e646e0496481d33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_platform_id.h @@ -0,0 +1,34 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_PLATFORM_ID_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_PLATFORM_ID_H_ + +#include "xla/stream_executor/platform.h" + +namespace stream_executor { +namespace cuda { + +// Opaque and unique identifier for the cuda platform. +// This is needed so that plugins can refer to/identify this platform without +// instantiating a CudaPlatform object. +// This is broken out here to avoid a circular dependency between CudaPlatform +// and CudaExecutor. +extern const Platform::Id kCudaPlatformId; + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_PLATFORM_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..a99fe6d5eecb85dea24c4e594216aead4af5ffa6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/cuda/cuda_stream.h @@ -0,0 +1,36 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Defines the GpuStream type - the CUDA-specific implementation of the generic +// StreamExecutor Stream interface. + +#ifndef XLA_STREAM_EXECUTOR_CUDA_CUDA_STREAM_H_ +#define XLA_STREAM_EXECUTOR_CUDA_CUDA_STREAM_H_ + +#include "xla/stream_executor/gpu/gpu_stream.h" + +namespace stream_executor { +namespace cuda { + +using CUDAStream = gpu::GpuStream; + +inline CUDAStream* AsCUDAStream(Stream* stream) { + return gpu::AsGpuStream(stream); +} + +} // namespace cuda +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_CUDA_CUDA_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/data_type.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..c0f900d4794e4d2c89741c97dd3e80c2b0fc2330 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/data_type.h @@ -0,0 +1,95 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_DATA_TYPE_H_ +#define XLA_STREAM_EXECUTOR_DATA_TYPE_H_ + +#include +#include + +#include "tsl/platform/float8.h" +#include "tsl/protobuf/dnn.pb.h" + +namespace Eigen { +struct bfloat16; +struct half; +} // namespace Eigen + +namespace stream_executor { +namespace dnn { + +// A helper class to convert C/C++ types to the proper enums. +template +struct ToDataType; + +// Note: If you add a new specialization below, make sure to add the +// corresponding definition in stream_executor/dnn.cc. +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E4M3FN; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E5M2; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E4M3FNUZ; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kF8E5M2FNUZ; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kFloat; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kDouble; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kHalf; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kBF16; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kInt8; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kInt32; +}; +template <> +struct ToDataType { + static constexpr DataType value = DataType::kInt64; +}; +template <> +struct ToDataType> { + static constexpr DataType value = DataType::kComplexFloat; +}; +template <> +struct ToDataType> { + static constexpr DataType value = DataType::kComplexDouble; +}; + +} // namespace dnn +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DATA_TYPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.h new file mode 100644 index 0000000000000000000000000000000000000000..84653c070ec56f1599213d778e43f227b48207a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.h @@ -0,0 +1,549 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Describes the underlying platform for a StreamExecutor; e.g. OpenCL or CUDA +// device and platform properties. Also contains convenience functions for +// checking/calculating launch dimensionality based on device properties. + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_DESCRIPTION_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_DESCRIPTION_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_join.h" +#include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { +namespace internal { +class DeviceDescriptionBuilder; +} // namespace internal + +// CUDA compute capability, as reported by the device description. +struct CudaComputeCapability { + int major = 0; + int minor = 0; + + // MSVC does not like "PASCAL" symbol. + enum CudaComputeCapabilities { + PASCAL_ = 6, + VOLTA = 7, + AMPERE = 8, + HOPPER = 9 + }; + + CudaComputeCapability() = default; + CudaComputeCapability(int major, int minor) { + this->major = major; + this->minor = minor; + } + + explicit CudaComputeCapability(const CudaComputeCapabilityProto &proto) { + this->major = proto.major(); + this->minor = proto.minor(); + } + + bool IsAtLeast(int other_major, int other_minor = 0) const { + return !(*this < CudaComputeCapability{other_major, other_minor}); + } + + bool operator<(const CudaComputeCapability &other) const { + return ToPair() < other.ToPair(); + } + + bool operator==(const CudaComputeCapability &other) const { + return ToPair() == other.ToPair(); + } + + bool operator!=(const CudaComputeCapability &other) const { + return !(*this == other); + } + + // Maximum resident blocks per multiprocessor, values taken from + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capabilities. + int GetMaxResidentBlocksPerSM() const { + if (IsAtLeast(8, 6)) { + return 16; + } else if (IsAtLeast(8)) { + return 32; + } else if (IsAtLeast(7, 5)) { + return 16; + } + return 32; + } + + // Maximum resident warps per multiprocessor, values taken from + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#compute-capabilities. + int GetMaxResidentWarpsPerSM() const { + if (IsAtLeast(8, 6)) { + return 48; + } else if (IsAtLeast(8)) { + return 64; + } else if (IsAtLeast(7, 5)) { + return 32; + } + return 64; + } + + std::string ToString() const { return absl::StrCat(major, ".", minor); } + + std::pair ToPair() const { return std::make_pair(major, minor); } + + CudaComputeCapabilityProto ToProto() const { + CudaComputeCapabilityProto proto; + proto.set_major(major); + proto.set_minor(minor); + return proto; + } +}; + +// ROCm compute capability, as reported by the device description. +class RocmComputeCapability { + public: + // gcn_arch_name example -- gfx90a:sramecc+:xnack- + // gfx_version is the "gfx90a" part of the gcn_arch_name + explicit RocmComputeCapability(const std::string &gcn_arch_name) + : gcn_arch_name_(gcn_arch_name) {} + + explicit RocmComputeCapability(const RocmComputeCapabilityProto &proto) + : gcn_arch_name_(proto.gcn_arch_name()) {} + + RocmComputeCapability() = default; + ~RocmComputeCapability() = default; + + std::string gcn_arch_name() const { return gcn_arch_name_; } + + std::string gfx_version() const { + std::vector tokens = absl::StrSplit(gcn_arch_name_, ':'); + return tokens[0]; + } + + bool is_supported_gfx_version() const { + return absl::c_count(kSupportedGfxVersions, gfx_version()) != 0; + } + + std::string supported_gfx_versions_str() const { + return absl::StrJoin(kSupportedGfxVersions, ", "); + } + + bool has_nhwc_layout_support() const { + static constexpr absl::string_view kList[] = {"gfx908", "gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_bf16_dtype_support() const { + static constexpr absl::string_view kList[] = {"gfx908", "gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_fast_fp16_support() const { + static constexpr absl::string_view kList[] = {"gfx906", "gfx908", "gfx90a", + "gfx1030"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_mfma_instr_support() const { + static constexpr absl::string_view kList[] = {"gfx908", "gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + bool has_fp16_atomics_support() const { + // TODO(rocm): Check. This should be the same as has_fast_fp16_support(). + static constexpr absl::string_view kList[] = {"gfx90a"}; + return absl::c_count(kList, gfx_version()) != 0; + } + + RocmComputeCapabilityProto ToProto() const { + RocmComputeCapabilityProto proto; + proto.set_gcn_arch_name(gcn_arch_name_); + return proto; + } + + bool operator==(const RocmComputeCapability &other) const { + return gcn_arch_name_ == other.gcn_arch_name_; + } + + private: + std::string gcn_arch_name_ = "gfx000"; // default to invalid arch. + + static constexpr absl::string_view kSupportedGfxVersions[]{ + "gfx900", // MI25 + "gfx906", // MI50 / MI60 + "gfx908", // MI100 + "gfx90a", // MI200 + "gfx1030" // Navi21 + }; +}; + +using GpuComputeCapability = + std::variant; + +// Data that describes the execution target of the StreamExecutor, in terms of +// important logical parameters. These include dimensionality limits and +// physical parameters of interest, such as number of cores present on the +// device. +// +// Thread-safe: immutable post-initialization. +class DeviceDescription { + public: + // Returns the platform being run on; this value is primarily intended for + // printing, and comes out something like "OpenCL 1.2" or "Compute Capability + // 3.5". + const std::string &platform_version() const { return platform_version_; } + + // Returns the driver version interfacing with the underlying platform. Vendor + // dependent format. + const std::string &driver_version() const { return driver_version_; } + + // Return the runtime version, if one is provided by the underlying platform. + // Vendor dependent format / usefulness. + const std::string &runtime_version() const { return runtime_version_; } + + // Returns the name that the device reports. Vendor dependent. + const std::string &name() const { return name_; } + + // Gets a human-readable description of the device, e.g. "nvidia GPU + // supporting sm75 with 32GB RAM, 80 SMs, ...". This is intended to be the + // same if and only if two devices are "the same" (e.g. the same make/model of + // GPU), though it may not completely succeed at this for all platforms. + // + // This string is not guaranteed to be stable between versions. Please DO NOT + // rely on it never changing. (Within one version of the code, it won't + // change, don't worry.) + const std::string &model_str() const { return model_str_; } + + // Returns the PCI bus identifier for this device, of the form + // [domain]:[bus]:[device].[function] + const std::string &pci_bus_id() const { return pci_bus_id_; } + + // Returns the NUMA node associated with this device, for use in + // determining socket locality. If the NUMA node could not be determined, -1 + // is returned. + int numa_node() const { return numa_node_; } + + // Number of cores (traditional notion of core; i.e. an SM on an NVIDIA device + // or an AMD Compute Unit. + int core_count() const { return core_count_; } + + // Number of floating point operations one core (SM, compute unit) can execute + // in parallel. Corresponds to the number of "CUDA cores" for NVIDIA devices. + int fpus_per_core() const { return fpus_per_core_; } + + // Returns the limit on the thread dimensionality values in each of the + // respective dimensions. These limits affect what constitutes a legitimate + // kernel launch request. + const ThreadDim &thread_dim_limit() const { return thread_dim_limit_; } + + // Returns the limit on the block dimensionality values in each of the + // respective dimensions. These limits may affect what constitutes a + // legitimate kernel launch request. + const BlockDim &block_dim_limit() const { return block_dim_limit_; } + + // Returns the limit on the total number of threads that can be launched in a + // single block; i.e. the limit on x * y * z dimensions of a ThreadDim. + // This limit affects what constitutes a legitimate kernel launch request. + const int64_t &threads_per_block_limit() const { + return threads_per_block_limit_; + } + + // Returns the limit on the total number of threads that can be simultaneously + // launched on a given multiprocessor. + const int64_t &threads_per_core_limit() const { + return threads_per_core_limit_; + } + + // Returns the number of threads per warp/wavefront. + const int64_t &threads_per_warp() const { return threads_per_warp_; } + + // Returns the limit on the total number of registers per core. + const int64_t ®isters_per_core_limit() const { + return registers_per_core_limit_; + } + + // Returns the limit on the total number of registers that can be + // simultaneously used by a block. + const int64_t ®isters_per_block_limit() const { + return registers_per_block_limit_; + } + + // Returns the number of address bits available to kernel code running on the + // platform. This affects things like the maximum allocation size and perhaps + // types used in kernel code such as size_t. + const int64_t &device_address_bits() const { return device_address_bits_; } + + // Returns the device memory size in bytes. + int64_t device_memory_size() const { return device_memory_size_; } + + // Returns the L2 cache size in bytes. + int64_t l2_cache_size() const { return l2_cache_size_; } + + // Returns the device's memory bandwidth in bytes/sec. (This is for + // reads/writes to/from the device's own memory, not for transfers between the + // host and device.) + int64_t memory_bandwidth() const { return memory_bandwidth_; } + + // Returns the device's core clock rate in GHz. + float clock_rate_ghz() const { return clock_rate_ghz_; } + + // Returns whether ECC is enabled. + bool ecc_enabled() const { return ecc_enabled_; } + + // Returns the device vendor string, e.g., "NVIDIA Corporation", "Advanced + // Micro Devices, Inc.", or "GenuineIntel". + const std::string &device_vendor() const { return device_vendor_; } + + // Returns the CUDA compute capability if we're running on the CUDA platform. + // If a CUDA compute capability is not available, the major version will be + // zero. + CudaComputeCapability cuda_compute_capability() const; + + // Returns the ROCm compute capability if we're running on the ROCm platform. + // If a ROCm compute capability is not available, the default gfx_arch will + // be "gfx000" (which is an invalid gfx arch). + RocmComputeCapability rocm_compute_capability() const; + + const GpuComputeCapability &gpu_compute_capability() const; + + // Returns the maximum amount of shared memory present on a single core + // (i.e. Streaming Multiprocessor on NVIDIA GPUs; Compute Unit for OpenCL + // devices). Note that some devices, such as NVIDIA's have a configurable + // partitioning between shared memory and L1 cache. + int64_t shared_memory_per_core() const { return shared_memory_per_core_; } + + // Returns the maximum amount of static shared memory + // available for a single block. + int64_t shared_memory_per_block() const { return shared_memory_per_block_; } + + // Returns the maximum amount of shared memory available for a single block + // including the dynamically allocated one. + int64_t shared_memory_per_block_optin() const { + return shared_memory_per_block_optin_; + } + + GpuDeviceInfoProto ToGpuProto() const; + explicit DeviceDescription(const GpuDeviceInfoProto &proto); + + // For string values that are not available via the underlying platform, this + // value will be provided. + static const char *kUndefinedString; + + private: + friend class internal::DeviceDescriptionBuilder; + + DeviceDescription(); + + // For description of the following members, see the corresponding accessor + // above. + // + // N.B. If another field is added, update ToMap() above. + std::string device_vendor_; + std::string platform_version_; + std::string driver_version_; + std::string runtime_version_; + std::string pci_bus_id_; + std::string name_; + std::string model_str_; + + ThreadDim thread_dim_limit_; + BlockDim block_dim_limit_; + + int64_t threads_per_core_limit_; + int64_t threads_per_block_limit_; + int64_t threads_per_warp_; + + int64_t registers_per_core_limit_; + int64_t registers_per_block_limit_; + + int64_t device_address_bits_; + int64_t device_memory_size_; + int64_t l2_cache_size_; + int64_t memory_bandwidth_; + + // Shared memory limits on a given device. + int64_t shared_memory_per_core_; + int64_t shared_memory_per_block_; + int64_t shared_memory_per_block_optin_; + + float clock_rate_ghz_; + + GpuComputeCapability gpu_compute_capability_; + + int numa_node_; + int core_count_; + int fpus_per_core_; + bool ecc_enabled_; +}; + +namespace internal { + +// Helper class the builds a device description, given that it has a large +// number of fields that would be easily confused in constructor form. +class DeviceDescriptionBuilder { + public: + DeviceDescriptionBuilder() = default; + + // For descriptions of the following fields, see comments on the corresponding + // DeviceDescription::* accessors above. + + void set_gpu_compute_capability(GpuComputeCapability c) { + device_description_.gpu_compute_capability_ = c; + } + + void set_block_dim_limit_x(int64_t limit) { + device_description_.block_dim_limit_.x = limit; + } + + void set_block_dim_limit_y(int64_t limit) { + device_description_.block_dim_limit_.y = limit; + } + + void set_block_dim_limit_z(int64_t limit) { + device_description_.block_dim_limit_.z = limit; + } + + void set_device_vendor(const std::string &value) { + device_description_.device_vendor_ = value; + } + void set_platform_version(const std::string &value) { + device_description_.platform_version_ = value; + } + void set_driver_version(const std::string &value) { + device_description_.driver_version_ = value; + } + void set_runtime_version(const std::string &value) { + device_description_.runtime_version_ = value; + } + void set_pci_bus_id(const std::string &value) { + device_description_.pci_bus_id_ = value; + } + void set_name(const std::string &value) { device_description_.name_ = value; } + void set_model_str(const std::string &value) { + device_description_.model_str_ = value; + } + + void set_thread_dim_limit(const ThreadDim &value) { + device_description_.thread_dim_limit_ = value; + } + void set_block_dim_limit(const BlockDim &value) { + device_description_.block_dim_limit_ = value; + } + + void set_threads_per_core_limit(int64_t value) { + device_description_.threads_per_core_limit_ = value; + } + void set_threads_per_block_limit(int64_t value) { + device_description_.threads_per_block_limit_ = value; + } + void set_threads_per_warp(int64_t value) { + device_description_.threads_per_warp_ = value; + } + + void set_registers_per_core_limit(int64_t value) { + device_description_.registers_per_core_limit_ = value; + } + void set_registers_per_block_limit(int64_t value) { + device_description_.registers_per_block_limit_ = value; + } + + void set_device_address_bits(int64_t value) { + device_description_.device_address_bits_ = value; + } + void set_device_memory_size(int64_t value) { + device_description_.device_memory_size_ = value; + } + void set_l2_cache_size(int64_t value) { + device_description_.l2_cache_size_ = value; + } + void set_memory_bandwidth(int64_t value) { + device_description_.memory_bandwidth_ = value; + } + + void set_shared_memory_per_core(int64_t value) { + device_description_.shared_memory_per_core_ = value; + } + void set_shared_memory_per_block(int64_t value) { + device_description_.shared_memory_per_block_ = value; + } + void set_shared_memory_per_block_optin(int64_t value) { + device_description_.shared_memory_per_block_optin_ = value; + } + + void set_clock_rate_ghz(float value) { + device_description_.clock_rate_ghz_ = value; + } + + void set_cuda_compute_capability(int major, int minor) { + device_description_.gpu_compute_capability_ = + CudaComputeCapability{major, minor}; + } + + void set_rocm_compute_capability(std::string gcn_arch_name) { + device_description_.gpu_compute_capability_ = + RocmComputeCapability(gcn_arch_name); + } + + void set_numa_node(int value) { device_description_.numa_node_ = value; } + void set_core_count(int value) { device_description_.core_count_ = value; } + void set_fpus_per_core(int value) { + device_description_.fpus_per_core_ = value; + } + void set_ecc_enabled(bool value) { device_description_.ecc_enabled_ = value; } + + // Returns a built DeviceDescription with ownership transferred to the + // caller. There are currently no restrictions on which fields must be set in + // order to build the descriptor. + // + // Once the description is built, this builder object should be discarded. + std::unique_ptr Build() { + return std::make_unique(device_description_); + } + + DeviceDescription BuildObject() { return device_description_; } + + private: + DeviceDescription device_description_; + + DeviceDescriptionBuilder(const DeviceDescriptionBuilder &) = delete; + void operator=(const DeviceDescriptionBuilder &) = delete; +}; + +} // namespace internal + +// Returns whether the given thread_dim is acceptable given the limits described +// in device_description. For detailed reasons for failing the predicate, enable +// VLOG(2) for this module. +bool ThreadDimOk(const DeviceDescription &device_description, + const ThreadDim &thread_dim); + +// Calculate the number of threads/blocks required to process element_count +// elements. Note that you can still end up with more threads than +// element_count due to rounding, so kernels often start with an "is this +// thread id in the element_count range?" test. +void CalculateDimensionality(const DeviceDescription &device_description, + int64_t element_count, int64_t *threads_per_block, + int64_t *block_count); + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_DESCRIPTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..c47979277859a746c7d10c130c8dba9de6ac07e3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_description.pb.h @@ -0,0 +1,2164 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: xla/stream_executor/device_description.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include "xla/autotune_results.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE + +// Internal implementation detail -- do not use these members. +struct TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +namespace stream_executor { +class CudaComputeCapabilityProto; +struct CudaComputeCapabilityProtoDefaultTypeInternal; +extern CudaComputeCapabilityProtoDefaultTypeInternal _CudaComputeCapabilityProto_default_instance_; +class DnnVersionInfoProto; +struct DnnVersionInfoProtoDefaultTypeInternal; +extern DnnVersionInfoProtoDefaultTypeInternal _DnnVersionInfoProto_default_instance_; +class GpuDeviceInfoProto; +struct GpuDeviceInfoProtoDefaultTypeInternal; +extern GpuDeviceInfoProtoDefaultTypeInternal _GpuDeviceInfoProto_default_instance_; +class GpuTargetConfigProto; +struct GpuTargetConfigProtoDefaultTypeInternal; +extern GpuTargetConfigProtoDefaultTypeInternal _GpuTargetConfigProto_default_instance_; +class RocmComputeCapabilityProto; +struct RocmComputeCapabilityProtoDefaultTypeInternal; +extern RocmComputeCapabilityProtoDefaultTypeInternal _RocmComputeCapabilityProto_default_instance_; +} // namespace stream_executor +PROTOBUF_NAMESPACE_OPEN +template<> ::stream_executor::CudaComputeCapabilityProto* Arena::CreateMaybeMessage<::stream_executor::CudaComputeCapabilityProto>(Arena*); +template<> ::stream_executor::DnnVersionInfoProto* Arena::CreateMaybeMessage<::stream_executor::DnnVersionInfoProto>(Arena*); +template<> ::stream_executor::GpuDeviceInfoProto* Arena::CreateMaybeMessage<::stream_executor::GpuDeviceInfoProto>(Arena*); +template<> ::stream_executor::GpuTargetConfigProto* Arena::CreateMaybeMessage<::stream_executor::GpuTargetConfigProto>(Arena*); +template<> ::stream_executor::RocmComputeCapabilityProto* Arena::CreateMaybeMessage<::stream_executor::RocmComputeCapabilityProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace stream_executor { + +// =================================================================== + +class CudaComputeCapabilityProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.CudaComputeCapabilityProto) */ { + public: + inline CudaComputeCapabilityProto() : CudaComputeCapabilityProto(nullptr) {} + ~CudaComputeCapabilityProto() override; + explicit PROTOBUF_CONSTEXPR CudaComputeCapabilityProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CudaComputeCapabilityProto(const CudaComputeCapabilityProto& from); + CudaComputeCapabilityProto(CudaComputeCapabilityProto&& from) noexcept + : CudaComputeCapabilityProto() { + *this = ::std::move(from); + } + + inline CudaComputeCapabilityProto& operator=(const CudaComputeCapabilityProto& from) { + CopyFrom(from); + return *this; + } + inline CudaComputeCapabilityProto& operator=(CudaComputeCapabilityProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CudaComputeCapabilityProto& default_instance() { + return *internal_default_instance(); + } + static inline const CudaComputeCapabilityProto* internal_default_instance() { + return reinterpret_cast( + &_CudaComputeCapabilityProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CudaComputeCapabilityProto& a, CudaComputeCapabilityProto& b) { + a.Swap(&b); + } + inline void Swap(CudaComputeCapabilityProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CudaComputeCapabilityProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CudaComputeCapabilityProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CudaComputeCapabilityProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CudaComputeCapabilityProto& from) { + CudaComputeCapabilityProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(CudaComputeCapabilityProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.CudaComputeCapabilityProto"; + } + protected: + explicit CudaComputeCapabilityProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMajorFieldNumber = 1, + kMinorFieldNumber = 2, + }; + // int32 major = 1; + void clear_major(); + int32_t major() const; + void set_major(int32_t value); + private: + int32_t _internal_major() const; + void _internal_set_major(int32_t value); + public: + + // int32 minor = 2; + void clear_minor(); + int32_t minor() const; + void set_minor(int32_t value); + private: + int32_t _internal_minor() const; + void _internal_set_minor(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:stream_executor.CudaComputeCapabilityProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t major_; + int32_t minor_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class RocmComputeCapabilityProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.RocmComputeCapabilityProto) */ { + public: + inline RocmComputeCapabilityProto() : RocmComputeCapabilityProto(nullptr) {} + ~RocmComputeCapabilityProto() override; + explicit PROTOBUF_CONSTEXPR RocmComputeCapabilityProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + RocmComputeCapabilityProto(const RocmComputeCapabilityProto& from); + RocmComputeCapabilityProto(RocmComputeCapabilityProto&& from) noexcept + : RocmComputeCapabilityProto() { + *this = ::std::move(from); + } + + inline RocmComputeCapabilityProto& operator=(const RocmComputeCapabilityProto& from) { + CopyFrom(from); + return *this; + } + inline RocmComputeCapabilityProto& operator=(RocmComputeCapabilityProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const RocmComputeCapabilityProto& default_instance() { + return *internal_default_instance(); + } + static inline const RocmComputeCapabilityProto* internal_default_instance() { + return reinterpret_cast( + &_RocmComputeCapabilityProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(RocmComputeCapabilityProto& a, RocmComputeCapabilityProto& b) { + a.Swap(&b); + } + inline void Swap(RocmComputeCapabilityProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(RocmComputeCapabilityProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + RocmComputeCapabilityProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const RocmComputeCapabilityProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const RocmComputeCapabilityProto& from) { + RocmComputeCapabilityProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(RocmComputeCapabilityProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.RocmComputeCapabilityProto"; + } + protected: + explicit RocmComputeCapabilityProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kGcnArchNameFieldNumber = 1, + }; + // string gcn_arch_name = 1; + void clear_gcn_arch_name(); + const std::string& gcn_arch_name() const; + template + void set_gcn_arch_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_gcn_arch_name(); + PROTOBUF_NODISCARD std::string* release_gcn_arch_name(); + void set_allocated_gcn_arch_name(std::string* gcn_arch_name); + private: + const std::string& _internal_gcn_arch_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_gcn_arch_name(const std::string& value); + std::string* _internal_mutable_gcn_arch_name(); + public: + + // @@protoc_insertion_point(class_scope:stream_executor.RocmComputeCapabilityProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr gcn_arch_name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class GpuDeviceInfoProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.GpuDeviceInfoProto) */ { + public: + inline GpuDeviceInfoProto() : GpuDeviceInfoProto(nullptr) {} + ~GpuDeviceInfoProto() override; + explicit PROTOBUF_CONSTEXPR GpuDeviceInfoProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + GpuDeviceInfoProto(const GpuDeviceInfoProto& from); + GpuDeviceInfoProto(GpuDeviceInfoProto&& from) noexcept + : GpuDeviceInfoProto() { + *this = ::std::move(from); + } + + inline GpuDeviceInfoProto& operator=(const GpuDeviceInfoProto& from) { + CopyFrom(from); + return *this; + } + inline GpuDeviceInfoProto& operator=(GpuDeviceInfoProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const GpuDeviceInfoProto& default_instance() { + return *internal_default_instance(); + } + enum ComputeCapabilityCase { + kCudaComputeCapability = 16, + kRocmComputeCapability = 17, + COMPUTE_CAPABILITY_NOT_SET = 0, + }; + + static inline const GpuDeviceInfoProto* internal_default_instance() { + return reinterpret_cast( + &_GpuDeviceInfoProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(GpuDeviceInfoProto& a, GpuDeviceInfoProto& b) { + a.Swap(&b); + } + inline void Swap(GpuDeviceInfoProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(GpuDeviceInfoProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + GpuDeviceInfoProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const GpuDeviceInfoProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const GpuDeviceInfoProto& from) { + GpuDeviceInfoProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(GpuDeviceInfoProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.GpuDeviceInfoProto"; + } + protected: + explicit GpuDeviceInfoProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kThreadsPerBlockLimitFieldNumber = 1, + kThreadsPerWarpFieldNumber = 2, + kSharedMemoryPerBlockFieldNumber = 3, + kSharedMemoryPerCoreFieldNumber = 4, + kThreadsPerCoreLimitFieldNumber = 5, + kCoreCountFieldNumber = 6, + kFpusPerCoreFieldNumber = 7, + kBlockDimLimitXFieldNumber = 8, + kBlockDimLimitYFieldNumber = 9, + kMemoryBandwidthFieldNumber = 11, + kBlockDimLimitZFieldNumber = 10, + kClockRateGhzFieldNumber = 13, + kL2CacheSizeFieldNumber = 12, + kDeviceMemorySizeFieldNumber = 14, + kSharedMemoryPerBlockOptinFieldNumber = 15, + kCudaComputeCapabilityFieldNumber = 16, + kRocmComputeCapabilityFieldNumber = 17, + }; + // int32 threads_per_block_limit = 1; + void clear_threads_per_block_limit(); + int32_t threads_per_block_limit() const; + void set_threads_per_block_limit(int32_t value); + private: + int32_t _internal_threads_per_block_limit() const; + void _internal_set_threads_per_block_limit(int32_t value); + public: + + // int32 threads_per_warp = 2; + void clear_threads_per_warp(); + int32_t threads_per_warp() const; + void set_threads_per_warp(int32_t value); + private: + int32_t _internal_threads_per_warp() const; + void _internal_set_threads_per_warp(int32_t value); + public: + + // int32 shared_memory_per_block = 3; + void clear_shared_memory_per_block(); + int32_t shared_memory_per_block() const; + void set_shared_memory_per_block(int32_t value); + private: + int32_t _internal_shared_memory_per_block() const; + void _internal_set_shared_memory_per_block(int32_t value); + public: + + // int32 shared_memory_per_core = 4; + void clear_shared_memory_per_core(); + int32_t shared_memory_per_core() const; + void set_shared_memory_per_core(int32_t value); + private: + int32_t _internal_shared_memory_per_core() const; + void _internal_set_shared_memory_per_core(int32_t value); + public: + + // int32 threads_per_core_limit = 5; + void clear_threads_per_core_limit(); + int32_t threads_per_core_limit() const; + void set_threads_per_core_limit(int32_t value); + private: + int32_t _internal_threads_per_core_limit() const; + void _internal_set_threads_per_core_limit(int32_t value); + public: + + // int32 core_count = 6; + void clear_core_count(); + int32_t core_count() const; + void set_core_count(int32_t value); + private: + int32_t _internal_core_count() const; + void _internal_set_core_count(int32_t value); + public: + + // int64 fpus_per_core = 7; + void clear_fpus_per_core(); + int64_t fpus_per_core() const; + void set_fpus_per_core(int64_t value); + private: + int64_t _internal_fpus_per_core() const; + void _internal_set_fpus_per_core(int64_t value); + public: + + // int32 block_dim_limit_x = 8; + void clear_block_dim_limit_x(); + int32_t block_dim_limit_x() const; + void set_block_dim_limit_x(int32_t value); + private: + int32_t _internal_block_dim_limit_x() const; + void _internal_set_block_dim_limit_x(int32_t value); + public: + + // int32 block_dim_limit_y = 9; + void clear_block_dim_limit_y(); + int32_t block_dim_limit_y() const; + void set_block_dim_limit_y(int32_t value); + private: + int32_t _internal_block_dim_limit_y() const; + void _internal_set_block_dim_limit_y(int32_t value); + public: + + // int64 memory_bandwidth = 11; + void clear_memory_bandwidth(); + int64_t memory_bandwidth() const; + void set_memory_bandwidth(int64_t value); + private: + int64_t _internal_memory_bandwidth() const; + void _internal_set_memory_bandwidth(int64_t value); + public: + + // int32 block_dim_limit_z = 10; + void clear_block_dim_limit_z(); + int32_t block_dim_limit_z() const; + void set_block_dim_limit_z(int32_t value); + private: + int32_t _internal_block_dim_limit_z() const; + void _internal_set_block_dim_limit_z(int32_t value); + public: + + // float clock_rate_ghz = 13; + void clear_clock_rate_ghz(); + float clock_rate_ghz() const; + void set_clock_rate_ghz(float value); + private: + float _internal_clock_rate_ghz() const; + void _internal_set_clock_rate_ghz(float value); + public: + + // int64 l2_cache_size = 12; + void clear_l2_cache_size(); + int64_t l2_cache_size() const; + void set_l2_cache_size(int64_t value); + private: + int64_t _internal_l2_cache_size() const; + void _internal_set_l2_cache_size(int64_t value); + public: + + // int64 device_memory_size = 14; + void clear_device_memory_size(); + int64_t device_memory_size() const; + void set_device_memory_size(int64_t value); + private: + int64_t _internal_device_memory_size() const; + void _internal_set_device_memory_size(int64_t value); + public: + + // int32 shared_memory_per_block_optin = 15; + void clear_shared_memory_per_block_optin(); + int32_t shared_memory_per_block_optin() const; + void set_shared_memory_per_block_optin(int32_t value); + private: + int32_t _internal_shared_memory_per_block_optin() const; + void _internal_set_shared_memory_per_block_optin(int32_t value); + public: + + // .stream_executor.CudaComputeCapabilityProto cuda_compute_capability = 16; + bool has_cuda_compute_capability() const; + private: + bool _internal_has_cuda_compute_capability() const; + public: + void clear_cuda_compute_capability(); + const ::stream_executor::CudaComputeCapabilityProto& cuda_compute_capability() const; + PROTOBUF_NODISCARD ::stream_executor::CudaComputeCapabilityProto* release_cuda_compute_capability(); + ::stream_executor::CudaComputeCapabilityProto* mutable_cuda_compute_capability(); + void set_allocated_cuda_compute_capability(::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability); + private: + const ::stream_executor::CudaComputeCapabilityProto& _internal_cuda_compute_capability() const; + ::stream_executor::CudaComputeCapabilityProto* _internal_mutable_cuda_compute_capability(); + public: + void unsafe_arena_set_allocated_cuda_compute_capability( + ::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability); + ::stream_executor::CudaComputeCapabilityProto* unsafe_arena_release_cuda_compute_capability(); + + // .stream_executor.RocmComputeCapabilityProto rocm_compute_capability = 17; + bool has_rocm_compute_capability() const; + private: + bool _internal_has_rocm_compute_capability() const; + public: + void clear_rocm_compute_capability(); + const ::stream_executor::RocmComputeCapabilityProto& rocm_compute_capability() const; + PROTOBUF_NODISCARD ::stream_executor::RocmComputeCapabilityProto* release_rocm_compute_capability(); + ::stream_executor::RocmComputeCapabilityProto* mutable_rocm_compute_capability(); + void set_allocated_rocm_compute_capability(::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability); + private: + const ::stream_executor::RocmComputeCapabilityProto& _internal_rocm_compute_capability() const; + ::stream_executor::RocmComputeCapabilityProto* _internal_mutable_rocm_compute_capability(); + public: + void unsafe_arena_set_allocated_rocm_compute_capability( + ::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability); + ::stream_executor::RocmComputeCapabilityProto* unsafe_arena_release_rocm_compute_capability(); + + void clear_compute_capability(); + ComputeCapabilityCase compute_capability_case() const; + // @@protoc_insertion_point(class_scope:stream_executor.GpuDeviceInfoProto) + private: + class _Internal; + void set_has_cuda_compute_capability(); + void set_has_rocm_compute_capability(); + + inline bool has_compute_capability() const; + inline void clear_has_compute_capability(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t threads_per_block_limit_; + int32_t threads_per_warp_; + int32_t shared_memory_per_block_; + int32_t shared_memory_per_core_; + int32_t threads_per_core_limit_; + int32_t core_count_; + int64_t fpus_per_core_; + int32_t block_dim_limit_x_; + int32_t block_dim_limit_y_; + int64_t memory_bandwidth_; + int32_t block_dim_limit_z_; + float clock_rate_ghz_; + int64_t l2_cache_size_; + int64_t device_memory_size_; + int32_t shared_memory_per_block_optin_; + union ComputeCapabilityUnion { + constexpr ComputeCapabilityUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability_; + ::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability_; + } compute_capability_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class DnnVersionInfoProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.DnnVersionInfoProto) */ { + public: + inline DnnVersionInfoProto() : DnnVersionInfoProto(nullptr) {} + ~DnnVersionInfoProto() override; + explicit PROTOBUF_CONSTEXPR DnnVersionInfoProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DnnVersionInfoProto(const DnnVersionInfoProto& from); + DnnVersionInfoProto(DnnVersionInfoProto&& from) noexcept + : DnnVersionInfoProto() { + *this = ::std::move(from); + } + + inline DnnVersionInfoProto& operator=(const DnnVersionInfoProto& from) { + CopyFrom(from); + return *this; + } + inline DnnVersionInfoProto& operator=(DnnVersionInfoProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const DnnVersionInfoProto& default_instance() { + return *internal_default_instance(); + } + static inline const DnnVersionInfoProto* internal_default_instance() { + return reinterpret_cast( + &_DnnVersionInfoProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(DnnVersionInfoProto& a, DnnVersionInfoProto& b) { + a.Swap(&b); + } + inline void Swap(DnnVersionInfoProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(DnnVersionInfoProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DnnVersionInfoProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DnnVersionInfoProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DnnVersionInfoProto& from) { + DnnVersionInfoProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(DnnVersionInfoProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.DnnVersionInfoProto"; + } + protected: + explicit DnnVersionInfoProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kMajorFieldNumber = 1, + kMinorFieldNumber = 2, + kPatchFieldNumber = 3, + }; + // int32 major = 1; + void clear_major(); + int32_t major() const; + void set_major(int32_t value); + private: + int32_t _internal_major() const; + void _internal_set_major(int32_t value); + public: + + // int32 minor = 2; + void clear_minor(); + int32_t minor() const; + void set_minor(int32_t value); + private: + int32_t _internal_minor() const; + void _internal_set_minor(int32_t value); + public: + + // int32 patch = 3; + void clear_patch(); + int32_t patch() const; + void set_patch(int32_t value); + private: + int32_t _internal_patch() const; + void _internal_set_patch(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:stream_executor.DnnVersionInfoProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t major_; + int32_t minor_; + int32_t patch_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// ------------------------------------------------------------------- + +class GpuTargetConfigProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:stream_executor.GpuTargetConfigProto) */ { + public: + inline GpuTargetConfigProto() : GpuTargetConfigProto(nullptr) {} + ~GpuTargetConfigProto() override; + explicit PROTOBUF_CONSTEXPR GpuTargetConfigProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + GpuTargetConfigProto(const GpuTargetConfigProto& from); + GpuTargetConfigProto(GpuTargetConfigProto&& from) noexcept + : GpuTargetConfigProto() { + *this = ::std::move(from); + } + + inline GpuTargetConfigProto& operator=(const GpuTargetConfigProto& from) { + CopyFrom(from); + return *this; + } + inline GpuTargetConfigProto& operator=(GpuTargetConfigProto&& from) noexcept { + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); + } else { + CopyFrom(from); + } + return *this; + } + + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const GpuTargetConfigProto& default_instance() { + return *internal_default_instance(); + } + static inline const GpuTargetConfigProto* internal_default_instance() { + return reinterpret_cast( + &_GpuTargetConfigProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(GpuTargetConfigProto& a, GpuTargetConfigProto& b) { + a.Swap(&b); + } + inline void Swap(GpuTargetConfigProto* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(GpuTargetConfigProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + GpuTargetConfigProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const GpuTargetConfigProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const GpuTargetConfigProto& from) { + GpuTargetConfigProto::MergeImpl(*this, from); + } + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; + bool IsInitialized() const final; + + size_t ByteSizeLong() const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } + + private: + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); + void SharedDtor(); + void SetCachedSize(int size) const final; + void InternalSwap(GpuTargetConfigProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "stream_executor.GpuTargetConfigProto"; + } + protected: + explicit GpuTargetConfigProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kPlatformNameFieldNumber = 4, + kDeviceDescriptionStrFieldNumber = 7, + kGpuDeviceInfoFieldNumber = 1, + kDnnVersionInfoFieldNumber = 5, + kAutotuneResultsFieldNumber = 6, + }; + // string platform_name = 4; + void clear_platform_name(); + const std::string& platform_name() const; + template + void set_platform_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_platform_name(); + PROTOBUF_NODISCARD std::string* release_platform_name(); + void set_allocated_platform_name(std::string* platform_name); + private: + const std::string& _internal_platform_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_platform_name(const std::string& value); + std::string* _internal_mutable_platform_name(); + public: + + // string device_description_str = 7; + void clear_device_description_str(); + const std::string& device_description_str() const; + template + void set_device_description_str(ArgT0&& arg0, ArgT... args); + std::string* mutable_device_description_str(); + PROTOBUF_NODISCARD std::string* release_device_description_str(); + void set_allocated_device_description_str(std::string* device_description_str); + private: + const std::string& _internal_device_description_str() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device_description_str(const std::string& value); + std::string* _internal_mutable_device_description_str(); + public: + + // .stream_executor.GpuDeviceInfoProto gpu_device_info = 1; + bool has_gpu_device_info() const; + private: + bool _internal_has_gpu_device_info() const; + public: + void clear_gpu_device_info(); + const ::stream_executor::GpuDeviceInfoProto& gpu_device_info() const; + PROTOBUF_NODISCARD ::stream_executor::GpuDeviceInfoProto* release_gpu_device_info(); + ::stream_executor::GpuDeviceInfoProto* mutable_gpu_device_info(); + void set_allocated_gpu_device_info(::stream_executor::GpuDeviceInfoProto* gpu_device_info); + private: + const ::stream_executor::GpuDeviceInfoProto& _internal_gpu_device_info() const; + ::stream_executor::GpuDeviceInfoProto* _internal_mutable_gpu_device_info(); + public: + void unsafe_arena_set_allocated_gpu_device_info( + ::stream_executor::GpuDeviceInfoProto* gpu_device_info); + ::stream_executor::GpuDeviceInfoProto* unsafe_arena_release_gpu_device_info(); + + // .stream_executor.DnnVersionInfoProto dnn_version_info = 5; + bool has_dnn_version_info() const; + private: + bool _internal_has_dnn_version_info() const; + public: + void clear_dnn_version_info(); + const ::stream_executor::DnnVersionInfoProto& dnn_version_info() const; + PROTOBUF_NODISCARD ::stream_executor::DnnVersionInfoProto* release_dnn_version_info(); + ::stream_executor::DnnVersionInfoProto* mutable_dnn_version_info(); + void set_allocated_dnn_version_info(::stream_executor::DnnVersionInfoProto* dnn_version_info); + private: + const ::stream_executor::DnnVersionInfoProto& _internal_dnn_version_info() const; + ::stream_executor::DnnVersionInfoProto* _internal_mutable_dnn_version_info(); + public: + void unsafe_arena_set_allocated_dnn_version_info( + ::stream_executor::DnnVersionInfoProto* dnn_version_info); + ::stream_executor::DnnVersionInfoProto* unsafe_arena_release_dnn_version_info(); + + // .xla.AutotuneResults autotune_results = 6; + bool has_autotune_results() const; + private: + bool _internal_has_autotune_results() const; + public: + void clear_autotune_results(); + const ::xla::AutotuneResults& autotune_results() const; + PROTOBUF_NODISCARD ::xla::AutotuneResults* release_autotune_results(); + ::xla::AutotuneResults* mutable_autotune_results(); + void set_allocated_autotune_results(::xla::AutotuneResults* autotune_results); + private: + const ::xla::AutotuneResults& _internal_autotune_results() const; + ::xla::AutotuneResults* _internal_mutable_autotune_results(); + public: + void unsafe_arena_set_allocated_autotune_results( + ::xla::AutotuneResults* autotune_results); + ::xla::AutotuneResults* unsafe_arena_release_autotune_results(); + + // @@protoc_insertion_point(class_scope:stream_executor.GpuTargetConfigProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr platform_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_description_str_; + ::stream_executor::GpuDeviceInfoProto* gpu_device_info_; + ::stream_executor::DnnVersionInfoProto* dnn_version_info_; + ::xla::AutotuneResults* autotune_results_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CudaComputeCapabilityProto + +// int32 major = 1; +inline void CudaComputeCapabilityProto::clear_major() { + _impl_.major_ = 0; +} +inline int32_t CudaComputeCapabilityProto::_internal_major() const { + return _impl_.major_; +} +inline int32_t CudaComputeCapabilityProto::major() const { + // @@protoc_insertion_point(field_get:stream_executor.CudaComputeCapabilityProto.major) + return _internal_major(); +} +inline void CudaComputeCapabilityProto::_internal_set_major(int32_t value) { + + _impl_.major_ = value; +} +inline void CudaComputeCapabilityProto::set_major(int32_t value) { + _internal_set_major(value); + // @@protoc_insertion_point(field_set:stream_executor.CudaComputeCapabilityProto.major) +} + +// int32 minor = 2; +inline void CudaComputeCapabilityProto::clear_minor() { + _impl_.minor_ = 0; +} +inline int32_t CudaComputeCapabilityProto::_internal_minor() const { + return _impl_.minor_; +} +inline int32_t CudaComputeCapabilityProto::minor() const { + // @@protoc_insertion_point(field_get:stream_executor.CudaComputeCapabilityProto.minor) + return _internal_minor(); +} +inline void CudaComputeCapabilityProto::_internal_set_minor(int32_t value) { + + _impl_.minor_ = value; +} +inline void CudaComputeCapabilityProto::set_minor(int32_t value) { + _internal_set_minor(value); + // @@protoc_insertion_point(field_set:stream_executor.CudaComputeCapabilityProto.minor) +} + +// ------------------------------------------------------------------- + +// RocmComputeCapabilityProto + +// string gcn_arch_name = 1; +inline void RocmComputeCapabilityProto::clear_gcn_arch_name() { + _impl_.gcn_arch_name_.ClearToEmpty(); +} +inline const std::string& RocmComputeCapabilityProto::gcn_arch_name() const { + // @@protoc_insertion_point(field_get:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) + return _internal_gcn_arch_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void RocmComputeCapabilityProto::set_gcn_arch_name(ArgT0&& arg0, ArgT... args) { + + _impl_.gcn_arch_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) +} +inline std::string* RocmComputeCapabilityProto::mutable_gcn_arch_name() { + std::string* _s = _internal_mutable_gcn_arch_name(); + // @@protoc_insertion_point(field_mutable:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) + return _s; +} +inline const std::string& RocmComputeCapabilityProto::_internal_gcn_arch_name() const { + return _impl_.gcn_arch_name_.Get(); +} +inline void RocmComputeCapabilityProto::_internal_set_gcn_arch_name(const std::string& value) { + + _impl_.gcn_arch_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* RocmComputeCapabilityProto::_internal_mutable_gcn_arch_name() { + + return _impl_.gcn_arch_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* RocmComputeCapabilityProto::release_gcn_arch_name() { + // @@protoc_insertion_point(field_release:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) + return _impl_.gcn_arch_name_.Release(); +} +inline void RocmComputeCapabilityProto::set_allocated_gcn_arch_name(std::string* gcn_arch_name) { + if (gcn_arch_name != nullptr) { + + } else { + + } + _impl_.gcn_arch_name_.SetAllocated(gcn_arch_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.gcn_arch_name_.IsDefault()) { + _impl_.gcn_arch_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:stream_executor.RocmComputeCapabilityProto.gcn_arch_name) +} + +// ------------------------------------------------------------------- + +// GpuDeviceInfoProto + +// int32 threads_per_block_limit = 1; +inline void GpuDeviceInfoProto::clear_threads_per_block_limit() { + _impl_.threads_per_block_limit_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_threads_per_block_limit() const { + return _impl_.threads_per_block_limit_; +} +inline int32_t GpuDeviceInfoProto::threads_per_block_limit() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.threads_per_block_limit) + return _internal_threads_per_block_limit(); +} +inline void GpuDeviceInfoProto::_internal_set_threads_per_block_limit(int32_t value) { + + _impl_.threads_per_block_limit_ = value; +} +inline void GpuDeviceInfoProto::set_threads_per_block_limit(int32_t value) { + _internal_set_threads_per_block_limit(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.threads_per_block_limit) +} + +// int32 threads_per_warp = 2; +inline void GpuDeviceInfoProto::clear_threads_per_warp() { + _impl_.threads_per_warp_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_threads_per_warp() const { + return _impl_.threads_per_warp_; +} +inline int32_t GpuDeviceInfoProto::threads_per_warp() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.threads_per_warp) + return _internal_threads_per_warp(); +} +inline void GpuDeviceInfoProto::_internal_set_threads_per_warp(int32_t value) { + + _impl_.threads_per_warp_ = value; +} +inline void GpuDeviceInfoProto::set_threads_per_warp(int32_t value) { + _internal_set_threads_per_warp(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.threads_per_warp) +} + +// int32 shared_memory_per_block = 3; +inline void GpuDeviceInfoProto::clear_shared_memory_per_block() { + _impl_.shared_memory_per_block_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_shared_memory_per_block() const { + return _impl_.shared_memory_per_block_; +} +inline int32_t GpuDeviceInfoProto::shared_memory_per_block() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.shared_memory_per_block) + return _internal_shared_memory_per_block(); +} +inline void GpuDeviceInfoProto::_internal_set_shared_memory_per_block(int32_t value) { + + _impl_.shared_memory_per_block_ = value; +} +inline void GpuDeviceInfoProto::set_shared_memory_per_block(int32_t value) { + _internal_set_shared_memory_per_block(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.shared_memory_per_block) +} + +// int32 shared_memory_per_core = 4; +inline void GpuDeviceInfoProto::clear_shared_memory_per_core() { + _impl_.shared_memory_per_core_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_shared_memory_per_core() const { + return _impl_.shared_memory_per_core_; +} +inline int32_t GpuDeviceInfoProto::shared_memory_per_core() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.shared_memory_per_core) + return _internal_shared_memory_per_core(); +} +inline void GpuDeviceInfoProto::_internal_set_shared_memory_per_core(int32_t value) { + + _impl_.shared_memory_per_core_ = value; +} +inline void GpuDeviceInfoProto::set_shared_memory_per_core(int32_t value) { + _internal_set_shared_memory_per_core(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.shared_memory_per_core) +} + +// int32 threads_per_core_limit = 5; +inline void GpuDeviceInfoProto::clear_threads_per_core_limit() { + _impl_.threads_per_core_limit_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_threads_per_core_limit() const { + return _impl_.threads_per_core_limit_; +} +inline int32_t GpuDeviceInfoProto::threads_per_core_limit() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.threads_per_core_limit) + return _internal_threads_per_core_limit(); +} +inline void GpuDeviceInfoProto::_internal_set_threads_per_core_limit(int32_t value) { + + _impl_.threads_per_core_limit_ = value; +} +inline void GpuDeviceInfoProto::set_threads_per_core_limit(int32_t value) { + _internal_set_threads_per_core_limit(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.threads_per_core_limit) +} + +// int32 core_count = 6; +inline void GpuDeviceInfoProto::clear_core_count() { + _impl_.core_count_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_core_count() const { + return _impl_.core_count_; +} +inline int32_t GpuDeviceInfoProto::core_count() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.core_count) + return _internal_core_count(); +} +inline void GpuDeviceInfoProto::_internal_set_core_count(int32_t value) { + + _impl_.core_count_ = value; +} +inline void GpuDeviceInfoProto::set_core_count(int32_t value) { + _internal_set_core_count(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.core_count) +} + +// int64 fpus_per_core = 7; +inline void GpuDeviceInfoProto::clear_fpus_per_core() { + _impl_.fpus_per_core_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_fpus_per_core() const { + return _impl_.fpus_per_core_; +} +inline int64_t GpuDeviceInfoProto::fpus_per_core() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.fpus_per_core) + return _internal_fpus_per_core(); +} +inline void GpuDeviceInfoProto::_internal_set_fpus_per_core(int64_t value) { + + _impl_.fpus_per_core_ = value; +} +inline void GpuDeviceInfoProto::set_fpus_per_core(int64_t value) { + _internal_set_fpus_per_core(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.fpus_per_core) +} + +// int32 block_dim_limit_x = 8; +inline void GpuDeviceInfoProto::clear_block_dim_limit_x() { + _impl_.block_dim_limit_x_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_block_dim_limit_x() const { + return _impl_.block_dim_limit_x_; +} +inline int32_t GpuDeviceInfoProto::block_dim_limit_x() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.block_dim_limit_x) + return _internal_block_dim_limit_x(); +} +inline void GpuDeviceInfoProto::_internal_set_block_dim_limit_x(int32_t value) { + + _impl_.block_dim_limit_x_ = value; +} +inline void GpuDeviceInfoProto::set_block_dim_limit_x(int32_t value) { + _internal_set_block_dim_limit_x(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.block_dim_limit_x) +} + +// int32 block_dim_limit_y = 9; +inline void GpuDeviceInfoProto::clear_block_dim_limit_y() { + _impl_.block_dim_limit_y_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_block_dim_limit_y() const { + return _impl_.block_dim_limit_y_; +} +inline int32_t GpuDeviceInfoProto::block_dim_limit_y() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.block_dim_limit_y) + return _internal_block_dim_limit_y(); +} +inline void GpuDeviceInfoProto::_internal_set_block_dim_limit_y(int32_t value) { + + _impl_.block_dim_limit_y_ = value; +} +inline void GpuDeviceInfoProto::set_block_dim_limit_y(int32_t value) { + _internal_set_block_dim_limit_y(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.block_dim_limit_y) +} + +// int32 block_dim_limit_z = 10; +inline void GpuDeviceInfoProto::clear_block_dim_limit_z() { + _impl_.block_dim_limit_z_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_block_dim_limit_z() const { + return _impl_.block_dim_limit_z_; +} +inline int32_t GpuDeviceInfoProto::block_dim_limit_z() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.block_dim_limit_z) + return _internal_block_dim_limit_z(); +} +inline void GpuDeviceInfoProto::_internal_set_block_dim_limit_z(int32_t value) { + + _impl_.block_dim_limit_z_ = value; +} +inline void GpuDeviceInfoProto::set_block_dim_limit_z(int32_t value) { + _internal_set_block_dim_limit_z(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.block_dim_limit_z) +} + +// int64 memory_bandwidth = 11; +inline void GpuDeviceInfoProto::clear_memory_bandwidth() { + _impl_.memory_bandwidth_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_memory_bandwidth() const { + return _impl_.memory_bandwidth_; +} +inline int64_t GpuDeviceInfoProto::memory_bandwidth() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.memory_bandwidth) + return _internal_memory_bandwidth(); +} +inline void GpuDeviceInfoProto::_internal_set_memory_bandwidth(int64_t value) { + + _impl_.memory_bandwidth_ = value; +} +inline void GpuDeviceInfoProto::set_memory_bandwidth(int64_t value) { + _internal_set_memory_bandwidth(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.memory_bandwidth) +} + +// int64 l2_cache_size = 12; +inline void GpuDeviceInfoProto::clear_l2_cache_size() { + _impl_.l2_cache_size_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_l2_cache_size() const { + return _impl_.l2_cache_size_; +} +inline int64_t GpuDeviceInfoProto::l2_cache_size() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.l2_cache_size) + return _internal_l2_cache_size(); +} +inline void GpuDeviceInfoProto::_internal_set_l2_cache_size(int64_t value) { + + _impl_.l2_cache_size_ = value; +} +inline void GpuDeviceInfoProto::set_l2_cache_size(int64_t value) { + _internal_set_l2_cache_size(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.l2_cache_size) +} + +// float clock_rate_ghz = 13; +inline void GpuDeviceInfoProto::clear_clock_rate_ghz() { + _impl_.clock_rate_ghz_ = 0; +} +inline float GpuDeviceInfoProto::_internal_clock_rate_ghz() const { + return _impl_.clock_rate_ghz_; +} +inline float GpuDeviceInfoProto::clock_rate_ghz() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.clock_rate_ghz) + return _internal_clock_rate_ghz(); +} +inline void GpuDeviceInfoProto::_internal_set_clock_rate_ghz(float value) { + + _impl_.clock_rate_ghz_ = value; +} +inline void GpuDeviceInfoProto::set_clock_rate_ghz(float value) { + _internal_set_clock_rate_ghz(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.clock_rate_ghz) +} + +// int64 device_memory_size = 14; +inline void GpuDeviceInfoProto::clear_device_memory_size() { + _impl_.device_memory_size_ = int64_t{0}; +} +inline int64_t GpuDeviceInfoProto::_internal_device_memory_size() const { + return _impl_.device_memory_size_; +} +inline int64_t GpuDeviceInfoProto::device_memory_size() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.device_memory_size) + return _internal_device_memory_size(); +} +inline void GpuDeviceInfoProto::_internal_set_device_memory_size(int64_t value) { + + _impl_.device_memory_size_ = value; +} +inline void GpuDeviceInfoProto::set_device_memory_size(int64_t value) { + _internal_set_device_memory_size(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.device_memory_size) +} + +// int32 shared_memory_per_block_optin = 15; +inline void GpuDeviceInfoProto::clear_shared_memory_per_block_optin() { + _impl_.shared_memory_per_block_optin_ = 0; +} +inline int32_t GpuDeviceInfoProto::_internal_shared_memory_per_block_optin() const { + return _impl_.shared_memory_per_block_optin_; +} +inline int32_t GpuDeviceInfoProto::shared_memory_per_block_optin() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.shared_memory_per_block_optin) + return _internal_shared_memory_per_block_optin(); +} +inline void GpuDeviceInfoProto::_internal_set_shared_memory_per_block_optin(int32_t value) { + + _impl_.shared_memory_per_block_optin_ = value; +} +inline void GpuDeviceInfoProto::set_shared_memory_per_block_optin(int32_t value) { + _internal_set_shared_memory_per_block_optin(value); + // @@protoc_insertion_point(field_set:stream_executor.GpuDeviceInfoProto.shared_memory_per_block_optin) +} + +// .stream_executor.CudaComputeCapabilityProto cuda_compute_capability = 16; +inline bool GpuDeviceInfoProto::_internal_has_cuda_compute_capability() const { + return compute_capability_case() == kCudaComputeCapability; +} +inline bool GpuDeviceInfoProto::has_cuda_compute_capability() const { + return _internal_has_cuda_compute_capability(); +} +inline void GpuDeviceInfoProto::set_has_cuda_compute_capability() { + _impl_._oneof_case_[0] = kCudaComputeCapability; +} +inline void GpuDeviceInfoProto::clear_cuda_compute_capability() { + if (_internal_has_cuda_compute_capability()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.compute_capability_.cuda_compute_capability_; + } + clear_has_compute_capability(); + } +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::release_cuda_compute_capability() { + // @@protoc_insertion_point(field_release:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + if (_internal_has_cuda_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::CudaComputeCapabilityProto* temp = _impl_.compute_capability_.cuda_compute_capability_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.compute_capability_.cuda_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::stream_executor::CudaComputeCapabilityProto& GpuDeviceInfoProto::_internal_cuda_compute_capability() const { + return _internal_has_cuda_compute_capability() + ? *_impl_.compute_capability_.cuda_compute_capability_ + : reinterpret_cast< ::stream_executor::CudaComputeCapabilityProto&>(::stream_executor::_CudaComputeCapabilityProto_default_instance_); +} +inline const ::stream_executor::CudaComputeCapabilityProto& GpuDeviceInfoProto::cuda_compute_capability() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + return _internal_cuda_compute_capability(); +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::unsafe_arena_release_cuda_compute_capability() { + // @@protoc_insertion_point(field_unsafe_arena_release:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + if (_internal_has_cuda_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::CudaComputeCapabilityProto* temp = _impl_.compute_capability_.cuda_compute_capability_; + _impl_.compute_capability_.cuda_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void GpuDeviceInfoProto::unsafe_arena_set_allocated_cuda_compute_capability(::stream_executor::CudaComputeCapabilityProto* cuda_compute_capability) { + clear_compute_capability(); + if (cuda_compute_capability) { + set_has_cuda_compute_capability(); + _impl_.compute_capability_.cuda_compute_capability_ = cuda_compute_capability; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::_internal_mutable_cuda_compute_capability() { + if (!_internal_has_cuda_compute_capability()) { + clear_compute_capability(); + set_has_cuda_compute_capability(); + _impl_.compute_capability_.cuda_compute_capability_ = CreateMaybeMessage< ::stream_executor::CudaComputeCapabilityProto >(GetArenaForAllocation()); + } + return _impl_.compute_capability_.cuda_compute_capability_; +} +inline ::stream_executor::CudaComputeCapabilityProto* GpuDeviceInfoProto::mutable_cuda_compute_capability() { + ::stream_executor::CudaComputeCapabilityProto* _msg = _internal_mutable_cuda_compute_capability(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuDeviceInfoProto.cuda_compute_capability) + return _msg; +} + +// .stream_executor.RocmComputeCapabilityProto rocm_compute_capability = 17; +inline bool GpuDeviceInfoProto::_internal_has_rocm_compute_capability() const { + return compute_capability_case() == kRocmComputeCapability; +} +inline bool GpuDeviceInfoProto::has_rocm_compute_capability() const { + return _internal_has_rocm_compute_capability(); +} +inline void GpuDeviceInfoProto::set_has_rocm_compute_capability() { + _impl_._oneof_case_[0] = kRocmComputeCapability; +} +inline void GpuDeviceInfoProto::clear_rocm_compute_capability() { + if (_internal_has_rocm_compute_capability()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.compute_capability_.rocm_compute_capability_; + } + clear_has_compute_capability(); + } +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::release_rocm_compute_capability() { + // @@protoc_insertion_point(field_release:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + if (_internal_has_rocm_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::RocmComputeCapabilityProto* temp = _impl_.compute_capability_.rocm_compute_capability_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.compute_capability_.rocm_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::stream_executor::RocmComputeCapabilityProto& GpuDeviceInfoProto::_internal_rocm_compute_capability() const { + return _internal_has_rocm_compute_capability() + ? *_impl_.compute_capability_.rocm_compute_capability_ + : reinterpret_cast< ::stream_executor::RocmComputeCapabilityProto&>(::stream_executor::_RocmComputeCapabilityProto_default_instance_); +} +inline const ::stream_executor::RocmComputeCapabilityProto& GpuDeviceInfoProto::rocm_compute_capability() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + return _internal_rocm_compute_capability(); +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::unsafe_arena_release_rocm_compute_capability() { + // @@protoc_insertion_point(field_unsafe_arena_release:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + if (_internal_has_rocm_compute_capability()) { + clear_has_compute_capability(); + ::stream_executor::RocmComputeCapabilityProto* temp = _impl_.compute_capability_.rocm_compute_capability_; + _impl_.compute_capability_.rocm_compute_capability_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void GpuDeviceInfoProto::unsafe_arena_set_allocated_rocm_compute_capability(::stream_executor::RocmComputeCapabilityProto* rocm_compute_capability) { + clear_compute_capability(); + if (rocm_compute_capability) { + set_has_rocm_compute_capability(); + _impl_.compute_capability_.rocm_compute_capability_ = rocm_compute_capability; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::_internal_mutable_rocm_compute_capability() { + if (!_internal_has_rocm_compute_capability()) { + clear_compute_capability(); + set_has_rocm_compute_capability(); + _impl_.compute_capability_.rocm_compute_capability_ = CreateMaybeMessage< ::stream_executor::RocmComputeCapabilityProto >(GetArenaForAllocation()); + } + return _impl_.compute_capability_.rocm_compute_capability_; +} +inline ::stream_executor::RocmComputeCapabilityProto* GpuDeviceInfoProto::mutable_rocm_compute_capability() { + ::stream_executor::RocmComputeCapabilityProto* _msg = _internal_mutable_rocm_compute_capability(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuDeviceInfoProto.rocm_compute_capability) + return _msg; +} + +inline bool GpuDeviceInfoProto::has_compute_capability() const { + return compute_capability_case() != COMPUTE_CAPABILITY_NOT_SET; +} +inline void GpuDeviceInfoProto::clear_has_compute_capability() { + _impl_._oneof_case_[0] = COMPUTE_CAPABILITY_NOT_SET; +} +inline GpuDeviceInfoProto::ComputeCapabilityCase GpuDeviceInfoProto::compute_capability_case() const { + return GpuDeviceInfoProto::ComputeCapabilityCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// DnnVersionInfoProto + +// int32 major = 1; +inline void DnnVersionInfoProto::clear_major() { + _impl_.major_ = 0; +} +inline int32_t DnnVersionInfoProto::_internal_major() const { + return _impl_.major_; +} +inline int32_t DnnVersionInfoProto::major() const { + // @@protoc_insertion_point(field_get:stream_executor.DnnVersionInfoProto.major) + return _internal_major(); +} +inline void DnnVersionInfoProto::_internal_set_major(int32_t value) { + + _impl_.major_ = value; +} +inline void DnnVersionInfoProto::set_major(int32_t value) { + _internal_set_major(value); + // @@protoc_insertion_point(field_set:stream_executor.DnnVersionInfoProto.major) +} + +// int32 minor = 2; +inline void DnnVersionInfoProto::clear_minor() { + _impl_.minor_ = 0; +} +inline int32_t DnnVersionInfoProto::_internal_minor() const { + return _impl_.minor_; +} +inline int32_t DnnVersionInfoProto::minor() const { + // @@protoc_insertion_point(field_get:stream_executor.DnnVersionInfoProto.minor) + return _internal_minor(); +} +inline void DnnVersionInfoProto::_internal_set_minor(int32_t value) { + + _impl_.minor_ = value; +} +inline void DnnVersionInfoProto::set_minor(int32_t value) { + _internal_set_minor(value); + // @@protoc_insertion_point(field_set:stream_executor.DnnVersionInfoProto.minor) +} + +// int32 patch = 3; +inline void DnnVersionInfoProto::clear_patch() { + _impl_.patch_ = 0; +} +inline int32_t DnnVersionInfoProto::_internal_patch() const { + return _impl_.patch_; +} +inline int32_t DnnVersionInfoProto::patch() const { + // @@protoc_insertion_point(field_get:stream_executor.DnnVersionInfoProto.patch) + return _internal_patch(); +} +inline void DnnVersionInfoProto::_internal_set_patch(int32_t value) { + + _impl_.patch_ = value; +} +inline void DnnVersionInfoProto::set_patch(int32_t value) { + _internal_set_patch(value); + // @@protoc_insertion_point(field_set:stream_executor.DnnVersionInfoProto.patch) +} + +// ------------------------------------------------------------------- + +// GpuTargetConfigProto + +// .stream_executor.GpuDeviceInfoProto gpu_device_info = 1; +inline bool GpuTargetConfigProto::_internal_has_gpu_device_info() const { + return this != internal_default_instance() && _impl_.gpu_device_info_ != nullptr; +} +inline bool GpuTargetConfigProto::has_gpu_device_info() const { + return _internal_has_gpu_device_info(); +} +inline void GpuTargetConfigProto::clear_gpu_device_info() { + if (GetArenaForAllocation() == nullptr && _impl_.gpu_device_info_ != nullptr) { + delete _impl_.gpu_device_info_; + } + _impl_.gpu_device_info_ = nullptr; +} +inline const ::stream_executor::GpuDeviceInfoProto& GpuTargetConfigProto::_internal_gpu_device_info() const { + const ::stream_executor::GpuDeviceInfoProto* p = _impl_.gpu_device_info_; + return p != nullptr ? *p : reinterpret_cast( + ::stream_executor::_GpuDeviceInfoProto_default_instance_); +} +inline const ::stream_executor::GpuDeviceInfoProto& GpuTargetConfigProto::gpu_device_info() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.gpu_device_info) + return _internal_gpu_device_info(); +} +inline void GpuTargetConfigProto::unsafe_arena_set_allocated_gpu_device_info( + ::stream_executor::GpuDeviceInfoProto* gpu_device_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.gpu_device_info_); + } + _impl_.gpu_device_info_ = gpu_device_info; + if (gpu_device_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuTargetConfigProto.gpu_device_info) +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::release_gpu_device_info() { + + ::stream_executor::GpuDeviceInfoProto* temp = _impl_.gpu_device_info_; + _impl_.gpu_device_info_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::unsafe_arena_release_gpu_device_info() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.gpu_device_info) + + ::stream_executor::GpuDeviceInfoProto* temp = _impl_.gpu_device_info_; + _impl_.gpu_device_info_ = nullptr; + return temp; +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::_internal_mutable_gpu_device_info() { + + if (_impl_.gpu_device_info_ == nullptr) { + auto* p = CreateMaybeMessage<::stream_executor::GpuDeviceInfoProto>(GetArenaForAllocation()); + _impl_.gpu_device_info_ = p; + } + return _impl_.gpu_device_info_; +} +inline ::stream_executor::GpuDeviceInfoProto* GpuTargetConfigProto::mutable_gpu_device_info() { + ::stream_executor::GpuDeviceInfoProto* _msg = _internal_mutable_gpu_device_info(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.gpu_device_info) + return _msg; +} +inline void GpuTargetConfigProto::set_allocated_gpu_device_info(::stream_executor::GpuDeviceInfoProto* gpu_device_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.gpu_device_info_; + } + if (gpu_device_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(gpu_device_info); + if (message_arena != submessage_arena) { + gpu_device_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, gpu_device_info, submessage_arena); + } + + } else { + + } + _impl_.gpu_device_info_ = gpu_device_info; + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.gpu_device_info) +} + +// string platform_name = 4; +inline void GpuTargetConfigProto::clear_platform_name() { + _impl_.platform_name_.ClearToEmpty(); +} +inline const std::string& GpuTargetConfigProto::platform_name() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.platform_name) + return _internal_platform_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GpuTargetConfigProto::set_platform_name(ArgT0&& arg0, ArgT... args) { + + _impl_.platform_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:stream_executor.GpuTargetConfigProto.platform_name) +} +inline std::string* GpuTargetConfigProto::mutable_platform_name() { + std::string* _s = _internal_mutable_platform_name(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.platform_name) + return _s; +} +inline const std::string& GpuTargetConfigProto::_internal_platform_name() const { + return _impl_.platform_name_.Get(); +} +inline void GpuTargetConfigProto::_internal_set_platform_name(const std::string& value) { + + _impl_.platform_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::_internal_mutable_platform_name() { + + return _impl_.platform_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::release_platform_name() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.platform_name) + return _impl_.platform_name_.Release(); +} +inline void GpuTargetConfigProto::set_allocated_platform_name(std::string* platform_name) { + if (platform_name != nullptr) { + + } else { + + } + _impl_.platform_name_.SetAllocated(platform_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.platform_name_.IsDefault()) { + _impl_.platform_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.platform_name) +} + +// .stream_executor.DnnVersionInfoProto dnn_version_info = 5; +inline bool GpuTargetConfigProto::_internal_has_dnn_version_info() const { + return this != internal_default_instance() && _impl_.dnn_version_info_ != nullptr; +} +inline bool GpuTargetConfigProto::has_dnn_version_info() const { + return _internal_has_dnn_version_info(); +} +inline void GpuTargetConfigProto::clear_dnn_version_info() { + if (GetArenaForAllocation() == nullptr && _impl_.dnn_version_info_ != nullptr) { + delete _impl_.dnn_version_info_; + } + _impl_.dnn_version_info_ = nullptr; +} +inline const ::stream_executor::DnnVersionInfoProto& GpuTargetConfigProto::_internal_dnn_version_info() const { + const ::stream_executor::DnnVersionInfoProto* p = _impl_.dnn_version_info_; + return p != nullptr ? *p : reinterpret_cast( + ::stream_executor::_DnnVersionInfoProto_default_instance_); +} +inline const ::stream_executor::DnnVersionInfoProto& GpuTargetConfigProto::dnn_version_info() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.dnn_version_info) + return _internal_dnn_version_info(); +} +inline void GpuTargetConfigProto::unsafe_arena_set_allocated_dnn_version_info( + ::stream_executor::DnnVersionInfoProto* dnn_version_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.dnn_version_info_); + } + _impl_.dnn_version_info_ = dnn_version_info; + if (dnn_version_info) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuTargetConfigProto.dnn_version_info) +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::release_dnn_version_info() { + + ::stream_executor::DnnVersionInfoProto* temp = _impl_.dnn_version_info_; + _impl_.dnn_version_info_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::unsafe_arena_release_dnn_version_info() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.dnn_version_info) + + ::stream_executor::DnnVersionInfoProto* temp = _impl_.dnn_version_info_; + _impl_.dnn_version_info_ = nullptr; + return temp; +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::_internal_mutable_dnn_version_info() { + + if (_impl_.dnn_version_info_ == nullptr) { + auto* p = CreateMaybeMessage<::stream_executor::DnnVersionInfoProto>(GetArenaForAllocation()); + _impl_.dnn_version_info_ = p; + } + return _impl_.dnn_version_info_; +} +inline ::stream_executor::DnnVersionInfoProto* GpuTargetConfigProto::mutable_dnn_version_info() { + ::stream_executor::DnnVersionInfoProto* _msg = _internal_mutable_dnn_version_info(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.dnn_version_info) + return _msg; +} +inline void GpuTargetConfigProto::set_allocated_dnn_version_info(::stream_executor::DnnVersionInfoProto* dnn_version_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.dnn_version_info_; + } + if (dnn_version_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(dnn_version_info); + if (message_arena != submessage_arena) { + dnn_version_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, dnn_version_info, submessage_arena); + } + + } else { + + } + _impl_.dnn_version_info_ = dnn_version_info; + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.dnn_version_info) +} + +// .xla.AutotuneResults autotune_results = 6; +inline bool GpuTargetConfigProto::_internal_has_autotune_results() const { + return this != internal_default_instance() && _impl_.autotune_results_ != nullptr; +} +inline bool GpuTargetConfigProto::has_autotune_results() const { + return _internal_has_autotune_results(); +} +inline const ::xla::AutotuneResults& GpuTargetConfigProto::_internal_autotune_results() const { + const ::xla::AutotuneResults* p = _impl_.autotune_results_; + return p != nullptr ? *p : reinterpret_cast( + ::xla::_AutotuneResults_default_instance_); +} +inline const ::xla::AutotuneResults& GpuTargetConfigProto::autotune_results() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.autotune_results) + return _internal_autotune_results(); +} +inline void GpuTargetConfigProto::unsafe_arena_set_allocated_autotune_results( + ::xla::AutotuneResults* autotune_results) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.autotune_results_); + } + _impl_.autotune_results_ = autotune_results; + if (autotune_results) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:stream_executor.GpuTargetConfigProto.autotune_results) +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::release_autotune_results() { + + ::xla::AutotuneResults* temp = _impl_.autotune_results_; + _impl_.autotune_results_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::unsafe_arena_release_autotune_results() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.autotune_results) + + ::xla::AutotuneResults* temp = _impl_.autotune_results_; + _impl_.autotune_results_ = nullptr; + return temp; +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::_internal_mutable_autotune_results() { + + if (_impl_.autotune_results_ == nullptr) { + auto* p = CreateMaybeMessage<::xla::AutotuneResults>(GetArenaForAllocation()); + _impl_.autotune_results_ = p; + } + return _impl_.autotune_results_; +} +inline ::xla::AutotuneResults* GpuTargetConfigProto::mutable_autotune_results() { + ::xla::AutotuneResults* _msg = _internal_mutable_autotune_results(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.autotune_results) + return _msg; +} +inline void GpuTargetConfigProto::set_allocated_autotune_results(::xla::AutotuneResults* autotune_results) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.autotune_results_); + } + if (autotune_results) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(autotune_results)); + if (message_arena != submessage_arena) { + autotune_results = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, autotune_results, submessage_arena); + } + + } else { + + } + _impl_.autotune_results_ = autotune_results; + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.autotune_results) +} + +// string device_description_str = 7; +inline void GpuTargetConfigProto::clear_device_description_str() { + _impl_.device_description_str_.ClearToEmpty(); +} +inline const std::string& GpuTargetConfigProto::device_description_str() const { + // @@protoc_insertion_point(field_get:stream_executor.GpuTargetConfigProto.device_description_str) + return _internal_device_description_str(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void GpuTargetConfigProto::set_device_description_str(ArgT0&& arg0, ArgT... args) { + + _impl_.device_description_str_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:stream_executor.GpuTargetConfigProto.device_description_str) +} +inline std::string* GpuTargetConfigProto::mutable_device_description_str() { + std::string* _s = _internal_mutable_device_description_str(); + // @@protoc_insertion_point(field_mutable:stream_executor.GpuTargetConfigProto.device_description_str) + return _s; +} +inline const std::string& GpuTargetConfigProto::_internal_device_description_str() const { + return _impl_.device_description_str_.Get(); +} +inline void GpuTargetConfigProto::_internal_set_device_description_str(const std::string& value) { + + _impl_.device_description_str_.Set(value, GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::_internal_mutable_device_description_str() { + + return _impl_.device_description_str_.Mutable(GetArenaForAllocation()); +} +inline std::string* GpuTargetConfigProto::release_device_description_str() { + // @@protoc_insertion_point(field_release:stream_executor.GpuTargetConfigProto.device_description_str) + return _impl_.device_description_str_.Release(); +} +inline void GpuTargetConfigProto::set_allocated_device_description_str(std::string* device_description_str) { + if (device_description_str != nullptr) { + + } else { + + } + _impl_.device_description_str_.SetAllocated(device_description_str, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_description_str_.IsDefault()) { + _impl_.device_description_str_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:stream_executor.GpuTargetConfigProto.device_description_str) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace stream_executor + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fstream_5fexecutor_2fdevice_5fdescription_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_host_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_host_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..b724f2e1d2292dc716a2b14502cde3a1f1c2a306 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_host_allocator.h @@ -0,0 +1,86 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_HOST_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_HOST_ALLOCATOR_H_ + +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/platform/macros.h" +#include "tsl/profiler/lib/traceme.h" + +namespace stream_executor { +// Allocator for pinned CPU RAM that is made known to a StreamExecutor-based +// device for the purpose of efficient DMA with the device. +class DeviceHostAllocator : public tsl::SubAllocator { + public: + // Note: stream_exec cannot be null. + explicit DeviceHostAllocator(StreamExecutor* stream_exec, int numa_node, + const std::vector& alloc_visitors, + const std::vector& free_visitors) + : SubAllocator(alloc_visitors, free_visitors), + stream_exec_(stream_exec), + numa_node_(numa_node) { + CHECK(stream_exec_ != nullptr); + } + + ~DeviceHostAllocator() override = default; + + void* Alloc(size_t alignment, size_t num_bytes, + size_t* bytes_received) override { + tsl::profiler::TraceMe traceme("DeviceHostAllocator::Alloc"); + + void* ptr = nullptr; + *bytes_received = num_bytes; + if (num_bytes > 0) { + ptr = stream_exec_->HostMemoryAllocate(num_bytes); + if (ptr == nullptr) { + LOG(WARNING) << "could not allocate pinned host memory of size: " + << num_bytes; + return ptr; + } + VisitAlloc(ptr, numa_node_, num_bytes); + } + return ptr; + } + + void Free(void* ptr, size_t num_bytes) override { + tsl::profiler::TraceMe traceme("DeviceHostAllocator::Free"); + + if (ptr != nullptr) { + VisitFree(ptr, numa_node_, num_bytes); + stream_exec_->HostMemoryDeallocate(ptr); + } + } + + bool SupportsCoalescing() const override { return false; } + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kHostPinned; + } + + private: + StreamExecutor* stream_exec_; // not owned, non-null + const int numa_node_; + + DeviceHostAllocator(const DeviceHostAllocator&) = delete; + void operator=(const DeviceHostAllocator&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_HOST_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_id_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_id_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..76aada1dcfec0af1ad8cd0c1cd976fe611c69abd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_id_utils.h @@ -0,0 +1,47 @@ + +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_ID_UTILS_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_ID_UTILS_H_ + +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/device_id.h" +#include "tsl/framework/device_id_manager.h" + +namespace stream_executor { + +// Utility methods for getting the associated executor given a TfDeviceId +// or PlatformDeviceId. +class DeviceIdUtil { + public: + static tsl::StatusOr ExecutorForPlatformDeviceId( + Platform* device_manager, tsl::PlatformDeviceId platform_device_id) { + return device_manager->ExecutorForDevice(platform_device_id.value()); + } + static tsl::StatusOr ExecutorForTfDeviceId( + const tsl::DeviceType& type, Platform* device_manager, + tsl::TfDeviceId tf_device_id) { + tsl::PlatformDeviceId platform_device_id; + TF_RETURN_IF_ERROR(tsl::DeviceIdManager::TfToPlatformDeviceId( + type, tf_device_id, &platform_device_id)); + return ExecutorForPlatformDeviceId(device_manager, platform_device_id); + } +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_ID_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_mem_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_mem_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..fe02b44f5fd5bdc931afa282fc5f413f09e55400 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_mem_allocator.h @@ -0,0 +1,96 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_MEM_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_MEM_ALLOCATOR_H_ + +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" +#include "tsl/profiler/lib/traceme.h" + +namespace stream_executor { + +// Suballocator for StreamExecutor-based device memory. +class DeviceMemAllocator : public tsl::SubAllocator { + public: + // 'platform_device_id' refers to the ID of the device within + // the process and must reference a valid ID in the process. + // Note: stream_exec cannot be null. + explicit DeviceMemAllocator(StreamExecutor* stream_exec, + tsl::PlatformDeviceId device_id, + bool use_unified_memory, + const std::vector& alloc_visitors, + const std::vector& free_visitors) + : SubAllocator(alloc_visitors, free_visitors), + stream_exec_(stream_exec), + device_id_(device_id), + use_unified_memory_(use_unified_memory) { + CHECK(stream_exec_ != nullptr); + } + + ~DeviceMemAllocator() override = default; + + void* Alloc(size_t alignment, size_t num_bytes, + size_t* bytes_received) override { + tsl::profiler::TraceMe traceme("DeviceMemAllocator::Alloc"); + + void* ptr = nullptr; + *bytes_received = num_bytes; + if (num_bytes > 0) { + if (use_unified_memory_) { + ptr = stream_exec_->UnifiedMemoryAllocate(num_bytes); + } else { + ptr = stream_exec_->AllocateArray(num_bytes).opaque(); + } + VisitAlloc(ptr, device_id_.value(), num_bytes); + } + return ptr; + } + + void Free(void* ptr, size_t num_bytes) override { + tsl::profiler::TraceMe traceme("DeviceMemAllocator::Free"); + + if (ptr != nullptr) { + VisitFree(ptr, device_id_.value(), num_bytes); + if (use_unified_memory_) { + stream_exec_->UnifiedMemoryDeallocate(ptr); + } else { + DeviceMemoryBase device_ptr(ptr); + stream_exec_->Deallocate(&device_ptr); + } + } + } + + bool SupportsCoalescing() const override { return false; } + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kDevice; + } + + private: + StreamExecutor* stream_exec_; // not owned, non-null + const tsl::PlatformDeviceId device_id_; + const bool use_unified_memory_ = false; + + DeviceMemAllocator(const DeviceMemAllocator&) = delete; + void operator=(const DeviceMemAllocator&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_MEM_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..f69fe8148c67a014da76b6c7a3daeb87ec63065e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory.h @@ -0,0 +1,202 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Suite of types that represent device memory allocations. These are +// allocated by the StreamExecutor interface, which produces values appropriate +// for the underlying platform (whether it be CUDA or OpenCL). +// +// The untyped base class (like a device void*) is DeviceMemoryBase, which can +// be specialized for a given allocation type (like a device T*) using +// DeviceMemory. + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_MEMORY_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_MEMORY_H_ + +#include + +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class DeviceMemoryAllocator; +class StreamExecutor; + +// void*-analogous device memory allocation. For the typed variation, see +// DeviceMemory. +// +// This is effectively a two-tuple of a pointer and size; however, note that the +// pointer may not be to the virtual address itself -- in OpenCL the pointer is +// to a cl_mem handle that describes the device allocation. Therefore, +// DeviceMemoryBase::opaque does not necessarily produce a pointer that can be +// referenced directly, so use it with caution. +// +// Thread-compatible. +class DeviceMemoryBase { + public: + // Default constructor instantiates a null-pointed, zero-sized device memory + // region. An opaque pointer may be provided -- see header for details on the + // opacity of that pointer. + explicit DeviceMemoryBase(void *opaque = nullptr, uint64_t size = 0) + : opaque_(opaque), size_(size) {} + + // Returns whether the backing memory is the null pointer. + // A `== nullptr` convenience method is also provided. + bool is_null() const { return opaque_ == nullptr; } + bool operator==(std::nullptr_t other) const { return is_null(); } + bool operator!=(std::nullptr_t other) const { return !is_null(); } + + // Provides a partial order between device memory values. + // + // This operator is provided so that this object can be used as a key in an + // ordered map. + bool operator<(const DeviceMemoryBase &other) const { + return opaque() < other.opaque(); + } + + // Returns the size, in bytes, for the backing memory. + uint64_t size() const { return size_; } + + // Warning: note that the pointer returned is not necessarily directly to + // device virtual address space, but is platform-dependent. + void *opaque() { return opaque_; } + const void *opaque() const { return opaque_; } + + // Returns the payload of this memory region. + uint64_t payload() const { return payload_; } + + // Sets payload to given value. + void SetPayload(uint64_t payload) { payload_ = payload; } + + // Returns whether the two DeviceMemoryBase segments are identical (both in + // their opaque pointer and size). + bool IsSameAs(const DeviceMemoryBase &other) const { + return opaque() == other.opaque() && size() == other.size(); + } + + protected: + friend class StreamExecutor; + + // Resets the internal values of the opaque pointer and number of bytes in the + // memory region, just as in the constructor. + void Reset(void *opaque, uint64_t bytes) { + opaque_ = opaque; + size_ = bytes; + } + + private: + void *opaque_; // Platform-dependent value representing allocated memory. + uint64_t size_; // Size in bytes of this allocation. + uint64_t payload_ = 0; // Payload data associated with this allocation. +}; + +// Typed wrapper around "void *"-like DeviceMemoryBase. +// +// For example, DeviceMemory is a simple wrapper around DeviceMemoryBase +// that represents one or more integers in Device memory. +// +// Thread-compatible. +template +class DeviceMemory final : public DeviceMemoryBase { + public: + // Default constructor instantiates a null-pointed, zero-sized memory region. + DeviceMemory() : DeviceMemoryBase(nullptr, 0) {} + explicit DeviceMemory(std::nullptr_t) : DeviceMemory() {} + + // Typed device memory regions may be constructed from untyped device memory + // regions, this effectively amounts to a cast from a void*. + explicit DeviceMemory(const DeviceMemoryBase &other) + : DeviceMemoryBase(const_cast(other).opaque(), + other.size()) { + SetPayload(other.payload()); + } + + // Returns the number of elements of type ElemT that constitute this + // allocation. + uint64_t ElementCount() const { return size() / sizeof(ElemT); } + + // Returns whether this is a single-element allocation. + bool IsScalar() const { return ElementCount() == 1; } + + // Create a typed area of DeviceMemory with a given opaque pointer and the + // quantity of bytes in the allocation. This function is broken out to + // distinguish bytes from an element count. + static DeviceMemory MakeFromByteSize(void *opaque, uint64_t bytes) { + return DeviceMemory(opaque, bytes); + } + + // Resets the DeviceMemory data, in MakeFromByteSize fashion. + // This simply clobbers the prior values. + void ResetFromByteSize(void *opaque, uint64_t bytes) { + // TODO(leary) when NVCC is eliminated we can add this check (and the + // logging include it requires). + // CHECK_EQ(0, bytes % sizeof(ElemT)); + DeviceMemoryBase::Reset(opaque, bytes); + } + + // ------------------------------------------------------------ + + protected: + // This constructor is solely used from derived classes; it is made protected + // because it accepts a byte-size instead of an element count, which could + // potentially be misused given the ElementCount() nature of this interface. + // + // In order to specify the desire to use byte size instead of element count + // explicitly, use MakeFromByteSize. + DeviceMemory(void *opaque, uint64_t size) : DeviceMemoryBase(opaque, size) {} +}; + +// A class to encapsulate the type and size of a dynamic shared memory +// buffer. Because the buffer exists solely on the device and is not copyable +// to the host, memory objects of this type do not maintain buffer pointers +// on the host. +template +class SharedDeviceMemory final : public DeviceMemoryBase { + public: + explicit SharedDeviceMemory(uint64_t elem_count) + : DeviceMemoryBase(nullptr, elem_count * kElemSize) {} + + static constexpr size_t kElemSize = sizeof(ElemT); + + // Returns the number of elements of type ElemT that constitute this + // allocation. + uint64_t ElementCount() const { return size() / kElemSize; } + + // Returns whether this is a single-element allocation. + bool IsScalar() const { return ElementCount() == 1; } +}; + +// Host-side representation of packed-and-aligned vector datatypes on the device +// side. Since these can appear in device kernel signatures, we support +// launching them with these datatypes in launch signatures. + +struct Float2 { + float x, y; +}; + +struct Float4 { + Float2 xz, yw; +}; + +struct Double2 { + double x, y; +}; + +static_assert(sizeof(Float2) == 2 * sizeof(float), "Float2 must be packed"); +static_assert(sizeof(Float4) == 4 * sizeof(float), "Float4 must be packed"); +static_assert(sizeof(Double2) == 2 * sizeof(double), "Double2 must be packed"); + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_MEMORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..500428b0ed24b5f70b5679535a088ca11820d063 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_memory_allocator.h @@ -0,0 +1,289 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_MEMORY_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_MEMORY_ALLOCATOR_H_ + +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/platform.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; +class DeviceMemoryAllocator; + +// Owning pointer for memory on a device. +// +// ScopedDeviceMemory is an owning pointer like std::unique_ptr, but it can +// point to memory that resides on a "device" (e.g. a GPU). When a +// ScopedDeviceMemory goes out of scope, it frees the memory it owns. +// +// We say that an instance of ScopedDeviceMemory is "active" if it currently +// owns a (possibly empty) slice of memory on the device. Moving, +// Release()'ing, Free()'ing, and other actions can deactivate an active object. +template +class ScopedDeviceMemory { + public: + // Default construction initializes the internal state to nullptr. This + // mirrors the std::unique_ptr<> functionality, where default construction + // produces a nullptr unique_ptr, which can be assigned later. + ScopedDeviceMemory() : device_ordinal_(-1), allocator_(nullptr) {} + + // Construct a ScopedDeviceMemory from a custom allocator. + // + // Parameters: + // mem: Already-allocated device memory value for this scoped mechanism to + // deallocate. This memory must have been allocated by parent. + // device_ordinal: Device on which the memory was allocated. + // allocator: Allocator used to deallocate memory when this instance goes + // out of scope. + ScopedDeviceMemory(DeviceMemoryBase mem, int device_ordinal, + DeviceMemoryAllocator *allocator) + : wrapped_(mem), device_ordinal_(device_ordinal), allocator_(allocator) { + DCHECK_GE(device_ordinal_, 0); + } + + // A helper constructor to generate a scoped device memory given an already + // allocated memory and a stream executor. + // + // Precondition: memory was allocated by the stream executor `parent`. + ScopedDeviceMemory(StreamExecutor *parent, DeviceMemoryBase value); + + // Constructor overload that places a literal array into device memory. + // + // Relies on the allocation function exposed by the stream executor `parent`, + // which will be also used for deallocating the memory + ScopedDeviceMemory(StreamExecutor *parent, + std::initializer_list values); + + // Moves ownership of the memory from other to the constructed + // object. + // + // Postcondition: other == nullptr. + ScopedDeviceMemory(ScopedDeviceMemory &&other) + : wrapped_(other.Release()), + device_ordinal_(other.device_ordinal_), + allocator_(other.allocator_) {} + + // Releases the memory that was provided in the constructor, through the + // "parent" StreamExecutor. + ~ScopedDeviceMemory() { TF_CHECK_OK(Free()); } + + // Moves ownership of the memory from other to this object. + // + // Postcondition: other == nullptr. + ScopedDeviceMemory &operator=(ScopedDeviceMemory &&other) { + TF_CHECK_OK(Free()); + wrapped_ = other.Release(); + allocator_ = other.allocator_; + device_ordinal_ = other.device_ordinal_; + return *this; + } + + // Returns the memory that backs this scoped allocation converted to + // DeviceMemory apparent type. This is useful for cases where the + // DeviceMemory must be passed by const-ref, as the ScopedDeviceMemory doesn't + // allow copying, for scoped-object-lifetime reasons. + const DeviceMemory &cref() const { return wrapped_; } + + // Returns a pointer to the DeviceMemory apparent type for use in mutable + // operations. The value returned should not be used outside the scope of this + // ScopedDeviceMemory object's lifetime. + DeviceMemory *ptr() { return &wrapped_; } + const DeviceMemory *ptr() const { return &wrapped_; } + + // Smart-pointer-like operators for the wrapped DeviceMemory. + // This reference must not be used outside the lifetime of this + // ScopedDeviceMemory. + const DeviceMemory &operator*() const { return cref(); } + DeviceMemory *operator->() { return ptr(); } + const DeviceMemory *operator->() const { return ptr(); } + + bool is_null() const { return wrapped_.is_null(); } + bool operator==(std::nullptr_t other) const { return is_null(); } + bool operator!=(std::nullptr_t other) const { return !is_null(); } + + // Analogous to std::unique_ptr::release, releases ownership of the held + // memory and transfers it to the caller. + // + // Postcondition: *this == nullptr + DeviceMemory Release() { + DeviceMemory tmp = wrapped_; + wrapped_ = DeviceMemory{}; + return tmp; + } + + // The returned allocator is nonnull iff this object is active. + DeviceMemoryAllocator *allocator() const { return allocator_; } + + int device_ordinal() const { return device_ordinal_; } + + // Frees the existing memory, resets the wrapped memory to null. + tsl::Status Free(); + + private: + DeviceMemory wrapped_; // Value we wrap with scoped-release. + int device_ordinal_; // Negative one for inactive object. + DeviceMemoryAllocator *allocator_; // Null if this object is inactive. + + ScopedDeviceMemory(const ScopedDeviceMemory &) = delete; + void operator=(const ScopedDeviceMemory &) = delete; +}; + +// Type alias for compatibility with the previous managed memory implementation. +using OwningDeviceMemory = ScopedDeviceMemory; + +// Memory allocator interface for the device. +// +// Intended usage is through Allocate() functions which return an owning smart +// pointer. +class DeviceMemoryAllocator { + public: + // Parameter platform indicates which platform the allocator allocates memory + // on. Must be non-null. + explicit DeviceMemoryAllocator(const Platform *platform) + : platform_(platform) {} + virtual ~DeviceMemoryAllocator() {} + + // Allocates memory on the device. + // + // If size > 0 and the returned StatusOr is OK, the wrapped OwningDeviceMemory + // must not be null. If size == 0, must return a null OwningDeviceMemory. + // + // 'retry_on_failure': If false, and the first attempt to allocate the memory + // fails, the allocation should return immediately without retrying. An + // example use case is optional scratch spaces where a failure has only + // performance impact. + virtual tsl::StatusOr Allocate(int device_ordinal, + uint64_t size, + bool retry_on_failure, + int64_t memory_space) = 0; + + // Two-arg version of Allocate(), which sets retry-on-failure to true and + // memory_space to default (0). + // + // (We don't simply use a default argument on the virtual Allocate function + // because default args on virtual functions are disallowed by the Google + // style guide.) + tsl::StatusOr Allocate(int device_ordinal, + uint64_t size) { + return Allocate(device_ordinal, size, /*retry_on_failure=*/true, + /*memory_space=*/0); + } + + // Three-arg version of Allocate(), which sets memory_space to default (0). + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure) { + return Allocate(device_ordinal, size, retry_on_failure, + /*memory_space=*/0); + } + + // Typed version of the allocation, returning typed memory. + template + tsl::StatusOr> Allocate( + int device_ordinal, uint64_t size, bool retry_on_failure = true, + int64_t memory_space = 0) { + return Allocate(device_ordinal, size, retry_on_failure, memory_space); + } + + // Must be a nop for null pointers. Should not be used. + // + // TODO(cheshire): Add deprecation notice. + virtual tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) = 0; + + // Return the platform that the allocator allocates memory on. + const Platform *platform() const { return platform_; } + + // Can we call Deallocate() as soon as a computation has been scheduled on + // a stream, or do we have to wait for the computation to complete first? + virtual bool AllowsAsynchronousDeallocation() const { return false; } + + // Returns a stream pointer on which it is always safe to access memory + // allocated by this allocator. It is not necessary to use the returned stream + // though, as clients may have additional information letting them safely use + // a different stream. + virtual tsl::StatusOr GetStream(int device_ordinal) = 0; + + protected: + const Platform *platform_; +}; + +// Default memory allocator for a platform which uses +// StreamExecutor::Allocate/Deallocate. +class StreamExecutorMemoryAllocator : public DeviceMemoryAllocator { + public: + // Create an allocator supporting a single device, corresponding to the passed + // executor. + explicit StreamExecutorMemoryAllocator(StreamExecutor *executor); + + // Create an allocator supporting multiple stream executors. + // + // Precondition: all stream_executors have different device ordinals. + StreamExecutorMemoryAllocator( + const Platform *platform, + absl::Span stream_executors); + + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure, + int64_t memory_space) override; + + // Pull in two-arg overload that sets retry_on_failure to true. + using DeviceMemoryAllocator::Allocate; + + tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) override; + + bool AllowsAsynchronousDeallocation() const override; + + // Gets-or-creates a stream for a given `device_ordinal` from an appropriate + // stream executor. + tsl::StatusOr GetStream(int device_ordinal) override; + + // Gets the stream executor for given device ordinal. + tsl::StatusOr GetStreamExecutor(int device_ordinal) const; + + private: + // Available stream executors. Each stream executor has a different device + // ordinal. + std::vector stream_executors_; + + absl::Mutex mutex_; + + // Cache of streams for GetStream. + std::map streams_ ABSL_GUARDED_BY(mutex_); +}; + +template +tsl::Status ScopedDeviceMemory::Free() { + if (!wrapped_.is_null()) { + CHECK(allocator_ != nullptr) << "Owning pointer in inconsistent state"; + TF_RETURN_IF_ERROR(allocator_->Deallocate(device_ordinal_, wrapped_)); + } + wrapped_ = DeviceMemory{}; + return ::tsl::OkStatus(); +} + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_MEMORY_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_options.h new file mode 100644 index 0000000000000000000000000000000000000000..776fa4220813c4cf159b3b0482885edce0836677 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/device_options.h @@ -0,0 +1,104 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Contains device-level options that can be specified at a platform level. +// Example usage: +// auto device_options = DeviceOptions::Default(); + +#ifndef XLA_STREAM_EXECUTOR_DEVICE_OPTIONS_H_ +#define XLA_STREAM_EXECUTOR_DEVICE_OPTIONS_H_ + +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/str_join.h" + +namespace stream_executor { + +// Indicates a set of options for a device's usage, which generally must be +// provided at StreamExecutor device-initialization time. +// +// These are intended to be useful-but-not-mandatorily-supported options for +// using devices on the underlying platform. Presently, if the option requested +// is not available on the target platform, a warning will be emitted. +struct DeviceOptions { + public: + // When it is observed that more memory has to be allocated for thread stacks, + // this flag prevents it from ever being deallocated. Potentially saves + // thrashing the thread stack memory allocation, but at the potential cost of + // some memory space. + static constexpr unsigned kDoNotReclaimStackAllocation = 0x1; + + // The following options refer to synchronization options when + // using SynchronizeStream or SynchronizeContext. + + // Synchronize with spinlocks. + static constexpr unsigned kScheduleSpin = 0x02; + // Synchronize with spinlocks that also call CPU yield instructions. + static constexpr unsigned kScheduleYield = 0x04; + // Synchronize with a "synchronization primitive" (e.g. mutex). + static constexpr unsigned kScheduleBlockingSync = 0x08; + + static constexpr unsigned kMask = 0xf; // Mask of all available flags. + + // Constructs an or-d together set of device options. + explicit DeviceOptions(unsigned flags) : flags_(flags) { + CHECK((flags & kMask) == flags); + } + + // Factory for the default set of device options. + static DeviceOptions Default() { return DeviceOptions(0); } + + unsigned flags() const { return flags_; } + + bool operator==(const DeviceOptions& other) const { + return flags_ == other.flags_ && + non_portable_tags == other.non_portable_tags; + } + + bool operator!=(const DeviceOptions& other) const { + return !(*this == other); + } + + std::string ToString() const { + std::vector flags_on; + if (flags_ & kDoNotReclaimStackAllocation) { + flags_on.push_back("kDoNotReclaimStackAllocation"); + } + if (flags_ & kScheduleSpin) { + flags_on.push_back("kScheduleSpin"); + } + if (flags_ & kScheduleYield) { + flags_on.push_back("kScheduleYield"); + } + if (flags_ & kScheduleBlockingSync) { + flags_on.push_back("kScheduleBlockingSync"); + } + return flags_on.empty() ? "none" : absl::StrJoin(flags_on, "|"); + } + + // Platform-specific device options. Expressed as key-value pairs to avoid + // DeviceOptions subclass proliferation. + std::map non_portable_tags; + + private: + unsigned flags_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DEVICE_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/dnn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/dnn.h new file mode 100644 index 0000000000000000000000000000000000000000..3561a1ffd4f13b21a74a6beabe80f8acf5cf0500 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/dnn.h @@ -0,0 +1,2603 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Neural Net operation support for StreamExecutor instances. +// +// This is an abstract interface for a platform to optionally support common +// neural net operations; it accommodates implementations such as the cudnn +// library operations. + +#ifndef XLA_STREAM_EXECUTOR_DNN_H_ +#define XLA_STREAM_EXECUTOR_DNN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "google/protobuf/wrappers.pb.h" +#include "absl/types/optional.h" +#include "absl/types/span.h" +#include "xla/stream_executor/data_type.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_description.pb.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/logging.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" +#include "tsl/protobuf/dnn.pb.h" + +namespace Eigen { +struct half; +} // namespace Eigen + +namespace stream_executor { + +class HostBuffer; +class Stream; +class ScratchAllocator; + +namespace dnn { + +// Specifies an index to use when accessing specific spatial dimensions. +enum class DimIndex : int { + X = 0, + Y = 1, + Z = 2, +}; + +// Return a reordered dims. +std::vector ReorderDims(const std::vector& input, + const DataLayout& from, const DataLayout& to); + +// Helper functions to make methods more readable. +inline int64_t GetDim(absl::Span data, DimIndex dim) { + return data.rbegin()[static_cast(dim)]; +} + +inline void SetDim(absl::Span data, DimIndex dim, int64_t value) { + data.rbegin()[static_cast(dim)] = value; +} + +inline void SetDim(std::vector* data, DimIndex dim, int64_t value) { + return SetDim(absl::MakeSpan(*data), dim, value); +} + +// int64_t is not the same type as tensorflow::protobuf_int64 in open-source. +// This wrapper function gives an int64_t array slice view of a repeated int64 +// protobuf field. +// +// T should be a protobuf RepeatedField. +template +inline absl::Span AsInt64Slice(const T& repeated_field) { + using data_ty = + typename std::remove_reference::type; + static_assert(std::is_integral::value && + std::is_signed::value && sizeof(data_ty) == 8, + "repeated_field.data() must return a pointer to a signed " + "64-bit integer type."); + return absl::Span( + reinterpret_cast(repeated_field.data()), + repeated_field.size()); +} +template +inline absl::Span AsInt64Slice(T* repeated_field) { + using data_ty = + typename std::remove_referencedata())>::type; + static_assert(std::is_integral::value && + std::is_signed::value && sizeof(data_ty) == 8, + "repeated_field->data() must return a pointer to a signed " + "64-bit integer type."); + return absl::Span( + reinterpret_cast(repeated_field->mutable_data()), + repeated_field->size()); +} + +// Returns a string representation of the given data layout. +std::string DataLayoutString(DataLayout layout); + +// Specifies a quantization for activations in a given BatchDescriptor. +enum class QuantizedActivationMode { + k8Bit = 1, + k16Bit = 2, + k32Bit = 4, +}; + +// Specifies the types of a RNN model. +enum class RnnMode { + kRnnRelu = 0, + kRnnTanh = 1, + kRnnLstm = 2, + kRnnGru = 3, +}; + +// Specifies the input model and whether there is a linear transformation +// between the input state and the first layer hidden state. +enum class RnnInputMode { + kRnnLinearSkip = 0, + kRnnSkipInput = 1, +}; + +// Specifies the number of directions used in a RNN model. When bidirection +// is used, the input states and output sequence contain data for both +// directions. +enum class RnnDirectionMode { + kRnnUnidirectional = 0, + kRnnBidirectional = 1, +}; + +// Relevant to DepthToSpace and SpaceToDepth. This is the write layout when +// performing depth to space and the read layout when performing space to depth. +// It's specified with most-major dimension first and most-minor dimension last. +// In DepthToSpace, the D*M^2 values are read in and then, for DepthHeightWidth, +// written out to the output patch, by varying first width, then height, then +// depth. In C array format, it looks like [depth][height][width]. See +// DepthToSpace comment for more information. +enum class DepthToSpaceLayout { DepthHeightWidth }; + +class TensorDescriptor { + public: + TensorDescriptor() = default; + tsl::StatusOr> GetPhysicalDimensionsMajorToMinor() const; + std::vector GetPhysicalStridesMajorToMinor() const; + std::vector GetLogicalStrides() const; + + static TensorDescriptor For(DataType type, + absl::Span dimensions, + absl::Span minor_to_major); + int ndims() const; + std::vector dimensions() const { return dimensions_; } + std::vector minor_to_major() const { return minor_to_major_; } + DataType type() const { return d_type_; } + std::string ToString() const; + + protected: + TensorDescriptor(DataType type, std::vector dimensions, + std::vector minor_to_major) + : d_type_(type), + dimensions_(dimensions), + minor_to_major_(minor_to_major) {} + + private: + DataType d_type_; + std::vector dimensions_; + std::vector minor_to_major_; +}; + +class MatmulTensorDescriptor { + public: + MatmulTensorDescriptor() = default; + tsl::StatusOr> GetNonContractingDims() const; + std::vector GetCudnnCompatibleDimensions( + bool is_lhs + /*if not lhs, then rhs*/) const; + std::vector GetCudnnCompatibleStrides( + bool is_lhs + /*if not lhs, then rhs*/) const; + tsl::StatusOr> MakeCudnnCompatible( + const std::vector&, bool is_lhs) const; + + static MatmulTensorDescriptor For(DataType type, + absl::Span dimensions, + absl::Span minor_to_major, + absl::Span batch_dims, + absl::Span contracting_dims); + std::vector dimensions() const { return tensor_.dimensions(); } + std::vector minor_to_major() const { + return tensor_.minor_to_major(); + } + DataType type() const { return tensor_.type(); } + + std::string ToString() const; + + protected: + MatmulTensorDescriptor(TensorDescriptor tensor, + std::vector batch_dims, + std::vector contracting_dims) + : tensor_(tensor), + batch_dimension_numbers_(batch_dims), + contracting_dim_(contracting_dims) {} + + private: + TensorDescriptor tensor_; + std::vector batch_dimension_numbers_; + std::vector contracting_dim_; +}; + +// Specifies the descriptor for a RNN model. +// +// An example use case: +// * The user first creates a model through createRnnDescriptor. +// * The user queries the size of the underlying opaque parameter buffer. +// * The user creates and initializes a parameter buffer of the proper size. +// * The user runs forward and backward operations using this RNN descriptor. +// * Once a while, user queries maintainable weights and bias regions from +// the underlying parameter buffer. They are more likely to be forward +// compatible and should used in saving and restoring a model. +// * The user releases the RNN descriptor when the model is no longer in use. +class RnnDescriptor { + public: + struct ParamsRegion { + int64_t offset; + int64_t size; + }; + typedef std::vector ParamsRegions; + virtual ~RnnDescriptor() = default; + virtual int64_t ParamsSizeInBytes() const { return -1; } + virtual ParamsRegions ParamsWeightRegions() const { return ParamsRegions(); } + virtual ParamsRegions ParamsBiasRegions() const { return ParamsRegions(); } +}; + +// Specifies the sequence in a RNN model. +// +// The user is responsible for releasing this descriptor when it is no longer +// in use. The destructor releases the underlying descriptors. +class RnnSequenceTensorDescriptor { + public: + virtual ~RnnSequenceTensorDescriptor() = default; +}; + +// Specifies either the input and hidden state in a RNN model. +// +// The user is responsible for releasing this descriptor when it is no longer +// in use. The destructor releases the underlying descriptors. +class RnnStateTensorDescriptor { + public: + virtual ~RnnStateTensorDescriptor() = default; +}; + +// Returns a string representation of the given quantization mode. +std::string QuantizedActivationModeString(QuantizedActivationMode mode); + +// Describes the dimensions that a layer consumes/produces. +// +// This is a matrix (height, width), its "depth" (feature_map_count), +// how many of these matrices are present (count), +// and the maximum and minimum values expected in the matrix (value_max, +// value_min). +// If input is quantized, all values greater +// than value_max will be clipped to value_max and all values less than +// value_min will be clipped to value_min. +// When quantized output is dequantized no value will be greater than +// value_max or less than value_min. +// +// Uses the named argument construction form: +// +// auto input_batch_dimensions = +// BatchDescriptor().set_count(42).set_feature_map_count(7)... +// +// Details: +// +// For a convolutional layer, a single inference takes a 3-dimensional matrix +// of input and produces a 3-dimensional matrix of output. We call the three +// dimensions height, width and feature_map_count, where for an image, the +// height and width correspond to the Y and X pixel indices, respectively, and +// the feature_map_count corresponds to the RGB dimension of the input data. +// Then the count indicates how many 3D matrices are being presented to be +// processed at once; this corresponds to the neural network concept of +// minibatch size. +// +// For a fully connected layer, it's better to put the nodes of the layer in +// the feature_map_count, and leave the height and weight as degenerate (== 1). +// Count indicates how many input vectors (degenerate 3D matrices) are to be +// processed. +// +// If unspecified, value_max and value_min default to 0.0. +// If value_max == value_min the Stream will attempt to derive valid values - +// for example the output of Relu6 activation will always be in the range +// [0.0, 6.0]. +// +// If unspecified, layout defaults to kYXDepthBatch. +class BatchDescriptor { + public: + // Creates a "blank" batch descriptor, which should be initialized via the + // named argument helpers. + BatchDescriptor(); + explicit BatchDescriptor(int ndims); + + // Clones values from 'other' for initialization. + void CloneFrom(const BatchDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + + // Pre-condition: + // value_max_ == 0 + // value_min_ == 0 + // quantized_activation_mode_ == QuantizedActivationMode::k8Bit + TensorDescriptorProto ToProto(DataType data_type) const; + + // Accessors. + int64_t count() const { return tensor_.dimensions(0); } + int64_t feature_map_count() const { return tensor_.dimensions(1); } + int64_t height() const { return GetDim(spatial_size(), DimIndex::Y); } + int64_t width() const { return GetDim(spatial_size(), DimIndex::X); } + int64_t spatial_dim(DimIndex dim) const { + return GetDim(spatial_size(), dim); + } + int ndims() const { return spatial_size().size(); } + float value_max() const { return value_max_; } + float value_min() const { return value_min_; } + DataLayout layout() const { return tensor_.data_layout(); } + QuantizedActivationMode quantized_activation_mode() const { + return quantized_activation_mode_; + } + // Full dimensions of the underlying data, ordered according to a specific + // layout. + std::vector full_dims(const DataLayout& layout) const; + + // Full strides of the underlying data, ordered according to a specific + // layout. + std::vector full_strides(const DataLayout& layout) const; + + // Vectorized dimensions where users can specify the dimension that the number + // of dimensions is reported rather than the full number of elements. + std::vector vectorized_dims(const DataLayout& layout, + int vector_size, int vector_dim) const; + + // Vectorized strides correspond to the vectorized_dims. + std::vector vectorized_strides(const DataLayout& layout, + int vector_size, + int vector_dim) const; + + // Named-argument helpers for avoiding user error during construction. + BatchDescriptor& set_count(int64_t value) { + tensor_.set_dimensions(0, value); + return *this; + } + BatchDescriptor& set_feature_map_count(int64_t value) { + tensor_.set_dimensions(1, value); + return *this; + } + BatchDescriptor& set_height(int64_t value) { + SetDim(spatial_size(), DimIndex::Y, value); + return *this; + } + BatchDescriptor& set_width(int64_t value) { + SetDim(spatial_size(), DimIndex::X, value); + return *this; + } + BatchDescriptor& set_spatial_dim(DimIndex dim, int64_t value) { + SetDim(spatial_size(), dim, value); + return *this; + } + BatchDescriptor& set_value_max(float value) { + value_max_ = value; + return *this; + } + BatchDescriptor& set_value_min(float value) { + value_min_ = value; + return *this; + } + BatchDescriptor& set_layout(DataLayout layout) { + tensor_.set_data_layout(layout); + return *this; + } + BatchDescriptor& set_quantized_activation_mode( + QuantizedActivationMode quantized_activation_mode) { + quantized_activation_mode_ = quantized_activation_mode; + return *this; + } + + // Return the number of nodes in a single feature map. + int64_t NodesPerFeatureMap() const; + + // Return the number of nodes across all feature maps. Note that this is not + // affected by the batch count. + int64_t NodesAcrossFeatureMaps() const; + + // Returns the number of elements (e.g. RGB pixel values) required to hold a + // given batch descriptor, given a no-padding assumption. Note that this is + // affected by the batch count. + int64_t ElementCount() const; + + // Return the number of weights required to fully connect a layer with + // dimensions given by the 'input' descriptor with a layer with dimensions + // given by the 'output' descriptor. + static int64_t FullyConnectedWeightCount(const BatchDescriptor& input, + const BatchDescriptor& output); + + // Return the number of biases required to fully connect to an output layer + // with dimensions given the 'output' descriptor. + static int64_t FullyConnectedBiasCount(const BatchDescriptor& output); + + // Return a BatchDescriptor for the output of a depth concatenation + // with the given input descriptors. The inputs should have the same + // dimensions, except possibly for feature_map_count(), though this + // function does not verify that. + static BatchDescriptor DepthConcatenateOutputDescriptor( + absl::Span inputs); + + private: + absl::Span spatial_size() const { + return AsInt64Slice(tensor_.dimensions()).subspan(2); + } + + absl::Span spatial_size() { + return AsInt64Slice(tensor_.mutable_dimensions()).subspan(2); + } + + TensorDescriptorProto tensor_; + float value_max_; + float value_min_; + QuantizedActivationMode quantized_activation_mode_; +}; + +// Returns a string representation of the given filter layout. +std::string FilterLayoutString(FilterLayout layout); + +// Describes a filter for the convolution. This is the "window" from +// height-by-width patches of each of the feature maps in the input layer to the +// cells within the output feature map. +// +// Uses the named argument construction form: +// +// FilterDescriptor filter_dimensions; +// filter_dimensions +// .set_output_feature_map_count(42) +// .set_input_feature_map_count(7) +// ... +// +// Arguments: +// - output_feature_map_count: number of feature maps in the output layer. +// - input_feature_map_count: number of feature maps in the input layer (from +// which the filter patch is taken). +// - input_filter_height: "height" number of neurons used in the sliding window +// over the input layer. +// - input_filter_width: "width" number of neurons used in the sliding window +// over the input layer. +// +// Sometimes names like "filter input height" are referred to by synonymous +// terminology, such as "kernel y size". +// +// If unspecified, layout defaults to kOutputInputYX. +class FilterDescriptor { + public: + // By default construction, all dimensions are set to zero, so they should all + // be populated by the user via the named-argument helpers below. (See class + // comment for details.) + FilterDescriptor(); + explicit FilterDescriptor(int ndims); + ~FilterDescriptor(); + + // Named-argument helpers for avoiding user error during construction. + FilterDescriptor& set_output_feature_map_count(int64_t value) { + tensor_.set_dimensions(0, value); + return *this; + } + FilterDescriptor& set_input_feature_map_count(int64_t value) { + tensor_.set_dimensions(1, value); + return *this; + } + FilterDescriptor& set_input_filter_height(int64_t value) { + SetDim(input_filter_dims(), DimIndex::Y, value); + return *this; + } + FilterDescriptor& set_input_filter_width(int64_t value) { + SetDim(input_filter_dims(), DimIndex::X, value); + return *this; + } + FilterDescriptor& set_layout(FilterLayout layout) { + tensor_.set_filter_layout(layout); + return *this; + } + FilterDescriptor& set_spatial_dim(DimIndex dim, int64_t value) { + SetDim(input_filter_dims(), dim, value); + return *this; + } + int ndims() const { return input_filter_dims().size(); } + + void CloneFrom(const FilterDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + TensorDescriptorProto ToProto(DataType data_type) const; + + // Returns the number of weights required as parameters for a convolution + // using this filter descriptor. + int64_t ComputeWeightCount() const; + + // Returns the number of biases required as parameters for a convolution + // using this filter descriptor. + int64_t bias_count() const { return output_feature_map_count(); } + + int64_t output_feature_map_count() const { return tensor_.dimensions(0); } + int64_t input_feature_map_count() const { return tensor_.dimensions(1); } + int64_t input_filter_height() const { + return GetDim(input_filter_dims(), DimIndex::Y); + } + int64_t input_filter_width() const { + return GetDim(input_filter_dims(), DimIndex::X); + } + int64_t input_filter_dim(DimIndex dim) const { + return GetDim(input_filter_dims(), dim); + } + + FilterLayout layout() const { return tensor_.filter_layout(); } + + absl::Span input_filter_dims() const { + return AsInt64Slice(tensor_.dimensions()).subspan(2); + } + + // Full dimensions of the underlying filter, + // ordered according to a specific layout. + std::vector full_dims(const FilterLayout& layout) const; + + // Full strides of the underlying filter, + // ordered according to a specific layout. + std::vector full_strides(const FilterLayout& layout) const; + + // Vectorized dimensions where users can specify the dimension that the number + // of dimensions is reported rather than the full number of elements. + std::vector vectorized_dims(const FilterLayout& layout, + int vector_size, int vector_dim) const; + + // Vectorized strides correspond to the vectorized_dims. + std::vector vectorized_strides(const FilterLayout& layout, + int vector_size, + int vector_dim) const; + + private: + absl::Span input_filter_dims() { + return AsInt64Slice(tensor_.mutable_dimensions()).subspan(2); + } + + TensorDescriptorProto tensor_; +}; + +// Describes how padding should be aligned when the total number of pad +// elements is odd. +enum class PadAlignment : int64_t { + kDefault = 0, // default padding for the device. + kCudnnPadding, // cuDNN padding - prefer to pad at the start. + kTensorFlowPadding, // TensorFlow padding - prefer to pad at the end. +}; + +// Returns a string representation of the given padding alignment. +std::string PadAlignmentString(PadAlignment alignment); + +// Print alignment to str. Needed to use CHECK_EQ between two PadAlignments. +std::ostream& operator<<(std::ostream& str, dnn::PadAlignment alignment); + +// Describes a convolution. +// +// Uses the named argument construction form: +// +// ConvolutionDescriptor convolution_dimensions; +// convolution_dimensions +// .set_vertical_filter_stride(2) +// .set_horizontal_filter_stride(2) +// ... +// +// Arguments: +// - zero_padding_height: padding of the "y dimension" of the input data. Note +// that this is different from the height of the filter. +// - zero_padding_width: analogous to the height above, but in the "x +// dimension". +// - vertical_filter_stride: the convolution slides a 2-dimensional window of +// filter-height-by-filter-width over the input layer -- the center of that +// window is moved in the "y dimension" according to this stride value. +// - horizontal_filter_stride: analogous to the vertical stride above, but in +// the "x dimension". +// - vertical_dilation_rate: there will be (vertical_dilation_rate - 1) skipped +// cells between each filter element in the "y dimension". +// - horizontal_dilation_rate: there will be (horizontal_dilation_rate - 1) +// skipped cells between each filter element in the "x dimension". +// - convolution_not_crosscor: By default (convolution_not_crosscor == false), +// we perform cross correlation rather than convolution. With the flag set, +// we perform convolution. Convolution and cross correlation are related by +// rotating the filter by 180 degrees (or equivalently flipping all spatial +// dimensions). +class ConvolutionDescriptor { + public: + // By default construction, there is no zero-padding and the filter stride is + // 1x1 (centering the filter on every cell in the input layer's + // width-by-height area). + ConvolutionDescriptor(); + explicit ConvolutionDescriptor(int ndims); + ~ConvolutionDescriptor(); + + std::string ToString() const; + std::string ToShortString() const; + ConvolutionDescriptorProto ToProto() const { return proto_; } + + ConvolutionDescriptor& set_zero_padding_height(int64_t value) { + SetDim(padding(), DimIndex::Y, value); + return *this; + } + ConvolutionDescriptor& set_zero_padding_width(int64_t value) { + SetDim(padding(), DimIndex::X, value); + return *this; + } + ConvolutionDescriptor& set_zero_padding(DimIndex dim, int64_t value) { + SetDim(padding(), dim, value); + return *this; + } + ConvolutionDescriptor& set_vertical_filter_stride(int64_t value) { + SetDim(strides(), DimIndex::Y, value); + return *this; + } + ConvolutionDescriptor& set_horizontal_filter_stride(int64_t value) { + SetDim(strides(), DimIndex::X, value); + return *this; + } + ConvolutionDescriptor& set_filter_stride(DimIndex dim, int64_t value) { + SetDim(strides(), dim, value); + return *this; + } + ConvolutionDescriptor& set_vertical_dilation_rate(int64_t value) { + SetDim(dilations(), DimIndex::Y, value); + return *this; + } + ConvolutionDescriptor& set_horizontal_dilation_rate(int64_t value) { + SetDim(dilations(), DimIndex::X, value); + return *this; + } + ConvolutionDescriptor& set_dilation_rate(DimIndex dim, int64_t value) { + SetDim(dilations(), dim, value); + return *this; + } + ConvolutionDescriptor& set_group_count(int group_count) { + proto_.set_group_count(group_count); + return *this; + } + ConvolutionDescriptor& set_convolution_not_crosscorr(bool conv) { + proto_.set_convolution_mode(conv ? ConvolutionMode::CONVOLUTION + : ConvolutionMode::CROSS_CORRELATION); + return *this; + } + ConvolutionDescriptor& set_name(const std::string& name) { + proto_.set_name(name); + return *this; + } + int64_t zero_padding_height() const { return GetDim(padding(), DimIndex::Y); } + int64_t zero_padding_width() const { return GetDim(padding(), DimIndex::X); } + int64_t vertical_filter_stride() const { + return GetDim(strides(), DimIndex::Y); + } + int64_t horizontal_filter_stride() const { + return GetDim(strides(), DimIndex::X); + } + int64_t vertical_dilation_rate() const { + return GetDim(dilations(), DimIndex::Y); + } + int64_t horizontal_dilation_rate() const { + return GetDim(dilations(), DimIndex::X); + } + + int zero_padding(DimIndex dim) const { return GetDim(padding(), dim); } + int filter_stride(DimIndex dim) const { return GetDim(strides(), dim); } + int dilation_rate(DimIndex dim) const { return GetDim(dilations(), dim); } + // TODO(timshen): remove this function. No users of this class is setting a + // non-default pad alignment. + PadAlignment pad_alignment() const { return PadAlignment::kDefault; } + int group_count() const { return proto_.group_count(); } + int ndims() const { return padding().size(); } + bool convolution_not_crosscorr() const { + return proto_.convolution_mode() == ConvolutionMode::CONVOLUTION; + } + + absl::Span strides() const { + return AsInt64Slice(proto_.strides()); + } + + absl::Span dilations() const { + return AsInt64Slice(proto_.dilations()); + } + + absl::Span padding() const { + return AsInt64Slice(proto_.paddings()); + } + + std::string name() const { return proto_.name(); } + + private: + absl::Span strides() { + return AsInt64Slice(proto_.mutable_strides()); + } + + absl::Span dilations() { + return AsInt64Slice(proto_.mutable_dilations()); + } + + absl::Span padding() { + return AsInt64Slice(proto_.mutable_paddings()); + } + + ConvolutionDescriptorProto proto_; + + // TODO(leary) cudnn provides these fields, but need to characterize what + // their effect is -- they may be boolean rather than integral. + // int64_t upscale_input_x; + // int64_t upscale_input_y; +}; + +// A patch of values in the input can be pooled via either a max or an average +// operation. +// Specify int64_t so there's no padding in PoolingDescriptor. +enum class PoolingMode : int64_t { + kMaximum, + kAverage, +}; + +// Specify the dimension in which to concatenate inputs in space. +// Specify int64_t so there's no padding in SpaceConcatenateMode. +enum class SpaceConcatenateMode : int64_t { + XDirection, + YDirection, +}; + +// Returns a short name for the pooling mode, e.g. "Avg". +std::string ShortPoolingModeString(PoolingMode mode); + +// Describes a pooling operation to be enqueued onto a stream via a platform's +// DnnSupport. +// +// TODO(broune): describe how padding works and what happens if the +// window height/width is not divisible by the vertical/horizontal +// stride. +// +// Arguments: +// pooling_mode: pooling operator to use on the input patch +// window_height: height of input window +// window_width: width of input window +// vertical_stride: vertical delta for center of the input patch +// horizontal_stride: horizontal delta for center of the input patch +class PoolingDescriptor { + public: + PoolingDescriptor(); + explicit PoolingDescriptor(int ndims); + + PoolingDescriptor& set_pooling_mode(PoolingMode value) { + mode_ = value; + return *this; + } + PoolingDescriptor& set_window_height(int64_t value) { + SetDim(&window_, DimIndex::Y, value); + return *this; + } + PoolingDescriptor& set_window_width(int64_t value) { + SetDim(&window_, DimIndex::X, value); + return *this; + } + PoolingDescriptor& set_window(DimIndex dim, int64_t value) { + SetDim(&window_, dim, value); + return *this; + } + PoolingDescriptor& set_vertical_padding(int64_t value) { + SetDim(&padding_, DimIndex::Y, value); + return *this; + } + PoolingDescriptor& set_horizontal_padding(int64_t value) { + SetDim(&padding_, DimIndex::X, value); + return *this; + } + PoolingDescriptor& set_padding(DimIndex dim, int64_t value) { + SetDim(&padding_, dim, value); + return *this; + } + PoolingDescriptor& set_vertical_stride(int64_t value) { + SetDim(&strides_, DimIndex::Y, value); + return *this; + } + PoolingDescriptor& set_horizontal_stride(int64_t value) { + SetDim(&strides_, DimIndex::X, value); + return *this; + } + PoolingDescriptor& set_stride(DimIndex dim, int64_t value) { + SetDim(&strides_, dim, value); + return *this; + } + PoolingDescriptor& set_propagate_nans(bool value) { + propagate_nans_ = value; + return *this; + } + PoolingDescriptor& set_name(const std::string& name) { + name_ = name; + return *this; + } + + int ndims() const { return ndims_; } + void CloneFrom(const PoolingDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + + PoolingMode mode() const { return mode_; } + int64_t window_height() const { return GetDim(window_, DimIndex::Y); } + int64_t window_width() const { return GetDim(window_, DimIndex::X); } + int64_t window(DimIndex dim) const { return GetDim(window_, dim); } + int64_t vertical_padding() const { return GetDim(padding_, DimIndex::Y); } + int64_t horizontal_padding() const { return GetDim(padding_, DimIndex::X); } + int64_t padding(DimIndex dim) const { return GetDim(padding_, dim); } + int64_t vertical_stride() const { return GetDim(strides_, DimIndex::Y); } + int64_t horizontal_stride() const { return GetDim(strides_, DimIndex::X); } + int64_t stride(DimIndex dim) const { return GetDim(strides_, dim); } + absl::Span window() const { return window_; } + absl::Span padding() const { return padding_; } + absl::Span strides() const { return strides_; } + bool propagate_nans() const { return propagate_nans_; } + std::string name() const { return name_; } + + private: + PoolingMode mode_; + int ndims_; + bool propagate_nans_; + std::string name_; // Name as in Tensorflow NodeDef, for debugging purposes. + + // Stored as: ..., y, x. + std::vector window_; + std::vector padding_; + std::vector strides_; +}; + +// Collects parameters for DNN algorithms +class AlgorithmDesc { + public: + typedef int64_t Index; + AlgorithmDesc() : AlgorithmDesc(0, false, std::nullopt) {} + explicit AlgorithmDesc(AlgorithmProto proto) : proto_(std::move(proto)) {} + AlgorithmDesc(Index algo_id, bool use_tensor_ops) + : AlgorithmDesc(algo_id, use_tensor_ops, std::nullopt) {} + AlgorithmDesc(Index algo_id, bool use_tensor_ops, + std::optional workspace_size) { + proto_.set_is_cudnn_frontend(false); + proto_.set_algo_id(algo_id); + proto_.set_math_type(use_tensor_ops ? AlgorithmProto::TENSOR_OP_MATH + : AlgorithmProto::DEFAULT_MATH); + if (workspace_size) { + proto_.mutable_workspace_size()->set_value(*workspace_size); + } + } + AlgorithmDesc(int64_t engine_id, + const std::vector>& tuning_knobs, + std::optional workspace_size); + bool is_cudnn_frontend() const { return proto_.is_cudnn_frontend(); } + + bool tensor_ops_enabled() const { + return proto_.math_type() == AlgorithmProto::TENSOR_OP_MATH; + } + std::optional workspace_size() const { + if (proto_.has_workspace_size()) { + return proto_.workspace_size().value(); + } + return std::nullopt; + } + Index algo_id() const { return proto_.algo_id(); } + + std::vector> TuningKnobs() const; + + bool operator==(const AlgorithmDesc& other) const; + + uint64_t hash() const; + + AlgorithmProto ToProto() const { return proto_; } + + std::string ToString() const; + + private: + AlgorithmProto proto_; +}; + +// Describes the result from a perf experiment. +// +// Arguments: +// algorithm: returns the exact algorithm that was used. +// elapsed_time_in_ms: returns the measured elapsed time in milliseconds. +class ProfileResult { + public: + bool is_valid() const { + return algorithm_.has_value() && + elapsed_time_in_ms() != std::numeric_limits::max(); + } + + AlgorithmDesc algorithm() const { return *algorithm_; } + void set_algorithm(AlgorithmDesc val) { algorithm_ = val; } + + float elapsed_time_in_ms() const { return elapsed_time_in_ms_; } + void set_elapsed_time_in_ms(float val) { elapsed_time_in_ms_ = val; } + + size_t scratch_size() const { return scratch_size_; } + void set_scratch_size(size_t val) { scratch_size_ = val; } + + private: + std::optional algorithm_; + float elapsed_time_in_ms_ = std::numeric_limits::max(); + // The scratch size algorithm_ requires. Currently it's only populated by + // convolutions. + size_t scratch_size_ = 0; +}; + +// Backend-specific data shared between repeated launches of the same +// convolution. +template +class OpRunner; + +// An abstract class owning cached state for a particular op/configuration. +// +// The primary motivation for this is cuDNN backend ExecutionPlans, which are +// costly to recreate. +// +// All OpRunners must be outlived by their parent Stream. +template +class OpRunner { + public: + virtual ~OpRunner() = default; + + // Get a description of the runner, for uniqueness of autotune entries. + // + // Since this is used to determine whether runners are equivalent for the + // purpose of scoring autotune entries, it shall be unique among runners of + // the same op and parameters. + virtual std::string ToString() const = 0; + + // Get the number of bytes of scratch space needed for `operator()`. + // + // If determining the workspace size can fail, runners should precompute and + // cache it at construction time. + virtual size_t GetWorkspaceSize() const = 0; + + // Convert to an AlgorithmDesc for AoT compilation or autotuning. + virtual tsl::StatusOr ToAlgorithmDesc() const = 0; + + // Launch the operation, with the signature determined by `Sig`. + virtual tsl::Status operator()(Stream*, ProfileResult*, + DeviceMemoryBase scratch_memory, + Args... args) const = 0; +}; + +using ConvSignature = void(DeviceMemoryBase /* input_data */, + DeviceMemoryBase /* filter_data */, + DeviceMemoryBase /* output_data */); +using ConvRunner = OpRunner; + +using GraphConvSignature = void(std::vector); +using GraphConvRunner = OpRunner; + +using FusedConvSignature = void(DeviceMemoryBase /* input_data */, + DeviceMemoryBase /* filter_data */, + DeviceMemoryBase /* side_input_data */, + DeviceMemoryBase /* bias_data */, + DeviceMemoryBase /* output_data */); +using FusedConvRunner = OpRunner; + +using FusedMatmulSignature = void(DeviceMemoryBase /* a_data */, + DeviceMemoryBase /* b_data */, + DeviceMemoryBase /* bias_data */, + DeviceMemoryBase /* c_data */); +using FusedMatmulRunner = OpRunner; + +using FusedMHASignature = void(DeviceMemoryBase /*BMM1_inputA_data*/, + DeviceMemoryBase /* BMM1_inputB_data */, + DeviceMemoryBase /* BMM2_inputA_data */, + DeviceMemoryBase /* output_data */, + DeviceMemoryBase /* mask_data */, + DeviceMemoryBase /* bias_data */, + DeviceMemoryBase /* activation_data */); +using FusedMHARunner = OpRunner; + +using FusedMHABackwardSignature = void( + DeviceMemoryBase /* BMM1_GRAD_GEMM1_inputA_data */, + DeviceMemoryBase /* BMM1_GRAD_GEMM2_inputB_data */, + DeviceMemoryBase /* BMM2_GRAD_GEMM1_inputA_data */, + DeviceMemoryBase /* BMM2_GRAD_GEMM2_inputB_data */, + DeviceMemoryBase /* d_output_data */, + DeviceMemoryBase /* d_BMM1_inputA_data */, + DeviceMemoryBase /* d_BMM1_inputB_data */, + DeviceMemoryBase /* d_BMM2_inputB_data */, DeviceMemoryBase /* d_s_data */, + DeviceMemoryBase /* mask_data */, DeviceMemoryBase /* d_bias_data */); +using FusedMHABackwardRunner = OpRunner; + +// Describes the configuration for the algorithms that will used. +// +// Arguments: +// algorithm: the primary algorithm that should be used. +// algorithm_no_scratch: a secondary algorithm that should be used, if the +// the allocation for the scratch memory fails. +// scrach_size: specify the size of scratch memory in bytes needed for the +// algorithm used. +// +// On CUDA platform with CUDNN library, algorithm and algorithm_no_scratch +// would be used. On ROCm platform with MIOpen library, algorithm and +// scratch_size would be used. The major difference between the two platforms +// are whether it's possible to get an algorithm without scratch memory. On +// CUDA + CUDNN it's possible, and algorithm_no_scratch can be used to track +// such information, whereas on ROCm + MIOpen there is no guarantee to getting +// one without scratch memory, and scratch_size field is used to track it. +class AlgorithmConfig { + public: + AlgorithmConfig() = default; + explicit AlgorithmConfig(AlgorithmDesc algorithm) : algorithm_(algorithm) {} + AlgorithmConfig(AlgorithmDesc algorithm, size_t scratch_size) + : algorithm_(algorithm), scratch_size_(scratch_size) {} + AlgorithmConfig(AlgorithmDesc algorithm, AlgorithmDesc algorithm_no_scratch) + : algorithm_(algorithm), algorithm_no_scratch_(algorithm_no_scratch) {} + AlgorithmConfig(AlgorithmDesc algorithm, size_t scratch_size, + AlgorithmDesc algorithm_no_scratch) + : algorithm_(algorithm), + algorithm_no_scratch_(algorithm_no_scratch), + scratch_size_(scratch_size) {} + + // TODO(ruochengw): After cl/380702564, add support for algorithm configs with + // cuDNN Frontend APIs. + explicit AlgorithmConfig(const AlgorithmConfigProto& algorithm_config_proto) { + const AlgorithmProto& algorithm_proto = algorithm_config_proto.algorithm(); + algorithm_ = AlgorithmDesc(algorithm_proto); + if (algorithm_config_proto.optional_scratch_size_case() != + /*ONEOF_NAME_NOT_SET=*/0) { + scratch_size_ = algorithm_config_proto.scratch_size(); + } + if (algorithm_config_proto.optional_algorithm_no_scratch_case() != + /*ONEOF_NAME_NOT_SET=*/0) { + const AlgorithmProto& algorithm_no_scratch_proto = + algorithm_config_proto.algorithm_no_scratch(); + algorithm_no_scratch_ = AlgorithmDesc(algorithm_no_scratch_proto); + } + } + + std::optional algorithm() const { return algorithm_; } + void set_algorithm(AlgorithmDesc val) { algorithm_ = val; } + std::optional algorithm_no_scratch() const { + return algorithm_no_scratch_; + } + void set_algorithm_no_scratch(AlgorithmDesc val) { + algorithm_no_scratch_ = val; + } + std::optional scratch_size() const { return scratch_size_; } + void set_scratch_size(size_t val) { scratch_size_ = val; } + bool operator==(const AlgorithmConfig& other) const { + return this->algorithm_ == other.algorithm_ && + this->algorithm_no_scratch_ == other.algorithm_no_scratch_ && + this->scratch_size_ == other.scratch_size_; + } + bool operator!=(const AlgorithmConfig& other) const { + return !(*this == other); + } + std::string ToString() const; + + // TODO(ruochengw): After cl/380702564, add support for algorithm configs with + // cuDNN Frontend APIs. + AlgorithmConfigProto ToProto() const { + AlgorithmConfigProto algorithm_config_proto; + if (algorithm_.has_value()) { + *algorithm_config_proto.mutable_algorithm() = + algorithm_.value().ToProto(); + } + if (algorithm_no_scratch_.has_value()) { + *algorithm_config_proto.mutable_algorithm_no_scratch() = + algorithm_no_scratch_.value().ToProto(); + } + if (scratch_size_.has_value()) { + algorithm_config_proto.set_scratch_size(scratch_size_.value()); + } + return algorithm_config_proto; + } + + private: + std::optional algorithm_; + std::optional algorithm_no_scratch_; + std::optional scratch_size_; +}; + +// Describes a local response normalization (LRN). LRN is used e.g. in +// dist_belief. +// +// Let V be the vector of feature maps at some (batch, y, x) +// coordinate. LRN applies independently to each vector V in the +// input, across all coordinates (batch, y, x), by mapping each V to +// another vector U of the same size using the formula +// +// U_i = V_i / ((bias + alpha * (sum_j V_j^2)) ^ beta) +// +// where the sum is taken over j in the closed range [i - range, i + range]. +// +// When calculating U_i the j in the sum can extend beyond the bounds +// of V. If wrap_around is true, then V_j = V_{j mod F} where F is the +// size of V, which is the number of feature maps. If wrap_around is +// false, then V_j = 0 for j outside [0, F-1]. +// +// If segment_size <= F, where F is the number of feature_maps, then +// segment_size has no effect. Otherwise, each consecutive segment of +// segment_size entries in V are normalized separately. +// +// Not all StreamExecutors allow wrap_around == true or segment_size +// != 64. Some do not implement normalization at all. +class NormalizeDescriptor { + public: + NormalizeDescriptor(); + + NormalizeDescriptor& set_bias(float bias) { + bias_ = bias; + return *this; + } + + NormalizeDescriptor& set_range(int32_t range) { + range_ = range; + return *this; + } + + NormalizeDescriptor& set_alpha(float alpha) { + alpha_ = alpha; + return *this; + } + + NormalizeDescriptor& set_beta(float beta) { + beta_ = beta; + return *this; + } + + NormalizeDescriptor& set_wrap_around(bool wrap_around) { + wrap_around_ = wrap_around; + return *this; + } + + NormalizeDescriptor& set_segment_size(int32_t segment_size) { + segment_size_ = segment_size; + return *this; + } + + void CloneFrom(const NormalizeDescriptor& other); + + std::string ToString() const; + std::string ToShortString() const; + + float bias() const { return bias_; } + int32_t range() const { return range_; } + float alpha() const { return alpha_; } + float beta() const { return beta_; } + bool wrap_around() const { return wrap_around_; } + int32_t segment_size() const { return segment_size_; } + + private: + float bias_; + int32_t range_; + float alpha_; + float beta_; + bool wrap_around_; + int32_t segment_size_; +}; + +// Returns a string representation of the given activation mode. +std::string ActivationModeString(ActivationMode mode); + +// Describes the operation that DoElementwiseOperation should perform on its +// inputs. +enum class ElementwiseOperation { kAdd, kMultiply }; + +std::string ElementwiseOperationString(ElementwiseOperation op); + +// A simple class representing the version of the backing library, to +// workaround the "too perfect forwarding" issue in gcc6+ compilers. +// See PR#16309 and issue #18402 for links discussing the issue. +class VersionInfo { + public: + explicit VersionInfo(int major = 0, int minor = 0, int patch = 0) + : major_(major), minor_(minor), patch_(patch) {} + explicit VersionInfo(DnnVersionInfoProto proto) + : major_(proto.major()), minor_(proto.minor()), patch_(proto.patch()) {} + + DnnVersionInfoProto ToProto() const { + DnnVersionInfoProto proto; + proto.set_major(major_); + proto.set_minor(minor_); + proto.set_patch(patch_); + return proto; + } + + int major_version() const { return major_; } + int minor_version() const { return minor_; } + int patch() const { return patch_; } + + std::tuple as_tuple() const { + return std::make_tuple(major_, minor_, patch_); + } + + friend bool operator<(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() < b.as_tuple(); + } + friend bool operator>(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() > b.as_tuple(); + } + friend bool operator<=(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() <= b.as_tuple(); + } + friend bool operator>=(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() >= b.as_tuple(); + } + friend bool operator==(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() == b.as_tuple(); + } + friend bool operator!=(const VersionInfo& a, const VersionInfo& b) { + return a.as_tuple() != b.as_tuple(); + } + + std::string ToString() const { + return absl::StrCat(major_, ".", minor_, ".", patch_); + } + + private: + int major_; + int minor_; + int patch_; +}; + +// Suite of operations typically used for implementing Deep/Convolutional Neural +// Nets. Note: A false return value of an operation indicates the +// implementation is not available. +// +// TODO(b/118763918): this class (or rather dispatch table) has several +// problems: +// * Some overloads are missing. Ideally we want to have template virtual +// functions while the template arguments is a closed set. However, we don't +// get that from the language. +// * The API is a union of cuDNN and another private backend. Only 10% of the +// functions are actually implemented by both backends, the rest are +// actually backend-specific. The massive interface creates extra mental +// burden. +// * Poor error handling: the API should return tsl::Status objects. +// +// PrepareForConvolution is an example for how new APIs should be written. +class DnnSupport { + public: + DnnSupport() = default; + virtual ~DnnSupport() = default; + + virtual tsl::Status Init() = 0; + + // Gets the version of the backing library, as a VersionInfo object. + virtual tsl::StatusOr GetVersion() { + return tsl::errors::Unimplemented( + "DnnSupport::GetVersion not implemented on this platform."); + } + + // Performs a single-precision forward batch normalization operation onto + // the stream. + // + // Arguments: + // stream: borrowed pointer to the stream that the batch normalization + // operation should be enqueued onto. + // x: input data. + // scale: scaling parameters. + // offset: offset parameters. + // estimated_mean: population mean estimated during training. + // Used for inference only; empty for training. + // estimated_variance: population variance estimated during training, + // used for inference only; empty for training. + // side_input: optional input that is element-wise added to the output of + // batch normalization. + // x_desc: dimensions of the input data, which is the same as the dimensions + // of the output and side input. + // scale_offset_desc: dimensions of scale and offset. + // epsilon: a small floating point number added to the variance of x. + // activation_mode: activation applied to the result of batch normalization + // (or after adding optional side input) + // y: output data. + // batch_mean: batch mean, to be used to compute the running mean. + // batch_variance: batch variance, to be used to compute + // the running variance. + // reserve_space_1: saved mean, to be reused in the backward gradient + // computation. + // reserve_space_2: saved inv_var (1/sqrt(epsilon + variance), to be reused + // in the backward gradient computation. + // is_training: Set to true for training, false for inference. + virtual bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* reserve_space_1, + DeviceMemory* reserve_space_2, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a half-precision forwards batch normalization operation onto the + // stream. See DoBatchNormalizationForward above for argument details. + virtual bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* reserve_space_1, + DeviceMemory* reserve_space_2, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a bfloat16 forward batch normalization operation onto the + // stream. See DoBatchNormalizationForward above for argument details. + virtual bool DoBatchNormalizationForward( + Stream* stream, const DeviceMemory& x, + const DeviceMemory& scale, const DeviceMemory& offset, + const DeviceMemory& estimated_mean, + const DeviceMemory& estimated_variance, + const DeviceMemory& side_input, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory* y, + DeviceMemory* batch_mean, DeviceMemory* batch_var, + DeviceMemory* reserve_space_1, + DeviceMemory* reserve_space_2, bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a single-precision backward batch normalization gradient + // computation operation onto the stream. + // + // Arguments: + // stream: borrowed pointer to the stream that the batch normalization + // gradient computation operation should be enqueued onto. + // y_backprop: gradient with regard to output y. + // x: input data. + // scale: scaling parameters. + // inv_var: 1/sqrt(epsilon + variance) of x. + // x_desc: dimensions of the input data, which is the same as the dimensions + // of the output. + // scale_offset_desc: dimensions of scale and offset. + // epsilon: a small floating point number added to the variance of x. + // x_backprop: gradient with respect to input x. + // scale_backprop: gradient with respect to scale. + // offset_backprop: gradient with respect to offset. + virtual bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a half-precision backward batch normalization gradient computation + // operation onto the stream. See DoBatchNormalizationBackward above for + // argument details. + virtual bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Performs a bfloat16 backward batch normalization gradient computation + // operation onto the stream. See DoBatchNormalizationBackward above for + // argument details. + virtual bool DoBatchNormalizationBackward( + Stream* stream, const DeviceMemory& y_backprop, + const DeviceMemory& x, const DeviceMemory& scale, + const DeviceMemory& offset, const DeviceMemory& mean, + const DeviceMemory& inv_var, + const DeviceMemory& y, + const dnn::BatchDescriptor& x_desc, + const dnn::BatchDescriptor& scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory* x_backprop, + DeviceMemory* scale_backprop, DeviceMemory* offset_backprop, + DeviceMemory* side_input_backprop, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Enqueues a fused convolution operation onto the stream. + // We provide several variants with different types for inputs, biases and + // scaling parameters. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'convolve' operation + // should be enqueued onto. + // conv_input_descriptor: dimensions of the convolution input layer. + // conv_input_data: un-owned device memory region which contains the + // convolution input. + // conv_input_scale: a floating point scale to multiply with each element + // of conv_input_data. + // filter_descriptor: dimensions of the convolution filter. + // filter_data: un-owned device memory region which contains the + // convolution filter weights. + // convolution_descriptor: stride of the convolution filter. + // biases: un-owned device memory region containing biases to add to the + // input. + // activation_mode: Type of activation to perform. + // side_input_data: un-owned device memory region which contains optional + // side input data. If 'side_input_scale' is non-zero, then this must + // point to data in the tensor shape specified by output_shape. + // It will be scaled by 'side_input_scale' and added to the convolution + // result and bias prior to applying the activation function. + // side_input_scale: a floating point scale to multiply with each element + // of side_input_data. + // output_descriptor: dimensions of the output layer. + // output_data: un-owned device memory region in which to place the + // convolution result. + // scratch_allocator: un-owned, may-be-null object that may allocate scratch + // space in order to speed up the convolution operation. + // algorithm_config: specifies which algorithm should be used for the + // operation. + // output_profile_result: the output profile result for this call. The + // profiling is only enabled when this is not nullptr. + // + // conv_input_descriptor, filter_descriptor, convolution_descriptor and + // output_descriptor together specify exactly how the convolution is aligned + // with the input data: + // + // * (input dimensions - filter size + 1) / filter stride == output dimensions + // corresponds to dist_belief padding = VALID, i.e. the input is not padded. + // * input dimensions / filter stride == output dimensions + // corresponds to dist_belief padding = SAME, i.e. input and output are the + // same size - this requires padding the input. + // * (input dimensions + filter size - 1) / filter stride == output dimensions + // corresponds to dist_belief padding = FULL, i.e. the output is sized so + // that if the inverse of the filter is applied to the output in VALID mode + // the result is the same size as the input - this requires even more + // padding of the input. + virtual tsl::Status DoFusedConvolve( + Stream* stream, DataType input_type, DataType side_input_type, + DataType bias_type, DataType output_type, + const dnn::BatchDescriptor& conv_input_descriptor, + DeviceMemoryBase conv_input_data, double conv_input_scale, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + DeviceMemoryBase side_input_data, double side_input_scale, + const dnn::BatchDescriptor& bias_descriptor, DeviceMemoryBase biases, + dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, ScratchAllocator* scratch_allocator, + const dnn::AlgorithmConfig& algorithm_config, + dnn::ProfileResult* output_profile_result) { + return tsl::errors::Unimplemented( + "DnnSupport::DoFusedConvolve not implemented on this platform."); + } + + template + tsl::Status PrepareForConvolution( + ConvolutionKind kind, Stream* stream, + const BatchDescriptor& batch_descriptor, + DeviceMemory input_data, + const FilterDescriptor& filter_descriptor, + DeviceMemory filter_data, + const BatchDescriptor& output_descriptor, + DeviceMemory output_data, + const ConvolutionDescriptor& convolution_descriptor, + const AlgorithmConfig& algorithm_config, + ScratchAllocator* scratch_allocator, AlgorithmDesc* algorithm_desc, + DeviceMemory* scratch_memory) { + return DoPrepareForConvolution( + kind, ToDataType::value, stream, batch_descriptor, + input_data, filter_descriptor, filter_data, output_descriptor, + output_data, convolution_descriptor, algorithm_config, + scratch_allocator, algorithm_desc, scratch_memory); + } + + // cuDNN-specific input transformation that allows running int8x32 + // convolutions faster using Tensor Core IMMA instruction. + virtual tsl::Status CudnnReorderConvolutionFilterAndBias( + Stream* stream, const FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_input, + DeviceMemory* filter_output, + std::optional> bias_input, + std::optional> bias_output) { + return tsl::errors::Unimplemented( + "DnnSupport::CudnnReorderConvolutionFilterAndBias is specific to CUDA " + "convolution implementation."); + } + + // Enqueues a single-precision convolution operation onto the stream. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'convolve' operation + // should be enqueued onto. + // input_descriptor: dimensions of the input layer. + // input_data: un-owned device memory region which contains the + // convolution input. + // filter_descriptor: dimensions of the convolution filter. + // convolution_descriptor: stride of the convolution filter. + // output_descriptor: dimensions of the output layer. + // output_data: un-owned device memory region in which to place the + // convolution result. + // algorithm_desc: specifies which algorithm should be used for the + // operation. + // scratch: un-owned device memory for scratch space in order to speed up + // the convolution operation. + // output_profile_result: the output profile result for this call. The + // profiling is only enabled when this is not nullptr. + // + // input_descriptor, filter_descriptor, convolution_descriptor and + // output_descriptor together specify exactly how the convolution is aligned + // with the input data: + // + // * (input dimensions - filter size + 1) / filter stride == output dimensions + // corresponds to dist_belief padding = VALID, i.e. the input is not padded. + // * input dimensions / filter stride == output dimensions + // corresponds to dist_belief padding = SAME, i.e. input and output are the + // same size - this requires padding the input. + // * (input dimensions + filter size - 1) / filter stride == output dimensions + // corresponds to dist_belief padding = FULL, i.e. the output is sized so + // that if the inverse of the filter is applied to the output in VALID mode + // the result is the same size as the input - this requires even more + // padding of the input. + virtual tsl::Status DoConvolve( + ConvolutionKind kind, DataType element_type, DataType output_type, + Stream* stream, const BatchDescriptor& input_descriptor, + DeviceMemoryBase input_data, const FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, const BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const ConvolutionDescriptor& convolution_descriptor, + AlgorithmDesc algorithm_desc, DeviceMemory scratch_memory, + ProfileResult* output_profile_result) = 0; + + virtual tsl::Status GetConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, ScratchAllocator* scratch_allocator, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + virtual tsl::StatusOr> + ConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor); + + virtual tsl::Status GetGraphConvolveRunners( + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, const NumericOptions& numeric_options, + std::vector>* out_exec_plans, + std::string serialized_graph); + + virtual tsl::StatusOr> + GraphConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType output_type, const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + std::string serialized_graph); + + virtual tsl::Status GetFusedConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_input_scale, + double side_input_scale, double leakyrelu_alpha, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, dnn::ActivationMode activation_mode, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + virtual tsl::Status GetFusedMatmulRunners( + bool use_cudnn_frontend, dnn::DataType element_type, + dnn::DataType bias_type, dnn::DataType output_type, Stream* stream, + bool trans_a, bool trans_b, uint64_t m, uint64_t n, uint64_t k, + int64_t lda, int64_t ldb, int64_t ldc, + dnn::ActivationMode activation_mode, bool use_fallback, + const NumericOptions& numeric_options, + std::vector>* + out_exec_plans); + + virtual tsl::StatusOr> + FusedConvolveRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::ConvolutionKind kind, dnn::DataType element_type, + dnn::DataType bias_type, dnn::DataType output_type, double conv_scale, + double side_input_scale, double leakyrelu_alpha, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + dnn::ActivationMode activation_mode); + + virtual tsl::StatusOr> + FusedMHARunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor& bmm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor& bmm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor& intermediate_bmm2_lhs_descriptor, + const dnn::TensorDescriptor& output_descriptor, + std::optional activation_descriptor, + std::optional mask_descriptor, + std::optional bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed); + + virtual tsl::StatusOr> + FusedMHABackwardRunnerFromDesc( + Stream* stream, const dnn::AlgorithmDesc& algorithm_desc, + dnn::FusedMHAKind kind, + const MatmulTensorDescriptor& bmm1_grad_gemm1_rhs_descriptor, + const MatmulTensorDescriptor& bmm1_grad_gemm2_rhs_descriptor, + const MatmulTensorDescriptor& bmm2_grad_gemm1_lhs_descriptor, + const MatmulTensorDescriptor& bmm2_grad_gemm2_rhs_descriptor, + const MatmulTensorDescriptor& d_output_descriptor, + const TensorDescriptor& d_bmm1_lhs_descriptor, + const TensorDescriptor& d_bmm1_rhs_descriptor, + const TensorDescriptor& d_bmm2_rhs_descriptor, + const TensorDescriptor& d_s_descriptor, + std::optional mask_descriptor, + std::optional d_bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed); + + virtual bool GetMIOpenConvolveAlgorithms( + dnn::ConvolutionKind kind, dnn::DataType element_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + ScratchAllocator* scratch_allocator, + std::vector* out_algorithms); + + // Returns a list of supported rnn algorithms. + virtual bool GetRnnAlgorithms(std::vector* out_algorithms); + + // Version of DoConvolve that uses pre-quantized 8 bit coefficients. + // coefficient_scales specifies the scaling of each column of coefficients: + // original float coefficient[row * num_columns + column] = + // quantized coefficient[row * num_columns + column] * + // coefficient_scales[column]. + virtual bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) = 0; + + // Same as DoConvolveQuantized above, but int8 filter coefficients. + virtual bool DoConvolveQuantized( + Stream* stream, const dnn::BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const dnn::FilterDescriptor& filter_descriptor, + const DeviceMemory& filter_coefficients, + const DeviceMemory& coefficient_scales, + const dnn::ConvolutionDescriptor& convolution_descriptor, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemory* output_data) = 0; + + // Variation of the above with the weight matrix split into two matrices. + // first_weights: Coefficients of the first matrix. + // second_weights: Coefficients of the second matrix. + // depth_multiplier: specifies the columns of the first matrix and rows + // of the second one - first_weights columns = depth_multiplier, + // second_weights rows = depth_multiplier * + // filter_descriptor.input_feature_map_count(). + // see go/separable for documentation on separable convolutions. + virtual bool DoSeparableConvolve( + Stream* stream, const BatchDescriptor& input_descriptor, + const DeviceMemory& input_data, + const FilterDescriptor& filter_descriptor, int depth_multiplier, + const DeviceMemory& first_weights, + const DeviceMemory& second_weights, + const ConvolutionDescriptor& convolution_descriptor, + const BatchDescriptor& output_descriptor, + DeviceMemory* output_data) = 0; + + // Fully connects the "nodes" (float values) in input_data with + // shape input_dimensions to output_data with output_dimensions + // using provided weights. This is equivalent to computing a matrix + // product, hence the name MatMul. + // + // A BatchDescriptor has four dimensions: batch, y, x, depth. Matrix products + // happen in two dimensions. To get down to two dimensions, we consider the + // input y, x and depth dimension as one combined dimension T. For now, + // assume that the output height and width are 1 and let OD be the output + // depth. + // + // There are three device memory buffers passed in to this + // function. We can now view all three as matrices: + // + // input_data: A batch x T matrix + // weights: A T x OD matrix + // output_data: A batch x OD matrix + // + // This function then computes the matrix product of input_data and + // weights and writes the result into output_data. + // + // Here the weights buffer is in row major order, i.e. the first OD + // entries in weights are the first row, the second OD entries in + // weights are the second row and so on. + // + // The case for output width*height > 1 is more complicated. Let K = + // OY * OX where OY is the output height and OX is the output + // width. Then weights is divided into K sub-arrays W_i, for + // i=0,...,k-1, that each represent a T x OD matrix. This function + // then computes the K matrix multiplications of input_data with + // each W_i. This creates K matrices with dimensions batch x + // OD. These K matrices are concatenated horizontally to form one + // larger matrix with dimensions batch x (K*OD); note that this is + // not the same as concatenating the bytes of the matrices. The + // combined matrix can then be interpreted as a tensor with + // dimensions (batch, OY, OX, OD). If the output tensor format is + // not kBatchYXDepth, this function would then need to arrange for + // the output to be in the requested layout, if that is + // supported. Note that the case K=1 is equivalent to the + // description above. It is recommended to prefer the case K=1. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'fully connect' operation + // should be enqueued onto. + // output_data: un-owned device memory region in which to place the + // fully connected result. + virtual bool DoMatMul(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& weights, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Version of DoMatMul that uses pre-quantized 8 bit weights. + // weight_scales specifies the scaling of each column of weights: + // original float weight[row * num_columns + column] = + // quantized_weight[row * nnum_columns + column] * weight_scales[column]. + virtual bool DoMatMulQuantized(Stream* stream, + const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Version of DoMatMul that uses pre-quantized 16 bit weights. + // weight_scales specifies the scaling of each column of weights: + // original float weight[row * num_columns + column] = + // quantized_weight[row * nnum_columns + column] * weight_scales[column]. + virtual bool DoMatMulQuantized(Stream* stream, + const DeviceMemory& input_data, + const DeviceMemory& quantized_weights, + const DeviceMemory& weight_scales, + const dnn::BatchDescriptor& input_dimensions, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Adds biases to the feature maps in input_data producing + // output_data. input_data can equal output_data, but must not + // partially overlap it. + // + // Let K = count() * height() * width() and N = feature_map_count() + // on dimensions. Then input_value contains K*N values and biases + // contains N values. We can thus logically consider input_value to + // contain K vectors of N elements each. This function adds biases + // to each of those N vectors. + // + // TODO(broune): This works differently when width() * height() > 1 + // and the call to ThenBiasAdd() follows a call to ThenMatMul(). In + // that case there should be width() * height() * + // feature_map_count() biases, but this is not implemented on all + // StreamExecutors. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'bias add' operation + // should be enqueued onto. + // input_data: un-owned device memory region containing the input. + // biases: un-owned device memory region containing biases to add to the + // input. + // dimensions: dimensions of input_data and output_data. + // output_data: un-owned device memory region in which to place the result. + virtual bool DoBiasAdd(Stream* stream, const DeviceMemory& input_data, + const DeviceMemory& biases, + const dnn::BatchDescriptor& dimensions, + DeviceMemory* output_data) = 0; + + // Performs a forward pooling operation on input_data, writing to + // output_data. See PoolingDescriptor for how to configure the + // pooling operation. + // + // Pooling happens as a window that moves across the Y and X + // dimensions of input_data, where each position of the window + // yields one output value. E.g. for max pooling, the computed value + // is the maximum element in the window. The operation is applied + // independently to each batch and at each feature map (depth), so + // that the output depth and feature_map_count are the same as for + // the input. The output width and height can be different. + // + // See PoolingDescriptor for how to configure the pooling operation. + virtual tsl::Status DoPoolForward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, ScratchAllocator* workspace_allocator) = 0; + + virtual tsl::Status DoPoolForward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, ScratchAllocator* workspace_allocator); + + // Performs differentiation of the pooling operation. + virtual tsl::Status DoPoolBackward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, + ScratchAllocator* workspace_allocator) = 0; + + virtual tsl::Status DoPoolBackward( + DataType element_type, Stream* stream, + const dnn::PoolingDescriptor& pooling_dimensions, + const NumericOptions& numeric_options, + const dnn::BatchDescriptor& input_dimensions, DeviceMemoryBase input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemoryBase output_data, DeviceMemoryBase input_diff_data, + DeviceMemoryBase output_diff_data, ScratchAllocator* workspace_allocator); + + // Applies local response normalization to the values from input_data and + // writes the result to output_data. + // + // See comments on NormalizeDescriptor for a description of local response + // normalization. + virtual bool DoNormalizeWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, DeviceMemory* output_data) { + return false; + } + + // Performs backpropagation for the normalization operation + // + // Given raw data, its corresponding normalized output, and a gradient of some + // unspecified function with respect to the normalized variables, computes the + // gradient of that unspecified function with respect to the raw variables. + // + // The normalized data input array is expected to match the output that would + // be obtained by running the raw data input array through the DoNormalize + // method above. + // + // See comments on NormalizeDescriptor for a description of local response + // normalization. + virtual bool DoNormalizeBackwardWithDimensions( + Stream* stream, const dnn::NormalizeDescriptor& normalize_descriptor, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& raw_data, + const DeviceMemory& normalized_data, + const DeviceMemory& normalized_variable_gradient, + DeviceMemory* raw_variable_gradient, + ScratchAllocator* workspace_allocator) { + return false; + } + + // Applies an activation function (see ActivationMode) to all of the values + // held on the device in 'input_data', whose dimensions are described by + // 'dimensions'. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'activate' operation + // should be enqueued onto. + // activation_mode: Type of activation to perform. + // input_data: un-owned device memory region which contains the + // activate input. + // output_data: un-owned device memory region in which to place the + // activate result. + virtual bool DoActivate(Stream* stream, ActivationMode activation_mode, + const BatchDescriptor& dimensions, + const DeviceMemory& input_data, + DeviceMemory* output_data, uint64_t options) { + return false; + } + + // Concatenates several layers into one, by concatenating the depth of each + // layer at matching x and y coordinates. + // The inputs must all have the same width and height, the output will have + // the same width and height as the inputs and its depth will be the sum of + // the input depths. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'depth concatenate' + // operation should be enqueued onto. + // input_dimensions: The dimensions of each input. + // input_data: un-owned device memory region which contains the + // input data for each input layer. + // output_data: un-owned device memory region in which to place the + // depth concatenate result. + virtual bool DoDepthConcatenate( + Stream* stream, absl::Span input_dimensions, + absl::Span* const> input_data, + DeviceMemory* output_data) = 0; + + // Depth to space takes an X by Y image with depth D*M^2 and changes it to an + // MX x MY image with depth D. Each input location (x,y) with depth D*M^2 in + // the input image is changed to an MxM contiguous area in the output image, + // with the values being laid out in the raster order by DepthToSpaceLayout, + // and will have a new depth of D. + // + // Example. + // M=2, Din =8, Xin=2, Yin=2. Xout=4, Yout=4, Dout=2 + // DepthHeightWidth layout + // Values within a 'cell' are at different depths and same x & y. + // Input: + // abcdefgh ijklmnop + // qrstuvwx yz012345 + // Output: + // ae bf im jn + // cg dh ko lp + // qu rv y2 z3 + // sw tx 04 15 + // + // sqrt_depth_reduction: 'M' in the comment above + virtual bool DoDepthToSpace(Stream* stream, + const dnn::BatchDescriptor& input_dimensions, + const DeviceMemory& input_data, + const DepthToSpaceLayout& depth_to_space_layout, + const int& sqrt_depth_reduction, + DeviceMemory* output_data) { + return false; + } + + // Computes the specified operation (e.g. addition or multiplication) + // between corresponding elements in the inputs and stores the result in the + // output element. + // The inputs and output must all have the same dimensions, but may have + // different quantization parameters (min_value and max_value). + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // operation: The operation to perform. + // input_dimensions: The dimensions of each input. + // input_data: un-owned device memory region which contains the + // input data for each input layer. + // output_dimensions: The dimensions of the output. + // output_data: un-owned device memory region in which to place the + // operation result. + virtual bool DoElementwiseOperate( + Stream* stream, ElementwiseOperation operation, + absl::Span input_dimensions, + absl::Span* const> input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) = 0; + + // Computes the specified operation (e.g. addition or multiplication) + // between corresponding elements in the inputs and stores the result in the + // output element. Each input is multiplied by a scalar constant and the + // result is divided by a scalar constant. + // e.g. To perform Z = 0.9*X + 1.1*Y, set the input multiplicands to 9 and 11 + // and the output divisor to 10. + // The inputs and output must all have the same dimensions, but may have + // different quantization parameters (min_value and max_value). + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // operation: The operation to perform. + // input_multiplicands: Amount to scale each input. + // output_divisor: Amount to divide the output. + // input_dimensions: The dimensions of each input. + // input_data: un-owned device memory region which contains the + // input data for each input layer. + // output_dimensions: The dimensions of the output. + // output_data: un-owned device memory region in which to place the + // operation result. + virtual bool DoElementwiseOperateScaledQuantized( + Stream* stream, ElementwiseOperation operation, + absl::Span input_multiplicands, int output_divisor, + absl::Span input_dimensions, + absl::Span* const> input_data, + const dnn::BatchDescriptor& output_dimensions, + DeviceMemory* output_data) { + return false; + } + + // Pads the input with zeros in the X and Y dimensions. The feature_map + // dimension is unchanged. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // dimensions: The dimensions of the input. + // input_data: un-owned device memory region which contains the + // input data for the input layer. + // left_pad: Amount to pad the input on the left. + // right_pad: Amount to pad the input on the right. + // top_pad: Amount to pad the input at the top (low Y). + // bottom_pad: Amount to pad the input at the bottom (high Y). + // output_data: un-owned device memory region in which to place the + // padded result. + virtual bool DoXYPad(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, int64_t left_pad, + int64_t right_pad, int64_t top_pad, int64_t bottom_pad, + DeviceMemory* output_data) = 0; + + // Extracts a slice of the input in the X and Y dimensions. The feature_map + // dimension is unchanged. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // dimensions: The dimensions of the input. + // input_data: un-owned device memory region which contains the + // input data for the input layer. + // left_trim: Amount to cut off the input on the left. + // right_trim: Amount to cut off the input on the right. + // top_trim: Amount to cut off the input at the top (low y). + // bottom_trim: Amount to cut off the input at the bottom (high Y). + // output_data: un-owned device memory region in which to place the + // padded result. + virtual bool DoXYSlice(Stream* stream, const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + int64_t left_trim, int64_t right_trim, + int64_t top_trim, int64_t bottom_trim, + DeviceMemory* output_data) = 0; + + // Grows the input tensor by replicating the X and Y dimensions. The batch and + // depth/feature_map dimensions are unchanged. Currently, the input tensor is + // limited to X=1 and Y=1. + // + // For example, the input has dimensions x=2, y=3, and replicate_x=3, + // replicate_y=2. The diagonal elements of the output would be: [x0y0, x1y1, + // x0y2, x1y0, x0y1, x1y2]. + // Here is the example as a picture. input: + // AB + // CD + // EF + // broadcast result: + // ABABAB + // CDCDCD + // EFEFEF + // ABABAB + // CDCDCD + // EFEFEF + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'elementwise operation' + // should be enqueued onto. + // dimensions: The dimensions of the input. + // input_data: un-owned device memory region which contains the + // input data for the input layer. + // replicate_x: Amount to replicate the input's X dimension. + // replicate_y: Amount to replicate the input's Y dimension. + // output_data: un-owned device memory region in which to place the + // padded result. + virtual bool DoXYBroadcast(Stream* stream, + const dnn::BatchDescriptor& dimensions, + const DeviceMemory& input_data, + int64_t replicate_x, int64_t replicate_y, + DeviceMemory* output_data) { + return false; + } + + // Enqueues an asynchronous memcpy of the *quantized* output of a layer (that + // is, bytes instead of scaled floats) into 'host_dst' if they are available + // for the underlying DNN implementation. If this quantized output is not + // available, false is returned, which will place 'stream' into an error + // state. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'quantized memcpy' + // operation should be enqueued onto. + // gpu_unquantized_src: the device memory that contains the unquantized data + // -- this data should also have a corresponding quantized representation + // on the device for this operation to succeed. + // mode: Type of quantization of the data to write into host_dst. + // host_dst: un-owned host memory region that is mutated in place, + // it is clobbered by the values in 'gpu_unquantized_src' when the enqueued + // (asynchronous) memcpy operation is performed. + // size: size in bytes of the host_dst host memory region. + virtual bool DoMemcpyD2HQuantized( + Stream* stream, const DeviceMemory& gpu_unquantized_src, + QuantizedActivationMode mode, void* host_dst, int64_t size) = 0; + + // Enqueues an asynchronous memcpy of 'host_dst' into the *quantized* input + // of a layer (that is, bytes instead of scaled floats) if they are supported + // by the underlying DNN implementation. If this quantized input is not + // supported, false is returned, which will place 'stream' into an error + // state. + // + // Arguments (all borrowed): + // stream: borrowed pointer to the stream that the 'quantized memcpy' + // operation should be enqueued onto. + // host_src: un-owned host memory region that contains the quantized data. + // size: size in bytes of the host_src host memory region. + // mode: Type of quantization of the data to read from host_src. + // gpu_unquantized_dst: the device memory that is clobbered by the values in + // 'host_src' when the enqueued (asynchronous) memcpy operation is + // performed. -- this data should also have a corresponding quantized + // representation on the device for this operation to + // succeed. + virtual bool DoMemcpyH2DQuantized( + Stream* stream, const void* host_src, int64_t size, + QuantizedActivationMode mode, + DeviceMemory* gpu_unquantized_dst) = 0; + + // Create an RNN descriptor based on model shapes and configurations. + // The caller retains the ownership of the descriptor. + // + // Arguments: + // num_layers: the number of layers for a RNN model. + // hidden_size: the size of the hidden state. + // input_size: the size of the input state. + // cell_size: the size of the cell state + // input_mode: an enum to specify whether a linear transformation is added + // after the input state. If input_size is different from hidden_size, this + // is required. + // direction_mode: an enum to specify whether this model is unidirectional or + // bidirectional. + // rnn_mode: an enum to specify the type of model to build. + // data_type: an enum to specify the data types used in this model. + // dropout: the dropout threshold between layers. When it is 0., no dropout + // is added. + // seed: a seed for initializing the dropout layers. + // state_allocator: an memory allocator that will be used to store the state + // for dropout layer. The user has to maintain the memory until the model + // is no longer in use. + // use_padded_io: a bool to specify whether the input is using padded IO. + virtual tsl::StatusOr> + createRnnDescriptor(int num_layers, int hidden_size, int input_size, + int cell_size, int batch_size, + dnn::RnnInputMode input_mode, + dnn::RnnDirectionMode direction_mode, + dnn::RnnMode rnn_mode, dnn::DataType data_type, + const dnn::AlgorithmConfig& algorithm_config, + const NumericOptions& numeric_options, float dropout, + uint64_t seed, ScratchAllocator* state_allocator, + bool use_padded_io) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnDescriptor is unimplemented"); + } + + // Create a RNN sequence descriptor that specifies either the input or output + // sequence. The caller retains the ownership of the returned descriptor. + // + // Arguments: + // max_seq_length: the max length of the sequences. + // batch_size: the size of a minibatch. + // data_size: the size of the state. + // seq_lengths: the lengths of sequences in a batch. + // data_type: an enum to specify the type for the underlying data. + virtual tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, dnn::DataType data_type) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnSequenceTensorDescriptor is unimplemented"); + } + + virtual tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + const absl::Span& seq_lengths, + bool time_major, dnn::DataType data_type) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnSequenceTensorDescriptor is unimplemented"); + } + + // Create an RNN state descriptor that specifies the input or hidden state. + // The caller retains the ownership of the returned descriptor. + virtual tsl::StatusOr> + createRnnStateTensorDescriptor(int num_layer, int batch_size, int data_size, + dnn::DataType data_type) { + return tsl::Status(absl::StatusCode::kUnimplemented, + "createRnnStateTensorDescriptor is unimplemented"); + } + + // Enqueue a forward operation of the RNN model onto the stream. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // rnn_desc: a RNN descriptor created by createRnnDescriptor. + // input_desc: descriptor for the input sequence. + // input_data: the device memory region that contains the input data. + // input_h_desc: descriptor for the input "h" state. + // input_h_data: the device memory region that contains the input "h" data. + // input_c_desc: descriptor for the input "c" state. + // input_c_data: the device memory region that contains the input "c" data. + // This must be specified for LSTM models. + // params: the device memory region that contains the parameters used in this + // model. + // output_desc: descriptor for the output sequence. + // output_data: the memory region that stores the output sequence data. + // output_h_desc: descriptor for the output "h" state. + // output_h_data: the memory region that stores the output "h" data. + // output_c_desc: descriptor for the output "c" state. + // output_c_data: the memory region that stores the output "c" data. This + // must be specified for LSTM models. + // is_training: whether this is used in training or inference. That decides + // whether respace_space data need to be produced. + // reserve_space_allocator: if "is_training" is true, an memory allocator + // to create memory that holds the produced reserve_space. The caller is + // retains the data and feed it to the backward pass. + // workspace_allocator: an allocator to create temporary workspace used in + // this kernel. The caller is responsible for retaining the memory long + // enough for the lifespan of this operation, and recycles afterwards. + virtual bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, + bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, + bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnForward(Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + DeviceMemory* output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + DeviceMemory* output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + DeviceMemory* output_c_data, + bool is_training, + ScratchAllocator* reserve_space_allocator, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + // Enqueue a backward operation of the RNN model onto the stream. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // rnn_desc: a RNN descriptor created by createRnnDescriptor. + // input_desc: descriptor for the input sequence. + // input_data: the device memory region that contains the input data. + // input_h_desc: descriptor for the input "h" state. + // input_h_data: the device memory region that contains the input "h" data. + // input_c_desc: descriptor for the input "c" state. + // input_c_data: the device memory region that contains the input "c" data. + // This must be specified for LSTM models. + // params: the device memory region that contains the parameters used in this + // model. + // output_desc: descriptor for the output sequence. + // output_data: the memory region that stores the output sequence data. + // output_h_desc: descriptor for the output "h" state. + // output_h_data: the memory region that stores the output "h" data. + // output_c_desc: descriptor for the output "c" state. + // output_c_data: the memory region that stores the output "c" data. This + // must be specified for LSTM models. + // output_backprop_data: the device memory region that contains the backprop + // to the output sequence. + // output_h_backprop_data: the device memory region that contains the + // backprop to the output "h" state. + // output_c_backprop_data: the device memory region that contains the + // backprop to the output "c" state. + // input_backprop_data: the device memory region that stores the backprop + // to the input sequence. + // input_h_backprop_data: the device memory region that stores the backprop + // to the input "h" state. + // input_c_backprop_data: the device memory region that stores the backprop + // to the input "c" state. + // params_backprop_data: the device memory region that stores the backprop + // to the parameters. + // reserve_space_data: the reserve_space data that is produced by the forward + // operation. This memory region could be modified by this operation. + // workspace_allocator: a memory allocator that creates the temporary + // workspace memory used by this operation. The caller is responsible for + // keeping the memory alive long enough for this operation, and recylces + // afterwards. + virtual bool DoRnnBackward( + Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnBackward( + Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + virtual bool DoRnnBackward( + Stream* stream, const dnn::RnnDescriptor& rnn_desc, + const dnn::RnnSequenceTensorDescriptor& input_desc, + const DeviceMemory& input_data, + const DeviceMemory& seq_lengths_data, + const dnn::RnnStateTensorDescriptor& input_h_desc, + const DeviceMemory& input_h_data, + const dnn::RnnStateTensorDescriptor& input_c_desc, + const DeviceMemory& input_c_data, + const DeviceMemory& params, + const dnn::RnnSequenceTensorDescriptor& output_desc, + const DeviceMemory& output_data, + const dnn::RnnStateTensorDescriptor& output_h_desc, + const DeviceMemory& output_h_data, + const dnn::RnnStateTensorDescriptor& output_c_desc, + const DeviceMemory& output_c_data, + const DeviceMemory& output_backprop_data, + const DeviceMemory& output_h_backprop_data, + const DeviceMemory& output_c_backprop_data, + DeviceMemory* input_backprop_data, + DeviceMemory* input_h_backprop_data, + DeviceMemory* input_c_backprop_data, + DeviceMemory* params_backprop_data, + DeviceMemory* reserve_space_data, + ScratchAllocator* workspace_allocator, + dnn::ProfileResult* output_profile_result) { + return false; + } + + template + tsl::Status PrepareForCtcLoss(Stream* stream, + const RnnStateTensorDescriptor& probs_desc, + DeviceMemory probs_data, + const RnnStateTensorDescriptor& grads_desc, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions& numeric_options, + ScratchAllocator* workspace_allocator, + DeviceMemory* scratch_memory, + int* ctc_loss_algo_id) { + return DoPrepareForCtcLoss( + stream, ToDataType::value, probs_desc, grads_desc, + labels_data, labels_lengths_data, input_lengths_data, numeric_options, + workspace_allocator, scratch_memory, ctc_loss_algo_id); + } + + // Enqueue a CTC Loss operation onto the stream. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // element_type: date type of the input tensors + // probs_desc: specifies the shape and the data layout of the input tensor. + // probs_data: the device memory region that contains the input tensor. + // labels_data: the device memory region that contains the labels_value + // tensor. + // labels_lengths_data: the device memory region that contains the + // labels_lengths tensor + // input_lengths_data: the device memory region that contains the seq_lengths + // tensor + // costs_data: the device memory region that contains the costs tensor. + // grads_desc: specifies the shape and the data layout of the grads tensor. + // grads_data: the device memory region that contains the grads tensor. + // ctc_loss_desc: a CTCLoss descriptor. + // workspace_allocator: a memory allocator that creates the temporary + // workspace memory used by this operation. The caller is responsible for + // keeping the memory alive long enough for this operation, and recylces + // afterwards. + virtual tsl::Status DoCtcLoss( + Stream* stream, dnn::DataType element_type, + const RnnStateTensorDescriptor& probs_desc, + const DeviceMemoryBase probs_data, absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, DeviceMemoryBase costs_data, + const RnnStateTensorDescriptor& grads_desc, DeviceMemoryBase grads_data, + DeviceMemory scratch_memory, int ctc_loss_algo_id); + + template + bool DoCtcLoss(Stream* stream, + const dnn::RnnStateTensorDescriptor& probs_desc, + const DeviceMemory& probs_data, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + DeviceMemory* costs_data, + const dnn::RnnStateTensorDescriptor& grads_desc, + DeviceMemory* grads_data, + DeviceMemory* scratch_memory, int ctc_loss_algo_id) { + return IsStatusOk( + DoCtcLoss(stream, ToDataType::value, probs_desc, + probs_data, labels_data, labels_lengths_data, + input_lengths_data, *costs_data, grads_desc, *grads_data, + *scratch_memory, ctc_loss_algo_id), + false); + } + + // Transforms a tensor into another tensor with a different layout and/or data + // type. + // + // Arguments: + // stream: pointer to the stream where this operation should be enqueued to. + // input_desc: specifies the shape and the data layout of the input tensor. + // input_type: the data type of the input tensor. + // input_data: the device memory region that contains the input tensor. + // output_desc: specifies the shape and the data layout of the output tensor. + // output_type: the data type of the output tensor. + // scale: an element-wise scaling factor to apply. + // output_data: the device memory region that contains the output tensor. + virtual bool DoTransformTensor(Stream* stream, + const dnn::BatchDescriptor& input_desc, + dnn::DataType input_type, + const DeviceMemoryBase& input_data, + const dnn::BatchDescriptor& output_desc, + dnn::DataType output_type, float scale, + DeviceMemoryBase* output_data) { + return false; + } + + // Notifies that a stream is being destroyed and should be invalidated from + // any internal caching. This exists to allow the CUDA implementation to + // avoid redundant cudnnSetStream calls without risking problems when a stream + // is destroyed and a new stream later created in the same memory. + virtual void NotifyStreamDestroyed(Stream* stream) {} + + protected: + // Returns whether status is 'ok', and potentially logs the error. + static bool IsStatusOk(const tsl::Status& status, bool report_error); + + private: + virtual tsl::Status DoPrepareForConvolution( + ConvolutionKind kind, DataType element_type, Stream* stream, + const BatchDescriptor& batch_descriptor, DeviceMemoryBase input_data, + const FilterDescriptor& filter_descriptor, DeviceMemoryBase filter_data, + const BatchDescriptor& output_descriptor, DeviceMemoryBase output_data, + const ConvolutionDescriptor& convolution_descriptor, + const AlgorithmConfig& algorithm_config, + ScratchAllocator* scratch_allocator, AlgorithmDesc* algorithm_desc, + DeviceMemory* scratch_memory) { + *algorithm_desc = {}; + *scratch_memory = {}; + return ::tsl::OkStatus(); + } + + virtual tsl::Status DoPrepareForCtcLoss( + Stream* stream, DataType element_type, + const RnnStateTensorDescriptor& probs_desc, + const RnnStateTensorDescriptor& grads_desc, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions& numeric_options, + ScratchAllocator* scratch_allocator, + DeviceMemory* scratch_memory, int* ctc_loss_algo_id) { + *scratch_memory = {}; + return ::tsl::OkStatus(); + } + + DnnSupport(const DnnSupport&) = delete; + void operator=(const DnnSupport&) = delete; +}; + +} // namespace dnn +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_DNN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/event.h new file mode 100644 index 0000000000000000000000000000000000000000..8721c9d53d559b512726b88e59efffa156ace847 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/event.h @@ -0,0 +1,89 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_EVENT_H_ +#define XLA_STREAM_EXECUTOR_EVENT_H_ + +#include + +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/status.h" + +namespace stream_executor { + +namespace internal { +class EventInterface; +} + +class Stream; +class StreamExecutor; + +// The Event class, when supported by a platform, enables low-overhead status +// reporting for a Stream. An Event is inserted at a location in a stream via +// the Stream::ThenRecordEvent() API. From then on, the Event's status can be +// monitored via the nonblocking Event::PollForStatus() call. +class Event { + public: + // Potential states for an Event. If PollForStatus() returns anything aside + // from kPending or kComplete, an error has occurred; kUnknown is a bad state. + // Not all implementations are able to return all enumeration values. Refer to + // the platform-specific implementation for details. + enum class Status { + kUnknown, + kError, + kPending, + kComplete, + }; + + explicit Event(StreamExecutor* stream_exec); // NOLINT + + // Releases any resources held by the Event object. + ~Event(); + + // Performs any platform-specific or potentially error-generating + // initialization. + bool Init(); + + // Returns the current Status for the event. + Status PollForStatus(); + + // Blocks `stream` on this event. `stream` is a raw platform-specific + // stream (e.g. GpuStreamHandle). + tsl::Status WaitForEventOnExternalStream(std::intptr_t stream); + + // Returns a pointer to the underlying platform-specific implementation. + internal::EventInterface* implementation() { return implementation_.get(); } + + Event(Event&&); + Event& operator=(Event&&); + + private: + friend class Stream; + + // Pointer to the StreamExecutor interface used to create this object. + // Not owned. + StreamExecutor* stream_exec_; + + // Pointer to the platform-specific EventInterface implementation underlying + // the object. Owned. + std::unique_ptr implementation_; + + Event(const Event&) = delete; + void operator=(const Event&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/executor_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/executor_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..6e9668afdbf39da6f2c04cb19123c4e30dabb3d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/executor_cache.h @@ -0,0 +1,90 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_EXECUTOR_CACHE_H_ +#define XLA_STREAM_EXECUTOR_EXECUTOR_CACHE_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/node_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +// Forward declare. +class StreamExecutor; + +// Utility class to allow Platform objects to manage cached StreamExecutors. +// Thread-safe. +class ExecutorCache { + public: + using ExecutorFactory = + std::function>()>; + + ExecutorCache(); + ~ExecutorCache(); + + // Looks up 'config' in the cache. Returns a pointer to the existing executor, + // if already present, or creates it using 'factory', if it does not. + // Factories may be executed concurrently for different device ordinals. + tsl::StatusOr GetOrCreate(const StreamExecutorConfig& config, + const ExecutorFactory& factory); + + // Returns a pointer to the described executor (if one with a matching config + // has been created), or a NOT_FOUND status. + tsl::StatusOr Get(const StreamExecutorConfig& config); + + // Destroys all Executors and clears the cache. + // Performs no synchronization with the executors - undefined behavior may + // occur if any executors are active! + void DestroyAllExecutors(); + + private: + // Each Entry contains zero or more cached executors for a device ordinal. + struct Entry { + ~Entry(); + + // Mutex that guards the contents of each entry. The 'mutex_' of the + // ExecutorCache class protects both the 'cache_' and the existence of each + // Entry, but not the Entry's contents. 'configurations_mutex' protects the + // contents of the entry after 'mutex_' has been dropped. + absl::Mutex configurations_mutex; + + // Vector of cached {config, executor} pairs. + std::vector< + std::pair>> + configurations ABSL_GUARDED_BY(configurations_mutex); + }; + + // Maps ordinal number to a list of cached executors for that ordinal. + // We key off of ordinal (instead of just looking up all fields in the + // StreamExecutorConfig) for a slight improvement in lookup time. + absl::Mutex mutex_; + absl::node_hash_map cache_ ABSL_GUARDED_BY(mutex_); + + ExecutorCache(const ExecutorCache&) = delete; + void operator=(const ExecutorCache&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_EXECUTOR_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/fft.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/fft.h new file mode 100644 index 0000000000000000000000000000000000000000..88a383b84cb1e74e762260fe54fbc803546ef4a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/fft.h @@ -0,0 +1,270 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Exposes the family of FFT routines as pre-canned high performance calls for +// use in conjunction with the StreamExecutor abstraction. +// +// Note that this interface is optionally supported by platforms.. +// +// This abstraction makes it simple to entrain FFT operations on GPU data into +// a Stream -- users typically will not use this API directly, but will use the +// Stream builder methods to entrain these operations "under the hood". For +// example: +// +// DeviceMemory> x = +// stream_exec->AllocateArray>(1024); +// DeviceMemory> y = +// stream_exec->AllocateArray>(1024); +// // ... populate x and y ... +// Stream stream{stream_exec}; +// std::unique_ptr plan = +// stream_exec.AsFft()->Create1dPlan(&stream, 1024, Type::kC2CForward); +// stream +// .Init() +// .ThenFft(plan.get(), x, &y); +// TF_CHECK_OK(stream.BlockHostUntilDone()); +// +// By using stream operations in this manner the user can easily intermix custom +// kernel launches (via StreamExecutor::ThenLaunch()) with these pre-canned FFT +// routines. + +#ifndef XLA_STREAM_EXECUTOR_FFT_H_ +#define XLA_STREAM_EXECUTOR_FFT_H_ + +#include +#include + +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class Stream; +template +class DeviceMemory; +class ScratchAllocator; + +namespace fft { + +// Specifies FFT input and output types, and the direction. +// R, D, C, and Z stand for SP real, DP real, SP complex, and DP complex. +enum class Type { + kInvalid, + kC2CForward, + kC2CInverse, + kC2R, + kR2C, + kZ2ZForward, + kZ2ZInverse, + kZ2D, + kD2Z +}; + +// FFT plan class. Each FFT implementation should define a plan class that is +// derived from this class. It does not provide any interface but serves +// as a common type that is used to execute the plan. +class Plan { + public: + virtual ~Plan() {} +}; + +// FFT support interface -- this can be derived from a GPU executor when the +// underlying platform has an FFT library implementation available. See +// StreamExecutor::AsFft(). +// +// This support interface is not generally thread-safe; it is only thread-safe +// for the CUDA platform (cuFFT) usage; host side FFT support is known +// thread-compatible, but not thread-safe. +class FftSupport { + public: + virtual ~FftSupport() {} + + // Creates a 1d FFT plan. + virtual std::unique_ptr Create1dPlan(Stream *stream, uint64_t num_x, + Type type, bool in_place_fft) = 0; + + // Creates a 2d FFT plan. + virtual std::unique_ptr Create2dPlan(Stream *stream, uint64_t num_x, + uint64_t num_y, Type type, + bool in_place_fft) = 0; + + // Creates a 3d FFT plan. + virtual std::unique_ptr Create3dPlan(Stream *stream, uint64_t num_x, + uint64_t num_y, uint64 num_z, + Type type, bool in_place_fft) = 0; + + // Creates a 1d FFT plan with scratch allocator. + virtual std::unique_ptr Create1dPlanWithScratchAllocator( + Stream *stream, uint64_t num_x, Type type, bool in_place_fft, + ScratchAllocator *scratch_allocator) = 0; + + // Creates a 2d FFT plan with scratch allocator. + virtual std::unique_ptr Create2dPlanWithScratchAllocator( + Stream *stream, uint64_t num_x, uint64 num_y, Type type, + bool in_place_fft, ScratchAllocator *scratch_allocator) = 0; + + // Creates a 3d FFT plan with scratch allocator. + virtual std::unique_ptr Create3dPlanWithScratchAllocator( + Stream *stream, uint64_t num_x, uint64 num_y, uint64 num_z, Type type, + bool in_place_fft, ScratchAllocator *scratch_allocator) = 0; + + // Creates a batched FFT plan. + // + // stream: The GPU stream in which the FFT runs. + // rank: Dimensionality of the transform (1, 2, or 3). + // elem_count: Array of size rank, describing the size of each dimension. + // input_embed, output_embed: + // Pointer of size rank that indicates the storage dimensions + // of the input/output data in memory. If set to null_ptr all + // other advanced data layout parameters are ignored. + // input_stride: Indicates the distance (number of elements; same below) + // between two successive input elements. + // input_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the input data. + // output_stride: Indicates the distance between two successive output + // elements. + // output_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the output data. + virtual std::unique_ptr CreateBatchedPlan( + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, + uint64_t output_stride, uint64 output_distance, Type type, + bool in_place_fft, int batch_count) = 0; + + // Creates a batched FFT plan with scratch allocator. + // + // stream: The GPU stream in which the FFT runs. + // rank: Dimensionality of the transform (1, 2, or 3). + // elem_count: Array of size rank, describing the size of each dimension. + // input_embed, output_embed: + // Pointer of size rank that indicates the storage dimensions + // of the input/output data in memory. If set to null_ptr all + // other advanced data layout parameters are ignored. + // input_stride: Indicates the distance (number of elements; same below) + // between two successive input elements. + // input_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the input data. + // output_stride: Indicates the distance between two successive output + // elements. + // output_distance: Indicates the distance between the first element of two + // consecutive signals in a batch of the output data. + virtual std::unique_ptr CreateBatchedPlanWithScratchAllocator( + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, + uint64_t output_stride, uint64 output_distance, Type type, + bool in_place_fft, int batch_count, + ScratchAllocator *scratch_allocator) = 0; + + // Updates the plan's work area with space allocated by a new scratch + // allocator. This facilitates plan reuse with scratch allocators. + // + // This requires that the plan was originally created using a scratch + // allocator, as otherwise scratch space will have been allocated internally + // by cuFFT. + virtual void UpdatePlanWithScratchAllocator( + Stream *stream, Plan *plan, ScratchAllocator *scratch_allocator) = 0; + + // Computes complex-to-complex FFT in the transform direction as specified + // by direction parameter. + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output) = 0; + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output) = 0; + + // Computes real-to-complex FFT in forward direction. + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory &input, + DeviceMemory> *output) = 0; + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory &input, + DeviceMemory> *output) = 0; + + // Computes complex-to-real FFT in inverse direction. + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output) = 0; + virtual bool DoFft(Stream *stream, Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output) = 0; + + protected: + FftSupport() {} + + private: + FftSupport(const FftSupport &) = delete; + void operator=(const FftSupport &) = delete; +}; + +// Macro used to quickly declare overrides for abstract virtuals in the +// fft::FftSupport base class. Assumes that it's emitted somewhere inside the +// ::stream_executor namespace. +#define TENSORFLOW_STREAM_EXECUTOR_GPU_FFT_SUPPORT_OVERRIDES \ + std::unique_ptr Create1dPlan(Stream *stream, uint64_t num_x, \ + fft::Type type, bool in_place_fft) \ + override; \ + std::unique_ptr Create2dPlan(Stream *stream, uint64_t num_x, \ + uint64_t num_y, fft::Type type, \ + bool in_place_fft) override; \ + std::unique_ptr Create3dPlan( \ + Stream *stream, uint64_t num_x, uint64 num_y, uint64 num_z, \ + fft::Type type, bool in_place_fft) override; \ + std::unique_ptr Create1dPlanWithScratchAllocator( \ + Stream *stream, uint64_t num_x, fft::Type type, bool in_place_fft, \ + ScratchAllocator *scratch_allocator) override; \ + std::unique_ptr Create2dPlanWithScratchAllocator( \ + Stream *stream, uint64_t num_x, uint64 num_y, fft::Type type, \ + bool in_place_fft, ScratchAllocator *scratch_allocator) override; \ + std::unique_ptr Create3dPlanWithScratchAllocator( \ + Stream *stream, uint64_t num_x, uint64 num_y, uint64 num_z, \ + fft::Type type, bool in_place_fft, ScratchAllocator *scratch_allocator) \ + override; \ + std::unique_ptr CreateBatchedPlan( \ + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, \ + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, \ + uint64_t output_stride, uint64 output_distance, fft::Type type, \ + bool in_place_fft, int batch_count) override; \ + std::unique_ptr CreateBatchedPlanWithScratchAllocator( \ + Stream *stream, int rank, uint64_t *elem_count, uint64 *input_embed, \ + uint64_t input_stride, uint64 input_distance, uint64 *output_embed, \ + uint64_t output_stride, uint64 output_distance, fft::Type type, \ + bool in_place_fft, int batch_count, ScratchAllocator *scratch_allocator) \ + override; \ + void UpdatePlanWithScratchAllocator(Stream *stream, fft::Plan *plan, \ + ScratchAllocator *scratch_allocator) \ + override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory &input, \ + DeviceMemory> *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory *output) override; \ + bool DoFft(Stream *stream, fft::Plan *plan, \ + const DeviceMemory> &input, \ + DeviceMemory *output) override; + +} // namespace fft +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_FFT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/asm_compiler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/asm_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..0e15e326ca23e5ca7eb086065c42ee12c0c9def2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/asm_compiler.h @@ -0,0 +1,143 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_ASM_COMPILER_H_ +#define XLA_STREAM_EXECUTOR_GPU_ASM_COMPILER_H_ + +#include +#include +#include +#include + +#include "absl/base/const_init.h" +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/platform/statusor.h" +#if GOOGLE_CUDA +#include "xla/stream_executor/cuda/cuda_driver.h" +#endif // GOOGLE_CUDA + +namespace stream_executor { +namespace gpu { +class GpuContext; +} + +// Compiles the given PTX string using ptxas and returns the resulting machine +// code (i.e. a cubin) as a byte array. The generated cubin matches the compute +// capabilities of the device associated with 'device_ordinal'. +// +// 'options' is used to query for the CUDA location in case it is +// customized in a passed flag, and for controlling ptxas optimizations. +tsl::StatusOr> CompileGpuAsm(int device_ordinal, + const char* ptx_contents, + GpuAsmOpts options); + +// Compiles the given PTX string using ptxas and returns the resulting machine +// code (i.e. a cubin) as a byte array. The generated cubin matches the compute +// capabilities provided by 'cc_major' and 'cc_minor'. +// +// 'options' is used to query for the CUDA location in case it is +// customized in a passed flag, and for controlling ptxas optimizations. +tsl::StatusOr> CompileGpuAsm( + int cc_major, int cc_minor, const char* ptx_contents, GpuAsmOpts options, + bool cancel_if_reg_spill = false); + +// Same as CompileGpuAsm, but caches the result, and returns unowned view of +// the compiled binary. +// +// A copy of the string provided in ptx will be made. +tsl::StatusOr> CompileGpuAsmOrGetCached( + int device_ordinal, const char* ptx, GpuAsmOpts compilation_options); + +struct CubinOrPTXImage { + std::string profile; + std::vector bytes; +}; + +// Bundles the GPU machine code (cubins) and PTX if requested and returns the +// resulting binary (i.e. a fatbin) as a byte array. +tsl::StatusOr> BundleGpuAsm( + std::vector images, GpuAsmOpts options); + +struct HsacoImage { + std::string gfx_arch; + std::vector bytes; +}; + +// Bundles the GPU machine code (HSA Code Object) and returns the resulting +// binary (i.e. a fatbin) as a byte array. +tsl::StatusOr> BundleGpuAsm( + std::vector images, const std::string rocm_root_dir); + +// Links multiple relocatable GPU images (e.g. results of ptxas -c) into a +// single image. +tsl::StatusOr> LinkGpuAsm( + gpu::GpuContext* context, std::vector images); + +tsl::StatusOr> LinkUsingNvlink( + absl::string_view preferred_cuda_dir, gpu::GpuContext* context, + std::vector images); + +std::string FindCudaExecutable(const std::string& binary_name, + const std::string& preferred_cuda_dir); + +// Runs tool --version and parses its version string. +tsl::StatusOr> GetToolVersion( + absl::string_view tool_path); + +// On NVIDIA GPUs, returns the CUDA toolkit version supported by the driver, +tsl::StatusOr> GetAsmCompilerVersion( + const std::string& preferred_cuda_dir); + +#if GOOGLE_CUDA +// Maintains a cache of pointers to loaded kernels +template +tsl::StatusOr>> LoadKernelOrGetPtr( + StreamExecutor* executor, absl::string_view kernel_name, + absl::string_view ptx, absl::Span cubin_data) { + using KernelPtrCacheKey = + std::tuple; + + static absl::Mutex kernel_ptr_cache_mutex(absl::kConstInit); + static auto& kernel_ptr_cache ABSL_GUARDED_BY(kernel_ptr_cache_mutex) = + *new absl::flat_hash_map>>(); + CUcontext current_context = cuda::CurrentContextOrDie(); + KernelPtrCacheKey kernel_ptr_cache_key{current_context, kernel_name, ptx}; + absl::MutexLock lock(&kernel_ptr_cache_mutex); + + auto it = kernel_ptr_cache.find(kernel_ptr_cache_key); + if (it == kernel_ptr_cache.end()) { + TF_ASSIGN_OR_RETURN( + std::shared_ptr> loaded, + executor->CreateTypedKernel(kernel_name, ptx, cubin_data)); + it = + kernel_ptr_cache.emplace(kernel_ptr_cache_key, std::move(loaded)).first; + } + + CHECK(it != kernel_ptr_cache.end()); + return it->second; +} +#endif // GOOGLE_CUDA + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_ASM_COMPILER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_activation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_activation.h new file mode 100644 index 0000000000000000000000000000000000000000..385644d7ac197529765e8058dcce2660f3af169c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_activation.h @@ -0,0 +1,60 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file contains APIs that assume a StreamExecutor is backed by CUDA. +// It reaches into the CUDA implementation to activate an underlying CUDA +// context. +// +// Having this file separate from gpu/gpu_executor.h means that dependent +// code does not also have to depend on cuda.h. + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_ACTIVATION_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_ACTIVATION_H_ + +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class StreamExecutor; + +namespace gpu { + +class GpuExecutor; +class ScopedActivateContext; + +// Activates a CUDA context within an enclosing scope. +class ScopedActivateExecutorContext { + public: + // Form that takes a CUDA executor implementation. + explicit ScopedActivateExecutorContext(GpuExecutor* gpu_exec); + + // Form that takes a pImpl executor and extracts a CUDA implementation -- + // fatal failure if it is not CUDA inside. + explicit ScopedActivateExecutorContext(StreamExecutor* stream_exec); + + ~ScopedActivateExecutorContext(); + + private: + // The cuda.h-using datatype that we wrap. + ScopedActivateContext* driver_scoped_activate_context_; + + ScopedActivateExecutorContext(const ScopedActivateExecutorContext&) = delete; + void operator=(const ScopedActivateExecutorContext&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_ACTIVATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_asm_opts.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_asm_opts.h new file mode 100644 index 0000000000000000000000000000000000000000..6a10c2653e906c8340fa205996e3e24ea4d216ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_asm_opts.h @@ -0,0 +1,54 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_ASM_OPTS_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_ASM_OPTS_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/span.h" + +namespace stream_executor { +// Compilation options for compiling ptxas. +struct GpuAsmOpts { + // Disable Cuda ptxas optimizations. + bool disable_gpuasm_optimizations; + + // Cuda directory which would be searched first. + std::string preferred_cuda_dir; + + std::vector extra_flags; + + explicit GpuAsmOpts(bool disable_gpuasm_optimizations = false, + absl::string_view preferred_cuda_dir = "", + absl::Span extra_flags = {}) + : disable_gpuasm_optimizations(disable_gpuasm_optimizations), + preferred_cuda_dir(preferred_cuda_dir), + extra_flags(extra_flags.begin(), extra_flags.end()) {} + + using PtxOptionsTuple = + std::tuple>; + + PtxOptionsTuple ToTuple() { + return std::make_tuple(disable_gpuasm_optimizations, preferred_cuda_dir, + extra_flags); + } +}; +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_ASM_OPTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_command_buffer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_command_buffer.h new file mode 100644 index 0000000000000000000000000000000000000000..9b620e7bca1801f0920d627ff26727e193bd5c48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_command_buffer.h @@ -0,0 +1,112 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_COMMAND_BUFFER_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_COMMAND_BUFFER_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/gpu/gpu_executor.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/status.h" + +namespace stream_executor::gpu { + +// GpuCommandBuffer provides platform-specific CommandBufferInterface +// implementation (it's backed by CUDA or HIP graphs on NVIDIA and AMD devices). +class GpuCommandBuffer : public internal::CommandBufferInterface { + public: + GpuCommandBuffer(CommandBuffer::Mode mode, GpuExecutor* parent, + GpuGraphHandle graph); + ~GpuCommandBuffer() override; + + tsl::Status Trace(Stream* stream, + absl::AnyInvocable function) override; + + tsl::Status Launch(const ThreadDim& threads, const BlockDim& blocks, + const KernelBase& kernel, + const KernelArgsArrayBase& args) override; + + tsl::Status MemcpyDeviceToDevice(DeviceMemoryBase* dst, + const DeviceMemoryBase& src, + uint64_t size) override; + + tsl::Status Finalize() override; + tsl::Status Update() override; + + GpuGraphExecHandle executable() const { return exec_; } + + CommandBuffer::Mode mode() const override { return mode_; } + CommandBuffer::State state() const override { return state_; } + + // We track the total number of allocated and alive executable graphs in the + // process to track the command buffers resource usage. Executable graph + // allocates resources on a GPU devices (rule of thumb is ~8kb per node), so + // we have to be careful not to keep too many of them alive for too long, or + // we have a higher risk of OOM errors. + // + // TODO(ezhulenev): We need to have a policy for how to evict unused + // executable graph instances from a device, currently lifetime of an + // executable graph is tied to a parent command buffer, and we can have + // thousands of command buffers alive at the same time. + static int64_t AllocatedExecs(); + static int64_t AliveExecs(); + + static const GpuCommandBuffer* Cast(const CommandBuffer* command_buffer) { + return static_cast( + command_buffer->implementation()); + } + + private: + // Returns OK status if command buffer is not finalized and it is still + // possible to add new commands to it, otherwise returns internal error. + tsl::Status CheckNotFinalized(); + + static_assert(std::is_pointer_v, + "GpuGraphHandle must be a pointer"); + static_assert(std::is_pointer_v, + "GpuGraphExecHandle must be a pointer"); + static_assert(std::is_pointer_v, + "GpuGraphNodeHandle must be a pointer"); + + CommandBuffer::Mode mode_; + CommandBuffer::State state_ = CommandBuffer::State::kCreate; + + GpuExecutor* parent_; // not owned, must outlive *this + GpuGraphHandle graph_ = nullptr; // owned handle + GpuGraphExecHandle exec_ = nullptr; // owned handle + + // Handles to graph nodes corresponding to command buffer commands. Owned by + // the `graph_` instance. + std::vector nodes_; + + // When command buffer is in update state this index will point to the graph + // node inside `nodes_` that will be updated next. + int64_t node_update_idx_ = 0; + + // Track the number of command buffer updates for debugging. + int64_t num_updates_ = 0; +}; + +} // namespace stream_executor::gpu + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_COMMAND_BUFFER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..c428132d74aa9367deb6c158b3c9d62a6a1501ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_cudamallocasync_allocator.h @@ -0,0 +1,142 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_CUDAMALLOCASYNC_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_CUDAMALLOCASYNC_ALLOCATOR_H_ + +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" +#include "tsl/platform/macros.h" +#include "tsl/platform/mutex.h" + +#if GOOGLE_CUDA +#include "third_party/gpus/cuda/include/cuda.h" + +#define TF_CUDA_MALLOC_ASYNC_SUPPORTED CUDA_VERSION >= 11020 +#endif // GOOGLE_CUDA + + +namespace stream_executor { + +// An allocator that wraps cudaMallocAsync. It has fewer fragmentation +// issues then the BFC memory allocator. The compute-sanitizer tool +// helps to detect OOB memory errors when using cudaMallocAsync. Use +// the environment variable `TF_GPU_ALLOCATOR=cuda_malloc_async` to +// enable it. +// +// It needs CUDA 11.2+. When using a container, this only needs the +// container driver to be 11.2. It has a WAR again a driver bug in +// multi-GPU setup with CUDA 11.2. The WAR creates an extra context on +// GPU 0. +// +// We configure cudaMallocAsync to grow when more memory is needed +// instead of preallocating everything up front and to keep a local +// pool up to pool_size bytes that is never released to other processes. +// So no other process will "steal" the GPU memory already used by the +// current process. This is to speed up execution and prevent crashes +// of long-running jobs. Use `reserve_memory=true` if you want to +// preallocate the full pool_size. You can also use the environment +// variable `TF_CUDA_MALLOC_ASYNC_SUPPORTED_PREALLOC=nb_bytes` to preallocate +// that amount of memory. `TF_CUDA_MALLOC_ASYNC_SUPPORTED_PREALLOC=-1` is a +// special value that preallocate all what the BFC memory allocator +// would have allocated. This is useful when benchmarking as it doesn't +// change when driver allocations are done. +// +// Here, the pool_size isn't the absolute max as for [Gpu]BFCAllocator. +// The pool can grow above that up to the total GPU memory. But the +// driver can return the excess memory to other processes. +class GpuCudaMallocAsyncAllocator : public tsl::Allocator { + public: + explicit GpuCudaMallocAsyncAllocator(tsl::PlatformDeviceId platform_device_id, + size_t pool_size, + bool reserve_memory = false, + bool compute_stats = true); + ~GpuCudaMallocAsyncAllocator() override; + std::string Name() override { return name_; } + void* AllocateRaw(size_t alignment, + size_t num_bytes) override ABSL_NO_THREAD_SAFETY_ANALYSIS; + void DeallocateRaw(void* ptr) override ABSL_NO_THREAD_SAFETY_ANALYSIS; + + bool TracksAllocationSizes() const override; + + size_t RequestedSize(const void* ptr) const override; + + size_t AllocatedSize(const void* ptr) const override; + + std::optional GetStats() override; + + bool ClearStats() override; + + void SetStreamAndPreallocateMemory(void* stream) override; + + // With the right VLOG set, it prints: + // - the number of ptr currently allocated per size (histogram). + // - each ptr value and its size. + // - If CUDA_VERSION >= 11030, print cudaMallocAsync statistics. + void PrintAllocatorStatistics(); + + static int GetInstantiatedCountTestOnly() { return number_instantiated_; } + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kDevice; + } + + private: + void PrintAllocatorStatisticsNoLock() ABSL_EXCLUSIVE_LOCKS_REQUIRED(lock_); + +#if TF_CUDA_MALLOC_ASYNC_SUPPORTED + StreamExecutor* stream_exec_; // Not owned. + + // cudaMallocAsync is stream aware. But TF StreamExecutor use only 1 + // compute stream and already synchronize with the h2d, d2h and d2d + // stream. So we do not need to ask cudaMallocAsync to add extra + // synchronization. + // Not owned. + CUstream cuda_stream_; + + // Not owned. The default pool of the associated GPU. + // If null, then the instanciation failed and the first allocation + // will return an error. + CUmemoryPool pool_; +#endif // TF_CUDA_MALLOC_ASYNC_SUPPORTED + + // Just a counter for the number of time this class is instantiated. + // Only useful for tests. + static std::atomic number_instantiated_; + + std::string name_; + + bool reserve_memory_; + + GpuCudaMallocAsyncAllocator(const GpuCudaMallocAsyncAllocator&) = delete; + void operator=(const GpuCudaMallocAsyncAllocator&) = delete; + + // Stats. + // Structures mutable after construction + mutable tsl::mutex lock_; + std::unique_ptr stats_ ABSL_PT_GUARDED_BY(lock_); + absl::flat_hash_map size_map_ ABSL_GUARDED_BY(lock_); +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_CUDAMALLOCASYNC_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_diagnostics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_diagnostics.h new file mode 100644 index 0000000000000000000000000000000000000000..7892a3bcf4f50830b53b94bd69614b9c0afb28dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_diagnostics.h @@ -0,0 +1,99 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_ + +#include + +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace gpu { + +// e.g. DriverVersion{346, 3, 4} +using DriverVersion = std::tuple; + +// FIXME: These functions are in stream_executor::cuda namespaces for now +// Will move to stream_executor::gpu namespace in the near future +// +//// Converts a parsed driver version to string form. +// string DriverVersionToString(DriverVersion version); +// +//// Converts a parsed driver version or status value to natural string form. +// string DriverVersionStatusToString(tsl::StatusOr version); +// +//// Converts a string of a form like "331.79" to a DriverVersion{331, 79}. +// tsl::StatusOr StringToDriverVersion(const string& value); + +class Diagnostician { + public: + // Logs diagnostic information when CUDA appears to be misconfigured (e.g. is + // not initializing). + // + // Note: if we're running on a machine that has no GPUs, we don't want to + // produce very much log spew beyond saying, "looks like there's no CUDA + // kernel + // module running". + // + // Note: we use non-Google-File:: API here because we may be called before + // InitGoogle has completed. + static void LogDiagnosticInformation(); + + // Given the driver version file contents, finds the kernel module version and + // returns it as a string. + // + // This is solely used for more informative log messages when the user is + // running on a machine that happens to have a libcuda/kernel driver mismatch. + static tsl::StatusOr FindKernelModuleVersion( + const std::string& driver_version_file_contents); + + // Extracts the kernel driver version from the current host. + static tsl::StatusOr FindKernelDriverVersion(); + + // Iterates through loaded DSOs with DlIteratePhdrCallback to find the + // driver-interfacing DSO version number. Returns it as a string. + static tsl::StatusOr FindDsoVersion(); + + // Logs information about the kernel driver version and userspace driver + // library version. + static void LogDriverVersionInformation(); + + private: + // Given the DSO version number and the driver version file contents, extracts + // the driver version and compares, warning the user in the case of + // incompatibility. + // + // This is solely used for more informative log messages when the user is + // running on a machine that happens to have a libcuda/kernel driver mismatch. + static void WarnOnDsoKernelMismatch( + tsl::StatusOr dso_version, + tsl::StatusOr kernel_version); + + // Logs information about the dev nodes present on this machine: their + // existence, permissions, accessibility from this uid/gid. + static void LogDevNodeDiagnosticInformation(); + + static std::string GetDevNodePath(int dev_node_ordinal); + + Diagnostician(const Diagnostician&) = delete; + void operator=(const Diagnostician&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_driver.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_driver.h new file mode 100644 index 0000000000000000000000000000000000000000..3895e7b0bf008c9132b85d5ce95089349cc90d39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_driver.h @@ -0,0 +1,793 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// CUDA/ROCm userspace driver library wrapper functionality. + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_DRIVER_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_DRIVER_H_ + +#include + +#include + +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/platform.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace gpu { + +// Identifies the memory space where an allocation resides. See +// GpuDriver::GetPointerMemorySpace(). +enum class MemorySpace { kHost, kDevice }; + +// Returns a casual string, such as "host" for the provided memory space. +std::string MemorySpaceString(MemorySpace memory_space); + +class GpuContext; + +// GpuDriver contains wrappers for calls to the userspace library driver. It's +// useful to isolate these calls and put basic wrappers around them to separate +// userspace library driver behaviors from the rest of the program. +// +// At the moment it's simply used as a namespace. +// +// The calls log any specific errors internally and return whether the operation +// was successful to the caller. +// +// The order of parameters is generally kept symmetric with the underlying +// CUDA/ROCm driver API. +// +// Links on functions are to specific documentation under +// http://docs.nvidia.com/cuda/cuda-driver-api/ +// https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html +// +// Thread safety: these functions should not be used from signal handlers. +class GpuDriver { + public: + // Wraps a call to cuInit/hipInit with logging to help indicate what has gone + // wrong in the case of failure. Safe to call multiple times; will be fast on + // all calls after the first. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__INITIALIZE.html#group__CUDA__INITIALIZE_1g0a2f1517e1bd8502c7194c3a8c134bc3 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#initialization + static tsl::Status Init(); + + // Returns the device associated with the given context. + // device is an outparam owned by the caller, must not be null. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g4e84b109eba36cdaaade167f34ae881e + static tsl::StatusOr DeviceFromContext(GpuContext* context); + + // Creates a new CUDA/HIP stream associated with the given context via + // cuStreamCreate/hipStreamCreateWithFlags. + // stream is an outparam owned by the caller, must not be null. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1ga581f0c5833e21ded8b5a56594e243f4 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#stream-management + static bool CreateStream(GpuContext* context, GpuStreamHandle* stream, + int priority = 0); + + // Destroys a CUDA/HIP stream associated with the given context. + // stream is owned by the caller, must not be null, and *stream is set to null + // if the stream is successfully destroyed. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g244c8833de4596bcd31a06cdf21ee758 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#stream-management + static void DestroyStream(GpuContext* context, GpuStreamHandle* stream); + + // CUDA/HIP events can explicitly disable event TSC retrieval for some + // presumed performance improvement if timing is unnecessary. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g450687e75f3ff992fe01662a43d9d3db + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + enum class EventFlags { kDefault, kDisableTiming }; + + // Creates a new event associated with the given context. + // result is an outparam owned by the caller and must not be null. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g450687e75f3ff992fe01662a43d9d3db + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + static tsl::Status InitEvent(GpuContext* context, GpuEventHandle* result, + EventFlags flags); + + // Destroys *event and turns it into a nullptr. event may not be null, but + // *event may be, via cuEventDestroy/hipEventDestroy + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g593ec73a8ec5a5fc031311d3e4dca1ef + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#event-management + static tsl::Status DestroyEvent(GpuContext* context, GpuEventHandle* event); + + // Allocates a GPU memory space of size bytes associated with the given + // context via cuMemAlloc/hipMalloc. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gb82d2a09844a58dd9e744dc31e8aa467 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void* DeviceAllocate(GpuContext* context, uint64_t bytes); + + // Deallocates a GPU memory space of size bytes associated with the given + // context via cuMemFree/hipFree. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g89b3f154e17cc89b6eea277dbdf5c93a + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void DeviceDeallocate(GpuContext* context, void* location); + + // Allocates a unified memory space of size bytes associated with the given + // context via cuMemAllocManaged. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gb347ded34dc326af404aa02af5388a32 + // (supported on CUDA only) + static void* UnifiedMemoryAllocate(GpuContext* context, uint64_t bytes); + + // Deallocates a unified memory space of size bytes associated with the given + // context via cuMemFree. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g89b3f154e17cc89b6eea277dbdf5c93a + // (supported on CUDA only) + static void UnifiedMemoryDeallocate(GpuContext* context, void* location); + + // Allocates page-locked and CUDA-registered memory on the host via + // cuMemAllocHost/hipHostMalloc. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gdd8311286d2c2691605362c689bc64e0 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void* HostAllocate(GpuContext* context, uint64_t bytes); + + // Deallocates a location created by HostAllocate, via + // cuMemFreeHost/hipHostFree. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g62e0fdbe181dab6b1c90fa1a51c7b92c + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static void HostDeallocate(GpuContext* context, void* location); + + // Registers a memory region at location of size bytes via + // cuMemHostRegister/hipHostRegister. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gf0a9fe11544326dabd743b7aa6b54223 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + static bool HostRegister(GpuContext* context, void* location, uint64_t bytes); + + // Unregisters a memory region that was previously registered at location via + // cuMemHostUnregister/hipHostUnregister. + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g63f450c8125359be87b7623b1c0b2a14 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#memory-management + // + // TODO(leary) verify an error will be returned if the location wasn't + // previously registered. + static bool HostUnregister(GpuContext* context, void* location); + + // Queries the priority range and returns the corresponding integer value via + // cuCtxGetStreamPriorityRange/hipDeviceGetStreamPriorityRange + // + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g137920ab61a71be6ce67605b9f294091 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#context-management + static int GetGpuStreamPriority( + GpuContext* context, stream_executor::StreamPriority stream_priority); + + // Virtual memory support was added to CUDA in 10.2 +#if CUDA_VERSION >= 10020 + + // Reserves a range of virtual device memory addresses via + // cuMemAddressReserve. bytes must be a multiple of the host page size. + // Returns nullptr base address in VmemSpan if the reservation fails. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1ge489256c107df2a07ddf96d80c86cd9b + struct VmemSpan { + GpuDevicePtr base; + // Size in bytes. + uint64_t size_bytes; + }; + static tsl::StatusOr ReserveVirtualMemory(GpuContext* context, + uint64_t bytes); + + // Frees a range of virtual addresses that were previously reserved through + // ReserveVirtualMemory via cuMemAddressFree. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g6993ecea2ea03e1b802b8255edc2da5b + static void FreeVirtualMemory(GpuContext* context, VmemSpan reservation); + + // Calculates the minimum alignment for memory allocations done through + // cuMemCreate via cuMemGetAllocationGranularity. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g30ee906c2cf66a0347b3dfec3d7eb31a + static tsl::StatusOr GetMinAllocationGranularity( + GpuDeviceHandle device); + + // Allocates physical memory and returns a handle that can be mapped to + // virtual addresses via cuMemCreate. bytes must be a multiple of the + // granularity returned by GetMinAllocationGranularity. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g899d69a862bba36449789c64b430dc7c + struct GenericMemoryHandle { + uint64_t handle; + uint64_t bytes; + }; + static tsl::StatusOr CreateMemoryHandle( + GpuContext* context, uint64_t bytes); + + // Frees memory represented by the provided MemoryHandle via cuMemRelease. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g3014f0759f43a8d82db951b8e4b91d68 + static void ReleaseMemoryHandle(GpuContext* context, + GenericMemoryHandle handle); + + // Maps a memory allocation handle to a reserved virtual address range via + // cuMemMap and sets the appropriate access settings via cuMemSetAccess. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1gff1d395423af5c5c75375516959dae56 + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1g1b6b12b10e8324bf462ecab4e7ef30e1 + static tsl::Status MapMemory( + GpuContext* context, GpuDevicePtr va, const GenericMemoryHandle& handle, + const std::vector& device_handles); + + // Unmaps the backing memory from the given virtual address range. This range + // must fully unmap a memory handle that was mapped using MapMemory; partial + // unmapping is not supported. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VA.html#group__CUDA__VA_1gfb50aac00c848fd7087e858f59bf7e2a + static void UnmapMemory(GpuContext* context, GpuDevicePtr va, uint64_t bytes); + +#endif // CUDA_VERSION >= 10200 + + // Given a device ordinal, returns a device handle into the device outparam, + // which must not be null. + // + // N.B. these device handles do not have a corresponding destroy function in + // the CUDA/HIP driver API. + static tsl::Status GetDevice(int device_ordinal, GpuDeviceHandle* device); + + // Given a device handle, returns the name reported by the driver for the + // device. + static tsl::Status GetDeviceName(GpuDeviceHandle device, + std::string* device_name); + + // Given a device to create a context for, returns a context handle into the + // context outparam, which must not be null. + // + // N.B. CUDA contexts are weird. They are implicitly associated with the + // calling thread. Current documentation on contexts and their influence on + // userspace processes is given here: + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g65dc0012348bc84810e2103a40d8e2cf + static tsl::Status CreateContext(int device_ordinal, GpuDeviceHandle device, + const DeviceOptions& device_options, + GpuContext** context); + + // Destroys the provided context via cuCtxDestroy. + // Don't do this while clients could still be using the context, per the docs + // bad things will happen. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g27a365aebb0eb548166309f58a1e8b8e + static void DestroyContext(GpuContext* context); + + // Returns the context handle (CUcontext for CUDA and hipCtx_t for ROCm) of a + // GpuContext. + static GpuContextHandle GetContextHandle(GpuContext* context); + + // Queries the runtime for the specified attribute of the specified function. + // cuFuncGetAttribute (the underlying CUDA driver API routine) only operates + // in terms of integer-sized values, so there's no potential for overrun (as + // of CUDA 5.5). + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1g5e92a1b0d8d1b82cb00dcfb2de15961b + static tsl::Status FuncGetAttribute(GpuFunctionAttribute attribute, + GpuFunctionHandle function, + int* attribute_value); + + // Sets the preferred cache configuration for the specified function. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1g40f8c11e81def95dc0072a375f965681 + static tsl::Status FuncSetCacheConfig(GpuFunctionHandle function, + GpuFuncCachePreference cache_config); + + // Gets the preferred shared memory bank configuration for the specified + // CONTEXT (not function!), either default or four- or eight-byte bank size. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g17153a1b8b8c756f7ab8505686a4ad74 + // https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___execution.html + static tsl::StatusOr ContextGetSharedMemConfig( + GpuContext* context); + + // Sets the preferred shared memory bank configuration for the specified + // CONTEXT (not function!), either default or four- or eight-byte bank size. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g2574235fa643f8f251bf7bc28fac3692 + // https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___execution.html + static tsl::Status ContextSetSharedMemConfig( + GpuContext* context, GpuSharedMemConfig shared_mem_config); + + // Launches a CUDA/ROCm kernel via cuLaunchKernel/hipModuleLaunchKernel. + // TODO(leary) describe the structure of kernel_params and extra in a readable + // way. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gb8f3dc3031b40da29d5f9a7139e52e15 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#execution-control + static tsl::Status LaunchKernel( + GpuContext* context, absl::string_view kernel_name, + GpuFunctionHandle function, unsigned int grid_dim_x, + unsigned int grid_dim_y, unsigned int grid_dim_z, + unsigned int block_dim_x, unsigned int block_dim_y, + unsigned int block_dim_z, unsigned int shared_mem_bytes, + GpuStreamHandle stream, void** kernel_params, void** extra); + + // Creates a new GPU graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gd885f719186010727b75c3315f865fdf + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status CreateGraph(GpuGraphHandle* graph); + + // Destroys GPU graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g718cfd9681f078693d4be2426fd689c8 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status DestroyGraph(GpuGraphHandle graph); + + // Begins graph capture on a stream. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g767167da0bbf07157dc20b6c258a2143 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + enum class StreamCaptureMode { kGlobal, kThreadLocal, kRelaxed }; + static tsl::Status StreamBeginCapture(GpuStreamHandle stream, + StreamCaptureMode mode); + + // Ends capture on a stream, returning the captured graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g03dab8b2ba76b00718955177a929970c + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status StreamEndCapture(GpuStreamHandle stream, + GpuGraphHandle* graph); + + // Graph instantiation flags. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1g070bf5517d3a7915667c256eefce4956 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + struct GraphInstantiateFlags { + // Automatically free memory allocated in a graph before relaunching. + bool auto_free_on_launch = false; + // Automatically upload the graph after instantiation. + bool upload = false; + // Instantiate the graph to be launchable from the device. + bool device_launch = false; + // Run the graph using the per-node priority attributes rather than the + // priority of the stream it is launched into. + bool use_node_prirotiy = false; + }; + + // Creates an executable graph from a graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gb53b435e178cccfa37ac87285d2c3fa1 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphInstantiate(GpuGraphExecHandle* exec, + GpuGraphHandle graph, + const GraphInstantiateFlags& flags); + + // Launches an executable graph in a stream. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g6b2dceb3901e71a390d2bd8b0491e471 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphLaunch(GpuGraphExecHandle exec, + GpuStreamHandle stream); + + // Graph update result. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1g8edc8969ff6ae00b7cd5d7292f812c3c + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#cuda-driver-data-types + enum class GraphExecUpdateResult { + kSuccess, + kError, + kTopologyChanged, + kNodeTypeChanged, + kFunctionChanged, + kParametersChanged, + kNotSupported, + kUnsupportedFunctionChange, + kAttributesChanged + }; + + // Graph update result info. + // https://docs.nvidia.com/cuda/cuda-driver-api/structCUgraphExecUpdateResultInfo__v1.html#structCUgraphExecUpdateResultInfo__v1 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + struct GraphExecUpdateResultInfo { + GpuGraphNodeHandle error_from_node; + GpuGraphNodeHandle error_node; + GraphExecUpdateResult result; + }; + + // Check whether an executable graph can be updated with a graph and perform + // the update if possible. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g96efefc56df46927da7297f122adfb9f + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphExecUpdate(GpuGraphExecHandle exec, + GpuGraphHandle graph, + GraphExecUpdateResultInfo* result); + + // Graph node type. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TYPES.html#group__CUDA__TYPES_1g0731a28f826922120d783d8444e154dc + // https://docs.amd.com/projects/HIP/en/docs-5.0.0/doxygen/html/group___graph.html#ga4727d20b89566832c74b762f987b9728 + enum class GraphNodeType { + kKernel, + kMemcpy, + kMemset, + kHost, + kGraph, + kEmpty, + kWaitEvent, + kEventRecord, + kExtSemasSignal, + kExtSemasWait, + kMemAlloc, + kMemFree, + kBatchMemOp, + }; + + // Return the node type of the graph node. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gdb1776d97aa1c9d5144774b29e4b8c3e + // https://docs.amd.com/projects/HIP/en/docs-5.0.0/doxygen/html/group___graph.html#ga87c68ae9408a6438d4a1101560ceea11 + static tsl::StatusOr GraphNodeGetType(GpuGraphNodeHandle node); + + // Destroys an executable graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1ga32ad4944cc5d408158207c978bc43a7 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status DestroyGraphExec(GpuGraphExecHandle exec); + + // Write a DOT file describing graph structure. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g0fb0c4d319477a0a98da005fcb0dacc4 + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphDebugDotPrint(GpuGraphHandle graph, const char* path); + + // Returns a stream's capture status. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g37823c49206e3704ae23c7ad78560bca + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#stream-management + static tsl::StatusOr StreamIsCapturing(GpuStreamHandle stream); + + // Creates a kernel execution node and adds it to a graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g50d871e3bd06c1b835e52f2966ef366b + // https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Driver_API_functions_supported_by_HIP.html#graph-management + static tsl::Status GraphAddKernelNode( + GpuGraphNodeHandle* node, GpuGraphHandle graph, + absl::Span deps, absl::string_view kernel_name, + GpuFunctionHandle function, unsigned int grid_dim_x, + unsigned int grid_dim_y, unsigned int grid_dim_z, + unsigned int block_dim_x, unsigned int block_dim_y, + unsigned int block_dim_z, unsigned int shared_mem_bytes, + void** kernel_params, void** extra); + + // Sets the parameters for a kernel node in the given graph exec. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1gd84243569e4c3d6356b9f2eea20ed48c + static tsl::Status GraphExecKernelNodeSetParams( + GpuGraphExecHandle exec, GpuGraphNodeHandle node, + absl::string_view kernel_name, GpuFunctionHandle function, + unsigned int grid_dim_x, unsigned int grid_dim_y, unsigned int grid_dim_z, + unsigned int block_dim_x, unsigned int block_dim_y, + unsigned int block_dim_z, unsigned int shared_mem_bytes, + void** kernel_params, void** extra); + + // Creates a memcpy node and adds it to a graph. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__GRAPH.html#group__CUDA__GRAPH_1g674da6ab54a677f13e0e0e8206ff5073 + static tsl::Status GraphAddMemcpyD2DNode(GpuContext* context, + GpuGraphNodeHandle* node, + GpuGraphHandle graph, + absl::Span deps, + GpuDevicePtr gpu_dst, + GpuDevicePtr gpu_src, uint64_t size); + + // Loads ptx_contents with the CUDA driver's PTX JIT and stores the resulting + // handle in "module". Any error logs that are produced are logged internally. + // (supported on CUDA only) + static tsl::Status LoadPtx(GpuContext* context, const char* ptx_contents, + GpuModuleHandle* module); + + // Loads cubin_bytes with the CUDA driver's blob loading interface and stores + // the resulting handle in "module". + // (supported on CUDA only) + static tsl::Status LoadCubin(GpuContext* context, const char* cubin_bytes, + GpuModuleHandle* module); + + // Loads HSACO with the ROCM runtime and stores the resulting handle in + // "module". Any error logs that are produced are logged internally. + // (supported on ROCm only) + static tsl::Status LoadHsaco(GpuContext* context, const char* hsaco_contents, + GpuModuleHandle* module); + + // Retrieves a named kernel from a loaded module, and places the resulting + // handle into function (outparam) on success. Neither kernel_name nor + // function may be null. No ownership is taken of kernel_name. + static tsl::Status GetModuleFunction(GpuContext* context, + GpuModuleHandle module, + const char* kernel_name, + GpuFunctionHandle* function); + + // Retrieves a named global/constant symbol from a loaded module, and returns + // a device pointer and size of the symbol on success. symbol_name may not be + // null. At least one of dptr or bytes should not be null. No ownership is + // taken of symbol_name. + static bool GetModuleSymbol(GpuContext* context, GpuModuleHandle module, + const char* symbol_name, GpuDevicePtr* dptr, + size_t* bytes); + + // Unloads module from the current context via cuModuleUnload. + // TODO(leary) the documentation doesn't say what kind of disasters happen + // if you try to unload a module while its GpuFunctionHandles are in use. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MODULE.html#group__CUDA__MODULE_1g8ea3d716524369de3763104ced4ea57b + static void UnloadModule(GpuContext* context, GpuModuleHandle module); + + // Performs a synchronous memset of the device memory segment via cuMemsetD8. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g6e582bf866e9e2fb014297bfaf354d7b + static tsl::Status SynchronousMemsetUint8(GpuContext* context, + GpuDevicePtr location, + uint8_t value, size_t size); + + // Performs a synchronous memset of the device memory segment via cuMemsetD32. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g983e8d8759acd1b64326317481fbf132 + static tsl::Status SynchronousMemsetUint32(GpuContext* context, + GpuDevicePtr location, + uint32_t value, + size_t uint32_count); + + // Performs an asynchronous memset of the device memory segment via + // cuMemsetD8Async. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1gaef08a7ccd61112f94e82f2b30d43627 + static tsl::Status AsynchronousMemsetUint8(GpuContext* context, + GpuDevicePtr location, + uint8_t value, size_t uint32_count, + GpuStreamHandle stream); + + // Performs an asynchronous memset of the device memory segment via + // cuMemsetD32Async. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g58229da5d30f1c0cdf667b320ec2c0f5 + static tsl::Status AsynchronousMemsetUint32(GpuContext* context, + GpuDevicePtr location, + uint32_t value, + size_t uint32_count, + GpuStreamHandle stream); + + // -- Synchronous memcopies. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g4d32266788c440b0220b1a9ba5795169 + + static tsl::Status SynchronousMemcpyD2H(GpuContext* context, void* host_dst, + GpuDevicePtr gpu_src, uint64_t size); + static tsl::Status SynchronousMemcpyH2D(GpuContext* context, + GpuDevicePtr gpu_dst, + const void* host_src, uint64_t size); + static tsl::Status SynchronousMemcpyD2D(GpuContext* context, + GpuDevicePtr gpu_dst, + GpuDevicePtr gpu_src, uint64_t size); + + // -- Asynchronous memcopies. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g56f30236c7c5247f8e061b59d3268362 + + static bool AsynchronousMemcpyD2H(GpuContext* context, void* host_dst, + GpuDevicePtr gpu_src, uint64_t size, + GpuStreamHandle stream); + static bool AsynchronousMemcpyH2D(GpuContext* context, GpuDevicePtr gpu_dst, + const void* host_src, uint64_t size, + GpuStreamHandle stream); + static bool AsynchronousMemcpyD2D(GpuContext* context, GpuDevicePtr gpu_dst, + GpuDevicePtr gpu_src, uint64_t size, + GpuStreamHandle stream); + + // The CUDA stream callback type signature. + // The data passed to AddStreamCallback is subsequently passed to this + // callback when it fires. + // + // Some notable things: + // * Callbacks must not make any CUDA API calls. + // * Callbacks from independent streams execute in an undefined order and may + // be serialized. + // https://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EXEC.html#group__CUDA__EXEC_1gab95a78143bae7f21eebb978f91e7f3f + typedef void (*StreamCallback)(void* data); + + // Enqueues a callback operation into stream. + // See StreamCallback above and the NVIDIA documentation for additional + // details. + static bool AddStreamCallback(GpuContext* context, GpuStreamHandle stream, + StreamCallback callback, void* data); + + // Causes stream to wait for event to trigger before proceeding via + // cuStreamWaitEvent. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#axzz334nAXAhM + static bool WaitStreamOnEvent(GpuContext* context, GpuStreamHandle stream, + GpuEventHandle event); + + // Blocks the calling thread until the operations enqueued onto stream have + // been completed, via cuStreamSynchronize. + // + // TODO(leary) if a pathological thread enqueues operations onto the stream + // while another thread blocks like this, can you wind up waiting an unbounded + // amount of time? + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__STREAM.html#group__CUDA__STREAM_1g15e49dd91ec15991eb7c0a741beb7dad + static tsl::Status SynchronizeStream(GpuContext* context, + GpuStreamHandle stream); + + // Blocks the calling thread until the operations associated with the context + // have been completed, via cuCtxSynchronize. + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1g7a54725f28d34b8c6299f0c6ca579616 + static bool SynchronizeContext(GpuContext* context); + + // Returns true if all stream tasks have completed at time of the call. Note + // the potential for races around this call (if another thread adds work to + // the stream immediately after this returns). + static bool IsStreamIdle(GpuContext* context, GpuStreamHandle stream); + + // Returns whether code in the from context can access memory in the to + // context via cuDeviceCanAccessPeer. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS_1g496bdaae1f632ebfb695b99d2c40f19e + static bool CanEnablePeerAccess(GpuContext* from, GpuContext* to); + + // Returns whether the from device can access memory in the to + // device via cuDeviceCanAccessPeer. Because of differences between ROCM and + // CUDA, this API is not supported in ROCM builds and will result in a link + // error if used. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS_1g496bdaae1f632ebfb695b99d2c40f19e + static bool CanEnablePeerAccess(GpuDeviceHandle from, GpuDeviceHandle to); + + // Enables peer access per CanEnablePeerAccess, via cuCtxEnablePeerAccess. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__PEER__ACCESS.html#group__CUDA__PEER__ACCESS_1g0889ec6728e61c05ed359551d67b3f5a + static tsl::Status EnablePeerAccess(GpuContext* from, GpuContext* to); + + // Returns the elapsed milliseconds between start and stop via + // cuEventElapsedTime. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1gdfb1178807353bbcaa9e245da497cf97 + static bool GetEventElapsedTime(GpuContext* context, + float* elapsed_milliseconds, + GpuEventHandle start, GpuEventHandle stop); + + // Records that an event occurred when execution reaches the current point in + // thestream via cuEventRecord. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g95424d3be52c4eb95d83861b70fb89d1 + static tsl::Status RecordEvent(GpuContext* context, GpuEventHandle event, + GpuStreamHandle stream); + + // Polls (without blocking) to determine the status of an event - pending or + // complete (or an error status). + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__EVENT.html#group__CUDA__EVENT_1g6f0704d755066b0ee705749ae911deef + static tsl::StatusOr QueryEvent(GpuContext* context, + GpuEventHandle event); + + // -- Pointer-specific calls. + + // Returns the context in which pointer was allocated or registered. + static tsl::StatusOr GetPointerContext(GpuDevicePtr pointer); + + // Returns the device associated with the context from GetPointerContext(). + static tsl::StatusOr GetPointerDevice(GpuDevicePtr pointer); + + // Returns the memory space addressed by pointer. + static tsl::StatusOr GetPointerMemorySpace(GpuDevicePtr pointer); + + // Returns the base address and size of the device pointer dptr. + static tsl::Status GetPointerAddressRange(GpuDevicePtr dptr, + GpuDevicePtr* base, size_t* size); + + // -- Device-specific calls. + + // Returns the compute capability for the device; i.e (3, 5). + // This is currently done via the deprecated device API. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE__DEPRECATED.html#group__CUDA__DEVICE__DEPRECATED_1ge2091bbac7e1fb18c2821612115607ea + // (supported on CUDA only) + static tsl::Status GetComputeCapability(int* cc_major, int* cc_minor, + GpuDeviceHandle device); + + // Returns Gpu ISA version for the device; i.e 803, 900. + // (supported on ROCm only) + static tsl::Status GetGpuISAVersion(int* version, GpuDeviceHandle device); + + // Return the full GCN Architecture Name for the device + // for eg: amdgcn-amd-amdhsa--gfx908:sramecc+:xnack- + // (supported on ROCm only) + static tsl::Status GetGpuGCNArchName(GpuDeviceHandle device, + std::string* gcnArchName); + +#if TENSORFLOW_USE_ROCM + // tests the current device for MFMA insn support (ROCm only) + static tsl::StatusOr GetMFMASupport(); +#endif + + // Returns the number of multiprocessors on the device (note that the device + // may be multi-GPU-per-board). + static tsl::StatusOr GetMultiprocessorCount(GpuDeviceHandle device); + + // Returns the limit on number of threads that can be resident in a single + // multiprocessor. + static tsl::StatusOr GetMaxThreadsPerMultiprocessor( + GpuDeviceHandle device); + + // Returns the limit on number of threads which may be resident for a single + // block (cooperative thread array). + static tsl::StatusOr GetMaxThreadsPerBlock(GpuDeviceHandle device); + + // Returns the amount of shared memory available on a single GPU core (i.e. + // SM on NVIDIA devices). + static tsl::StatusOr GetMaxSharedMemoryPerCore( + GpuDeviceHandle device); + + // Returns the amount of static shared memory available for a single block + // (cooperative thread array). + static tsl::StatusOr GetMaxSharedMemoryPerBlock( + GpuDeviceHandle device); + + // Returns the total amount of shared memory available for a single block + // (cooperative thread array). + static tsl::StatusOr GetMaxSharedMemoryPerBlockOptin( + GpuDeviceHandle device); + + // Returns the maximum supported number of registers per block. + static tsl::StatusOr GetMaxRegistersPerBlock(GpuDeviceHandle device); + + // Returns the number of threads per warp. + static tsl::StatusOr GetThreadsPerWarp(GpuDeviceHandle device); + + // Queries the grid limits for device with cuDeviceGetAttribute calls. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g9c3e1414f0ad901d3278a4d6645fc266 + static tsl::Status GetGridLimits(int* x, int* y, int* z, + GpuDeviceHandle device); + + // Returns a grab-bag of device properties in a caller-owned device_properties + // structure for device_ordinal via cuDeviceGetProperties. + // + // This call is deprecated in the NVIDIA driver API; its replacement is + // GetDeviceAttribute + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE__DEPRECATED.html#group__CUDA__DEVICE__DEPRECATED_1g65a5b4e25186bd257df80b98c98cffe6 + static bool GetDeviceProperties(GpuDeviceProperty* device_properties, + int device_ordinal); + + // Gets a specific integer-valued property about the given device. + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g9c3e1414f0ad901d3278a4d6645fc266 + static tsl::StatusOr GetDeviceAttribute(GpuDeviceAttribute attribute, + GpuDeviceHandle device); + + // Returns whether ECC is enabled for the given GpuDeviceHandle via + // cuDeviceGetattribute with CU_DEVICE_ATTRIBUTE_ECC_ENABLED. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g9c3e1414f0ad901d3278a4d6645fc266 + static bool IsEccEnabled(GpuDeviceHandle device, bool* result); + + // Returns the total amount of memory available for allocation by the CUDA + // context, in bytes, via cuDeviceTotalMem. + static bool GetDeviceTotalMemory(GpuDeviceHandle device, uint64_t* result); + + // Returns the free amount of memory and total amount of memory, as reported + // by cuMemGetInfo. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g808f555540d0143a331cc42aa98835c0 + static bool GetDeviceMemoryInfo(GpuContext* context, int64_t* free, + int64_t* total); + + // Returns a PCI bus id string for the device. + // [domain]:[bus]:[device].[function] + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__MEM.html#group__CUDA__MEM_1g85295e7d9745ab8f0aa80dd1e172acfc + static std::string GetPCIBusID(GpuDeviceHandle device); + + // -- Context- and device-independent calls. + + // Returns the number of visible CUDA device via cuDeviceGetCount. + // This should correspond to the set of device ordinals available. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__DEVICE.html#group__CUDA__DEVICE_1g52b5ce05cb8c5fb6831b2c0ff2887c74 + static int GetDeviceCount(); + + // Returns the driver version number via cuDriverGetVersion. + // This is, surprisingly, NOT the actual driver version (e.g. 331.79) but, + // instead, the CUDA toolkit release number that this driver is compatible + // with; e.g. 6000 (for a CUDA 6.0 compatible driver) or 6050 (for a CUDA 6.5 + // compatible driver). + // + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__VERSION.html#group__CUDA__VERSION_1g8b7a10395392e049006e61bcdc8ebe71 + static bool GetDriverVersion(int* driver_version); + + // -- Other calls + + // Returns the maximum number of blocks (per multiprocessor) occupied by the + // specified kernel/GpuFunctionHandle when launched with the specified + // parameters. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__OCCUPANCY.html#group__CUDA__OCCUPANCY_1gcc6e1094d05cba2cee17fe33ddd04a98 + static tsl::StatusOr GetMaxOccupiedBlocksPerCore( + GpuContext* context, GpuFunctionHandle kernel, int threads_per_block, + size_t dynamic_shared_memory_bytes); + + // Seam for injecting an error at CUDA initialization time for testing + // purposes. + static bool driver_inject_init_error_; +}; + +// Ensures a context is activated within a scope. +class ScopedActivateContext { + public: + // Activates the context via cuCtxSetCurrent, if it is not the currently + // active context (a la cuCtxGetCurrent). Note the alternative push/pop + // mechanism is said by NVIDIA to be relatively slow and deprecated. + // http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__CTX.html#group__CUDA__CTX_1gbe562ee6258b4fcc272ca6478ca2a2f7 + explicit ScopedActivateContext(GpuContext* context); + + // Checks that the context has remained activated for the duration of the + // scope. + ~ScopedActivateContext(); + + private: + GpuContext* to_restore_ = nullptr; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_DRIVER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_event.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_event.h new file mode 100644 index 0000000000000000000000000000000000000000..5653e309c675f2af5a02b85fc9d5c442e5fafa90 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_event.h @@ -0,0 +1,62 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_EVENT_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_EVENT_H_ + +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/gpu/gpu_stream.h" +#include "tsl/platform/status.h" + +namespace stream_executor { +namespace gpu { + +// GpuEvent wraps a GpuEventHandle in the platform-independent EventInterface +// interface. +class GpuEvent : public internal::EventInterface { + public: + explicit GpuEvent(GpuExecutor* parent); + + ~GpuEvent() override; + + // Populates the CUDA-platform-specific elements of this object. + tsl::Status Init(); + + // Deallocates any platform-specific elements of this object. This is broken + // out (not part of the destructor) to allow for error reporting. + tsl::Status Destroy(); + + // Inserts the event at the current position into the specified stream. + tsl::Status Record(GpuStream* stream); + + // Polls the CUDA platform for the event's current status. + Event::Status PollForStatus(); + + // The underlying CUDA event element. + GpuEventHandle gpu_event(); + + private: + // The Executor used to which this object and GpuEventHandle are bound. + GpuExecutor* parent_; + + // The underlying CUDA event element. + GpuEventHandle gpu_event_; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_EVENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..c93073ffd9dafabfaf3712b1a224f1197c1ff865 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_executor.h @@ -0,0 +1,401 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The CUDA implementation of the StreamExecutorInterface functionality. +// CUDA inclusions are ideally confined to this implementation file. +// +// The notions from the StreamExecutor basically correspond to the CUDA streams +// programming model provided by the libcuda.so driver APIs, so we don't have +// to do much more than wrap the calls to the libraries appropriately. +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_EXECUTOR_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_EXECUTOR_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "absl/functional/any_invocable.h" +#include "absl/strings/string_view.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/gpu/gpu_kernel.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/fingerprint.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class StreamExecutor; + +namespace gpu { + +// CUDA-platform implementation of the platform-agnostic +// StreamExecutorInterface. +class GpuExecutor : public internal::StreamExecutorInterface { + // Helper classes to attach a type erased state to the GpuExecutor. Currently, + // we just need to support some XLA specific state. + class Object { + struct Concept { + virtual ~Concept() {} + }; + template + struct Model : Concept { + explicit Model(StreamExecutor* se) : object(se) {} + T object; + }; + + public: + template + T* getOrCreate(StreamExecutor* se) { + absl::MutexLock l(&mu_); + if (!object_) { + object_ = std::make_unique>(se); + } + return &(dynamic_cast*>(object_.get())->object); + } + + private: + absl::Mutex mu_; + std::unique_ptr object_ ABSL_GUARDED_BY(mu_); + }; + + public: + // sub_platform indicates the subplatform used in this executor; it must + // be a CUDA type. + GpuExecutor() + : device_(0), + context_(nullptr), + device_ordinal_(0), + cc_major_(0), + cc_minor_(0), + version_(0) {} + + // See the corresponding StreamExecutor methods for method comments on the + // following overrides. + + ~GpuExecutor() override; + + tsl::Status Init(int device_ordinal, DeviceOptions device_options) override; + + tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, + KernelBase* kernel) override; + + // (supported on CUDA only) + void UnloadKernel(const KernelBase* kernel) override; + tsl::Status LoadModule(const MultiModuleLoaderSpec& spec, + ModuleHandle* module_handle) override; + bool UnloadModule(ModuleHandle module_handle) override; + + // Allocates and initializes a new constant on the device with the given + // content. Or, if a device with identical content is already on-device, + // returns a pointer to that buffer with shared ownership. + tsl::StatusOr> CreateOrShareConstant( + Stream* stream, const std::vector& content) override; + + tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& k, + const KernelArgsArrayBase& args) override; + + tsl::Status Submit(Stream* stream, + const CommandBuffer& command_buffer) override; + + // (supported on CUDA only) + int CalculateOccupancy(const DeviceDescription& device_description, + uint64_t registers_per_thread, + uint64_t shared_memory_per_block, + const ThreadDim& thread_dims, GpuFunctionHandle func); + + // (supported on CUDA only) + int CompareOccupancy(int* initial_blocks, + const DeviceDescription& device_description, + uint64_t registers_per_thread, + uint64_t shared_memory_per_block, + const ThreadDim& thread_dims, GpuFunctionHandle func); + + DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space) override; + + void* GetSubBuffer(DeviceMemoryBase* mem, uint64_t offset_bytes, + uint64_t size_bytes) override; + + void Deallocate(DeviceMemoryBase* mem) override; + + void* UnifiedMemoryAllocate(uint64_t size) override { + return GpuDriver::UnifiedMemoryAllocate(context_, size); + } + + void UnifiedMemoryDeallocate(void* location) override { + return GpuDriver::UnifiedMemoryDeallocate(context_, location); + } + + // CUDA allocation/registration functions are necessary because the driver + // internally sets up buffers for DMA operations (and page locks them). + // There's no external interface for us to otherwise control these DMA + // settings. + void* HostMemoryAllocate(uint64_t size) override { + return GpuDriver::HostAllocate(context_, size); + } + + void HostMemoryDeallocate(void* location) override { + return GpuDriver::HostDeallocate(context_, location); + } + + bool HostMemoryRegister(void* location, uint64_t size) override; + + bool HostMemoryUnregister(void* location) override; + + bool SynchronizeAllActivity() override; + + tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) override; + + tsl::Status SynchronousMemSet(DeviceMemoryBase* location, int value, + uint64_t size) override; + + tsl::Status SynchronousMemcpy(DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + + tsl::Status SynchronousMemcpy(void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + tsl::Status SynchronousMemcpyDeviceToDevice(DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) override; + tsl::Status Memset(Stream* stream, DeviceMemoryBase* location, + uint8_t pattern, uint64_t size) override; + tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size) override; + + bool Memcpy(Stream* stream, void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + bool Memcpy(Stream* stream, DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + + bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + bool HostCallback(Stream* stream, + absl::AnyInvocable callback) override; + + bool AllocateStream(Stream* stream) override; + + void DeallocateStream(Stream* stream) override; + + bool CreateStreamDependency(Stream* dependent, Stream* other) override; + + tsl::Status AllocateEvent(Event* event) override; + + tsl::Status DeallocateEvent(Event* event) override; + + tsl::Status RecordEvent(Stream* stream, Event* event) override; + + tsl::Status WaitForEvent(Stream* stream, Event* event) override; + + tsl::Status WaitForEventOnExternalStream(std::intptr_t stream, + Event* event) override; + + Event::Status PollForEventStatus(Event* event) override; + + tsl::Status BlockHostUntilDone(Stream* stream) override; + + tsl::Status EnablePeerAccessTo(StreamExecutorInterface* other) override; + + bool CanEnablePeerAccessTo(StreamExecutorInterface* other) override; + + bool DeviceMemoryUsage(int64_t* free, int64_t* total) const override; + + // Search for the symbol in the given module and returns a device pointer and + // size. Returns false if symbol does not exist. 'module_handle' must not + // be null. + bool GetSymbol(const std::string& symbol_name, ModuleHandle module_handle, + void** mem, size_t* bytes) override; + + tsl::StatusOr> CreateDeviceDescription() + const override { + return CreateDeviceDescription(device_ordinal_); + } + + static tsl::StatusOr> + CreateDeviceDescription(int device_ordinal); + + blas::BlasSupport* CreateBlas() override; + + fft::FftSupport* CreateFft() override; + + dnn::DnnSupport* CreateDnn() override; + + std::unique_ptr CreateEventImplementation() + override; + + std::unique_ptr CreateKernelImplementation() + override; + + std::unique_ptr GetStreamImplementation() override; + + tsl::StatusOr> + GetCommandBufferImplementation(CommandBuffer::Mode mode) override; + + void* GpuContextHack() override; + + GpuContext* gpu_context(); + + // Provide a type-erased way of attaching arbitrary XLA specific state to the + // GpuExecutor. XLA based execution will use this method to attach per-stream + // executor XLA specific objects (like the Infeed and Outfeed managers) to the + // stream executor, so that their lifetimes can be tied to the lifetime of the + // stream executor for which that object is allocated for. This simplifies + // memory management as compared to having these objects reside on the side + // and then either leaking or having to implement callbacks that the SE + // destructors call to deallocate any side state that is associated with that + // SE object. + template + T* getOrCreateXLAState(StreamExecutor* se) { + return xla_state_.getOrCreate(se); + } + + Stream* FindAllocatedStream(void* gpu_stream) override { + absl::MutexLock lock(&alive_gpu_streams_mu_); + auto it = alive_gpu_streams_.find(gpu_stream); + if (it == alive_gpu_streams_.end()) { + return nullptr; + } + return it->second; + } + + private: + // Host callback landing routine invoked by CUDA. + // data: User-provided callback provided to HostCallback() above, captured + // as a std::function. Allocated/initialized inside + // HostCallback() and owned and deleted by this call. + static void InternalHostCallback(void* data); + + // Collects metadata for the specified kernel. + tsl::Status GetKernelMetadata(GpuKernel* cuda_kernel, + KernelMetadata* kernel_metadata); + + // Prints to VLOG(2) information about the kernel's occupancy and how it might + // be improved. + void VlogOccupancyInfo(const KernelBase& kernel, const ThreadDim& thread_dims, + const BlockDim& block_dims); + + // (supported on CUDA only) + tsl::Status LoadModuleFromCuBin(const char* cubin, GpuModuleHandle* module) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + // Loads the PTX text `ptx` as a CUDA module. `ptx` must be null terminated. + // (supported on CUDA only) + tsl::Status LoadModuleFromPtx(const char* ptx, GpuModuleHandle* module) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + // (supported on ROCm only) + tsl::Status LoadModuleFromHsaco(const char* hsaco, GpuModuleHandle* module) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + bool UnloadGpuBinary(const void* gpu_binary) + TF_EXCLUSIVE_LOCKS_REQUIRED(in_memory_modules_mu_); + + // Guards the on-disk-module mapping. + absl::Mutex disk_modules_mu_; + + // Mapping from filename to GPUModuleHandle, if it was already retrieved. + // Multiple GPUFunctionHandle are usually obtained from a single + // GPUModuleHandle so we attempt to hit in this mapping first, before + // retrieving it. + std::map disk_modules_ + ABSL_GUARDED_BY(disk_modules_mu_); + + // Guards the in-memory-module mapping. + absl::Mutex in_memory_modules_mu_; + + std::map in_memory_modules_ + ABSL_GUARDED_BY(in_memory_modules_mu_); + + absl::Mutex shared_constants_mu_; + // On-device constants that can be shared between multiple executables. A + // pointer for a given constant will expire when no executables require use + // of that constant anymore. + std::map> + shared_constants_ ABSL_GUARDED_BY(shared_constants_mu_); + + // Kernel -> loaded GPU binary. Many kernels may load the same binary. + std::unordered_map kernel_to_gpu_binary_ + ABSL_GUARDED_BY(in_memory_modules_mu_); + // GPU binary (PTX or CUBIN or HSACO) -> {CUDA module, reference count}. + std::unordered_map> + gpu_binary_to_module_ ABSL_GUARDED_BY(in_memory_modules_mu_); + + // Guards the launched kernel set. + absl::Mutex launched_kernels_mu_; + + // Keeps track of the set of launched kernels. Currently used to suppress the + // occupancy check on subsequent launches. + std::set launched_kernels_ + ABSL_GUARDED_BY(launched_kernels_mu_); + + // Handle for the CUDA device being operated on. Immutable + // post-initialization. + GpuDeviceHandle device_; + + // Handle for session with the library/driver. Immutable post-initialization. + GpuContext* context_; + + // The device ordinal value that this executor was initialized with; recorded + // for use in getting device metadata. Immutable post-initialization. + int device_ordinal_; + + // The major version of the compute capability for device_. + int cc_major_; + + // The minor version of the compute capability for device_. + int cc_minor_; + + // GPU ISA version for device_. + int version_; + + // Type erased XLA specific state attached to GpuExecutor. + Object xla_state_; + + absl::Mutex alive_gpu_streams_mu_; + + // Lookup map for alive streams, from raw stream pointers. + absl::flat_hash_map alive_gpu_streams_ + ABSL_GUARDED_BY(alive_gpu_streams_mu_); + + GpuExecutor(const GpuExecutor&) = delete; + void operator=(const GpuExecutor&) = delete; +}; + +inline GpuExecutor* ExtractGpuExecutor(StreamExecutor* stream_exec) { + return static_cast(stream_exec->implementation()); +} + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_graph.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..af58a4102c29f3d6eef9073443b9a48fbef4aab4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_graph.h @@ -0,0 +1,140 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_GRAPH_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_GRAPH_H_ + +#include +#include +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/types/span.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/stream.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace gpu { + +// Forward declare. +class GpuContext; + +class GpuGraphSupport { + public: + // Deleters for gpu graph and graph exec instance that check the returned + // status and terminate on error. + struct DestroyGraph { + void operator()(GpuGraphHandle); + }; + struct DestroyGraphExec { + void operator()(GpuGraphExecHandle); + }; + + static size_t NotifyGraphExecCreated(); + static size_t NotifyGraphExecDestroyed(); + + static size_t allocated_gpu_graph_execs(); + static size_t alive_gpu_graph_execs(); + + private: + // Global counters for the total number of allocated and alive gpu graph + // execs to track the resource usage at run time. + static std::atomic allocated_gpu_graph_execs_; + static std::atomic alive_gpu_graph_execs_; +}; + +//===----------------------------------------------------------------------===// +// RAII helpers for gpu graph types. +//===----------------------------------------------------------------------===// + +class OwnedGpuGraph + : public std::unique_ptr, + GpuGraphSupport::DestroyGraph> { + // Bring std::unique_ptr constructors in scope. + using std::unique_ptr, + GpuGraphSupport::DestroyGraph>::unique_ptr; +}; + +class OwnedGpuGraphExec + : public std::unique_ptr, + GpuGraphSupport::DestroyGraphExec> { + using Base = std::unique_ptr, + GpuGraphSupport::DestroyGraphExec>; + + public: + OwnedGpuGraphExec(uint64_t id, GpuGraphExecHandle exec) + : Base(exec), id_(id) {} + ~OwnedGpuGraphExec(); + + OwnedGpuGraphExec(OwnedGpuGraphExec&&) = default; + OwnedGpuGraphExec& operator=(OwnedGpuGraphExec&&) = default; + + enum class UpdateResult { kSuccess, kFallback }; + + // Updates executable graph instance with a newly captured graph. Returns an + // error if the new graph is not compatible (see `cudaGraphExecUpdate`). + tsl::StatusOr Update(OwnedGpuGraph graph); + + // Launches captured graph on a given stream. + tsl::Status Launch(stream_executor::Stream* stream); + + uint64_t id() const { return id_; } + + private: + uint64_t id_; + uint64_t num_updates_ = 0; + uint64_t num_launches_ = 0; +}; + +//===----------------------------------------------------------------------===// +// Gpu Graph Helpers. +//===----------------------------------------------------------------------===// + +// Creates new empty Gpu graph. +tsl::StatusOr CreateGpuGraph(); + +// Adds a kernel node to the graph. +tsl::StatusOr AddKernelNode( + GpuGraphHandle graph, absl::Span deps, + ThreadDim threads, BlockDim blocks, const KernelBase& kernel, + const KernelArgsArrayBase& args); + +// Adds a memory copy node to the graph. +tsl::StatusOr AddMemcpyD2DNode( + GpuContext* context, GpuGraphHandle graph, + absl::Span deps, const DeviceMemoryBase& dst, + const DeviceMemoryBase& src); + +// Captures all operations added to a `stream` by the `capture` function into +// the gpu graph instance. +tsl::StatusOr CaptureGpuGraph( + stream_executor::Stream* stream, absl::AnyInvocable capture); + +// Instantiates a captured gpu graph instance into a gpu graph executable. +tsl::StatusOr InstantiateGpuGraph(OwnedGpuGraph graph); + +// Returns true if the stream is in graph capture mode +tsl::StatusOr IsStreamCapturing(stream_executor ::Stream* stream); + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_GRAPH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_helpers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..cefd0a6af15dfd70d06c94677230a20d66d219f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_helpers.h @@ -0,0 +1,114 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Common helper functions used for dealing with CUDA API datatypes. +// +// These are typically placed here for use by multiple source components (for +// example, BLAS and executor components). + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_HELPERS_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_HELPERS_H_ + +#include + +#include + +#include "xla/stream_executor/gpu/gpu_types.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { + +template +class DeviceMemory; + +namespace gpu { + +// Converts a const DeviceMemory reference to its underlying typed pointer in +// CUDA device memory. +template +const T* GpuMemory(const DeviceMemory& mem) { + return static_cast(mem.opaque()); +} + +// Converts a (non-const) DeviceMemory pointer reference to its underlying typed +// pointer in CUDA device memory. +template +T* GpuMemoryMutable(DeviceMemory* mem) { + return static_cast(mem->opaque()); +} + +static_assert( + sizeof(std::complex) == sizeof(GpuComplexType), + "std::complex and GpuComplexType should have the same size"); +static_assert(offsetof(GpuComplexType, x) == 0, + "The real part of GpuComplexType should appear first."); +static_assert( + sizeof(std::complex) == sizeof(GpuDoubleComplexType), + "std::complex and GpuDoubleComplexType should have the same " + "size"); +static_assert(offsetof(GpuDoubleComplexType, x) == 0, + "The real part of GpuDoubleComplexType should appear first."); + +// Type traits to get CUDA complex types from std::complex<>. + +template +struct GpuComplexT { + typedef T type; +}; + +template <> +struct GpuComplexT> { + typedef GpuComplexType type; +}; + +template <> +struct GpuComplexT> { + typedef GpuDoubleComplexType type; +}; + +// Converts pointers of std::complex<> to pointers of +// GpuComplexType/GpuDoubleComplexType. No type conversion for non-complex +// types. + +template +inline const typename GpuComplexT::type* GpuComplex(const T* p) { + auto* result = reinterpret_cast::type*>(p); + CHECK_EQ(reinterpret_cast(p) % alignof(decltype(*result)), 0) + << "Source pointer is not aligned by " << alignof(decltype(*result)); + return result; +} + +template +inline typename GpuComplexT::type* GpuComplex(T* p) { + auto* result = reinterpret_cast::type*>(p); + CHECK_EQ(reinterpret_cast(p) % alignof(decltype(*result)), 0) + << "Source pointer is not aligned by " << alignof(decltype(*result)); + return result; +} + +// Converts values of std::complex to values of +// GpuComplexType/GpuDoubleComplexType. +inline GpuComplexType GpuComplexValue(std::complex val) { + return {val.real(), val.imag()}; +} + +inline GpuDoubleComplexType GpuComplexValue(std::complex val) { + return {val.real(), val.imag()}; +} + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_HELPERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_init.h new file mode 100644 index 0000000000000000000000000000000000000000..bcdce71f9ffce79f59d14f7d3e6e84db13d6ac29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_init.h @@ -0,0 +1,43 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_INIT_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_INIT_H_ + +#include + +#include "tsl/platform/status.h" + +namespace stream_executor { +class Platform; + +// Initializes the GPU platform and returns OK if the GPU +// platform could be initialized. +tsl::Status ValidateGPUMachineManager(); + +// Returns the GPU machine manager singleton, creating it and +// initializing the GPUs on the machine if needed the first time it is +// called. Must only be called when there is a valid GPU environment +// in the process (e.g., ValidateGPUMachineManager() returns OK). +Platform* GPUMachineManager(); + +// Returns the string describing the name of the GPU platform in use. +// This value is "CUDA" by default, and +// "ROCM" when TF is built with `--config==rocm` +std::string GpuPlatformName(); + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_INIT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..b7fa33c87e5acefbf1932be3b18ba825bab65bbb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_kernel.h @@ -0,0 +1,105 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The CUDA implementation of the StreamExecutorInterface functionality. +// CUDA inclusions are ideally confined to this implementation file. +// +// The notions from the StreamExecutor basically correspond to the CUDA streams +// programming model provided by the libcuda.so driver APIs, so we don't have +// to do much more than wrap the calls to the libraries appropriately. +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_KERNEL_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_KERNEL_H_ + +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/kernel_cache_config.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { +namespace gpu { + +// Wraps a GpuFunctionHandle to implement the platform-independent +// KernelInterface. +class GpuKernel : public internal::KernelInterface { + public: + GpuKernel() + : gpu_function_(nullptr), + arity_(0), + preferred_cache_config_(KernelCacheConfig::kNoPreference) {} + + // Note that the function is unloaded when the module is unloaded, and the + // module that the function is contained in is owned by the GpuExecutor. + ~GpuKernel() override {} + + // As arity cannot be reflected upon using the CUDA API, the arity is + // explicitly set during the GpuExecutor::GetKernel initialization process. + void set_arity(unsigned arity) { arity_ = arity; } + unsigned Arity() const override { return arity_; } + + // Returns the GpuFunctionHandle value for passing to the CUDA API. + GpuFunctionHandle AsGpuFunctionHandle() const { + DCHECK(gpu_function_ != nullptr); + return const_cast(gpu_function_); + } + + // Returns the slot that the GpuFunctionHandle is stored within for this + // object, for the CUDA API which wants to load into a GpuFunctionHandle*. + GpuFunctionHandle* gpu_function_ptr() { return &gpu_function_; } + + // CUDA supports setting the preferred cache configuration of a + // GpuFunctionHandle (more-or-less equivalent to a GpuKernel). We support this + // via the below functions; users can set a preference, and that is applied + // when the kernel is [lazy-]loaded (in GpuExecutor::Launch). The alternative + // would be to load the kernel & set the preference when the user calls the + // setter below; either approach is valid. Sets the current kernel cache + // configuration preference. + void SetPreferredCacheConfig(KernelCacheConfig config) override { + preferred_cache_config_ = config; + } + + // Returns the current kernel cache configuration preference. + KernelCacheConfig GetPreferredCacheConfig() const override { + return preferred_cache_config_; + } + + // Returns the current kernel cache configuration preference as a + // CUfunc_cache. + GpuFuncCachePreference GetGpuCacheConfig() const; + + private: + GpuFunctionHandle gpu_function_; // Wrapped CUDA kernel handle. + unsigned arity_; // Number of formal parameters the kernel takes. + + // Preferred (but not required) cache configuration for this kernel. + KernelCacheConfig preferred_cache_config_; +}; + +// Given a platform-independent kernel datatype, returns the (const) internal +// CUDA platform implementation pointer. +inline const GpuKernel* AsGpuKernel(const KernelBase* kernel) { + return static_cast(kernel->implementation()); +} + +// Given a platform-independent kernel datatype, returns the (non-const) +// internal CUDA platform implementation pointer. +inline GpuKernel* AsGpuKernel(KernelBase* kernel) { + return static_cast(kernel->implementation()); +} + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..66a6df44ee1012f2999fd08a326d4f34a423a955 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_stream.h @@ -0,0 +1,107 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Defines the GpuStream type - the CUDA-specific implementation of the generic +// StreamExecutor Stream interface. + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_STREAM_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_STREAM_H_ + +#include + +#include "xla/stream_executor/gpu/gpu_types.h" +#include "xla/stream_executor/stream_executor_internal.h" + +namespace stream_executor { +namespace gpu { + +class GpuExecutor; + +// Wraps a GpuStreamHandle in order to satisfy the platform-independent +// StreamInterface. +// +// Thread-safe post-initialization. +class GpuStream : public internal::StreamInterface { + public: + explicit GpuStream(GpuExecutor* parent) + : parent_(parent), gpu_stream_(nullptr), completed_event_(nullptr) {} + + // Note: teardown is handled by a parent's call to DeallocateStream. + ~GpuStream() override = default; + + void* GpuStreamHack() override { return gpu_stream_; } + void** GpuStreamMemberHack() override { + return reinterpret_cast(&gpu_stream_); + } + + // Explicitly initialize the CUDA resources associated with this stream, used + // by StreamExecutor::AllocateStream(). + bool Init(); + + void SetPriority(StreamPriority priority) override { + stream_priority_ = priority; + } + + void SetPriority(int priority) override { stream_priority_ = priority; } + + std::variant priority() const override { + return stream_priority_; + } + + // Explicitly destroy the CUDA resources associated with this stream, used by + // StreamExecutor::DeallocateStream(). + void Destroy(); + + // Returns true if no work is pending or executing on the stream. + bool IsIdle() const; + + // Retrieves an event which indicates that all work enqueued into the stream + // has completed. Ownership of the event is not transferred to the caller, the + // event is owned by this stream. + GpuEventHandle* completed_event() { return &completed_event_; } + + // Returns the GpuStreamHandle value for passing to the CUDA API. + // + // Precond: this GpuStream has been allocated (otherwise passing a nullptr + // into the NVIDIA library causes difficult-to-understand faults). + GpuStreamHandle gpu_stream() const { + DCHECK(gpu_stream_ != nullptr); + return const_cast(gpu_stream_); + } + + // TODO(timshen): Migrate away and remove this function. + GpuStreamHandle cuda_stream() const { return gpu_stream(); } + + GpuExecutor* parent() const { return parent_; } + + private: + GpuExecutor* parent_; // Executor that spawned this stream. + GpuStreamHandle gpu_stream_; // Wrapped CUDA stream handle. + std::variant stream_priority_; + + // Event that indicates this stream has completed. + GpuEventHandle completed_event_ = nullptr; +}; + +// Helper functions to simplify extremely common flows. +// Converts a Stream to the underlying GpuStream implementation. +GpuStream* AsGpuStream(Stream* stream); + +// Extracts a GpuStreamHandle from a GpuStream-backed Stream object. +GpuStreamHandle AsGpuStreamValue(Stream* stream); +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_timer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..23663cb1d978f1dc6a42d81db033330a87c86cf5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_timer.h @@ -0,0 +1,76 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_TIMER_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_TIMER_H_ + +#include +#include + +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/gpu/gpu_executor.h" +#include "xla/stream_executor/stream_executor_internal.h" + +namespace stream_executor { +namespace gpu { + +class GpuExecutor; +class GpuStream; + +// Timer is started once it's created, and is stopped once read. +class GpuTimer { + public: + static tsl::StatusOr Create(GpuStream* stream); + + // An ugly but a very convenient helper: creates a timer only when we need + // one, but always returns an object. If `is_needed` is false, returns an + // empty optional, acts like `Create` otherwise. + static tsl::StatusOr> CreateIfNeeded( + GpuStream* stream, bool is_needed); + + explicit GpuTimer(GpuExecutor* parent, GpuEventHandle start_event, + GpuEventHandle stop_event, GpuStream* stream) + : parent_(parent), + start_event_(start_event), + stop_event_(stop_event), + stream_(stream) {} + + GpuTimer(GpuTimer&& other) + : parent_(other.parent_), + start_event_(std::exchange(other.start_event_, nullptr)), + stop_event_(std::exchange(other.stop_event_, nullptr)), + stream_(other.stream_) {} + + ~GpuTimer(); + + // Stops the timer on the first call and returns the elapsed duration. + // Subsequent calls error out. + tsl::StatusOr GetElapsedDuration(); + + private: + GpuExecutor* parent_; + GpuEventHandle start_event_ = nullptr; + GpuEventHandle stop_event_ = nullptr; + GpuStream* stream_; + bool is_stopped_ = false; + + GpuTimer(const GpuTimer&) = delete; + void operator=(const GpuTimer&) = delete; +}; + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_TIMER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_types.h new file mode 100644 index 0000000000000000000000000000000000000000..dea81d66a1d59dbf6d95b7118845de39652cb37f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/gpu_types.h @@ -0,0 +1,87 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// GPU (ROCm / CUDA) specific type handle resolution + +#ifndef XLA_STREAM_EXECUTOR_GPU_GPU_TYPES_H_ +#define XLA_STREAM_EXECUTOR_GPU_GPU_TYPES_H_ + +#if TENSORFLOW_USE_ROCM + +#define __HIP_DISABLE_CPP_FUNCTIONS__ + +#include "rocm/include/hip/hip_complex.h" +#include "rocm/include/hip/hip_runtime.h" +#include "rocm/include/hiprand/hiprand.h" + +#else // CUDA + +#include "third_party/gpus/cuda/include/cuComplex.h" +#include "third_party/gpus/cuda/include/cuda.h" + +#endif + +namespace stream_executor { +namespace gpu { + +#if TENSORFLOW_USE_ROCM + +using GpuContextHandle = hipCtx_t; +using GpuStreamHandle = hipStream_t; +using GpuEventHandle = hipEvent_t; +using GpuFunctionHandle = hipFunction_t; +using GpuFunctionAttribute = hipFunction_attribute; +using GpuDeviceHandle = hipDevice_t; +using GpuDevicePtr = hipDeviceptr_t; +using GpuDeviceAttribute = hipDeviceAttribute_t; +using GpuDeviceProperty = hipDeviceProp_t; +using GpuModuleHandle = hipModule_t; +using GpuStatus = hipError_t; +using GpuFuncCachePreference = hipFuncCache_t; +using GpuSharedMemConfig = hipSharedMemConfig; +using GpuComplexType = hipComplex; +using GpuDoubleComplexType = hipDoubleComplex; +using GpuRngHandle = hiprandGenerator_t; +using GpuGraphHandle = hipGraph_t; +using GpuGraphExecHandle = hipGraphExec_t; +using GpuGraphNodeHandle = hipGraphNode_t; + +#else // CUDA + +using GpuContextHandle = CUcontext; +using GpuStreamHandle = CUstream; +using GpuEventHandle = CUevent; +using GpuFunctionHandle = CUfunction; +using GpuFunctionAttribute = CUfunction_attribute; +using GpuDeviceHandle = CUdevice; +using GpuDevicePtr = CUdeviceptr; +using GpuDeviceAttribute = CUdevice_attribute; +using GpuDeviceProperty = CUdevprop; +using GpuModuleHandle = CUmodule; +using GpuStatus = CUresult; +using GpuFuncCachePreference = CUfunc_cache; +using GpuSharedMemConfig = CUsharedconfig; +using GpuComplexType = cuComplex; +using GpuDoubleComplexType = cuDoubleComplex; +using GpuGraphHandle = CUgraph; +using GpuGraphExecHandle = CUgraphExec; +using GpuGraphNodeHandle = CUgraphNode; + +#endif + +} // namespace gpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_GPU_TYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/redzone_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/redzone_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..43694d3295c3864980e379438f09d7abc880c4de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/gpu/redzone_allocator.h @@ -0,0 +1,135 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_GPU_REDZONE_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_GPU_REDZONE_ALLOCATOR_H_ + +#include +#include + +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/gpu/asm_compiler.h" +#include "xla/stream_executor/gpu/gpu_asm_opts.h" +#include "xla/stream_executor/scratch_allocator.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/lib/math/math_util.h" + +namespace stream_executor { + +// An allocator that allocates a bit of extra memory around the beginning/end of +// every allocation and can check that this memory is unmodified. +// +// This can be used to check for out-of-bounds writes, and, if the redzone is +// filled with a sufficiently "ugly" pattern, may also be able to check for +// out-of-bounds reads. The default fill pattern of -1 is an unusual NaN +// pattern when interpreted as a floating-point number, so hopefully works for +// out-of-bounds reads and writes in those cases. +// +// This class implements ScratchAllocator, so can be used to allocate temp +// memory for cudnn convolutions. +class RedzoneAllocator : public ScratchAllocator { + public: + static constexpr int64_t kDefaultRedzoneSize = + 1LL << 23; // 8MiB per side, 16MiB total. + static constexpr uint8_t kDefaultRedzonePattern = -1; // NOLINT + RedzoneAllocator(Stream* stream, DeviceMemoryAllocator* memory_allocator, + GpuAsmOpts gpu_compilation_opts_, + int64_t memory_limit = (1LL << 32), // 4GB + int64_t redzone_size = kDefaultRedzoneSize, + uint8_t redzone_pattern = kDefaultRedzonePattern); + + // Redzones don't count towards the memory limit. + int64_t GetMemoryLimitInBytes() override { return memory_limit_; } + + int64_t TotalAllocatedBytesExcludingRedzones() const { + return allocated_bytes_excluding_redzones_; + } + + tsl::StatusOr> AllocateBytes(int64_t byte_size) override; + + // Non-empty redzone check status implies that there was a write into a + // redzone, with a string communicating the location of the write. + struct RedzoneCheckStatus { + RedzoneCheckStatus() = default; + + RedzoneCheckStatus(absl::string_view buffer_name, void* user_buffer_address, + int64_t offset, uint64_t expected_value, + uint64_t actual_value) + : buffer_name(buffer_name), + user_buffer_address(user_buffer_address), + offset(offset), + expected_value(expected_value), + actual_value(actual_value) {} + + static RedzoneCheckStatus OK() { return {}; } + + bool ok() { return user_buffer_address == nullptr; } + + std::string RedzoneFailureMsg() const; + + std::string buffer_name = {}; + void* user_buffer_address = nullptr; + int64_t offset = 0; + uint64_t expected_value = 0; + uint64_t actual_value = 0; + }; + + // Determines whether redzones around all allocated buffers are unmodified. + // + // Reinitializes redzones to the expected value, so that the same buffer + // can be reused for multiple checks. + // + // Returns: + // + // - RedzoneCheckStatus::OK() if everything went well. + // - RedzoneCheckStatus with a non-empty error message iff a write into a + // redzone has been detected. + // - A stream error, if loading or launching the kernel has failed. + tsl::StatusOr CheckRedzones() const; + + Stream* stream() const { return stream_; } + + private: + const int device_ordinal_; + Stream* stream_; + + // Memory limit of the allocator in bytes. + const int64_t memory_limit_; + + // Redzone size on *one side* of allocation in bytes. + // + // Must be a multiple of kXlaAllocatedBufferAlignBytes, otherwise the buffers + // returned to users will be misaligned. + const int64_t redzone_size_; + + const uint8_t redzone_pattern_; + DeviceMemoryAllocator* memory_allocator_; + GpuAsmOpts gpu_compilation_opts_; + + // The second element of the pair is the size of the user allocation. This + // isn't necessarily just first.size() - 2 * redzone_size_ because when the + // user allocation size is not a multiple of 4 bytes, we round up the size of + // the RHS redzone. + // + // ScratchAllocators need to free all allocated memory on destruction so we + // use `OwningDeviceMemory` here. + std::vector> allocated_buffers_; + + int64_t allocated_bytes_excluding_redzones_ = 0; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_GPU_REDZONE_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_gpu_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_gpu_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..2a92fd17c35ac4966c9d5680b0ebff1261de7724 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_gpu_executor.h @@ -0,0 +1,164 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Declares the HostExecutor class, which is a CPU-only implementation of +// the StreamExecutor interface. For now, this is used for testing and to +// examine the performance of host-based StreamExecutor code. +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_GPU_EXECUTOR_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_GPU_EXECUTOR_H_ + +#include + +#include "absl/functional/any_invocable.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/host/host_stream.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/errors.h" + +namespace stream_executor { +namespace host { + +// An implementation of StreamExecutor that does no communication or interaction +// with a device, but DOES perform memory operations backed by the host. +// Plugin routines (BLAS) are also supported and functional. +// Kernel invocations will fail, but host callbacks may be enqueued on this +// executor and its associated stream, and should follow standard ordering +// semantics. +// +// This is useful for evaluating the performance of host-based or fallback +// routines executed under the context of a GPU executor. +// See stream_executor.h for description of the below operations. +class HostExecutor : public internal::StreamExecutorInterface { + public: + HostExecutor() = default; + + // The stack size used for host streams can be set via + // device_options.non_portable_tags["host_stack_size"]. + tsl::Status Init(int device_ordinal, DeviceOptions device_options) override; + + tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, + KernelBase* kernel) override { + return tsl::errors::Unimplemented("Not Implemented"); + } + tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& kernel, + const KernelArgsArrayBase& args) override { + return tsl::errors::Unimplemented("Not Implemented"); + } + + DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space) override; + void* GetSubBuffer(DeviceMemoryBase* parent, uint64_t offset_bytes, + uint64_t size_bytes) override; + void Deallocate(DeviceMemoryBase* mem) override; + + void* HostMemoryAllocate(uint64_t size) override { return new char[size]; } + void HostMemoryDeallocate(void* mem) override { + delete[] static_cast(mem); + } + bool HostMemoryRegister(void* mem, uint64_t size) override { return true; } + bool HostMemoryUnregister(void* mem) override { return true; } + + bool Memcpy(Stream* stream, void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + bool Memcpy(Stream* stream, DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) override; + tsl::Status Memset(Stream* stream, DeviceMemoryBase* location, + uint8_t pattern, uint64_t size) override; + tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size) override; + + // No "synchronize all activity" implemented for this platform at the moment. + bool SynchronizeAllActivity() override { return true; } + tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) override; + + tsl::Status SynchronousMemSet(DeviceMemoryBase* location, int value, + uint64_t size) override; + + tsl::Status SynchronousMemcpy(DeviceMemoryBase* gpu_dst, const void* host_src, + uint64_t size) override; + tsl::Status SynchronousMemcpy(void* host_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) override; + tsl::Status SynchronousMemcpyDeviceToDevice(DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) override; + + bool HostCallback(Stream* stream, + absl::AnyInvocable callback) override; + + tsl::Status AllocateEvent(Event* event) override; + tsl::Status DeallocateEvent(Event* event) override; + tsl::Status RecordEvent(Stream* stream, Event* event) override; + tsl::Status WaitForEvent(Stream* stream, Event* event) override; + Event::Status PollForEventStatus(Event* event) override; + + bool AllocateStream(Stream* stream) override; + void DeallocateStream(Stream* stream) override; + bool CreateStreamDependency(Stream* dependent, Stream* other) override; + + tsl::Status BlockHostUntilDone(Stream* stream) override; + + bool DeviceMemoryUsage(int64_t* free, int64_t* total) const override; + + tsl::StatusOr> CreateDeviceDescription() + const override { + return CreateDeviceDescription(0); + } + + static tsl::StatusOr> + CreateDeviceDescription(int device_ordinal); + + tsl::Status EnablePeerAccessTo(StreamExecutorInterface* other) override { + return ::tsl::OkStatus(); + } + + bool CanEnablePeerAccessTo(StreamExecutorInterface* other) override { + return true; + } + + blas::BlasSupport* CreateBlas() override; + + dnn::DnnSupport* CreateDnn() override { return nullptr; } + + fft::FftSupport* CreateFft() override; + + std::unique_ptr CreateEventImplementation() + override; + + std::unique_ptr CreateKernelImplementation() + override { + return nullptr; + } + + std::unique_ptr GetStreamImplementation() override; + + void* GpuContextHack() override { return nullptr; } + + private: + // Size of thread stacks for streams in bytes. '0' means "the default size". + size_t thread_stack_size_in_bytes_ = 0; +}; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_GPU_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform.h new file mode 100644 index 0000000000000000000000000000000000000000..4461669b95bbd5a6a9d901680a983f830937c569 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform.h @@ -0,0 +1,77 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Declares the "host" platform, which is a CPU-only implementation of the +// StreamExecutor. The host platform only supports memory operations and plugin +// routines, and is primarily used for testing. +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_H_ + +#include +#include +#include + +#include "xla/stream_executor/executor_cache.h" +#include "xla/stream_executor/multi_platform_manager.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/stream_executor/trace_listener.h" + +namespace stream_executor { +namespace host { + +// Host (CPU) platform plugin, registered as a singleton value via module +// initializer. +class HostPlatform : public Platform { + public: + HostPlatform(); + ~HostPlatform() override; + + Platform::Id id() const override; + + // Device count is less clear-cut for CPUs than accelerators. This call + // currently returns the number of thread units in the host, as reported by + // base::NumCPUs(). + int VisibleDeviceCount() const override; + + const std::string& Name() const override; + + tsl::StatusOr> DescriptionForDevice( + int ordinal) const override; + + tsl::StatusOr ExecutorForDevice(int ordinal) override; + + tsl::StatusOr GetExecutor( + const StreamExecutorConfig& config) override; + + tsl::StatusOr> GetUncachedExecutor( + const StreamExecutorConfig& config) override; + + private: + // This platform's name. + std::string name_; + + // Cache of created StreamExecutors. + ExecutorCache executor_cache_; + + HostPlatform(const HostPlatform&) = delete; + void operator=(const HostPlatform&) = delete; +}; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform_id.h new file mode 100644 index 0000000000000000000000000000000000000000..e29fb5a5188b53d86bee610c176340dec19416d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_platform_id.h @@ -0,0 +1,34 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_ID_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_ID_H_ + +#include "xla/stream_executor/platform.h" + +namespace stream_executor { +namespace host { + +// Opaque and unique identifier for the host platform. +// This is needed so that plugins can refer to/identify this platform without +// instantiating a HostPlatform object. +// This is broken out here to avoid a circular dependency between HostPlatform +// and HostStreamExecutor. +extern const Platform::Id kHostPlatformId; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_PLATFORM_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..ed5bc0b056fc18b47363d69da5ffc9f0b0b0d3fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host/host_stream.h @@ -0,0 +1,66 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Class declaration for Stream type that enqueues tasks onto a host/CPU-based +// execution context (as opposed to a GPU device), HostExecutor. +#ifndef XLA_STREAM_EXECUTOR_HOST_HOST_STREAM_H_ +#define XLA_STREAM_EXECUTOR_HOST_HOST_STREAM_H_ + +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/stream_executor_internal.h" +#include "tsl/platform/env.h" + +namespace stream_executor { +namespace host { + +class HostStream : public internal::StreamInterface { + public: + // stack_size_in_bytes may be '0', meaning "use the default thread stack + // size". + explicit HostStream(size_t stack_size_in_bytes); + ~HostStream() override; + + // Enqueue a task that reports a status when finished. Tasks that fail do not + // stop the stream or block any other tasks from executing; rather, the stream + // will remember the first error encountered and return it from + // 'BlockUntilDone'. + bool EnqueueTaskWithStatus(absl::AnyInvocable task); + // Enqueue a task that doesn't report any status. + bool EnqueueTask(absl::AnyInvocable task); + + // Blocks until all tasks are done, returns the first error reported by a task + // (if any) and clears the error status. + tsl::Status BlockUntilDone(); + + private: + bool WorkAvailable() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + void WorkLoop(); + + absl::Mutex mu_; + std::queue> work_queue_ + ABSL_GUARDED_BY(mu_); + std::unique_ptr thread_; + tsl::Status status_; +}; + +} // namespace host +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_HOST_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host_or_device_scalar.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host_or_device_scalar.h new file mode 100644 index 0000000000000000000000000000000000000000..a7d428d05e5657459bd9f5c5aa8e83c07bf8eddc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/host_or_device_scalar.h @@ -0,0 +1,52 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ +#define XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ + +#include +#include + +#include "xla/stream_executor/device_memory.h" + +namespace stream_executor { + +// Allows to represent a value that is either a host scalar or a scalar stored +// on the device. +template +class HostOrDeviceScalar { + public: + explicit HostOrDeviceScalar(T host_value) : value_(std::move(host_value)) {} + explicit HostOrDeviceScalar(DeviceMemory device_ptr) + : value_(std::move(device_ptr)) { + CHECK_EQ(1, device_ptr.ElementCount()); + } + + bool on_device() const { + return std::holds_alternative>(value_); + } + + const void* opaque() const { + return on_device() ? std::get>(value_).opaque() + : &std::get(value_); + } + + private: + std::variant> value_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_HOST_OR_DEVICE_SCALAR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4a9f7fbbc95c66261d1447190c4249958de8d223 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel.h @@ -0,0 +1,743 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Suite of datatypes to represent data-parallel kernel objects (code entities). +// Kernel is the untyped variant, whereas TypedKernel takes a type signature +// to do some template-based helper generation and give compile-time type +// checking for kernel launch parameters. +// +// Users typically don't see KernelBase, they see typed kernels, analogous to a +// typed function pointer. TypedKernels express their argument types via +// template parameters like so: +// +// TypedKernel*, int> +// +// Which expresses a data parallel kernel signature for: +// +// void(int*, int); +// +// And for a const memory region: +// +// TypedKernel&, int> +// +// Corresponds to a data parallel kernel signature for: +// +// void(const int*, int) +// +// Note that kernels always have a void return type, so results typically must +// be memcpy'ied from device memory to the host. +// +// Also note that a scalar integer residing in device memory and an array of +// integers residing in device memory have the same signature: DeviceMemory. +// However, in the future, checks may be added for additional safety that arrays +// of minimum sizes are passed when those minimum sizes are contractually +// expected by the kernel. +// +// For user-defined types whose definitions are appropriately shared between the +// host code doing the launching and the kernel code being launched, the user +// defined types are similarly permitted to be expressed as residing in device +// memory: +// +// TypedKernel> +// +// And, when the alignment and padding are agreed upon, POD types will also be +// able to be passed by value; for example, it is a common idiom to specify a +// bunch of options simultaneously with a structure: +// +// TypedKernel> +// +// Which corresponds to a data parallel kernel signature like: +// +// void(MyOptionsStructurePassedByValue value, float *result); +// +// Users typically won't need to type out the TypedKernel signature in full, it +// will be typedef'd by automatically generated code; for example, see +// stream_executor::executor_sample::VecReduceAddKernel. + +#ifndef XLA_STREAM_EXECUTOR_KERNEL_H_ +#define XLA_STREAM_EXECUTOR_KERNEL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/kernel_cache_config.h" +#include "xla/stream_executor/platform/port.h" + +namespace stream_executor { + +class DeviceMemoryBase; +template +class DeviceMemory; +class StreamExecutor; + +namespace internal { +class KernelInterface; +} // namespace internal + +// KernelMetadata holds runtime-queryable attributes of a loaded kernel, such as +// registers allocated, shared memory used, etc. +// Not all platforms support reporting of all information, so each accessor +// returns false if the associated field is not populated in the underlying +// platform. +class KernelMetadata { + public: + KernelMetadata() + : has_registers_per_thread_(false), has_shared_memory_bytes_(false) {} + + // Returns the number of registers used per thread executing this kernel. + bool registers_per_thread(int *registers_per_thread) const; + + // Sets the number of registers used per thread executing this kernel. + void set_registers_per_thread(int registers_per_thread); + + // Returns the amount of [static] shared memory used per block executing this + // kernel. Note that dynamic shared memory allocations are not (and can not) + // be reported here (since they're not specified until kernel launch time). + bool shared_memory_bytes(int *shared_memory_bytes) const; + + // Sets the amount of [static] shared memory used per block executing this + // kernel. + void set_shared_memory_bytes(int shared_memory_bytes); + + private: + // Holds the value returned by registers_per_thread above. + bool has_registers_per_thread_; + int registers_per_thread_; + + // Holds the value returned by shared_memory_bytes above. + bool has_shared_memory_bytes_; + int64_t shared_memory_bytes_; +}; + +// A data-parallel kernel (code entity) for launching via the StreamExecutor, +// analogous to a void* device function pointer. See TypedKernel for the typed +// variant. +// +// Thread-compatible. +class KernelBase { + public: + KernelBase(KernelBase &&from); + + // Constructs an "empty" (not-yet-loaded) kernel instance. + // + // parent is the StreamExecutor that will be responsible for loading the + // implementation of this kernel. It must not be null. + explicit KernelBase(StreamExecutor *parent); + + // Test-only constructor that can take a mock KernelInterface implementation. + KernelBase(StreamExecutor *parent, internal::KernelInterface *implementation); + + // Releases resources associated with the kernel instance (i.e. + // platform-specific implementation). + ~KernelBase(); + + // Returns the number of parameters that this kernel accepts. (Arity refers to + // nullary, unary, ...). + unsigned Arity() const; + + // Returns the StreamExecutor that represents the platform this kernel + // executes upon. + StreamExecutor *parent() const { return parent_; } + + // Returns a const pointer to the (opaque) platform-dependent implementation. + const internal::KernelInterface *implementation() const { + return implementation_.get(); + } + + // Returns a non-const pointer to the (opaque) platform-dependent + // implementation. + internal::KernelInterface *implementation() { return implementation_.get(); } + + void set_metadata(const KernelMetadata &metadata) { metadata_ = metadata; } + + const KernelMetadata &metadata() const { return metadata_; } + + // Sets the preferred cache configuration for a kernel. This is just a + // suggestion to the runtime, and may not be honored during execution. + void SetPreferredCacheConfig(KernelCacheConfig config); + + // Gets the preferred cache configuration for a kernel. + KernelCacheConfig GetPreferredCacheConfig() const; + + void set_name(absl::string_view name); + const std::string &name() const { return name_; } + const std::string &demangled_name() const { return demangled_name_; } + + private: + // The StreamExecutor that loads this kernel object. + StreamExecutor *parent_; + + // Implementation delegated to for platform-specific functionality. + std::unique_ptr implementation_; + + std::string name_; + std::string demangled_name_; + + KernelMetadata metadata_; + + KernelBase(const KernelBase &) = delete; + void operator=(const KernelBase &) = delete; +}; + +// Whether T is a DeviceMemory-family pointer. +template +struct IsDeviceMemoryPointer { + static constexpr bool value = false; +}; + +template +struct IsDeviceMemoryPointer *> { + static constexpr bool value = true; +}; + +template <> +struct IsDeviceMemoryPointer { + static constexpr bool value = true; +}; + +// Whether T is a DeviceMemory-family value-like thing (which includes a +// reference). This trait is useful because we pack values in the same manner as +// references. +template +struct IsDeviceMemoryValueLike { + static constexpr bool value = false; +}; + +template +struct IsDeviceMemoryValueLike &> { + static constexpr bool value = true; +}; + +// We need to treat SharedDeviceMemory types differently than other DeviceMemory +// types (since they maintain no allocations), hence these specializations. +template +struct IsDeviceMemoryValueLike &> { + static constexpr bool value = false; +}; + +template <> +struct IsDeviceMemoryValueLike { + static constexpr bool value = true; +}; + +template +struct IsDeviceMemoryValueLike> { + static constexpr bool value = true; +}; + +template +struct IsDeviceMemoryValueLike> { + static constexpr bool value = false; +}; + +template <> +struct IsDeviceMemoryValueLike { + static constexpr bool value = true; +}; + +template +struct IsSharedDeviceMemory { + static constexpr bool value = false; +}; + +template +struct IsSharedDeviceMemory &> { + static constexpr bool value = true; +}; + +template +struct IsSharedDeviceMemory> { + static constexpr bool value = true; +}; + +// Basic data about a kernel argument. +struct KernelArg { + bool is_shared; + const void *address; + size_t size; +}; + +// An iterator for traversing all the arguments of a KernelArgsArray. +class KernelArgIterator { + public: + KernelArgIterator(int number_of_argument_addresses, + int number_of_shared_memory_arguments, + const void *const *arg_addresses_data, + const size_t *arg_sizes_data, + const size_t *shmem_bytes_data, + const size_t *shmem_indices_data) + : arg_index_(0), + number_of_arguments_(number_of_argument_addresses + + number_of_shared_memory_arguments), + arg_address_iter_(arg_addresses_data), + arg_size_iter_(arg_sizes_data), + shmem_bytes_iter_(shmem_bytes_data), + shmem_indices_iter_(shmem_indices_data), + shmem_indices_end_(shmem_indices_data + + number_of_shared_memory_arguments) {} + + // Returns true if another argument is present in the iterator. + bool has_next() { return arg_index_ < number_of_arguments_; } + + // Returns the next argument in the iterator. + // + // Returns a default-constructed KernelArg if there is no next argument. + KernelArg next() { + KernelArg result = {}; + if (!has_next()) { + return result; + } else if ((shmem_indices_iter_ != shmem_indices_end_) && + (arg_index_ == *shmem_indices_iter_)) { + result.is_shared = true; + result.address = nullptr; + result.size = *shmem_bytes_iter_; + ++shmem_indices_iter_; + ++shmem_bytes_iter_; + } else { + result.is_shared = false; + result.address = *arg_address_iter_; + result.size = *arg_size_iter_; + ++arg_address_iter_; + ++arg_size_iter_; + } + ++arg_index_; + return result; + } + + private: + size_t arg_index_; + size_t number_of_arguments_; + const void *const *arg_address_iter_; + const size_t *arg_size_iter_; + const size_t *shmem_bytes_iter_; + const size_t *shmem_indices_iter_; + const size_t *const shmem_indices_end_; +}; + +// Base class for KernelArgsArray. +// +// Supports all the getter methods that do not depend on the compile-time number +// of arguments template parameter. +// +// This class exists as a way to pass kernel arguments to +// StreamExecutorInterface::Launch. That Launch method is virtual, so it can't +// be templated to accept any KernelArgsArray type, therefore a reference to +// this base type is passed instead. +// +// Performance is not a concern here because each of these methods will be +// called at most once per kernel launch. Past performance concerns with +// KernelArgsArray have been in reference to the argument packing routines which +// are called once per kernel argument. Those packing routines are now handled +// by the templated KernelArgsArray subclass of this class where they can take +// advantage of compile-time knowledge of the number of arguments in order to be +// very efficient. +class KernelArgsArrayBase { + public: + virtual ~KernelArgsArrayBase() = default; + + // Gets the number of arguments added so far, including shared memory + // arguments. + virtual size_t number_of_arguments() const = 0; + + // Gets the total number of shared memory bytes added so far. + virtual uint64_t number_of_shared_bytes() const = 0; + + // Gets the list of argument addresses. + virtual absl::Span argument_addresses() const = 0; + + // Gets an iterator to the arguments in the array. + virtual KernelArgIterator arg_iterator() const = 0; +}; + +// A list of arguments for a kernel call. +// +// The template parameter kNumArgs is the maximum number of arguments which can +// be stored in the list. +// +// Contains a list of addresses for non-shared-memory arguments and a list of +// sizes for shared-memory arguments. Since the shared-memory arguments may be +// interspersed with the non-shared-memory arguments, it also stores a list of +// the indices at which the shared-memory arguments appeared. +// +// For example, if the argument address list contains {a, b, c, d, e}, the +// shared-memory arguments list contains the sizes of {A, B, C}, and the +// shared-memory indices list contains {0, 3, 5}, then the original list of +// arguments was {A, a, b, B, c, C, d, e}. +// +// This way of storing the arguments makes CUDA kernel calls efficient because +// they only require the argument address list and the total number of shared +// bytes, but it also makes it possible for OpenCL kernel calls because they +// depend on the location of each shared-memory argument and its size. +// +// Note that the code for adding arguments has been identified as a performance +// hotspot in some real-world applications so this structure has been optimized +// for the performance of argument adding. +template +class KernelArgsArray : public KernelArgsArrayBase { + public: + static constexpr int kMaxGenericArgSize = 8; + + // Adds an argument to the list. + template + void add_argument(const T &arg) { + static_assert(sizeof(T) <= kMaxGenericArgSize, + "Please adjust kMaxGenericArgSize"); + static_assert(std::is_pod::value, "Only pod types supported!"); + char *generic_arg_storage = + &generic_arguments_[number_of_generic_arguments_++ * + kMaxGenericArgSize]; + + CHECK_EQ(reinterpret_cast(generic_arg_storage) % alignof(T), 0); + std::memcpy(generic_arg_storage, &arg, sizeof(T)); + + argument_addresses_[number_of_argument_addresses_] = generic_arg_storage; + argument_sizes_[number_of_argument_addresses_] = sizeof(arg); + ++number_of_argument_addresses_; + } + + // Adds a device memory argument to the list. + void add_device_memory_argument(const DeviceMemoryBase &arg) { + const void **copy_ptr = + &device_memory_opaque_pointers_[number_of_argument_addresses_]; + *copy_ptr = arg.opaque(); + argument_addresses_[number_of_argument_addresses_] = copy_ptr; + argument_sizes_[number_of_argument_addresses_] = sizeof(void *); + ++number_of_argument_addresses_; + } + + // Adds a shared memory argument to the list. + // + // The only significant information about a shared argument is its size, so + // that is the only parameter in this function. + void add_shared_bytes(size_t number_of_bytes) { + shared_memory_indices_[number_of_shared_memory_arguments_] = + number_of_argument_addresses_ + number_of_shared_memory_arguments_; + shared_memory_bytes_[number_of_shared_memory_arguments_] = number_of_bytes; + ++number_of_shared_memory_arguments_; + total_shared_memory_bytes_ += number_of_bytes; + } + + // Gets the number of arguments added so far, including shared memory + // arguments. + size_t number_of_arguments() const override { + return number_of_argument_addresses_ + number_of_shared_memory_arguments_; + } + + // Gets the total number of shared memory bytes added so far. + uint64_t number_of_shared_bytes() const override { + return total_shared_memory_bytes_; + } + + // Gets the list of argument addresses. + absl::Span argument_addresses() const override { + return absl::Span(argument_addresses_.data(), + number_of_argument_addresses_); + } + + // Gets an iterator to the arguments in the array. + KernelArgIterator arg_iterator() const override { + return KernelArgIterator( + number_of_argument_addresses_, number_of_shared_memory_arguments_, + argument_addresses_.data(), argument_sizes_.data(), + shared_memory_bytes_.data(), shared_memory_indices_.data()); + } + + private: + // A place to store copies of opaque pointers from device memory arguments. + std::array device_memory_opaque_pointers_; + + // Addresses for non-shared-memory arguments. + std::array argument_addresses_; + + // Storage for arguments of templated type. + alignas(kMaxGenericArgSize) + std::array generic_arguments_; + + // Sizes for non-shared-memory arguments. + std::array argument_sizes_; + + // Size in bytes for each shared memory argument. + std::array shared_memory_bytes_; + + // Indices in the arguments array for shared memory arguments. + std::array shared_memory_indices_; + + // Total of all shared memory sizes. + size_t total_shared_memory_bytes_ = 0; + + // Number of significant entries in argument_addresses_ and argument_sizes_. + size_t number_of_argument_addresses_ = 0; + + // Number of significant entries in shared_memory_bytes_ and + // shared_memory_indices_. + size_t number_of_shared_memory_arguments_ = 0; + + // The number of generic arguments that have been added to generic_arguments_. + size_t number_of_generic_arguments_ = 0; +}; + +template +std::unique_ptr MakeKernelArgs( + absl::Span args, uint32_t shared_mem_bytes) { + auto kernel_args = std::make_unique>(); + for (const DeviceMemoryBase &buf : args) { + kernel_args->add_device_memory_argument(buf); + } + if (shared_mem_bytes > 0) { + kernel_args->add_shared_bytes(shared_mem_bytes); + } + return kernel_args; +} + +// Typed variant of KernelBase, like a typed device function pointer. See the +// file comment for details and example usage. +// +// This class contains template metaprogramming magic to type check the +// parameters passed to a kernel launch are acceptable, and subsequently pack +// them into a form which can be used by the StreamExecutorInterface +// implementation. (i.e. CUDA and OpenCL both bind void*s with associated +// sizes as kernel arguments.) +// +// Thread-compatible. +template +class TypedKernel : public KernelBase { + public: + static constexpr size_t kNumberOfParameters = sizeof...(Params); + + // Delegates to KernelBase::KernelBase(), see that constructor. + explicit TypedKernel(StreamExecutor *parent) : KernelBase(parent) {} + + // Test-only constructor that can take a mock KernelInterface implementation. + // Takes ownership of implementation, it should not be null. + TypedKernel(StreamExecutor *parent, internal::KernelInterface *implementation) + : KernelBase(parent, implementation) {} + + // This is the main entry point into the magic. Packs the parameters (which + // must type check against the class template) into the args and sizes + // arrays. + // + // Const refs are taken as parameters on all of the handlers to avoid + // implicit type promotion of integers. + // + // WARNING: as a performance optimization this method may store pointers to + // some of the input parameters in the kernel args structure, so any params + // passed into this method must live at least as long as the kernel args + // structure. + void PackParams(KernelArgsArray *args, + const Params &...params) const { + PackOneParamFromList(args, params...); + } + + private: + // Stream needs access to the specific parameter-packing functionality that + // the TypedKernel provides for its corresponding type signature (and no other + // type signatures). + friend class Stream; + + template + void PackOneParamFromList(KernelArgsArray *args, + const T &arg, const RestOfParams &...rest) const { + PackOneParam(args, arg); + PackOneParamFromList(args, rest...); + } + + // Base case for variadic template expansion - nothing to do! + void PackOneParamFromList(KernelArgsArray *args) const {} + + // Packs one (non-DeviceMemoryBase) parameter into the arg and sizes array. + // The enable_if<> is for excluding DeviceMemoryBase args, which have a + // separate implementation below. + template + void PackOneParam( + KernelArgsArray *args, const T &arg, + typename std::enable_if::value && + !IsDeviceMemoryPointer::value && + !IsSharedDeviceMemory::value>::type * = + nullptr) const { + static_assert(!std::is_pointer::value, + "cannot pass raw pointer to the device"); + static_assert(!std::is_convertible::value, + "cannot pass device memory as a normal value"); + args->add_argument(arg); + } + + // DeviceMemoryBase family reference override. + template + void PackOneParam( + KernelArgsArray *args, const T &arg, + typename std::enable_if::value>::type * = + nullptr) const { + args->add_device_memory_argument(arg); + } + + // DeviceMemoryBase family pointer override. + template + void PackOneParam( + KernelArgsArray *args, T arg, + typename std::enable_if::value>::type * = + nullptr) const { + DeviceMemoryBase *ptr = static_cast(arg); + args->add_device_memory_argument(*ptr); + } + + // Dynamic shared device memory has a size, but no associated allocation on + // the host; internally, the device will allocate storage. + template + void PackOneParam( + KernelArgsArray *args, T arg, + typename std::enable_if::value>::type * = + nullptr) const { + args->add_shared_bytes(arg.size()); + } + + TypedKernel(const TypedKernel &) = delete; + void operator=(const TypedKernel &) = delete; +}; + +// Template metaprogramming helper type that helps us produce better error +// messages at compile time when the are mismatches between the parameter +// type list and the argument type list. +template +struct KernelInvocationChecker { + // Whether the parameter tuple and argument tuple match in length. + static constexpr bool kLengthMatches = + std::tuple_size::value == std::tuple_size::value; + + // The (matching) length of the parameters and arguments type lists. + static constexpr int kTupleLength = + static_cast(std::tuple_size::value); + + // Helper trait to say whether the parameter wants a DeviceMemory-reference + // compatible type. This is for inexact type matches, so that it doesn't have + // to be precisely a const DeviceMemory&, but can also be a value that + // represents the same. + template + struct IsCompatibleDeviceMemoryRef { + static constexpr bool value = false; + }; + + // See type trait definition above. + template + struct IsCompatibleDeviceMemoryRef &, DeviceMemory> { + static constexpr bool value = true; + }; + + // See type trait definition above. + template + struct IsCompatibleDeviceMemoryRef &, + SharedDeviceMemory> { + static constexpr bool value = true; + }; + + // Returns whether ParamT and ArgT are compatible for data parallel kernel + // parameter packing without any assert functionality. + template + static constexpr bool CompatibleNoAssert() { + return std::is_same::type, + ArgT>::value || + IsCompatibleDeviceMemoryRef::value; + } + + // Checks whether ParamT and ArgT are compatible for data parallel kernel + // parameter packing. kArgumentNumber is unused, it just for error display. + // + // NOTE: if you encounter an error here, you can see the mismatch by looking + // at the end of the last error message, which will be of the form: + // + // ...::Compatible &, + // stream_executor::DeviceMemory, true, + // 0>' + // requested here + // + // This means that the 0th argument you passed to the kernel invocation should + // have been DeviceMemory but was observed to be + // DeviceMemory. + template + static constexpr bool Compatible() { + static_assert( + kShouldStaticAssert ? CompatibleNoAssert() : true, + "parameter type (LHS) is not compatible with argument type (RHS)"); + return CompatibleNoAssert(); + } + + // Checks the parameter/argument match at kArgumentNumber for an out of bounds + // argument number. + // + // This is the base case: we've run out of argument to check, so we're all + // good. + template + static constexpr bool CheckParam( + typename std::enable_if<(kArgumentNumber < 0)>::type *dummy = nullptr) { + return true; + } + + // Checks the parameter/argument match at kArgumentNumber. + // kShouldStaticAssert determines whether to assert out on a mismatch, or just + // yield the constexpr boolean value. + template + static constexpr bool CheckParam( + typename std::enable_if= 0>::type *dummy = nullptr) { + typedef + typename std::tuple_element::type ParamT; + typedef typename std::tuple_element::type ArgT; + return Compatible() && + CheckParam(); + } + + // Checks the parameters/arguments for match, but doesn't static assert out. + // This is useful for testing/inspecting whether a set of parameters match in + // things like tests. + static constexpr bool CheckAllNoStaticAssert() { + return kLengthMatches && CheckParam(); + } + + // Checks the parameters and static asserts out with a helpful error message + // (and useful template parameters in the instantiation stack) if there is an + // error. + static constexpr bool CheckAllStaticAssert() { + static_assert(kLengthMatches, + "argument length mismatched against typed kernel parameters"); + return kLengthMatches && CheckParam(); + } +}; + +// This is a convenience type for checking whether a typed kernel matches +// against a type list. +template +struct KernelParamsOk { + static constexpr bool kResult = false; +}; + +// See above. +template +struct KernelParamsOk, Args...> { + static constexpr bool kResult = + KernelInvocationChecker, + std::tuple>::CheckAllNoStaticAssert(); +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_KERNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_cache_config.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_cache_config.h new file mode 100644 index 0000000000000000000000000000000000000000..f72b3fcbf53fe3247f7caa2ab9c893ac49c8a38a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_cache_config.h @@ -0,0 +1,42 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file contains declarations relating to kernel cache configuration +// parameters recognized by the StreamExecutor. +#ifndef XLA_STREAM_EXECUTOR_KERNEL_CACHE_CONFIG_H_ +#define XLA_STREAM_EXECUTOR_KERNEL_CACHE_CONFIG_H_ + +namespace stream_executor { + +// This enum represents potential configurations of L1/shared memory when +// running a particular kernel. These values represent user preference, and +// the runtime is not required to respect these choices. +enum class KernelCacheConfig { + // Indicates no preference for device L1/shared memory configuration. + kNoPreference, + + // Indicates a preference for more shared memory than L1 cache. + kPreferShared, + + // Indicates a preference for more L1 cache than shared memory. + kPreferL1, + + // Indicates a preference for equal amounts of L1 cache and shared memory. + kPreferEqual, +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_KERNEL_CACHE_CONFIG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..68f45a0ee07f4df19349e12ca2e3932f81cf8ddc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/kernel_spec.h @@ -0,0 +1,316 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Kernel-loader specs are structures that describe how to load a data-parallel +// kernel on a given platform for subsequent launching. Headers that instantiate +// these data structures will typically be auto-generated. However, users can +// also instantiate them by hand. +// +// A kernel with the same exact functionality and type signature may be +// implemented on several different platforms. Typical usage is to create a +// singleton that describes how to load a kernel on the various supported +// platforms: +// +// static const MultiKernelLoaderSpec &SaxpySpec() { +// static auto *mkls = +// (new MultiKernelLoaderSpec{4 /* = arity */}) +// ->AddCudaPtxOnDisk(ptx_file_path, ptx_kernel_name); +// }; +// +// return *mkls; +// } +// +// This lazily instantiates an object that describes how to load CUDA PTX +// present on disk that implements saxpy for the CUDA platform. The +// CudaPtxOnDisk object is a subtype of KernelLoaderSpec -- KernelLoaderSpec +// describes how to load a kernel for subsequent launching on a single platform. +// +// For the loader functionality that accepts these KernelLoaderSpecs in order +// to grab the kernel appropriately, see StreamExecutor::GetKernel(). + +#ifndef XLA_STREAM_EXECUTOR_KERNEL_SPEC_H_ +#define XLA_STREAM_EXECUTOR_KERNEL_SPEC_H_ + +#include + +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { + +// Describes how to load a kernel on a target platform. +// +// This is an abstract base class, subclassed for specific platforms. +// The filename_or_text field represents the program location (i.e. PTX or +// OpenCL loadable translation unit path) and is simply stored; whether it is a +// filename or text is exposed via more specifically named accessors in +// subclasses. +// +// These kernel loader specifications are typically auto-generated into header +// files at build time, but can also be specified manually. +class KernelLoaderSpec { + public: + virtual ~KernelLoaderSpec() {} + + // Returns the kernel name to load out of the program. + const std::string &kernel_name() const { return kernel_name_; } + + protected: + explicit KernelLoaderSpec(absl::string_view kernel_name); + + private: + // The kernel name that should be loaded out of the program description given + // above. + std::string kernel_name_; + + KernelLoaderSpec(const KernelLoaderSpec &) = delete; + void operator=(const KernelLoaderSpec &) = delete; +}; + +// An abstract kernel loader spec that has an associated file path, where +// there's a canonical suffix for the filename; e.g. see CudaPtxOnDisk whose +// canonical filename suffix is ".ptx". +class OnDiskKernelLoaderSpec : public KernelLoaderSpec { + public: + ~OnDiskKernelLoaderSpec() override {} + + // Returns the path to the on-disk loadable kernel file. + const std::string &filename() const { return filename_; } + + // Returns the canonical suffix for this on-disk kernel loader spec format; + // e.g. PTX files on disk have a canonical suffix of ".ptx". + virtual const char *CanonicalSuffix() const = 0; + + protected: + OnDiskKernelLoaderSpec(absl::string_view filename, + absl::string_view kernel_name); + + std::string filename_; + + private: + OnDiskKernelLoaderSpec(const OnDiskKernelLoaderSpec &) = delete; + void operator=(const OnDiskKernelLoaderSpec &) = delete; +}; + +// Kernel loader specification for PTX text that resides on disk. +class CudaPtxOnDisk : public OnDiskKernelLoaderSpec { + public: + CudaPtxOnDisk(absl::string_view filename, absl::string_view kernel_name); + ~CudaPtxOnDisk() override {} + + const char *CanonicalSuffix() const override { return ".ptx"; } + + private: + CudaPtxOnDisk(const CudaPtxOnDisk &) = delete; + void operator=(const CudaPtxOnDisk &) = delete; +}; + +// Kernel loader specification for CUBIN binary that resides on disk. +class CudaCubinOnDisk : public OnDiskKernelLoaderSpec { + public: + CudaCubinOnDisk(absl::string_view filename, absl::string_view kernel_name); + ~CudaCubinOnDisk() override {} + + const std::string &filename() const { return filename_; } + + const char *CanonicalSuffix() const override { return ".cubin"; } + + private: + std::string filename_; + + CudaCubinOnDisk(const CudaCubinOnDisk &) = delete; + void operator=(const CudaCubinOnDisk &) = delete; +}; + +// Kernel loader specification for PTX text that resides in memory. +class CudaPtxInMemory : public KernelLoaderSpec { + public: + // Components: compute capability major number, compute capability minor + // number, and PTX source. + typedef std::tuple PtxSpec; + + // Single-PTX constructor. Adds the provided PTX version with an unknown + // compute capability. Since the CC is unknown, the PTX is assumed to be very + // generally usable - in other words, PTX specified in this manner is VERY + // likely to be used as the default! Note that the PTX can be compressed, + // which is indicated by the argument ptx_compressed. + // + // Warning: the string backing the provided absl::string_view ptx must outlive + // this instance. + CudaPtxInMemory(absl::string_view ptx, absl::string_view kernel_name, + bool ptx_compressed = false); + + // Multiple-PTX-version constructor. Adds each item in spec_list to this + // object. Note that the PTX can be compressed, which is indicated by the + // argument ptx_compressed. + CudaPtxInMemory(const std::initializer_list &spec_list, + absl::string_view kernel_name, bool ptx_compressed = false); + ~CudaPtxInMemory() override {} + + // Add the PTX implementation described by ptx_spec to this object. On + // collision (i.e., if a version with the same compute_capability already + // exists), the existing implementation will be overwritten. + void AddSpec(PtxSpec ptx_spec); + + // Returns pointer to the ptx of available implementation with the + // lowest-valued compute capability. For example, if PTX written to CC2.0, + // 3.0, and 3.5 are all available, the version for CC2.0 will be set. Returns + // nullptr on failed lookup (if any version is not available). + // When the ptx is compressed, returns the decompressed ptx. + const char *default_text() const; + + // Similar to default_text(). + // When the ptx is compressed, returns the decompressed ptx. + const char *original_default_text() const; + + // Returns pointer to the ptx for the requested compute capability. + // Returns nullptr on failed lookup (if the requested version is not + // available). + // When the ptx is compressed, returns the decompressed ptx. + const char *text(int compute_capability_major, + int compute_capability_minor) const; + + // Similar to text(). + // When the ptx is compressed, returns the original compressed ptx. + const char *original_text(int compute_capability_major, + int compute_capability_minor) const; + + // Decompresses the PTX string using bzip2. + static std::string DecompressPtx(const char *ptx); + + private: + // PTX translation unit text contents in memory. The key is of as a tuple + // ",", i.e., "2,0", "3,0", "3,5". Because CC's + // represented in this way have a clear sorting order, map::begin() will give + // the lowest-numbered version available, i.e. the default. + std::map, const char *, + bool (*)(const std::tuple &, const std::tuple &)> + ptx_by_compute_capability_; + + // Stores all decompressed ptx strings, with original ptx string as keys. + // It is marked as mutable for lazy decompression. + mutable std::map decompressed_ptx_; + mutable absl::Mutex mu_; + + // Defines the minimum compute capability possible. Used when PTX has no + // compute capability specified (in the single-PTX constructor). + static const std::tuple kMinimumCapability; + + CudaPtxInMemory(const CudaPtxInMemory &) = delete; + void operator=(const CudaPtxInMemory &) = delete; +}; + +// Kernel loader specification for a CUBIN blob that resides in memory. +class CudaCubinInMemory : public KernelLoaderSpec { + public: + CudaCubinInMemory(const char *bytes, absl::string_view kernel_name); + ~CudaCubinInMemory() override {} + + const char *bytes() const { return bytes_; } + + private: + const char *bytes_; + + CudaCubinInMemory(const CudaCubinInMemory &) = delete; + void operator=(const CudaCubinInMemory &) = delete; +}; + +// Describes how to load a kernel on any subset of a number of target platforms. +class MultiKernelLoaderSpec { + public: + explicit MultiKernelLoaderSpec(size_t arity); + + // Returns the number of arguments that this kernel accepts. + size_t arity() const { return arity_; } + + // Convenience getters for testing whether these platform variants have + // kernel loader specifications available. + bool has_cuda_ptx_on_disk() const { return cuda_ptx_on_disk_ != nullptr; } + bool has_cuda_cubin_on_disk() const { return cuda_cubin_on_disk_ != nullptr; } + bool has_cuda_cubin_in_memory() const { + return cuda_cubin_in_memory_ != nullptr; + } + bool has_cuda_ptx_in_memory() const { return cuda_ptx_in_memory_ != nullptr; } + + // Accessors for platform variant kernel load specifications. + // Precondition: corresponding has_* is true. + const CudaPtxOnDisk &cuda_ptx_on_disk() const { + CHECK(has_cuda_ptx_on_disk()); + return *cuda_ptx_on_disk_; + } + const CudaCubinOnDisk &cuda_cubin_on_disk() const { + CHECK(has_cuda_cubin_on_disk()); + return *cuda_cubin_on_disk_; + } + const CudaCubinInMemory &cuda_cubin_in_memory() const { + CHECK(has_cuda_cubin_in_memory()); + return *cuda_cubin_in_memory_; + } + const CudaPtxInMemory &cuda_ptx_in_memory() const { + CHECK(has_cuda_ptx_in_memory()); + return *cuda_ptx_in_memory_; + } + // Builder-pattern-like methods for use in initializing a + // MultiKernelLoaderSpec. Each of these should be used at most once for a + // single MultiKernelLoaderSpec object. See file comment for example usage. + // + // Note that the kernel_name parameter must be consistent with the kernel in + // the PTX being loaded. Also be aware that in CUDA C++ the kernel name may be + // mangled by the compiler if it is not declared in an extern "C" scope. + MultiKernelLoaderSpec *AddCudaPtxOnDisk(absl::string_view filename, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCubinOnDisk(absl::string_view filename, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCubinInMemory(const char *cubin_bytes, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaPtxInMemory(absl::string_view ptx, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCompressedPtxInMemory( + absl::string_view ptx, absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaPtxInMemory( + std::initializer_list spec_list, + absl::string_view kernel_name); + MultiKernelLoaderSpec *AddCudaCompressedPtxInMemory( + std::initializer_list spec_list, + absl::string_view kernel_name); + + private: + std::unique_ptr + cuda_ptx_on_disk_; // PTX text that resides in a file. + std::unique_ptr + cuda_cubin_on_disk_; // Binary CUDA program in a file. + std::unique_ptr + cuda_cubin_in_memory_; // Binary CUDA program in memory. + std::unique_ptr + cuda_ptx_in_memory_; // PTX text that resides in memory. + + // Number of parameters that the kernel takes. (This is nicer to have in a + // constexpr than having to determine it from the types via template + // metaprogramming). + size_t arity_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_KERNEL_SPEC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/launch_dim.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/launch_dim.h new file mode 100644 index 0000000000000000000000000000000000000000..ef7d03311bb6239d76aae5523b1f3a400cd37da2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/launch_dim.h @@ -0,0 +1,75 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Types to express dimensionality of a kernel launch. Blocks and threads +// are (up to) 3-dimensional. +// +// A thread is conceptually like a SIMD lane. Some number, typically 32 +// (though that fact should not be relied on) SIMD lanes are tied together with +// a single PC in a unit called a warp. There is a maximum number of threads +// that can execute in a shared-context entity called a block. Presently, that +// number is 1024 -- again, something that should not be relied on from this +// comment, but checked via stream_executor::DeviceDescription. +// +// For additional information, see +// http://docs.nvidia.com/cuda/kepler-tuning-guide/#device-utilization-and-occupancy +// +// Because of that modest thread-per-block limit, a kernel can be launched with +// multiple blocks. Each block is indivisibly scheduled onto a single core. +// Blocks can also be used in a multi-dimensional configuration, and the block +// count has much less modest limits -- typically they're similar to the maximum +// amount of addressable memory. + +#ifndef XLA_STREAM_EXECUTOR_LAUNCH_DIM_H_ +#define XLA_STREAM_EXECUTOR_LAUNCH_DIM_H_ + +#include +#include + +#include "absl/strings/str_cat.h" + +namespace stream_executor { + +// Thread dimensionality for use in a kernel launch. See file comment for +// details. +struct ThreadDim { + explicit ThreadDim(uint64_t x = 1, uint64_t y = 1, uint64_t z = 1) + : x(x), y(y), z(z) {} + + // Returns a string representation of the thread dimensionality. + std::string ToString() const { + return absl::StrCat("ThreadDim{", x, ", ", y, ", ", z, "}"); + } + + uint64_t x, y, z; +}; + +// Block dimensionality for use in a kernel launch. See file comment for +// details. +struct BlockDim { + explicit BlockDim(uint64_t x = 1, uint64_t y = 1, uint64_t z = 1) + : x(x), y(y), z(z) {} + + // Returns a string representation of the block dimensionality. + std::string ToString() const { + return absl::StrCat("BlockDim{", x, ", ", y, ", ", z, "}"); + } + + uint64_t x, y, z; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_LAUNCH_DIM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/lazy_op_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/lazy_op_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..2c390d75f921486c7463d20496943a34ce967bae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/lazy_op_runner.h @@ -0,0 +1,301 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +------------------------------------------------------------------------------*/ + +#ifndef XLA_STREAM_EXECUTOR_LAZY_OP_RUNNER_H_ +#define XLA_STREAM_EXECUTOR_LAZY_OP_RUNNER_H_ + +#include +#include +#include +#include +#include + +#include "absl/base/call_once.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/stream.h" + +namespace stream_executor { +namespace dnn { + +// A lazily-initialized OpRunner from an AlgorithmDesc. +// +// This exists to hold a choice of conv algorithm for a particular config, +// initialize its OpRunner at most once, and defer that initialization until the +// config is first needed. This allows AoT autotuning to load configurations +// for all convolutions it knows about, without doing expensive initialization +// (e.g. runtime codegen) and retaining non-negligible resources (e.g. compiled +// kernels) for potentially irrelevant configurations. It also enables XLA conv +// thunks to defer binding to a particular stream executor until the first run. +// +// `Op` must satisfy the following "concept": +// +// struct Op { +// // The function type signature parameter of an OpRunner. +// using Signature = _; +// +// // The parameter to be used by GetOrCreateRunner. +// struct Config; +// +// // Use a StreamExecutor to create an OpRunner. +// static StatusOr> OpRunnerFromDesc( +// const AlgorithmDesc& desc, Config config, StreamExecutor* stream); +// }; +template +class LazyOpRunner { + public: + // Construct from a pre-initialized OpRunner; all calls to GetOrCreateRunner + // will return a pointer to exactly this runner. + static tsl::StatusOr> FromOpRunner( + std::unique_ptr> runner) { + if (!runner) { + return tsl::errors::Internal("Null runner argument to FromOpRunner"); + } + TF_ASSIGN_OR_RETURN(auto desc, runner->ToAlgorithmDesc()); + // Private constructor cannot be called by make_unique :( + return {std::unique_ptr( + new LazyOpRunner(desc, std::move(runner)))}; + } + + // Construct from an AlgorithmDesc, with no pre-initialized OpRunner; it will + // be created on the first call to GetOrCreateRunner. + explicit LazyOpRunner(AlgorithmDesc desc) : LazyOpRunner(desc, nullptr) {} + + // Returns an already-initialized OpRunner if available, or creates one. + // + // Invariant: a particular instance of this class shall only receive calls + // with identical `config`s and `stream_executor`s. If the config is changed, + // only the first config it sees will have any effect, and second and + // subsequent configs will be ignored. If the stream executor is changed, + // some operations on the returned `OpRunner` using the changed stream + // executor will be errors. + // + // The result is owned by LazyOpRunner. + tsl::StatusOr*> GetOrCreateRunner( + typename Op::Config config, Stream* stream) { + absl::call_once(once_flag_, [&] { + if (runner_) return; // runner was passed via constructor argument + + auto r = Op::RunnerFromAlgorithmDesc(desc_, std::move(config), stream); + if (!r.ok()) { + error_ = std::move(r).status(); + } else { + runner_ = std::move(r).value(); + } + }); + + if (!error_.ok()) return error_; + return runner_.get(); + } + + // Get the contained runner with the invariant that it's already initialized. + tsl::StatusOr*> GetRunner() { + if (auto* runner = runner_ptr_.load(std::memory_order_acquire)) { + return runner; + } + return tsl::errors::Internal("LazyOpRunner::GetRunner: not initialized"); + } + + bool operator==(const LazyOpRunner& other) const { + return desc_ == other.desc_; + } + + std::string ToString() const { return desc_.ToString(); } + + const AlgorithmDesc& ToAlgorithmDesc() const { return desc_; } + + private: + LazyOpRunner(AlgorithmDesc desc, + std::unique_ptr> runner) + : desc_(std::move(desc)), + error_(tsl::OkStatus()), + runner_(std::move(runner)), + runner_ptr_(runner_.get()) {} + + AlgorithmDesc desc_; + + // We use absl::call_once to lazily initialize `runner_` (or `error_`). + absl::once_flag once_flag_; + tsl::Status error_; // holds error if runner can't be initialized + std::unique_ptr> runner_; + + // Once we initialize `runner_` we publish a pointer through atomic so that + // `GetRunner` can read it without data races with initialization. + std::atomic*> runner_ptr_; +}; + +// Implementation of the concept required by LazyOpRunner, for ConvRunner. +struct ConvOp { + using Signature = ConvSignature; + + struct Config { + ConvolutionKind kind; + DataType input_type, output_type; + const BatchDescriptor& input_descriptor; + const FilterDescriptor& filter_descriptor; + const BatchDescriptor& output_descriptor; + const ConvolutionDescriptor& convolution_descriptor; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->ConvolveRunnerFromDesc( + desc, config.kind, config.input_type, config.output_type, + config.input_descriptor, config.filter_descriptor, + config.output_descriptor, config.convolution_descriptor); + } +}; + +// Implementation of the concept required by LazyOpRunner, for +// GraphConvolveRunner. +struct GraphConvOp { + using Signature = GraphConvSignature; + + struct Config { + ConvolutionKind kind; + DataType input_type, output_type; + const BatchDescriptor& input_descriptor; + const FilterDescriptor& filter_descriptor; + const BatchDescriptor& output_descriptor; + const ConvolutionDescriptor& convolution_descriptor; + std::string serialized_graph; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->GraphConvolveRunnerFromDesc( + desc, config.kind, config.input_type, config.output_type, + config.input_descriptor, config.filter_descriptor, + config.output_descriptor, config.convolution_descriptor, + config.serialized_graph); + } +}; + +// Implementation of the concept required by LazyOpRunner, for LazyConvRunner. +struct FusedConvOp { + using Signature = FusedConvSignature; + + struct Config { + ConvolutionKind kind; + DataType input_type, bias_type, output_type; + double conv_scale, side_input_scale, leakyrelu_alpha; + const BatchDescriptor& input_descriptor; + const FilterDescriptor& filter_descriptor; + const BatchDescriptor& bias_descriptor; + const BatchDescriptor& output_descriptor; + const ConvolutionDescriptor& convolution_descriptor; + ActivationMode activation_mode; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->FusedConvolveRunnerFromDesc( + desc, config.kind, config.input_type, config.bias_type, + config.output_type, config.conv_scale, config.side_input_scale, + config.leakyrelu_alpha, config.input_descriptor, + config.filter_descriptor, config.bias_descriptor, + config.output_descriptor, config.convolution_descriptor, + config.activation_mode); + } +}; + +// Implementation of the concept required by LazyOpRunner, for FusedMatmul. +struct FusedMatmulOp { + using Signature = FusedMatmulSignature; + + // Config is mainly used in RunnerFromAlgorithmDesc() to lazily create the + // runner. At this moment we only get existing runners and don't implement + // this feature. + struct Config {}; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return tsl::errors::Unimplemented("Unimplemented"); + } +}; + +struct FusedMHAOp { + using Signature = FusedMHASignature; + struct Config { + FusedMHAKind kind; + double scale; + const MatmulTensorDescriptor& bmm1_lhs_descriptor; + const MatmulTensorDescriptor& bmm1_rhs_descriptor; + const MatmulTensorDescriptor& bmm2_rhs_descriptor; + const MatmulTensorDescriptor& intermediate_bmm2_lhs_descriptor; + const TensorDescriptor& output_descriptor; + std::optional bias_descriptor; + std::optional mask_descriptor; + std::optional activation_descriptor; + std::optional dropout_rate; + std::optional seed; + }; + + static tsl::StatusOr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->FusedMHARunnerFromDesc( + desc, config.kind, config.bmm1_lhs_descriptor, + config.bmm1_rhs_descriptor, config.bmm2_rhs_descriptor, + config.intermediate_bmm2_lhs_descriptor, config.output_descriptor, + config.activation_descriptor, config.mask_descriptor, + config.bias_descriptor, config.scale, config.dropout_rate, config.seed); + } +}; + +struct FusedMHABackwardOp { + using Signature = FusedMHABackwardSignature; + + struct Config { + FusedMHAKind kind; + double scale; + const MatmulTensorDescriptor& bmm1_grad_gemm1_rhs_descriptor; + const MatmulTensorDescriptor& bmm1_grad_gemm2_rhs_descriptor; + const MatmulTensorDescriptor& bmm2_grad_gemm1_lhs_descriptor; + const MatmulTensorDescriptor& bmm2_grad_gemm2_rhs_descriptor; + const MatmulTensorDescriptor& d_output_descriptor; + const TensorDescriptor& d_bmm1_lhs_descriptor; + const TensorDescriptor& d_bmm1_rhs_descriptor; + const TensorDescriptor& d_bmm2_rhs_descriptor; + const TensorDescriptor& d_s_descriptor; + std::optional mask_descriptor; + std::optional d_bias_descriptor; + std::optional dropout_rate; + std::optional seed; + }; + + static tsl::StatusOr< + std::unique_ptr>> + RunnerFromAlgorithmDesc(const AlgorithmDesc& desc, Config config, + Stream* stream) { + return stream->FusedMHABackwardRunnerFromDesc( + desc, config.kind, config.bmm1_grad_gemm1_rhs_descriptor, + config.bmm1_grad_gemm2_rhs_descriptor, + config.bmm2_grad_gemm1_lhs_descriptor, + config.bmm2_grad_gemm2_rhs_descriptor, config.d_output_descriptor, + config.d_bmm1_lhs_descriptor, config.d_bmm1_rhs_descriptor, + config.d_bmm2_rhs_descriptor, config.d_s_descriptor, + config.mask_descriptor, config.d_bias_descriptor, config.scale, + config.dropout_rate, config.seed); + } +}; + +} // namespace dnn +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_LAZY_OP_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/module_spec.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/module_spec.h new file mode 100644 index 0000000000000000000000000000000000000000..cfee31e514c14d4a72d6f6d01ec3f1d1798e4b70 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/module_spec.h @@ -0,0 +1,92 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_MODULE_SPEC_H_ +#define XLA_STREAM_EXECUTOR_MODULE_SPEC_H_ + +#include + +#include "absl/types/span.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/logging.h" + +namespace stream_executor { + +//===----------------------------------------------------------------------===// +// ModuleHandle +//===----------------------------------------------------------------------===// + +// An opaque handle to a loaded module. +// +// An instance of this is returned from StreamExecutor::GetModule. +class ModuleHandle { + public: + explicit ModuleHandle(void* id = nullptr) : id_(id) {} + + // A ModuleHandle with id() == nullptr is an invalid module handle, akin to a + // null pointer. + void* id() const { return id_; } + + explicit operator bool() const { return id() != nullptr; } + + private: + void* id_; +}; + +//===----------------------------------------------------------------------===// +// MultiModuleLoaderSpec +//===----------------------------------------------------------------------===// + +// Describes how to load a module on a target platform. +// +// The exact meaning of a "module" may differ from platform to platform but +// loosely speaking a module a collection of kernels and global variables. It +// corresponds to CUmodule when running on CUDA. +class MultiModuleLoaderSpec { + public: + bool has_cuda_cubin_in_memory() const { return has_cuda_cubin_in_memory_; } + absl::Span cuda_cubin_in_memory() const { + CHECK(has_cuda_cubin_in_memory()); + return {cuda_cubin_in_memory_.data(), cuda_cubin_in_memory_.size()}; + } + + bool has_cuda_ptx_in_memory() const { return has_cuda_ptx_in_memory_; } + const char* cuda_ptx_in_memory() const { + CHECK(has_cuda_ptx_in_memory()); + return cuda_ptx_in_memory_; + } + + void AddCudaCubinInMemory(absl::Span cubin_bytes) { + CHECK(!cubin_bytes.empty()); + has_cuda_cubin_in_memory_ = true; + cuda_cubin_in_memory_ = cubin_bytes; + } + + void AddCudaPtxInMemory(const char* ptx) { + has_cuda_ptx_in_memory_ = true; + // The CUDA driver does not like getting an empty string as PTX. + cuda_ptx_in_memory_ = *ptx ? ptx : nullptr; + } + + private: + absl::Span cuda_cubin_in_memory_; + bool has_cuda_cubin_in_memory_ = false; + const char* cuda_ptx_in_memory_; + bool has_cuda_ptx_in_memory_ = false; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_MODULE_SPEC_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/multi_platform_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/multi_platform_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f428bbf9bd81b8e13e297bc130d4acb6f7a243ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/multi_platform_manager.h @@ -0,0 +1,158 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This is a registration-oriented interface for multiple platforms. It will +// replace the MachineManager singleton interface, as MachineManager does not +// currently support simultaneous use of multiple platforms. +// +// Usage: +// +// In your BUILD rule, add a dependency on a platform plugin that you'd like +// to use, such as: +// +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:cuda_platform +// //third_party/tensorflow/compiler/xla/stream_executor/opencl:opencl_platform +// +// This will register platform plugins that can be discovered via this +// interface. Sample API usage: +// +// tsl::StatusOr platform_status = +// se::MultiPlatformManager::PlatformWithName("OpenCL"); +// if (!platform_status.ok()) { ... } +// Platform* platform = platform_status.value(); +// LOG(INFO) << platform->VisibleDeviceCount() << " devices visible"; +// if (platform->VisibleDeviceCount() <= 0) { return; } +// +// for (int i = 0; i < platform->VisibleDeviceCount(); ++i) { +// tsl::StatusOr executor_status = +// platform->ExecutorForDevice(i); +// if (!executor_status.ok()) { +// LOG(INFO) << "could not retrieve executor for device ordinal " << i +// << ": " << executor_status.status(); +// continue; +// } +// LOG(INFO) << "found usable executor: " << executor_status.value(); +// } +// +// A few things to note: +// - There is no standard formatting/practice for identifying the name of a +// platform. Ideally, a platform will list its registered name in its header +// or in other associated documentation. +// - Platform name lookup is case-insensitive. "OpenCL" or "opencl" (or even +// ("OpEnCl") would work correctly in the above example. +// +// And similarly, for standard interfaces (BLAS, etc.) you can add +// dependencies on support libraries, e.g.: +// +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:pluton_blas_plugin +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:cudnn_plugin +// //third_party/tensorflow/compiler/xla/stream_executor/cuda:cublas_plugin + +#ifndef XLA_STREAM_EXECUTOR_MULTI_PLATFORM_MANAGER_H_ +#define XLA_STREAM_EXECUTOR_MULTI_PLATFORM_MANAGER_H_ + +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/initialize.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +// Manages multiple platforms that may be present on the current machine. +class MultiPlatformManager { + public: + // Registers a platform object, returns an error status if the platform is + // already registered. The associated listener, if not null, will be used to + // trace events for ALL executors for that platform. + // Takes ownership of platform. + static tsl::Status RegisterPlatform(std::unique_ptr platform); + + // Retrieves the platform registered with the given platform name (e.g. + // "CUDA", "OpenCL", ...) or id (an opaque, comparable value provided by the + // Platform's Id() method). + // + // If the platform has not already been initialized, it will be initialized + // with a default set of parameters. + // + // If the requested platform is not registered, an error status is returned. + // Ownership of the platform is NOT transferred to the caller -- + // the MultiPlatformManager owns the platforms in a singleton-like fashion. + static tsl::StatusOr PlatformWithName(absl::string_view target); + static tsl::StatusOr PlatformWithId(const Platform::Id& id); + + // Same functions as above, but allows platforms to be returned without + // initialization if initialize_platform == false. + static tsl::StatusOr PlatformWithName(absl::string_view target, + bool initialize_platform); + + // Retrieves the platform registered with the given platform id (an opaque, + // comparable value provided by the Platform's Id() method). + // + // The platform will be initialized with the given options. If the platform + // was already initialized, an error will be returned. + // + // If the requested platform is not registered, an error status is returned. + // Ownership of the platform is NOT transferred to the caller -- + // the MultiPlatformManager owns the platforms in a singleton-like fashion. + static tsl::StatusOr InitializePlatformWithId( + const Platform::Id& id, + const std::map& options); + + // Retrieves the platforms satisfying the given filter, i.e. returns true. + // Returned Platforms are always initialized. + static tsl::StatusOr> PlatformsWithFilter( + const std::function& filter); + + static tsl::StatusOr> PlatformsWithFilter( + const std::function& filter, + bool initialize_platform); + + // Although the MultiPlatformManager "owns" its platforms, it holds them as + // undecorated pointers to prevent races during program exit (between this + // object's data and the underlying platforms (e.g., CUDA, OpenCL). + // Because certain platforms have unpredictable deinitialization + // times/sequences, it is not possible to strucure a safe deinitialization + // sequence. Thus, we intentionally "leak" allocated platforms to defer + // cleanup to the OS. This should be acceptable, as these are one-time + // allocations per program invocation. + // The MultiPlatformManager should be considered the owner + // of any platforms registered with it, and leak checking should be disabled + // during allocation of such Platforms, to avoid spurious reporting at program + // exit. +}; + +} // namespace stream_executor + +// multi_platform_manager.cc will define these instances. +// +// Registering a platform: +// REGISTER_MODULE_INITIALIZER_SEQUENCE(my_platform, multi_platform_manager); +// REGISTER_MODULE_INITIALIZER_SEQUENCE(multi_platform_manager_listener, +// my_platform); +// +// Registering a listener: +// REGISTER_MODULE_INITIALIZER_SEQUENCE(my_listener, +// multi_platform_manager_listener); +DECLARE_MODULE_INITIALIZER(multi_platform_manager); +DECLARE_MODULE_INITIALIZER(multi_platform_manager_listener); + +#endif // XLA_STREAM_EXECUTOR_MULTI_PLATFORM_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/numeric_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/numeric_options.h new file mode 100644 index 0000000000000000000000000000000000000000..f75dfb54ff65b33c76965ce01cad9d7c18ea0e71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/numeric_options.h @@ -0,0 +1,37 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +------------------------------------------------------------------------------*/ + +#ifndef XLA_STREAM_EXECUTOR_NUMERIC_OPTIONS_H_ +#define XLA_STREAM_EXECUTOR_NUMERIC_OPTIONS_H_ + +namespace stream_executor { + +// Options that specify the numeric behavior of operations like matrix +// multiplications and convolutions +struct NumericOptions { + NumericOptions(bool require_determinism, bool allow_tf32) + : require_determinism(require_determinism), allow_tf32(allow_tf32) {} + + NumericOptions() : require_determinism(false), allow_tf32(true) {} + + // If true, the op must be deterministic + bool require_determinism; + // If true, float32 inputs can be rounded to TensorFloat-32 precision + bool allow_tf32; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_NUMERIC_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..b03d046220bbbc72efadf6fc94b3750b31eff507 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform.h @@ -0,0 +1,153 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Defines types and declares functions for identifying and extracting +// information about the types of platforms and supporting libraries for which +// StreamExecutor implementations exist. +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_H_ + +#include +#include +#include + +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/platform/port.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class StreamExecutor; +class DeviceDescription; + +// An enum to represent different levels of stream priorities. +// This is to avoid platform-specific representations in abstractions. +enum class StreamPriority { Default = 0, Lowest, Highest }; + +// Returns a printable description of StreamPriority. +std::string StreamPriorityToString(StreamPriority priority); + +// StreamExecutorConfig encapsulates the set of options for constructing a +// StreamExecutor for a given platform. +struct StreamExecutorConfig { + // Sets members to defaults: -1 for ordinal (must be changed), and default + // PluginConfig and DeviceOptions. + StreamExecutorConfig(); + + // Simple ordinal-setting constructor. + explicit StreamExecutorConfig(int ordinal); + + // The GPU stream for which we are searching the executor. + // If this field is specified for the search, others will be ignored. + void* gpu_stream = nullptr; + + // The ordinal of the device to be managed by the returned StreamExecutor. + int ordinal; + + // The DeviceOptions for the returned StreamExecutor. + DeviceOptions device_options; +}; + +// Abstract base class for a platform registered with the MultiPlatformManager. +class Platform { + public: + virtual ~Platform(); + + // A platform ID is a unique identifier for each registered platform type - + // each platform is required to expose an ID to ensure unique registration and + // as a target against which plugins can register. + // + // The macro below is provided to help generate a [process-unique] identifier. + using Id = void*; + +// Helper macro to define a plugin ID. To be used only inside plugin +// implementation files. Works by "reserving" an address/value (guaranteed to be +// unique) inside a process space. +#define PLATFORM_DEFINE_ID(ID_VAR_NAME) \ + namespace { \ + int plugin_id_value; \ + } \ + const ::stream_executor::Platform::Id ID_VAR_NAME = &plugin_id_value; + + // Returns a key uniquely identifying this platform. + virtual Id id() const = 0; + + // Name of this platform. + virtual const std::string& Name() const = 0; + + // Returns the number of devices accessible on this platform. + // + // Note that, though these devices are visible, if there is only one userspace + // context allowed for the device at a time and another process is using this + // device, a call to ExecutorForDevice may return an error status. + virtual int VisibleDeviceCount() const = 0; + + // Returns true iff the platform has been initialized. + virtual bool Initialized() const; + + // Initializes the platform with a custom set of options. The platform must be + // initialized before obtaining StreamExecutor objects. The interpretation of + // the platform_options argument is implementation specific. This method may + // return an error if unrecognized options are provided. If using + // MultiPlatformManager, this method will be called automatically by + // InitializePlatformWithId/InitializePlatformWithName. + virtual tsl::Status Initialize( + const std::map& platform_options); + + // Returns a populated DeviceDescription for the device at the given ordinal. + // This should not require device initialization. Note that not all platforms + // may support acquiring the DeviceDescription indirectly. + // + // Alternatively callers may call GetDeviceDescription() on the StreamExecutor + // which returns a cached instance specific to the initialized StreamExecutor. + virtual tsl::StatusOr> + DescriptionForDevice(int ordinal) const = 0; + + // Returns a device with the given ordinal on this platform with a default + // plugin configuration or, if none can be found with the given ordinal or + // there is an error in opening a context to communicate with the device, an + // error status is returned. + // + // Ownership of the executor is NOT transferred to the caller -- + // the Platform owns the executors in a singleton-like fashion. + virtual tsl::StatusOr ExecutorForDevice(int ordinal) = 0; + + // Returns a device constructed with the options specified in "config". + // Ownership of the executor is NOT transferred to the caller. + virtual tsl::StatusOr GetExecutor( + const StreamExecutorConfig& config) = 0; + + // Returns a device constructed with the options specified in "config" without + // looking in or storing to the Platform's executor cache. + // Ownership IS transferred to the caller. + virtual tsl::StatusOr> GetUncachedExecutor( + const StreamExecutorConfig& config) = 0; + + protected: + // SE_DISALLOW_COPY_AND_ASSIGN declares a constructor, which suppresses the + // presence of the default constructor. This statement re-enables it, which + // simplifies subclassing. + Platform() = default; + + private: + Platform(const Platform&) = delete; + void operator=(const Platform&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..baf9de18876c676604b5c0b2136fb8b2318a9cc2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.h @@ -0,0 +1,86 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Common DSO loading functionality: exposes callables that dlopen DSOs +// in either the runfiles directories + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_DSO_LOADER_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_DSO_LOADER_H_ + +#include + +#include "absl/strings/string_view.h" +#include "tsl/platform/dso_loader.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace internal { + +namespace DsoLoader { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::internal::DsoLoader::GetCublasDsoHandle; +using tsl::internal::DsoLoader::GetCublasLtDsoHandle; +using tsl::internal::DsoLoader::GetCudaDriverDsoHandle; +using tsl::internal::DsoLoader::GetCudaRuntimeDsoHandle; +using tsl::internal::DsoLoader::GetCudnnDsoHandle; +using tsl::internal::DsoLoader::GetCufftDsoHandle; +using tsl::internal::DsoLoader::GetCuptiDsoHandle; +using tsl::internal::DsoLoader::GetCusolverDsoHandle; +using tsl::internal::DsoLoader::GetCusparseDsoHandle; +using tsl::internal::DsoLoader::GetHipDsoHandle; +using tsl::internal::DsoLoader::GetHipfftDsoHandle; +using tsl::internal::DsoLoader::GetHipsolverDsoHandle; +using tsl::internal::DsoLoader::GetHipsparseDsoHandle; +using tsl::internal::DsoLoader::GetMiopenDsoHandle; +using tsl::internal::DsoLoader::GetNvInferDsoHandle; +using tsl::internal::DsoLoader::GetNvInferPluginDsoHandle; +using tsl::internal::DsoLoader::GetRocblasDsoHandle; +using tsl::internal::DsoLoader::GetRocrandDsoHandle; +using tsl::internal::DsoLoader::GetRocsolverDsoHandle; +using tsl::internal::DsoLoader::GetRoctracerDsoHandle; +using tsl::internal::DsoLoader::MaybeTryDlopenGPULibraries; +using tsl::internal::DsoLoader::TryDlopenTensorRTLibraries; +// NOLINTEND(misc-unused-using-decls) +} // namespace DsoLoader + +namespace CachedDsoLoader { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::internal::CachedDsoLoader::GetCublasDsoHandle; +using tsl::internal::CachedDsoLoader::GetCublasLtDsoHandle; +using tsl::internal::CachedDsoLoader::GetCudaDriverDsoHandle; +using tsl::internal::CachedDsoLoader::GetCudaRuntimeDsoHandle; +using tsl::internal::CachedDsoLoader::GetCudnnDsoHandle; +using tsl::internal::CachedDsoLoader::GetCufftDsoHandle; +using tsl::internal::CachedDsoLoader::GetCuptiDsoHandle; +using tsl::internal::CachedDsoLoader::GetCusolverDsoHandle; +using tsl::internal::CachedDsoLoader::GetCusparseDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipblasltDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipfftDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipsolverDsoHandle; +using tsl::internal::CachedDsoLoader::GetHipsparseDsoHandle; +using tsl::internal::CachedDsoLoader::GetMiopenDsoHandle; +using tsl::internal::CachedDsoLoader::GetRocblasDsoHandle; +using tsl::internal::CachedDsoLoader::GetRocrandDsoHandle; +using tsl::internal::CachedDsoLoader::GetRocsolverDsoHandle; +using tsl::internal::CachedDsoLoader::GetRoctracerDsoHandle; +// NOLINTEND(misc-unused-using-decls) +} // namespace CachedDsoLoader + +} // namespace internal +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_DSO_LOADER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/initialize.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/initialize.h new file mode 100644 index 0000000000000000000000000000000000000000..6928d6adbb0c23668d0fc13d5f1d41e095cff81e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/default/initialize.h @@ -0,0 +1,62 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_INITIALIZE_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_INITIALIZE_H_ + +#undef REGISTER_MODULE_INITIALIZER +#undef DECLARE_MODULE_INITIALIZER +#undef REGISTER_MODULE_INITIALIZER_SEQUENCE + +namespace stream_executor { +namespace port { + +class Initializer { + public: + typedef void (*InitializerFunc)(); + explicit Initializer(InitializerFunc func) { func(); } + + struct Dependency { + Dependency(const char *n, Initializer *i) : name(n), initializer(i) {} + const char *const name; + Initializer *const initializer; + }; + + struct DependencyRegisterer { + DependencyRegisterer(const char *type, const char *name, + Initializer *initializer, + const Dependency &dependency); + }; +}; + +} // namespace port +} // namespace stream_executor + +#define REGISTER_INITIALIZER(type, name, body) \ + static void google_init_##type##_##name() { body; } \ + ::stream_executor::port::Initializer google_initializer_##type##_##name( \ + google_init_##type##_##name) + +#define REGISTER_MODULE_INITIALIZER(name, body) \ + REGISTER_INITIALIZER(module, name, body) + +#define DECLARE_INITIALIZER(type, name) \ + extern ::stream_executor::port::Initializer google_initializer_##type##_##name + +#define DECLARE_MODULE_INITIALIZER(name) DECLARE_INITIALIZER(module, name) + +#define REGISTER_MODULE_INITIALIZER_SEQUENCE(name1, name2) + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_DEFAULT_INITIALIZE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/dso_loader.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/dso_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..41538c0ef067ace7585cb10cc0abd92a781486ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/dso_loader.h @@ -0,0 +1,31 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_DSO_LOADER_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_DSO_LOADER_H_ + +#include "xla/stream_executor/platform/platform.h" + +// Include appropriate platform-dependent implementations +#if defined(PLATFORM_GOOGLE) || defined(PLATFORM_CHROMIUMOS) +#include "xla/stream_executor/platform/google/dso_loader.h" +#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) || \ + defined(PLATFORM_GOOGLE_ANDROID) || defined(PLATFORM_WINDOWS) +#include "xla/stream_executor/platform/default/dso_loader.h" +#else +#error Define the appropriate PLATFORM_ macro for this platform +#endif + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_DSO_LOADER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/initialize.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/initialize.h new file mode 100644 index 0000000000000000000000000000000000000000..d56bda8383ae2b3a2b0aa8aeccb871d1f9adcece --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/initialize.h @@ -0,0 +1,27 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_INITIALIZE_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_INITIALIZE_H_ + +#include "xla/stream_executor/platform/platform.h" + +#if defined(PLATFORM_GOOGLE) || defined(PLATFORM_CHROMIUMOS) +#include "xla/stream_executor/platform/google/initialize.h" // IWYU pragma: export +#else +#include "xla/stream_executor/platform/default/initialize.h" // IWYU pragma: export +#endif + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_INITIALIZE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/platform.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..3ea6fa66d362fc2396710fcf53ff8453702f8250 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/platform.h @@ -0,0 +1,43 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_PLATFORM_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_PLATFORM_H_ + +#if !defined(PLATFORM_POSIX) && !defined(PLATFORM_GOOGLE) && \ + !defined(PLATFORM_POSIX_ANDROID) && !defined(PLATFORM_GOOGLE_ANDROID) && \ + !defined(PLATFORM_WINDOWS) && !defined(PLATFORM_CHROMIUMOS) + +// Choose which platform we are on. +#if defined(ANDROID) || defined(__ANDROID__) +#define PLATFORM_POSIX_ANDROID + +#elif defined(__APPLE__) +#define PLATFORM_POSIX + +#elif defined(_WIN32) +#define PLATFORM_WINDOWS + +#elif defined(__TF_CHROMIUMOS__) +#define PLATFORM_CHROMIUMOS + +#else +// If no platform specified, use: +#define PLATFORM_POSIX + +#endif +#endif + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_PLATFORM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/port.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/port.h new file mode 100644 index 0000000000000000000000000000000000000000..dfb9c1997baf3a7dfcdcea4fb88444fb10f4104a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/platform/port.h @@ -0,0 +1,50 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// IWYU pragma: private, include "third_party/tensorflow/compiler/xla/stream_executor/stream_executor.h" + +#ifndef XLA_STREAM_EXECUTOR_PLATFORM_PORT_H_ +#define XLA_STREAM_EXECUTOR_PLATFORM_PORT_H_ + +#include "tsl/platform/macros.h" +#include "tsl/platform/types.h" + +namespace stream_executor { + +using tsl::int16; +using tsl::int32; +using tsl::int8; + +using tsl::uint16; +using tsl::uint32; +using tsl::uint64; +using tsl::uint8; + +#if !defined(PLATFORM_GOOGLE) +using std::string; +#endif + +#define SE_FALLTHROUGH_INTENDED TF_FALLTHROUGH_INTENDED + +} // namespace stream_executor + +// DEPRECATED: directly use the macro implementation instead. +#define SE_DISALLOW_COPY_AND_ASSIGN TF_DISALLOW_COPY_AND_ASSIGN + +#define SE_MUST_USE_RESULT TF_MUST_USE_RESULT +#define SE_PREDICT_TRUE TF_PREDICT_TRUE +#define SE_PREDICT_FALSE TF_PREDICT_FALSE + +#endif // XLA_STREAM_EXECUTOR_PLATFORM_PORT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..cb90171ac82bd1210ad6f1a73b36e79ad444e6eb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin.h @@ -0,0 +1,31 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_PLUGIN_H_ +#define XLA_STREAM_EXECUTOR_PLUGIN_H_ + +namespace stream_executor { + +// Enumeration to list the supported types of plugins / support libraries. +enum class PluginKind { + kInvalid, + kBlas, + kDnn, + kFft, +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLUGIN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..26ddf0bd60f080902ab262cac6b51782c62539cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/plugin_registry.h @@ -0,0 +1,122 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_PLUGIN_REGISTRY_H_ +#define XLA_STREAM_EXECUTOR_PLUGIN_REGISTRY_H_ + +#include + +#include "absl/base/macros.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/plugin.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +namespace internal { +class StreamExecutorInterface; +} + +// The PluginRegistry is a singleton that maintains the set of registered +// "support library" plugins. Currently, there are four kinds of plugins: +// BLAS, DNN, and FFT. Each interface is defined in the corresponding +// gpu_{kind}.h header. +// +// At runtime, a StreamExecutor object will query the singleton registry to +// retrieve the plugin kind that StreamExecutor was configured with (refer to +// the StreamExecutor declarations). +// +// Plugin libraries are best registered using REGISTER_MODULE_INITIALIZER, +// but can be registered at any time. When registering a DSO-backed plugin, it +// is usually a good idea to load the DSO at registration time, to prevent +// late-loading from distorting performance/benchmarks as much as possible. +class PluginRegistry { + public: + typedef blas::BlasSupport* (*BlasFactory)(internal::StreamExecutorInterface*); + typedef dnn::DnnSupport* (*DnnFactory)(internal::StreamExecutorInterface*); + typedef fft::FftSupport* (*FftFactory)(internal::StreamExecutorInterface*); + + // Gets (and creates, if necessary) the singleton PluginRegistry instance. + static PluginRegistry* Instance(); + + // Registers the specified factory with the specified platform. + // Returns a non-successful status if the factory has already been registered + // with that platform (but execution should be otherwise unaffected). + template + tsl::Status RegisterFactory(Platform::Id platform_id, const std::string& name, + FactoryT factory); + + // Return true if the factory/kind has been registered for the + // specified platform and plugin kind and false otherwise. + bool HasFactory(Platform::Id platform_id, PluginKind plugin_kind) const; + + // Retrieves the factory registered for the specified kind, + // or a tsl::Status on error. + template + tsl::StatusOr GetFactory(Platform::Id platform_id); + + private: + // Containers for the sets of registered factories, by plugin kind. + struct Factories { + std::optional blas; + std::optional dnn; + std::optional fft; + }; + + PluginRegistry(); + + // Actually performs the work of registration. + template + tsl::Status RegisterFactoryInternal(const std::string& plugin_name, + FactoryT factory, + std::optional* factories); + + // Returns true if the specified plugin has been registered with the specified + // platform factories. Unlike the other overload of this method, this does + // not implicitly examine the default factory lists. + bool HasFactory(const Factories& factories, PluginKind plugin_kind) const; + + // The singleton itself. + static PluginRegistry* instance_; + + // The set of registered factories, keyed by platform ID. + std::map factories_; + + PluginRegistry(const PluginRegistry&) = delete; + void operator=(const PluginRegistry&) = delete; +}; + +// Explicit specializations are defined in plugin_registry.cc. +#define DECLARE_PLUGIN_SPECIALIZATIONS(FACTORY_TYPE) \ + template <> \ + tsl::Status PluginRegistry::RegisterFactory( \ + Platform::Id platform_id, const std::string& name, \ + PluginRegistry::FACTORY_TYPE factory); \ + template <> \ + tsl::StatusOr PluginRegistry::GetFactory( \ + Platform::Id platform_id) + +DECLARE_PLUGIN_SPECIALIZATIONS(BlasFactory); +DECLARE_PLUGIN_SPECIALIZATIONS(DnnFactory); +DECLARE_PLUGIN_SPECIALIZATIONS(FftFactory); +#undef DECL_PLUGIN_SPECIALIZATIONS + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_PLUGIN_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/rocm/rocm_platform_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/rocm/rocm_platform_id.h new file mode 100644 index 0000000000000000000000000000000000000000..2ee37660ddea0b3d83c668eee270e15f64ecb559 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/rocm/rocm_platform_id.h @@ -0,0 +1,34 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_ID_H_ +#define XLA_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_ID_H_ + +#include "xla/stream_executor/platform.h" + +namespace stream_executor { +namespace rocm { + +// Opaque and unique identifier for the ROCm platform. +// This is needed so that plugins can refer to/identify this platform without +// instantiating a ROCmPlatform object. +// This is broken out here to avoid a circular dependency between ROCmPlatform +// and ROCmExecutor. +extern const Platform::Id kROCmPlatformId; + +} // namespace rocm +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/scratch_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/scratch_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..c3a321e9e5e8a8f1a5fb10d869ca5ef13e3e6500 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/scratch_allocator.h @@ -0,0 +1,115 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_ +#define XLA_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_ + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/temporary_device_memory.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; + +// Interface for "scratch" allocator for device memory, which deallocates all +// buffers it has allocated at destruction. Returned memory pointers are not +// owning. +// +// Used by stream operations (e.g. Stream::ThenConvolveWithScratch) to +// optionally request scratch space to speed up the operation. +class ScratchAllocator { + public: + virtual ~ScratchAllocator() {} + + // Returns a limit of memory this scratch allocator wants to produce, in + // bytes. This information may be used to help select an algorithm. + // + // Returns values < 0 to indicate that there is no recommended limit. + virtual int64_t GetMemoryLimitInBytes() = 0; + + // Returns an allocation on byte_size bytes for use in an operation on stream. + // + // This is a temporary allocation, and the caller is responsible for + // deallocating at some known-safe point. See the class comment above. + virtual tsl::StatusOr> AllocateBytes( + int64_t byte_size) = 0; +}; + +// Allocates a single temporary memory allocation -- this memory is deallocated +// at the next stream synchronization point after this object has gone out of +// scope. This satisfies the lifetime and deallocation properties given in the +// class comment above. +// +// Thread-compatible, but not thread-safe (use in scenarios where only one +// thread will request the scratch allocation). +class OneTimeScratchAllocator : public ScratchAllocator { + public: + explicit OneTimeScratchAllocator(Stream* stream) : stream_(stream) {} + + int64_t GetMemoryLimitInBytes() override { return -1; } + + tsl::StatusOr> AllocateBytes( + int64_t byte_size) override; + + private: + std::unique_ptr> temporary_; + Stream* stream_; + + OneTimeScratchAllocator(const OneTimeScratchAllocator&) = delete; + void operator=(const OneTimeScratchAllocator&) = delete; +}; + +// Can allocate several times -- this memory is deallocated when the scratch +// allocator is destroyed. +// +// Thread-compatible, but not thread-safe (use in scenarios where only one +// thread will request the scratch allocation). +template +class OwningScratchAllocator : public ScratchAllocator { + public: + OwningScratchAllocator(int device_ordinal, DeviceMemoryAllocator* allocator) + : device_ordinal_(device_ordinal), allocator_(allocator) {} + + int64_t GetMemoryLimitInBytes() override { return -1; } + + tsl::StatusOr> AllocateBytes( + int64_t byte_size) override { + TF_ASSIGN_OR_RETURN(OwningDeviceMemory buffer, + allocator_->Allocate(device_ordinal_, byte_size, + /*retry_on_failure=*/false)); + buffers_.push_back(std::move(buffer)); + return *buffers_.back(); + } + + private: + int device_ordinal_; + DeviceMemoryAllocator* allocator_; + absl::InlinedVector buffers_; + + OwningScratchAllocator(const OwningScratchAllocator&) = delete; + void operator=(const OwningScratchAllocator&) = delete; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..41a7435c30b67d0aa16e13a3eee05b74edeebede --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream.h @@ -0,0 +1,1570 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The Stream is used in conjunction with the StreamExecutor "parent" to +// perform actions with a linear stream of dependencies. Dependencies can also +// be created between Streams to do task management (i.e. limit which tasks +// can be performed concurrently and specify what task dependencies exist). + +#ifndef XLA_STREAM_EXECUTOR_STREAM_H_ +#define XLA_STREAM_EXECUTOR_STREAM_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/functional/any_invocable.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/stream_executor_pimpl.h" +#include "xla/stream_executor/temporary_memory_manager.h" + +namespace stream_executor { + +namespace internal { +class StreamInterface; +} // namespace internal + +class DeviceMemoryBase; +template +class DeviceMemory; + +namespace dnn { +class BatchDescriptor; +class FilterDescriptor; +class ConvolutionDescriptor; +class ProfileResult; +class AlgorithmDesc; +} // namespace dnn + +class StreamExecutor; +class ScratchAllocator; + +namespace detail { + +// Helper to return if `T` is the same type as `First` or any or `Rest`. +template +constexpr bool is_any_of() { + return false; +} + +template +constexpr bool is_any_of() { + return std::is_same_v || is_any_of(); +} + +} // namespace detail + +// Convert a type to the corresponding QuantizedActivationMode. +template +struct Quantization; + +// Represents a stream of dependent computations on a GPU device. +// +// The operations within a stream execute linearly and asynchronously until +// BlockHostUntilDone() is invoked, which synchronously joins host code with +// the execution of the stream. +// +// If any given operation fails when entraining work for the stream, ok() will +// indicate that an error has occurred. After initialization, once a stream is +// !ok(), it will never be ok(). +// +// Thread-safe post-initialization. +class Stream { + public: + // Platform specific handle for the underlying resources behind a Stream + // implementation (e.g. it gives access to CUstream for CUDA platform). + struct PlatformSpecificHandle { + void *stream = nullptr; // will be nullptr if not supported + }; + + // Instantiate a stream tied to parent as a platform executor. Work + // entrained onto this stream will be launched/managed on that + // StreamExecutor's platform. + explicit Stream(StreamExecutor *parent); + + // Deallocates any stream resources that the parent StreamExecutor has + // bestowed + // upon this object. + ~Stream(); + + // TODO(ezhulenev): Consider removing this platform-specific accessor and + // forward all users to platform-specific headers, however it requires careful + // build rules set up to avoid leaking even more implementation details. + PlatformSpecificHandle platform_specific_handle() const; + + // Returns whether any errors have occurred while entraining work for this + // stream. + bool ok() const { return !InErrorState(); } + + // Retrieves execution status back into the stream from the underlying + // implementation without blocking the stream. + // + // Normally, Stream::BlockHostUntilDone is used to get execution status. + // However, some devices use out-of-band mechnanisms to ensure their streams + // have finished on-device work, without needing to block the streams. (These + // devices should also override AllowsSyncOnCompletion to return false.) For + // these devices, this method can be used after work is finished to retrieve + // execution status. + tsl::Status RefreshStatus() TF_LOCKS_EXCLUDED(mu_); + + // Initialize the stream. This must be performed before entraining any other + // operations. + Stream &Init() TF_LOCKS_EXCLUDED(mu_); + + // Get or create a sub-stream from this stream. If there is any sub-stream in + // the pool that can be reused then just return this sub-stream. Otherwise + // create a new sub-stream. + // + // TODO(b/112196569): The semantics of failed sub-streams is error-prone. + Stream *GetOrCreateSubStream() TF_LOCKS_EXCLUDED(mu_); + + // Return the sub-stream back to the host stream so that it can be reused + // later. Sub-streams that are !ok() will not be reused. + // + // TODO(b/112196569): The semantics of failed sub-streams is error-prone. + void ReturnSubStream(Stream *sub_stream) TF_LOCKS_EXCLUDED(mu_); + + // Allocate temporary memories. The stream will deallocate them when blocked + // or destroyed. + template + tsl::StatusOr>> + AllocateTemporaryArray(uint64_t element_count); + + // Entrains onto the stream of operations: a kernel launch with the given + // (variadic) parameters for the invocation. These arguments can be things + // like DeviceMemory or primitive types such as int. What arguments you may + // pass to a given kernel are noted as the template parameters to the + // TypedKernel type that the machocc compiler generates. + // + // Template parameters: + // Params... The type list of formal parameters that the typed kernel + // expects, which is matched against Args... + // Args... The deduced type list for passed actual arguments + // + // Implementation: A compile-time compatibility check is performed that has + // some leniency versus an exact parameter pack match -- for example, + // `const DeviceMemory` is considered "pack compatible" with a + // `const DeviceMemory&` formal parameter; in part, because we don't have + // perfect forwarding support without rvalue references. It also attempts to + // spit out helpful static_assert error traces with information as to the + // argument number and types that were mismatched. + template + tsl::Status ThenLaunch(ThreadDim thread_dims, BlockDim block_dims, + const TypedKernel &kernel, Args... args); + + // Create a dependency for this stream's next work on the other stream + // completing. Does not take ownership of other, and other must not be + // null. + // + // Checks that a stream does not wait for itself, and it is up to the + // user to guarantee that a stream does not come to wait on itself in a + // cyclic manner; in that case, behavior is undefined. + // + // N.B. Base recursion case for the variadic ThenWaitFor. + Stream &ThenWaitFor(Stream *other); + + // Waits for all streams values in others. + // Checks that there is no shallow circular wait (i.e. that "this" is not in + // others) + template + Stream &ThenWaitFor(P others) { + for (auto &stream : *others) { + CHECK_NE(stream.get(), this); + ThenWaitFor(stream.get()); + } + return *this; + } + + // Waits for an event object to be set. + // Note that ThenRecordEvent must have been called on the event before + // you call this function; otherwise the event will be considered complete + // and this wait will do nothing. + Stream &ThenWaitFor(Event *event); + + // Inserts the specified event into the end of this stream. Once the stream + // has processed all events prior to the insertion point, the event will be + // marked as completed. + // The stream does not take ownership of event - meaning that event's lifetime + // must extend past the point at which it is marked complete! + Stream &ThenRecordEvent(Event *event); + + //////////////// + // DNN support + // + // See DnnSupport::* for comments on the following methods. + + Stream &ThenBatchNormalizationForward( + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, + const DeviceMemory &estimated_mean, + const DeviceMemory &estimated_variance, + const DeviceMemory &side_input, const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory *y, + DeviceMemory *batch_mean, DeviceMemory *batch_var, + DeviceMemory *saved_mean, DeviceMemory *saved_inv_var, + bool is_training, ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationBackward( + const DeviceMemory &y_backprop, const DeviceMemory &x, + const DeviceMemory &scale, const DeviceMemory &offset, + const DeviceMemory &mean, const DeviceMemory &inv_var, + const DeviceMemory &y, const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, DeviceMemory *x_backprop, + DeviceMemory *scale_backprop, DeviceMemory *offset_backprop, + DeviceMemory *side_input_backprop, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationForward( + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, + const DeviceMemory &estimated_mean, + const DeviceMemory &estimated_variance, + const DeviceMemory &side_input, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory *y, + DeviceMemory *batch_mean, DeviceMemory *batch_var, + DeviceMemory *saved_mean, DeviceMemory *saved_inv_var, + bool is_training, ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationBackward( + const DeviceMemory &y_backprop, + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, const DeviceMemory &mean, + const DeviceMemory &inv_var, const DeviceMemory &y, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory *x_backprop, + DeviceMemory *scale_backprop, DeviceMemory *offset_backprop, + DeviceMemory *side_input_backprop, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationForward( + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, + const DeviceMemory &estimated_mean, + const DeviceMemory &estimated_variance, + const DeviceMemory &side_input, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + const double exponential_average_factor, + dnn::ActivationMode activation_mode, DeviceMemory *y, + DeviceMemory *batch_mean, DeviceMemory *batch_var, + DeviceMemory *saved_mean, DeviceMemory *saved_inv_var, + bool is_training, ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator); + + Stream &ThenBatchNormalizationBackward( + const DeviceMemory &y_backprop, + const DeviceMemory &x, const DeviceMemory &scale, + const DeviceMemory &offset, const DeviceMemory &mean, + const DeviceMemory &inv_var, + const DeviceMemory &y, + const dnn::BatchDescriptor &x_desc, + const dnn::BatchDescriptor &scale_offset_desc, const double epsilon, + dnn::ActivationMode activation_mode, + DeviceMemory *x_backprop, + DeviceMemory *scale_backprop, DeviceMemory *offset_backprop, + DeviceMemory *side_input_backprop, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator); + + Stream &ThenConvolve(const dnn::BatchDescriptor &input_descriptor, + const DeviceMemory &input_data, + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_data, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output); + + Stream &ThenConvolveQuantized( + const dnn::BatchDescriptor &input_descriptor, + const DeviceMemory &input_data, + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_coefficients, + const DeviceMemory &coefficient_scales, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output_data); + + template + tsl::Status ConvolveWithAlgorithm( + dnn::ConvolutionKind kind, const dnn::BatchDescriptor &input_descriptor, + DeviceMemory input_data, + const dnn::FilterDescriptor &filter_descriptor, + DeviceMemory filter_data, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory output_data, + const dnn::ConvolutionDescriptor &convolution_descriptor, + ScratchAllocator *scratch_allocator, + const dnn::AlgorithmConfig &algorithm_config, + dnn::ProfileResult *output_profile_result) { + DeviceMemory scratch_memory; + dnn::AlgorithmDesc algorithm_desc; + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + TF_RETURN_IF_ERROR(dnn->PrepareForConvolution( + kind, this, input_descriptor, input_data, filter_descriptor, + filter_data, output_descriptor, output_data, convolution_descriptor, + algorithm_config, scratch_allocator, &algorithm_desc, + &scratch_memory)); + return dnn->DoConvolve(kind, dnn::ToDataType::value, + dnn::ToDataType::value, this, + input_descriptor, input_data, filter_descriptor, + filter_data, output_descriptor, output_data, + convolution_descriptor, algorithm_desc, + scratch_memory, output_profile_result); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + template + tsl::Status FusedConvolveWithAlgorithm( + const dnn::BatchDescriptor &conv_input_descriptor, + const DeviceMemory &conv_input_data, ScaleT conv_input_scale, + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_data, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const DeviceMemory &side_input_data, ScaleT side_input_scale, + const dnn::BatchDescriptor &bias_descriptor, + const DeviceMemory &biases, dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output, ScratchAllocator *scratch_allocator, + const dnn::AlgorithmConfig &algorithm_config, + dnn::ProfileResult *output_profile_result) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoFusedConvolve( + this, dnn::ToDataType::value, + dnn::ToDataType::value, dnn::ToDataType::value, + dnn::ToDataType::value, conv_input_descriptor, + conv_input_data, conv_input_scale, filter_descriptor, filter_data, + convolution_descriptor, side_input_data, side_input_scale, + bias_descriptor, biases, activation_mode, output_descriptor, *output, + scratch_allocator, algorithm_config, output_profile_result); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + tsl::Status CudnnReorderConvolutionFilterAndBias( + const dnn::FilterDescriptor &filter_descriptor, + const DeviceMemory &filter_input, + DeviceMemory *filter_output, + std::optional> bias_input, + std::optional> bias_output) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->CudnnReorderConvolutionFilterAndBias( + this, filter_descriptor, filter_input, filter_output, + std::move(bias_input), std::move(bias_output)); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + tsl::StatusOr> ConvolveRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType output_type, + const dnn::BatchDescriptor &input_descriptor, + const dnn::FilterDescriptor &filter_descriptor, + const dnn::BatchDescriptor &output_descriptor, + const dnn::ConvolutionDescriptor &convolution_descriptor) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return tsl::errors::Unimplemented("DNN library is not found."); + } + return dnn_support->ConvolveRunnerFromDesc( + this, algorithm_desc, kind, element_type, output_type, input_descriptor, + filter_descriptor, output_descriptor, convolution_descriptor); + } + + tsl::StatusOr> + GraphConvolveRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType output_type, + const dnn::BatchDescriptor &input_descriptor, + const dnn::FilterDescriptor &filter_descriptor, + const dnn::BatchDescriptor &output_descriptor, + const dnn::ConvolutionDescriptor &convolution_descriptor, + std::string serialized_graph) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return tsl::errors::Unimplemented("DNN library is not found."); + } + return dnn_support->GraphConvolveRunnerFromDesc( + this, algorithm_desc, kind, element_type, output_type, input_descriptor, + filter_descriptor, output_descriptor, convolution_descriptor, + serialized_graph); + } + + tsl::StatusOr> + FusedConvolveRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::ConvolutionKind kind, + dnn::DataType element_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_input_scale, + double side_input_scale, double leakyrelu_alpha, + const dnn::BatchDescriptor &input_descriptor, + const dnn::FilterDescriptor &filter_descriptor, + const dnn::BatchDescriptor &bias_descriptor, + const dnn::BatchDescriptor &output_descriptor, + const dnn::ConvolutionDescriptor &convolution_descriptor, + dnn::ActivationMode activation_mode) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return tsl::errors::Unimplemented("DNN library is not found."); + } + return dnn_support->FusedConvolveRunnerFromDesc( + this, algorithm_desc, kind, element_type, bias_type, output_type, + conv_input_scale, side_input_scale, leakyrelu_alpha, input_descriptor, + filter_descriptor, bias_descriptor, output_descriptor, + convolution_descriptor, activation_mode); + } + + tsl::StatusOr> + FusedMHARunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor &bmm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor &intermediate_bmm2_lhs_descriptor, + const dnn::TensorDescriptor &output_descriptor, + std::optional activation_descriptor, + std::optional mask_descriptor, + std::optional bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return absl::UnimplementedError("DNN library is not found."); + } + return dnn_support->FusedMHARunnerFromDesc( + this, algorithm_desc, kind, bmm1_lhs_descriptor, bmm1_rhs_descriptor, + bmm2_rhs_descriptor, intermediate_bmm2_lhs_descriptor, + output_descriptor, activation_descriptor, mask_descriptor, + bias_descriptor, scale, dropout_rate, seed); + } + + tsl::StatusOr> + FusedMHABackwardRunnerFromDesc( + const dnn::AlgorithmDesc &algorithm_desc, dnn::FusedMHAKind kind, + const dnn::MatmulTensorDescriptor &bmm1_grad_gemm1_rhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm1_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm2_grad_gemm1_lhs_descriptor, + const dnn::MatmulTensorDescriptor &bmm2_grad_gemm2_rhs_descriptor, + const dnn::MatmulTensorDescriptor &d_output_descriptor, + const dnn::TensorDescriptor &d_bmm1_lhs_descriptor, + const dnn::TensorDescriptor &d_bmm1_rhs_descriptor, + const dnn::TensorDescriptor &d_bmm2_rhs_descriptor, + const dnn::TensorDescriptor &d_s_descriptor, + std::optional mask_descriptor, + std::optional d_bias_descriptor, double scale, + std::optional dropout_rate, std::optional seed) { + dnn::DnnSupport *dnn_support = parent_->AsDnn(); + if (!dnn_support) { + return absl::UnimplementedError("DNN library is not found."); + } + return dnn_support->FusedMHABackwardRunnerFromDesc( + this, algorithm_desc, kind, bmm1_grad_gemm1_rhs_descriptor, + bmm1_grad_gemm2_rhs_descriptor, bmm2_grad_gemm1_lhs_descriptor, + bmm2_grad_gemm2_rhs_descriptor, d_output_descriptor, + d_bmm1_lhs_descriptor, d_bmm1_rhs_descriptor, d_bmm2_rhs_descriptor, + d_s_descriptor, mask_descriptor, d_bias_descriptor, scale, dropout_rate, + seed); + } + + Stream &ThenSeparableConvolve( + const dnn::BatchDescriptor &input_descriptor, + const DeviceMemory &input_data, + const dnn::FilterDescriptor &filter_descriptor, int depth_multiplier, + const DeviceMemory &first_weights, + const DeviceMemory &second_weights, + const dnn::ConvolutionDescriptor &convolution_descriptor, + const dnn::BatchDescriptor &output_descriptor, + DeviceMemory *output); + + Stream &ThenMatMul(const DeviceMemory &input_data, + const DeviceMemory &weights, + const dnn::BatchDescriptor &input_dimensions, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenMatMulQuantized(const DeviceMemory &input_data, + const DeviceMemory &weights, + const DeviceMemory &weight_scales, + const dnn::BatchDescriptor &input_dimensions, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenMatMulQuantized(const DeviceMemory &input_data, + const DeviceMemory &weights, + const DeviceMemory &weight_scales, + const dnn::BatchDescriptor &input_dimensions, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenBiasAdd(const DeviceMemory &input_data, + const DeviceMemory &biases, + const dnn::BatchDescriptor &dimensions, + DeviceMemory *output_data); + + template + tsl::Status ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions, + const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data, + ScratchAllocator *workspace_allocator = nullptr) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoPoolForward(dnn::ToDataType::value, this, + pooling_dimensions, input_dimensions, + input_data, output_dimensions, *output_data, + workspace_allocator); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + template + tsl::Status ThenPoolForward(const dnn::PoolingDescriptor &pooling_dimensions, + const NumericOptions &numeric_options, + const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data, + ScratchAllocator *workspace_allocator = nullptr) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoPoolForward(dnn::ToDataType::value, this, + pooling_dimensions, numeric_options, + input_dimensions, input_data, output_dimensions, + *output_data, workspace_allocator); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + template + tsl::Status ThenPoolBackward( + const dnn::PoolingDescriptor &pooling_dimensions, + const NumericOptions &numeric_options, + const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::BatchDescriptor &output_dimensions, + const DeviceMemory &output_data, + const DeviceMemory &input_diff_data, + DeviceMemory *output_diff_data, + ScratchAllocator *workspace_allocator = nullptr) { + if (dnn::DnnSupport *dnn = parent_->AsDnn()) { + return dnn->DoPoolBackward( + dnn::ToDataType::value, this, pooling_dimensions, + numeric_options, input_dimensions, input_data, output_dimensions, + output_data, input_diff_data, *output_diff_data, workspace_allocator); + } + return tsl::errors::Unimplemented("DNN library is not found."); + } + + Stream &ThenNormalizeWithDimensions( + const dnn::NormalizeDescriptor &normalize_descriptor, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, DeviceMemory *output_data); + + Stream &ThenNormalizeBackwardWithDimensions( + const dnn::NormalizeDescriptor &normalize_descriptor, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &raw_data, + const DeviceMemory &normalized_data, + const DeviceMemory &normalized_variable_gradient, + DeviceMemory *raw_variable_gradient, + ScratchAllocator *workspace_allocator = nullptr); + + Stream &ThenActivate(dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, + DeviceMemory *output_data); + + // Same as ThenActivate, but also takes an options argument that can be used + // for platform-specific option flags. + Stream &ThenActivateWithOptions(dnn::ActivationMode activation_mode, + const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, + DeviceMemory *output_data, + uint64_t options); + + Stream &ThenDepthConcatenate( + absl::Span input_dimensions, + absl::Span *const> input_data, + DeviceMemory *output_data); + + // Depth to space takes an X by Y image with depth D*M² and changes it to an + // MX x MY image with depth D. Each input location (x,y) with depth D*M² in + // the input image is changed to an MxM contiguous area in the output image, + // with the values being laid out in raster order specified by + // DepthToSpaceLayout, and will have a new depth of D. + // See the DoDepthToSpace comment for more information. + Stream &ThenDepthToSpace(const dnn::BatchDescriptor &input_dimensions, + const DeviceMemory &input_data, + const dnn::DepthToSpaceLayout &depth_to_space_layout, + const int sqrt_depth_reduction, + DeviceMemory *output_data); + + Stream &ThenElementwiseOperate( + dnn::ElementwiseOperation operation, + absl::Span input_dimensions, + absl::Span *const> input_data, + const dnn::BatchDescriptor &output_dimensions, + DeviceMemory *output_data); + + Stream &ThenXYPad(const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, int64_t left_pad, + int64_t right_pad, int64_t top_pad, int64_t bottom_pad, + DeviceMemory *output_data); + + Stream &ThenXYSlice(const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, int64_t left_trim, + int64_t right_trim, int64_t top_trim, int64_t bottom_trim, + DeviceMemory *output_data); + + // Grows the input tensor by replicating the X and Y dimensions. The batch and + // depth/feature_map dimensions are unchanged. Currently, the input tensor is + // limited to X=1 and Y=1. + Stream &ThenXYBroadcast(const dnn::BatchDescriptor &dimensions, + const DeviceMemory &input_data, + int64_t replicate_x, int64_t replicate_y, + DeviceMemory *output_data); + + // See DnnSupport::DoMemcpyD2HQuantized. + Stream &ThenMemcpyD2HQuantized(const DeviceMemory &gpu_unquantized_src, + dnn::QuantizedActivationMode mode, + void *host_dst, uint64_t size); + + // Template version of ThenMemcpyD2HQuantized that takes a mutable span and + // uses the Quantization trait to call the generic version of + // ThenMemcpyD2HQuantized with the correct QuantizedActivationMode. + template + Stream &ThenMemcpyD2HQuantized(const DeviceMemory &gpu_unquantized_src, + absl::Span host_dst) { + return ThenMemcpyD2HQuantized( + gpu_unquantized_src, Quantization::kModeId, + host_dst.data(), host_dst.size() * sizeof(ElementType)); + } + + // See DnnSupport::DoMemcpyH2DQuantized. + Stream &ThenMemcpyH2DQuantized(const void *host_src, uint64_t size, + dnn::QuantizedActivationMode mode, + DeviceMemory *gpu_unquantized_dst); + + // Template version of ThenMemcpyH2DQuantized that takes an array slice + // and uses the Quantization trait to call the generic version of + // ThenMemcpyH2DQuantized with the correct QuantizedActivationMode. + template + Stream &ThenMemcpyH2DQuantized(absl::Span host_src, + DeviceMemory *gpu_unquantized_dst) { + return ThenMemcpyH2DQuantized( + host_src.data(), host_src.size() * sizeof(ElementType), + Quantization::kModeId, gpu_unquantized_dst); + } + + ///////////////// + // BLAS support + + // See BlasSupport::DoBlasAxpy. Note that, even for the case where alpha is + // present in DeviceMemory, it must be an execution-time constant (i.e. a + // value + // that the stream does not change or populate during the course of + // execution). The value is effectively captured at stream-enqueue time. + Stream &ThenBlasAxpy(uint64_t elem_count, float alpha, + const DeviceMemory &x, int incx, + DeviceMemory *y, int incy); + + // See BlasSupport::DoBlasCopy. + Stream &ThenBlasCopy(uint64_t elem_count, const DeviceMemory &x, + int incx, DeviceMemory *y, int incy); + + // See BlasSupport::DoBlasScal. + Stream &ThenBlasScal(uint64_t elem_count, float alpha, DeviceMemory *x, + int incx); + Stream &ThenBlasScal(uint64_t elem_count, double alpha, + DeviceMemory *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, float alpha, + DeviceMemory> *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, double alpha, + DeviceMemory> *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, std::complex alpha, + DeviceMemory> *x, int incx); + Stream &ThenBlasScal(uint64_t elem_count, std::complex alpha, + DeviceMemory> *x, int incx); + + // See BlasSupport::DoBlasGemv. + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, float alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, float beta, + DeviceMemory *y, int incy); + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, + double alpha, const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, double beta, + DeviceMemory *y, int incy); + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy); + Stream &ThenBlasGemv(blas::Transpose trans, uint64_t m, uint64 n, + std::complex alpha, + const DeviceMemory> &a, int lda, + const DeviceMemory> &x, int incx, + std::complex beta, + DeviceMemory> *y, int incy); + + // See BlasSupport::DoBlasSbmv. + Stream &ThenBlasSbmv(blas::UpperLower uplo, uint64_t n, uint64 k, float alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &x, int incx, float beta, + DeviceMemory *y, int incy); + + template + tsl::Status ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, + const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, + DeviceMemory *c, int ldc, + const NumericOptions &numeric_options) { + InputType alpha{1.0}; + InputType beta{0.0}; + return ThenBlasGemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, + ldc, numeric_options); + } + + template + tsl::Status ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, ConstantType alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, + ConstantType beta, DeviceMemory *c, + int ldc, const NumericOptions &numeric_options) { + static_assert( + detail::is_any_of, + std::complex>(), + "Input can be int8_t, half, bf16, float, double, std::complex " + "or " + "std::complex"); + static_assert(!std::is_same_v || + detail::is_any_of(), + "If input is Eigen::half, constant has to be either " + "Eigen::half or float"); + static_assert(detail::is_any_of(), + "If input is not int8_t, Eigen::half, constant and input " + "types have to match"); + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + + return blas->DoBlasGemm(this, transa, transb, m, n, k, + blas::ToDataType::value, alpha_ptr, a, + lda, b, ldb, beta_ptr, c, ldc, numeric_options); + } + + // TODO(reedwm): Update all callers to pass correct NumericOptions. + template + tsl::Status ThenBlasGemm(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, ConstantType alpha, + const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, + ConstantType beta, DeviceMemory *c, + int ldc) { + return ThenBlasGemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, + ldc, NumericOptions{}); + } + + template + tsl::Status ThenBlasGemmWithAlgorithm( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, DeviceMemory *c, + int ldc, blas::ComputationType computation_type, + blas::AlgorithmType algorithm, + blas::ProfileResult *output_profile_result) { + OutputType alpha{1}; + OutputType beta{0}; + return ThenBlasGemmWithAlgorithm( + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc, + computation_type, algorithm, NumericOptions{}, output_profile_result); + } + + template + tsl::Status ThenBlasGemmWithAlgorithm( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, ConstantType alpha, const DeviceMemory &a, int lda, + const DeviceMemory &b, int ldb, ConstantType beta, + DeviceMemory *c, int ldc, + blas::ComputationType computation_type, blas::AlgorithmType algorithm, + const NumericOptions &numeric_options, + blas::ProfileResult *output_profile_result) { + TF_RETURN_IF_ERROR( + CheckTypesForExtendedBlas( + computation_type)); + + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + + tsl::Status st = blas->DoBlasGemmWithAlgorithm( + this, transa, transb, m, n, k, alpha_ptr, a, + blas::ToDataType::value, lda, b, + blas::ToDataType::value, ldb, beta_ptr, c, + blas::ToDataType::value, ldc, computation_type, algorithm, + numeric_options, output_profile_result); + if (output_profile_result) { + // The error is recorded in the profile. + return ::tsl::OkStatus(); + } + return st; + } + + template + tsl::Status ThenBlasGemmStridedBatchedWithAlgorithm( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, ConstantType alpha, const DeviceMemory &a, int lda, + int64_t stride_a, const DeviceMemory &b, int ldb, + int64_t stride_b, ConstantType beta, DeviceMemory *c, int ldc, + int64_t stride_c, int batch_count, blas::ComputationType computation_type, + blas::AlgorithmType algorithm, const NumericOptions &numeric_options, + blas::ProfileResult *output_profile_result) { + TF_RETURN_IF_ERROR( + CheckTypesForExtendedBlas( + computation_type)); + + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + tsl::Status st = blas->DoBlasGemmStridedBatchedWithAlgorithm( + this, transa, transb, m, n, k, alpha_ptr, a, + blas::ToDataType::value, lda, stride_a, b, + blas::ToDataType::value, ldb, stride_b, beta_ptr, c, + blas::ToDataType::value, ldc, stride_c, batch_count, + computation_type, algorithm, numeric_options, output_profile_result); + if (output_profile_result) { + // The error is recorded in the profile. + return ::tsl::OkStatus(); + } + return st; + } + + template + using DeviceMemorySlice = absl::Span *const>; + + // See BlasSupport::DoBlasGemmBatched. + Stream &ThenBlasGemmBatched(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64 k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, float beta, + DeviceMemorySlice c, int ldc, + int batch_count, + const NumericOptions &numeric_options); + Stream &ThenBlasGemmBatched(blas::Transpose transa, blas::Transpose transb, + uint64_t m, uint64 n, uint64_t k, + std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, + DeviceMemorySlice> c, int ldc, + int batch_count, + const NumericOptions &numeric_options); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, float alpha, DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, float beta, + DeviceMemorySlice c, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, float alpha, DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, float beta, + DeviceMemorySlice c, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch(blas::Transpose transa, + blas::Transpose transb, uint64_t m, + uint64 n, uint64_t k, float alpha, + DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, + float beta, DeviceMemorySlice c, + int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, double alpha, DeviceMemorySlice a, int lda, + DeviceMemorySlice b, int ldb, double beta, + DeviceMemorySlice c, int ldc, int batch_count, + const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + Stream &ThenBlasGemmBatchedWithScratch( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, std::complex alpha, + DeviceMemorySlice> a, int lda, + DeviceMemorySlice> b, int ldb, + std::complex beta, DeviceMemorySlice> c, + int ldc, int batch_count, const NumericOptions &numeric_options, + ScratchAllocator *scratch_allocator); + + template + tsl::Status ThenBlasGemmStridedBatched( + blas::Transpose transa, blas::Transpose transb, uint64_t m, uint64 n, + uint64_t k, ConstantType alpha, const DeviceMemory &a, int lda, + int64_t stride_a, const DeviceMemory &b, int ldb, + int64_t stride_b, ConstantType beta, DeviceMemory *c, int ldc, + int64_t stride_c, int batch_count, + const NumericOptions &numeric_options) { + static_assert( + detail::is_any_of, + std::complex>(), + "Unsupported input type"); + static_assert(std::is_same_v || + (detail::is_any_of() && + std::is_same_v), + "Mismatched input and alpha/beta types"); + blas::BlasSupport *blas = parent()->AsBlas(); + if (!blas) { + return tsl::errors::Internal( + "Attempting to perform BLAS operation using " + "StreamExecutor without BLAS support"); + } + + void *alpha_ptr = α + void *beta_ptr = β + float alpha_storage, beta_storage; + UpcastHalfToFloat(&alpha_ptr, &beta_ptr, &alpha_storage, + &beta_storage); + + return blas->DoBlasGemmStridedBatched( + this, transa, transb, m, n, k, blas::ToDataType::value, + alpha_ptr, a, lda, stride_a, b, ldb, stride_b, beta_ptr, c, ldc, + stride_c, batch_count, numeric_options); + } + + // See BlasSupport::DoBlasTrsm. + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, float alpha, const DeviceMemory &a, + int lda, DeviceMemory *b, int ldb); + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, double alpha, const DeviceMemory &a, + int lda, DeviceMemory *b, int ldb); + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb); + Stream &ThenBlasTrsm(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, uint64_t m, + uint64_t n, std::complex alpha, + const DeviceMemory> &a, int lda, + DeviceMemory> *b, int ldb); + + // See BlasSupport::DoBlasTrsmBatched. + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, float alpha, + const DeviceMemory &as, int lda, + DeviceMemory *bs, int ldb, + int batch_count); + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, double alpha, + const DeviceMemory &as, int lda, + DeviceMemory *bs, int ldb, + int batch_count); + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, std::complex alpha, + const DeviceMemory *> &as, + int lda, DeviceMemory *> *bs, + int ldb, int batch_count); + Stream &ThenBlasTrsmBatched(blas::Side side, blas::UpperLower uplo, + blas::Transpose transa, blas::Diagonal diag, + uint64_t m, uint64 n, std::complex alpha, + const DeviceMemory *> &as, + int lda, DeviceMemory *> *bs, + int ldb, int batch_count); + + // See FftSupport::DoFft. + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, const DeviceMemory &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, const DeviceMemory &input, + DeviceMemory> *output); + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output); + Stream &ThenFft(fft::Plan *plan, + const DeviceMemory> &input, + DeviceMemory *output); + + // Entrain onto the stream: a memcpy to a host destination from a GPU source + // of the given target size. host_dst must be a pointer to host memory + // allocated by StreamExecutor::HostMemoryAllocate or otherwise allocated and + // then registered with StreamExecutor::HostMemoryRegister. + Stream &ThenMemcpy(void *host_dst, const DeviceMemoryBase &gpu_src, + uint64_t size); + + // Entrain onto the stream: a memcpy to a GPU destination from a host source + // of the given target size. host_src must be a pointer to host memory + // allocated by StreamExecutor::HostMemoryAllocate or otherwise allocated and + // then registered with StreamExecutor::HostMemoryRegister. + Stream &ThenMemcpy(DeviceMemoryBase *gpu_dst, const void *host_src, + uint64_t size); + + // Alternative interface for memcpying from device to host that takes an + // array slice. Checks that the destination size can accommodate the host + // slice size. + template + Stream &ThenMemcpyD2H(const DeviceMemory &gpu_src, + absl::Span host_dst) { + auto host_size = host_dst.size() * sizeof(T); + CHECK(gpu_src.size() == 0 || host_size >= gpu_src.size()); + return ThenMemcpy(host_dst.begin(), gpu_src, host_size); + } + + // Alternative interface for memcpying from host to device that takes an + // array slice. Checks that the destination size can accommodate the host + // slice size. + template + Stream &ThenMemcpyH2D(absl::Span host_src, + DeviceMemory *gpu_dst) { + auto host_size = host_src.size() * sizeof(T); + CHECK(gpu_dst->size() == 0 || gpu_dst->size() >= host_size); + return ThenMemcpy(gpu_dst, host_src.begin(), host_size); + } + + // Entrain onto the stream: a memcpy to a GPU destination from a GPU source + // of the given target size. gpu_src/dst must be pointers to GPU memory and + // peer access must be enabled between their owning StreamExecutors. + Stream &ThenMemcpy(DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src, + uint64_t size); + + // Calls to the device-to-device copy overload of ThenMemcpy -- useful for + // ensuring that the host pointer isn't getting confused accidentally with a + // device pointer if you're not doing metaprogramming against the API. + Stream &ThenMemcpyD2D(DeviceMemoryBase *gpu_dst, + const DeviceMemoryBase &gpu_src, uint64_t size) { + return ThenMemcpy(gpu_dst, gpu_src, size); + } + + // Entrain onto the stream: a memset of zero at a GPU location of size bytes. + // The location must not be null. + Stream &ThenMemZero(DeviceMemoryBase *location, uint64_t size); + + // Entrain onto the stream: a memset of a 32-bit pattern at a GPU location of + // size bytes, where bytes must be evenly 32-bit sized (i.e. evenly divisible + // by 4). The location must not be null. + Stream &ThenMemset32(DeviceMemoryBase *location, uint32_t pattern, + uint64_t size); + + // Enqueue a forward operation of the RNN model onto the stream. + // See DnnSupport::DoRnnForward for more details. + Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + DeviceMemory *output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + DeviceMemory *output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + DeviceMemory *output_c_data, + bool is_training, + ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + DeviceMemory *output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + DeviceMemory *output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + DeviceMemory *output_c_data, bool is_training, + ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnForward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + DeviceMemory *output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + DeviceMemory *output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + DeviceMemory *output_c_data, bool is_training, + ScratchAllocator *reserve_space_allocator, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + // Enqueue a backward operation of the RNN model onto the stream. + // See DnnSupport::DoRnnBackward for more details. + Stream &ThenRnnBackward( + const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + const DeviceMemory &output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + const DeviceMemory &output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + const DeviceMemory &output_c_data, + const DeviceMemory &output_backprop_data, + const DeviceMemory &output_h_backprop_data, + const DeviceMemory &output_c_backprop_data, + DeviceMemory *input_backprop_data, + DeviceMemory *input_h_backprop_data, + DeviceMemory *input_c_backprop_data, + DeviceMemory *params_backprop_data, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnBackward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + const DeviceMemory &output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + const DeviceMemory &output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + const DeviceMemory &output_c_data, + const DeviceMemory &output_backprop_data, + const DeviceMemory &output_h_backprop_data, + const DeviceMemory &output_c_backprop_data, + DeviceMemory *input_backprop_data, + DeviceMemory *input_h_backprop_data, + DeviceMemory *input_c_backprop_data, + DeviceMemory *params_backprop_data, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + Stream &ThenRnnBackward(const dnn::RnnDescriptor &rnn_desc, + const dnn::RnnSequenceTensorDescriptor &input_desc, + const DeviceMemory &input_data, + const DeviceMemory &seq_lengths_data, + const dnn::RnnStateTensorDescriptor &input_h_desc, + const DeviceMemory &input_h_data, + const dnn::RnnStateTensorDescriptor &input_c_desc, + const DeviceMemory &input_c_data, + const DeviceMemory ¶ms, + const dnn::RnnSequenceTensorDescriptor &output_desc, + const DeviceMemory &output_data, + const dnn::RnnStateTensorDescriptor &output_h_desc, + const DeviceMemory &output_h_data, + const dnn::RnnStateTensorDescriptor &output_c_desc, + const DeviceMemory &output_c_data, + const DeviceMemory &output_backprop_data, + const DeviceMemory &output_h_backprop_data, + const DeviceMemory &output_c_backprop_data, + DeviceMemory *input_backprop_data, + DeviceMemory *input_h_backprop_data, + DeviceMemory *input_c_backprop_data, + DeviceMemory *params_backprop_data, + DeviceMemory *reserve_space_data, + ScratchAllocator *workspace_allocator, + dnn::ProfileResult *output_profile_result); + + // Enqueue a CTCLoss operation onto the stream. + // See DnnSupport::DoCtcLoss for more details. + Stream &ThenCtcLoss(const dnn::RnnStateTensorDescriptor &probs_desc, + const DeviceMemory &probs_data, + absl::Span labels_data, + absl::Span labels_lengths_data, + absl::Span input_lengths_data, + const NumericOptions &numeric_options, + DeviceMemory *costs_data, + const dnn::RnnStateTensorDescriptor &grads_desc, + DeviceMemory *grads_data, + ScratchAllocator *workspace_allocator); + + // Enqueue onto the stream a operation that transforms a tensor. + // See DnnSupport::DoTransformTensor for more details. + Stream &ThenTransformTensor(const dnn::BatchDescriptor &input_desc, + dnn::DataType input_type, + const DeviceMemoryBase &input_data, + const dnn::BatchDescriptor &output_desc, + dnn::DataType output_type, float scale, + DeviceMemoryBase *output_data); + + // (Synchronously) block the host code waiting for the operations + // entrained on the stream (enqueued to this point in program + // execution) to complete. + // + // Returns an OK status if the blocking was successful and the stream is ok(). + // Otherwise returns an error describing why the blocking failed. + tsl::Status BlockHostUntilDone() TF_LOCKS_EXCLUDED(mu_); + + // Warning! This method interacts with internal threads in + // sometimes-unpredictable ways and is intended for GPU-Executor-internal + // use + // only. Please check with a member of the FASTR team before making use of + // this method. + // + // Entrains onto the stream a function to be executed on the host at some + // point in the future. + // Async host callbacks DO NOT block the stream as device functions (or as + // synchronous host callbacks). No synchronization is possible with + // asynchronous callbacks; they are strictly fire-and-forget. + // This method is private due to the potential for undefined behavior with + // synchronization using OpenCL user events. + // The ONLY lifetime guarantee in these calls is that the StreamExecutor + // parameter will still be valid - this Stream may not be! + // Any callbacks requiring device API calls must use this method. + Stream &ThenEnqueueOnBackgroundThread( + std::function task); + + // Returns the (opaque) platform-specific backing object. Ownership is not + // transferred to the caller. + internal::StreamInterface *implementation() { return implementation_.get(); } + + // Entrains onto the stream a callback to the host (from the device). + // Behaves as ThenDoHostCallbackWithStatus below, but the callback should + // never fail or its failure is inconsequential. + // + // This is kept for backward compatibility. Future code should use + // ThenDoHostCallbackWithStatus and explicitly return a success status. + // TODO(b/112125301): Eventually remove this method. + Stream &ThenDoHostCallback(absl::AnyInvocable callback); + + // Entrains onto the stream a callback to the host (from the device). + // Host callbacks block/occupy the stream just as device functions + // (execute one at a time, block later stream operations). + // Whether the callback return status affects the result of BlockHostUntilDone + // is platform-dependent. + // + // Behavior is undefined when synchronizing using OpenCL user events. + // Behavior is undefined if host callbacks call device routines or insert + // them into any stream. + // + // On certain platforms, ThenDoHostCallback is expected to have significant + // negative effects on performance. + Stream &ThenDoHostCallbackWithStatus( + absl::AnyInvocable callback); + + // Returns the StreamExecutor (parent object) associated with this stream. + StreamExecutor *parent() const { + CHECK(parent_ != nullptr); + return parent_; + } + + // + CudaComputeCapability GetCudaComputeCapability() const { + return parent()->GetDeviceDescription().cuda_compute_capability(); + } + + RocmComputeCapability GetRocmComputeCapability() const { + return parent()->GetDeviceDescription().rocm_compute_capability(); + } + // Returns the (internal usage) temporary-memory-allocation manager associated + // with this stream. + internal::TemporaryMemoryManager *temporary_memory_manager(); + + // Returns a debugging string "[stream=0x...,impl=0x...]". + std::string DebugStreamPointers() const; + + void SetPriority(StreamPriority priority); + void SetPriority(int priority); + + std::variant priority() const; + + private: + template + friend struct ThenBlasImpl; // for implementing ThenBlasXXX. + + // Checks whether types match before a call to extended BLAS version. + template + tsl::Status CheckTypesForExtendedBlas( + blas::ComputationType computation_type) { + static_assert( + detail::is_any_of, std::complex>(), + "The only buffer types supported are: Eigen::half, float, " + "double, int8, std::complex and std::complex"); + static_assert( + std::is_same_v || + (std::is_same_v && + detail::is_any_of()), + "Mismatched alpha/beta and output types"); + + bool valid_computation_type = [computation_type] { + switch (computation_type) { + case blas::ComputationType::kF16: + return std::is_same_v; + case blas::ComputationType::kF32: + return detail::is_any_of>(); + case blas::ComputationType::kF64: + return detail::is_any_of>(); + case blas::ComputationType::kI32: + return std::is_same_v; + case blas::ComputationType::kF16AsF32: // fall-through + case blas::ComputationType::kBF16AsF32: // fall-through + case blas::ComputationType::kTF32AsF32: + return detail::is_any_of>(); + } + }(); + + if (!valid_computation_type) { + return tsl::errors::Internal( + "Invalid computation type ", + blas::ComputationTypeString(computation_type), " for output type: ", + blas::DataTypeString(blas::ToDataType::value)); + } + return ::tsl::OkStatus(); + } + + bool InErrorState() const TF_LOCKS_EXCLUDED(mu_) { + absl::ReaderMutexLock lock(&mu_); + return !status_.ok(); + } + + // Sets the error state if operation_retcode is false. + // This is a useful shorthand for many stream routines. + void CheckError(bool operation_retcode) TF_LOCKS_EXCLUDED(mu_); + + // Checks the status and logs the error message, if any. + void CheckStatus(tsl::Status status) TF_LOCKS_EXCLUDED(mu_); + + void SetError() { CheckError(false /* = operation_retcode */); } + + void SetErrorAndLogNoDnnSupport() { + SetError(); + LOG(WARNING) << "attempting to perform DNN operation using StreamExecutor " + "without DNN support"; + } + + // Runs the set of callbacks that are intended to run after + // BlockHostUntilDone. + void RunAfterBlockHostUntilDoneCallbacks(); + + // The StreamExecutor that supports the operation of this stream. + StreamExecutor *parent_; + + // The platform-dependent implementation that the StreamExecutor interface + // delegates to. + std::unique_ptr implementation_; + + // mutex that guards the allocation / error state flags. + // Mutable so that it can be obtained via const reader lock. + mutable absl::Mutex mu_; + + // Whether Init() was successfully called to allocate this stream on the + // underlying platform. It simply flips from 0 to 1 with a sanity check. + // See StreamExecutor::AllocateStream. + bool allocated_ ABSL_GUARDED_BY(mu_); + + // The last error (if any) of all method calls. + tsl::Status status_ ABSL_GUARDED_BY(mu_); + + // Sub-streams that are generated from this stream. Each element has a pointer + // to sub-stream and a boolean value indicating if this substream is ready to + // be reused. + std::vector, bool>> sub_streams_ + ABSL_GUARDED_BY(mu_); + + // Streams can allocate temporary memories to help with work they enqueue + // (e.g. for scratch memory spaces). This member tracks those allocations and + // notes when they can be reclaimed -- reclamation is attempted when + // BlockHostUntilDone() is called. + internal::TemporaryMemoryManager temporary_memory_manager_; + + // Callbacks enqueued to be run after the next call to BlockHostUntilDone(). + std::vector> + after_block_host_until_done_callbacks_ ABSL_GUARDED_BY(mu_); + + // Non-extended BLAS interface requires alpha/beta to be floats when input + // type is Eigen::half. However, for consistency purposes it is convenient + // for the interface to accept Eigen::half. + template + void UpcastHalfToFloat(void **alpha_ptr, void **beta_ptr, + float *alpha_storage, float *beta_storage) { + if (std::is_same::value) { + *alpha_storage = + static_cast(*reinterpret_cast(*alpha_ptr)); + *beta_storage = + static_cast(*reinterpret_cast(*beta_ptr)); + *alpha_ptr = alpha_storage; + *beta_ptr = beta_storage; + } else if (std::is_same::value) { + *alpha_storage = + static_cast(*reinterpret_cast(*alpha_ptr)); + *beta_storage = + static_cast(*reinterpret_cast(*beta_ptr)); + *alpha_ptr = alpha_storage; + *beta_ptr = beta_storage; + } + } + + Stream(const Stream &) = delete; + void operator=(const Stream &) = delete; +}; + +//////////// +// Inlines + +template +inline tsl::Status Stream::ThenLaunch(ThreadDim thread_dims, + BlockDim block_dims, + const TypedKernel &kernel, + Args... args) { + KernelInvocationChecker, + std::tuple>::CheckAllStaticAssert(); + + // This is the core that allows type-safe kernel launching. + // Since the platforms take kernel arguments as tuples of (void *, size), + // we pack the variadic parameters passed as ...args into the desired + // tuple form and pass that packed form to the StreamExecutor::Launch() + // implementation. + KernelArgsArray kernel_args; + kernel.PackParams(&kernel_args, args...); + TF_RETURN_IF_ERROR( + parent_->Launch(this, thread_dims, block_dims, kernel, kernel_args)); + return ::tsl::OkStatus(); +} + +template +inline tsl::StatusOr>> +Stream::AllocateTemporaryArray(uint64_t element_count) { + return temporary_memory_manager_.AllocateArray(element_count); +} + +inline internal::TemporaryMemoryManager *Stream::temporary_memory_manager() { + return &temporary_memory_manager_; +} + +template <> +struct Quantization { + static constexpr dnn::QuantizedActivationMode kModeId = + dnn::QuantizedActivationMode::k8Bit; +}; + +template <> +struct Quantization { + static constexpr dnn::QuantizedActivationMode kModeId = + dnn::QuantizedActivationMode::k16Bit; +}; + +template <> +struct Quantization { + static constexpr dnn::QuantizedActivationMode kModeId = + dnn::QuantizedActivationMode::k32Bit; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_STREAM_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..76b9921b24052366fbeaa9a2dbddde435f9e61b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor.h @@ -0,0 +1,37 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The StreamExecutor is a single-device abstraction for: +// +// * Loading/launching data-parallel-kernels +// * Invoking pre-canned high-performance library routines (like matrix +// multiply) + +#ifndef XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_H_ +#define XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_H_ + +#include "xla/stream_executor/device_description.h" // IWYU pragma: export +#include "xla/stream_executor/device_memory.h" // IWYU pragma: export +#include "xla/stream_executor/device_options.h" // IWYU pragma: export +#include "xla/stream_executor/event.h" // IWYU pragma: export +#include "xla/stream_executor/kernel.h" // IWYU pragma: export +#include "xla/stream_executor/kernel_spec.h" // IWYU pragma: export +#include "xla/stream_executor/launch_dim.h" // IWYU pragma: export +#include "xla/stream_executor/multi_platform_manager.h" // IWYU pragma: export +#include "xla/stream_executor/platform.h" // IWYU pragma: export +#include "xla/stream_executor/stream.h" // IWYU pragma: export +#include "xla/stream_executor/stream_executor_pimpl.h" // IWYU pragma: export + +#endif // XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_internal.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..47cd7de5bc19e8dd366693f5f4aa37784824d6c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_internal.h @@ -0,0 +1,439 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Interfaces for platform-dependent implementations to satisfy. This are +// delegated to from the StreamExecutor in pointer-to-implementation style; i.e. +// the StreamExecutor is just a husk that delegates calls to the +// platform-specific objects which implement the interfaces defined here. + +#ifndef XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_INTERNAL_H_ +#define XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_INTERNAL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/status/status.h" +#include "xla/stream_executor/allocator_stats.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/device_description.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/kernel_cache_config.h" +#include "xla/stream_executor/kernel_spec.h" +#include "xla/stream_executor/launch_dim.h" +#include "xla/stream_executor/module_spec.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/plugin_registry.h" +#include "xla/stream_executor/trace_listener.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +class Stream; + +namespace internal { + +//===----------------------------------------------------------------------===// +// EventInterface +//===----------------------------------------------------------------------===// + +// Platform-dependent interface class for the generic Events interface, in +// the PIMPL style. +class EventInterface { + public: + EventInterface() = default; + virtual ~EventInterface() = default; + + private: + EventInterface(const EventInterface&) = delete; + void operator=(const EventInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// KernelInterface +//===----------------------------------------------------------------------===// + +// Pointer-to-implementation object type (i.e. the KernelBase class delegates to +// this interface) with virtual destruction. This class exists for the +// platform-dependent code to hang any kernel data/resource info/functionality +// off of. +class KernelInterface { + public: + // Default constructor for the abstract interface. + KernelInterface() = default; + + // Default destructor for the abstract interface. + virtual ~KernelInterface() = default; + + // Returns the number of formal parameters that this kernel accepts. + virtual unsigned Arity() const = 0; + + // Sets the preferred cache configuration. + virtual void SetPreferredCacheConfig(KernelCacheConfig config) = 0; + + // Gets the preferred cache configuration. + virtual KernelCacheConfig GetPreferredCacheConfig() const = 0; + + private: + KernelInterface(const KernelInterface&) = delete; + void operator=(const KernelInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// CommandBufferInterface +//===----------------------------------------------------------------------===// + +// Platform-dependent interface class for implementing generic CommandBuffer. +// +// TODO(ezhulenev): Currently we assume that all operations between barriers +// can execute concurrently, and it's up to the caller to insert barriers to +// guarantee correctness. Consider adding finer grained synchronization +// mechanism between different commands. +// +// TODO(ezhulenev): Currently command buffers do no support updates, and once +// finalized can be executed as recorded. We need to support cheap command +// buffer updates that in GPU backend will be mapped to CUDA/HIP graph node +// updates. +class CommandBufferInterface { + public: + CommandBufferInterface() = default; + virtual ~CommandBufferInterface() = default; + + // Traces `function` invocation by recording all operations on the `stream` + // into the command buffer. Command buffer must be empty. + virtual tsl::Status Trace(Stream* stream, + absl::AnyInvocable function) = 0; + + // Adds a kernel launch command to the command buffer. + virtual tsl::Status Launch(const ThreadDim& threads, const BlockDim& blocks, + const KernelBase& kernel, + const KernelArgsArrayBase& args) = 0; + + // Adds a device-to-device memory copy to the command buffer. + virtual tsl::Status MemcpyDeviceToDevice(DeviceMemoryBase* dst, + const DeviceMemoryBase& src, + uint64_t size) = 0; + + // Finalizes command buffer and makes it executable. Once command buffer is + // finalized no commands can be added to it. + virtual tsl::Status Finalize() = 0; + + // Begins command buffer update. Command buffer update should be finalized + // before it can be executed. + virtual tsl::Status Update() = 0; + + // Returns command buffer execution mode. + virtual CommandBuffer::Mode mode() const = 0; + + // Returns command buffer state. + virtual CommandBuffer::State state() const = 0; + + private: + CommandBufferInterface(const CommandBufferInterface&) = delete; + void operator=(const CommandBufferInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// StreamInterface +//===----------------------------------------------------------------------===// + +// Pointer-to-implementation object type (i.e. the Stream class delegates to +// this interface) with virtual destruction. This class exists for the +// platform-dependent code to hang any kernel data/resource info/functionality +// off of. +class StreamInterface { + public: + // Default constructor for the abstract interface. + StreamInterface() = default; + + // Default destructor for the abstract interface. + virtual ~StreamInterface() = default; + + // Sets priority for a stream. + virtual void SetPriority(StreamPriority priority) { + LOG(ERROR) << "SetPriority unimplemented for this stream."; + } + + virtual void SetPriority(int priority) { + LOG(ERROR) << "SetPriority unimplemented for this stream."; + } + + // Gets priority for a stream. + virtual std::variant priority() const { + return StreamPriority::Default; + } + + // Returns the GPU stream associated with this platform's stream + // implementation, or nullptr otherwise. + virtual void* GpuStreamHack() { return nullptr; } + + // Returns a pointer to a GPU stream associated with this platform's stream, + // or a nullptr. + virtual void** GpuStreamMemberHack() { return nullptr; } + + private: + StreamInterface(const StreamInterface&) = delete; + void operator=(const StreamInterface&) = delete; +}; + +//===----------------------------------------------------------------------===// +// StreamExecutorInterface +//===----------------------------------------------------------------------===// + +// Interface for the different StreamExecutor platforms (i.e. CUDA, OpenCL). +// +// Various platforms will provide an implementation that satisfy this interface. +class StreamExecutorInterface { + public: + // Default constructor for the abstract interface. + StreamExecutorInterface() = default; + + // Default destructor for the abstract interface. + virtual ~StreamExecutorInterface() = default; + + // Returns the (transitively) wrapped executor if this executor is + // wrapping another executor; otherwise, returns this. + virtual StreamExecutorInterface* GetUnderlyingExecutor() { return this; } + + // See the StreamExecutor interface for comments on the same-named methods. + virtual tsl::Status Init(int device_ordinal, + DeviceOptions device_options) = 0; + + // This value is cached by the wrapping StreamExecutor instance, so it's OK if + // this function is slow. + // + // The wrapping StreamExecutor will use the platform name if this is nullopt. + virtual std::optional MakeDeviceDescriptionStr() const { + return std::nullopt; + } + + virtual tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, + KernelBase* kernel) { + return absl::UnimplementedError("Not Implemented"); + } + virtual bool UnloadModule(ModuleHandle module_handle) { return false; } + virtual tsl::Status LoadModule(const MultiModuleLoaderSpec& spec, + ModuleHandle* module_handle) { + return absl::UnimplementedError("Not Implemented"); + } + virtual tsl::StatusOr> + CreateOrShareConstant(Stream* stream, const std::vector& content) { + return absl::UnimplementedError("Not Implemented"); + } + virtual tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& k, + const KernelArgsArrayBase& args) { + return absl::UnimplementedError("Not Implemented"); + } + + virtual tsl::Status Submit(Stream* stream, + const CommandBuffer& command_buffer) { + return absl::UnimplementedError("Not Implemented"); + } + + // Releases any state associated with the kernel. + virtual void UnloadKernel(const KernelBase* kernel) {} + virtual DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space) = 0; + DeviceMemoryBase Allocate(uint64_t size) { + return Allocate(size, /*memory_space=*/0); + } + virtual void* GetSubBuffer(DeviceMemoryBase* parent, uint64_t offset, + uint64_t size) = 0; + virtual void Deallocate(DeviceMemoryBase* mem) = 0; + // Allocates unified memory space of the given size, if supported. + // See + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#um-unified-memory-programming-hd + // for more details on unified memory. + virtual void* UnifiedMemoryAllocate(uint64_t size) { return nullptr; } + + // Deallocates unified memory space previously allocated with + // UnifiedMemoryAllocate. + virtual void UnifiedMemoryDeallocate(void* mem) {} + virtual void* HostMemoryAllocate(uint64_t size) = 0; + virtual void HostMemoryDeallocate(void* mem) = 0; + virtual bool HostMemoryRegister(void* mem, uint64_t size) = 0; + virtual bool HostMemoryUnregister(void* mem) = 0; + virtual bool SynchronizeAllActivity() = 0; + virtual tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemSet(DeviceMemoryBase* location, int value, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemcpy(DeviceMemoryBase* gpu_dst, + const void* host_src, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemcpy(void* host_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) = 0; + virtual tsl::Status SynchronousMemcpyDeviceToDevice( + DeviceMemoryBase* gpu_dst, const DeviceMemoryBase& gpu_src, + uint64_t size) = 0; + virtual tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) = 0; + virtual tsl::Status Memset(Stream* stream, DeviceMemoryBase* location, + uint8 pattern, uint64_t size) { + return tsl::errors::Internal("Not implemented"); + } + virtual tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size) = 0; + virtual bool Memcpy(Stream* stream, void* host_dst, + const DeviceMemoryBase& gpu_src, uint64_t size) = 0; + virtual bool Memcpy(Stream* stream, DeviceMemoryBase* gpu_dst, + const void* host_src, uint64_t size) = 0; + virtual bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* gpu_dst, + const DeviceMemoryBase& gpu_src, + uint64_t size) = 0; + virtual bool HostCallback(Stream* stream, + absl::AnyInvocable callback) = 0; + virtual tsl::Status AllocateEvent(Event* event) = 0; + virtual tsl::Status DeallocateEvent(Event* event) = 0; + virtual tsl::Status RecordEvent(Stream* stream, Event* event) = 0; + virtual tsl::Status WaitForEvent(Stream* stream, Event* event) = 0; + virtual tsl::Status WaitForEventOnExternalStream(std::intptr_t stream, + Event* event) { + return absl::UnimplementedError( + "WaitForEventOnExternalStream not supported on this executor."); + } + virtual Event::Status PollForEventStatus(Event* event) = 0; + virtual bool AllocateStream(Stream* stream) = 0; + virtual void DeallocateStream(Stream* stream) = 0; + virtual bool CreateStreamDependency(Stream* dependent, Stream* other) = 0; + virtual tsl::Status BlockHostUntilDone(Stream* stream) = 0; + virtual tsl::Status GetStatus(Stream* stream) { + return absl::UnimplementedError( + "GetStatus is not supported on this executor."); + } + virtual tsl::Status EnablePeerAccessTo(StreamExecutorInterface* other) = 0; + virtual bool CanEnablePeerAccessTo(StreamExecutorInterface* other) = 0; + + virtual int64_t GetDeviceLoad() { return -1; } + + virtual bool DeviceMemoryUsage(int64_t* free, int64_t* total) const { + return false; + } + + // Retrieves device pointer and size for a symbol. The device pointer is + // stored at mem, and the size is stored at size. Either mem or bytes can be + // null, however, both of them cannot be null at the same time. To use + // constant memory in CUDA, GetSymbol has to be used. Returns true if symbol + // is found. + // + // If ModuleHandle is set then we search for `symbol_name` only within the + // module corresponding to `module_handle`. Otherwise all loaded modules are + // searched. + virtual bool GetSymbol(const std::string& symbol_name, + ModuleHandle module_handle, void** mem, + size_t* bytes) { + return false; + } + + // Creates a new DeviceDescription object. Ownership is transferred to the + // caller. + virtual tsl::StatusOr> + CreateDeviceDescription() const = 0; + + // Attempts to register the provided TraceListener with the device-specific + // Executor implementation. When this is called, the PIMPL interface has + // already taken ownership of the object and is managing the generic tracing + // events. The device-specific implementation must determine if the passed + // listener is of a type appropriate for it to trace during registration (and + // before dispatching events to it). + // Returns true if the listener was successfully registered, false otherwise. + // Does not take ownership of listener. + virtual bool RegisterTraceListener(TraceListener* listener) { return false; } + + // Unregisters the specified listener from the device-specific Executor. + // Returns true if the listener was successfully registered, false otherwise. + virtual bool UnregisterTraceListener(TraceListener* listener) { + return false; + } + + // Creates a new BlasSupport object, ownership is transferred to the caller. + // + // This may return null if the BLAS initialization fails or this object does + // not support BLAS. + virtual blas::BlasSupport* CreateBlas() { return nullptr; } + + // Creates a new fft::FftSupport object, ownership is transferred to the + // caller. + // This may return null if the FFT initialization fails or this object does + // not support FFT. + virtual fft::FftSupport* CreateFft() { return nullptr; } + + // Creates a new DnnSupport object, ownership is transferred to the caller. + // This may return null if the DNN initialization fails or this object does + // not support Dnns. + virtual dnn::DnnSupport* CreateDnn() { return nullptr; } + + // Each call creates a new instance of the platform-specific implementation of + // the corresponding interface type. + virtual std::unique_ptr CreateEventImplementation() = 0; + virtual std::unique_ptr CreateKernelImplementation() = 0; + virtual std::unique_ptr GetStreamImplementation() = 0; + + virtual tsl::StatusOr> + GetCommandBufferImplementation(CommandBuffer::Mode mode) { + return absl::UnimplementedError("Command buffers are not implemented"); + } + + // Returns the CUDA or ROCm context associated with this StreamExecutor + // platform implementation. + // + // WARNING: checks that the underlying platform is, in fact, CUDA or ROCm, + // causing a fatal error if it is not. This hack is made available solely for + // use from distbelief code, which temporarily has strong ties to CUDA or ROCm + // as a platform. + virtual void* GpuContextHack() { return nullptr; } + + // Return allocator statistics. + virtual std::optional GetAllocatorStats() { + return std::nullopt; + } + + // If implemented, clears the internal stats except for the `in_use` fields + // and sets the `peak_bytes_in_use` to be equal to the `bytes_in_use`. Returns + // true if implemented. + // + // REQUIRES: GetAllocatorStats is overridden. + virtual bool ClearAllocatorStats() { return false; } + + // Clears the compilation cache from volatile memory. Returns OK if no + // compilation cache exists or if clearing the compilation cache is + // unsupported. Caches in non-volatile storage are unaffected. + virtual tsl::Status FlushCompilationCache() { return ::tsl::OkStatus(); } + + // Returns a stream allocated by this executor, or nullptr if not found. + // Performs linear search over alive GPU streams. + virtual Stream* FindAllocatedStream(void* /*gpu_stream*/) { return nullptr; } + + private: + StreamExecutorInterface(const StreamExecutorInterface&) = delete; + void operator=(const StreamExecutorInterface&) = delete; +}; + +} // namespace internal +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_INTERNAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_pimpl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_pimpl.h new file mode 100644 index 0000000000000000000000000000000000000000..f8903f1c946ff5b6d476fcce4b481f1394757ae2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/stream_executor_pimpl.h @@ -0,0 +1,752 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_PIMPL_H_ +#define XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_PIMPL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/attributes.h" +#include "absl/base/thread_annotations.h" +#include "absl/functional/any_invocable.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "xla/stream_executor/allocator_stats.h" +#include "xla/stream_executor/blas.h" +#include "xla/stream_executor/command_buffer.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/dnn.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/fft.h" +#include "xla/stream_executor/kernel_spec.h" +#include "xla/stream_executor/module_spec.h" +#include "xla/stream_executor/numeric_options.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform/port.h" +#include "xla/stream_executor/trace_listener.h" +#include "tsl/platform/status.h" +#include "tsl/platform/threadpool.h" +#include "tsl/protobuf/dnn.pb.h" + +// TODO(ezhulenev): Remove include of internal header. Currently we have too +// many targets depending on transitive dependencies. +#include "xla/stream_executor/stream_executor_internal.h" + +namespace stream_executor { + +class Stream; + +namespace internal { +class StreamExecutorInterface; +} // namespace internal + +// Forward declaration of private friend class. +template +class ScopedTracer; + +// A StreamExecutor manages a single device, in terms of executing work (kernel +// launches) and memory management (allocation/deallocation, memory copies to +// and from the device). It is conceptually the "handle" for a device -- Stream +// objects, which are used to enqueue work to run on the +// coprocessor have a StreamExecutor instance as their "parent" object. +// +// StreamExecutor objects have an underlying platform that is specified up +// front; +// e.g. either it is a CUDA or OpenCL executor. +// +// Thread-safe after initialization. +// StreamExecutor interface should not be invoked from a signal handler. +class StreamExecutor { + public: + StreamExecutor( + const Platform* platform, + std::unique_ptr implementation, + int device_ordinal); + + ~StreamExecutor(); + + tsl::Status Init(); + tsl::Status Init(DeviceOptions device_options); + + // Returns a reference to the platform that created this executor. + const Platform* platform() const { return platform_; } + + // Retrieves (loads) a kernel for the platform this StreamExecutor is acting + // upon, if one exists. + // + // Parameters: + // spec: The MultiKernelLoaderSpec is usually generated as a compile-time + // constant into an appropriate namespace. For example, see + // stream_executor::executor_sample::kKernelLoaderSpecs, from which a + // MultiKernelLoaderSpec is selected. + // kernel: Outparam that the kernel is loaded into. A given Kernel + // instantiation should not be loaded into more than once. + // + // If an error occurs, or there is no kernel available for the StreamExecutor + // platform, error status is returned. + tsl::Status GetKernel(const MultiKernelLoaderSpec& spec, KernelBase* kernel); + + // Releases any state associated with the previously loaded kernel. + void UnloadKernel(const KernelBase* kernel); + + // Loads a module for the platform this StreamExecutor is acting upon. + // + // `spec` describes the module to be loaded. On success writes the handle for + // the loaded module to `module_handle` and returns OkStatus(). Otherwise, + // returns the error which has occurred. + tsl::Status LoadModule(const MultiModuleLoaderSpec& spec, + ModuleHandle* module_handle); + + // Unloads the module with handle `module_handle`. + bool UnloadModule(ModuleHandle module_handle); + + tsl::StatusOr> CreateOrShareConstant( + Stream* stream, const std::vector& content); + + // Synchronously allocates an array on the device of type T with element_count + // elements. + template + DeviceMemory AllocateArray(uint64_t element_count, + int64_t memory_space = 0); + + // As AllocateArray(), but returns a ScopedDeviceMemory. + template + ScopedDeviceMemory AllocateOwnedArray(uint64_t element_count) { + return ScopedDeviceMemory(this, AllocateArray(element_count)); + } + + // Convenience wrapper that allocates space for a single element of type T in + // device memory. + template + DeviceMemory AllocateScalar() { + return AllocateArray(1); + } + + // As AllocateScalar(), but returns a ScopedDeviceMemory. + template + ScopedDeviceMemory AllocateOwnedScalar() { + return AllocateOwnedArray(1); + } + + // Allocate a memory region inside another allocated memory region. + // Offset and size are specified in terms of T elements. + // Warning: Do not free a parent buffer before its sub-buffers; this may cause + // use-after-free issues (the specific behavior is not consistent across + // platforms). + // - Note: OpenCL uses refcounting to manage buffer lifetimes, so use of a + // sub-buffer after parent deallocation is expected to be safe. This will + // render your code non-platform-portable, however. + template + DeviceMemory GetSubBuffer(DeviceMemory* parent, uint64_t element_offset, + uint64_t element_count); + + // An untyped version of GetSymbol. + tsl::StatusOr GetUntypedSymbol( + const std::string& symbol_name, ModuleHandle module_handle); + + // Deallocate the DeviceMemory previously allocated via this interface. + // Deallocation of a nullptr-representative value is permitted. + // + // Resets the internal contents of mem to be null-representative, but this + // null-out effect should not be relied upon in client code. + void Deallocate(DeviceMemoryBase* mem); + + // Allocates unified memory space of the given size, if supported. + // See + // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#um-unified-memory-programming-hd + // for more details on unified memory. + void* UnifiedMemoryAllocate(uint64_t bytes); + + // Deallocates unified memory space previously allocated with + // UnifiedMemoryAllocate. + void UnifiedMemoryDeallocate(void* location); + + // Allocates a region of host memory and registers it with the platform API. + // Memory allocated in this manner (or allocated and registered with + // HostMemoryRegister() is required for use in asynchronous memcpy operations, + // such as Stream::ThenMemcpy. + void* HostMemoryAllocate(uint64_t size); + + // Deallocates a region of host memory allocated by HostMemoryAllocate(). + void HostMemoryDeallocate(void* location); + + // Synchronizes all activity occurring in the StreamExecutor's context (most + // likely a whole device). + bool SynchronizeAllActivity() ABSL_MUST_USE_RESULT; + + // Blocks the caller while "size" bytes are zeroed out (in POD fashion) at the + // given location in device memory. + tsl::Status SynchronousMemZero(DeviceMemoryBase* location, + uint64_t size) ABSL_MUST_USE_RESULT; + + // Same as SynchronousMemcpy(DeviceMemoryBase*, ...) above. + tsl::Status SynchronousMemcpyH2D(const void* host_src, int64_t size, + DeviceMemoryBase* device_dst); + + // Alternative interface for memcpying from host to device that takes an + // array slice. Checks that the destination size can accommodate the host + // slice size. + template + tsl::Status SynchronousMemcpyH2D(absl::Span host_src, + DeviceMemoryBase* device_dst) { + auto host_size = host_src.size() * sizeof(T); + CHECK(device_dst->size() == 0 || device_dst->size() >= host_size); + return SynchronousMemcpyH2D(host_src.begin(), host_size, device_dst); + } + + // Same as SynchronousMemcpy(void*, ...) above. + tsl::Status SynchronousMemcpyD2H(const DeviceMemoryBase& device_src, + int64_t size, void* host_dst); + + // Blocks the caller while a data segment of the given size is copied from the + // device source to the device destination. + bool SynchronousMemcpy(DeviceMemoryBase* device_dst, + const DeviceMemoryBase& device_src, + uint64_t size) ABSL_MUST_USE_RESULT; + + // Enqueues an operation onto stream to zero out size bytes at the given + // device memory location. Neither stream nor location may be null. Returns + // whether the operation was successfully enqueued onto the stream. + tsl::Status MemZero(Stream* stream, DeviceMemoryBase* location, + uint64_t size) ABSL_MUST_USE_RESULT; + + // Enqueues an operation onto stream to set 32-bit patterns starting at + // location, for byte count given by size. size must be 32-bit quantified + // (i.e. evently divisible by 4). Returns whether the operation was + // successfully enqueued onto the stream. + tsl::Status Memset32(Stream* stream, DeviceMemoryBase* location, + uint32_t pattern, uint64_t size); + + // Enables peer access from this StreamExecutor to memory + // allocated by other, such that launched device code, memcpies, etc may + // access it directly. + // + // Both this StreamExecutor and other must be backed by the same platform (as + // in + // CUDA vs OpenCL) implementation. + tsl::Status EnablePeerAccessTo(StreamExecutor* other); + + // Returns whether it's possible to enable peer access from this + // StreamExecutor + // to memory allocated by another. + // + // Even when this returns true, EnablePeerAccessTo may fail for other reasons; + // this is more an up-front test as to whether it's expressly forbidden. + bool CanEnablePeerAccessTo(StreamExecutor* other); + + // Obtains metadata about the underlying device. + // The value is cached on first use. + const DeviceDescription& GetDeviceDescription() const; + + // If implemented, returns device specific measurement of load + // (e.g. pending requests). + int64_t GetDeviceLoad() const; + + // Returns the underlying device memory usage information, if it is available. + // If it is not available (false is returned), free/total may not be + // initialized. + // + // Note: "Free" reflects the amount of free memory on the underlying device, + // so allocations via other StreamExecutors that have the same underlying + // device + // will be reflected in "free". + bool DeviceMemoryUsage(int64_t* free, int64_t* total) const; + + // Returns the supported algorithms / execution plans for a convolution. + tsl::Status GetConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, ScratchAllocator* scratch_allocator, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + tsl::Status GetGraphConvolveRunners( + dnn::ConvolutionKind kind, dnn::DataType input_type, + dnn::DataType output_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, const NumericOptions& numeric_options, + std::vector>* out_exec_plans, + std::string serialized_graph); + + tsl::Status GetFusedConvolveRunners( + bool use_cudnn_frontend, dnn::ConvolutionKind kind, + dnn::DataType input_type, dnn::DataType bias_type, + dnn::DataType output_type, double conv_input_scale, + double side_input_scale, double leakyrelu_alpha, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, + const dnn::FilterDescriptor& filter_descriptor, + const dnn::BatchDescriptor& bias_descriptor, + const dnn::BatchDescriptor& output_descriptor, + const dnn::ConvolutionDescriptor& convolution_descriptor, + bool use_fallback, dnn::ActivationMode activation_mode, + const NumericOptions& numeric_options, + std::vector>* out_exec_plans); + + tsl::Status GetFusedMatmulRunners( + bool use_cudnn_frontend, dnn::DataType input_type, + dnn::DataType bias_type, dnn::DataType output_type, Stream* stream, + bool trans_a, bool trans_b, uint64_t m, uint64_t n, uint64_t k, + int64_t lda, int64_t ldb, int64_t ldc, + dnn::ActivationMode activation_mode, bool use_fallback, + const NumericOptions& numeric_options, + std::vector>* + out_exec_plans); + + // Returns the list of supported algorithms for the forward convolution + // operation. + bool GetMIOpenConvolveAlgorithms( + dnn::ConvolutionKind kind, dnn::DataType element_type, Stream* stream, + const dnn::BatchDescriptor& input_descriptor, DeviceMemoryBase input_data, + const dnn::FilterDescriptor& filter_descriptor, + DeviceMemoryBase filter_data, + const dnn::BatchDescriptor& output_descriptor, + DeviceMemoryBase output_data, + const dnn::ConvolutionDescriptor& convolution_descriptor, + ScratchAllocator* scratch_allocator, + std::vector* out_algorithms); + + // Returns the list of supported algorithms for rnn operation. + bool GetRnnAlgorithms(std::vector* out_algorithms); + + // Get the list of supported algorithms for BLAS gemm. + bool GetBlasGemmAlgorithms(Stream* stream, + std::vector* out_algorithms); + + // Create an RNN descriptor based on model shapes and configurations. + // The caller retains the ownership of the descriptor. + tsl::StatusOr> createRnnDescriptor( + int num_layers, int hidden_size, int input_size, int cell_size, + int batch_size, dnn::RnnInputMode input_mode, + dnn::RnnDirectionMode direction_mode, dnn::RnnMode rnn_mode, + dnn::DataType data_type, const dnn::AlgorithmConfig& algorithm_config, + const NumericOptions& numeric_options, float dropout, uint64_t seed, + ScratchAllocator* state_allocator, bool use_padded_io); + + // Create a RNN sequence descriptor that specifies either the input or output + // sequence. The caller retains the ownership of the returned descriptor. + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, dnn::DataType data_type); + + tsl::StatusOr> + createRnnSequenceTensorDescriptor(int max_seq_length, int batch_size, + int data_size, + const absl::Span& seq_lengths, + bool time_major, dnn::DataType data_type); + + // Create an RNN state descriptor that specifies the input or hidden state. + // The caller retains the ownership of the returned descriptor. + tsl::StatusOr> + createRnnStateTensorDescriptor(int num_layer, int batch_size, int data_size, + dnn::DataType data_type); + + // Returns the device ordinal that this StreamExecutor was initialized with. + // Meaningless before initialization. + int device_ordinal() const { return device_ordinal_; } + + // Returns a borrowed pointer to the underlying StreamExecutor implementation. + internal::StreamExecutorInterface* implementation(); + + // Creates a kernel which can be launched with stream.ThenLaunch, such that + // the types of the arguments provided for launch would have to match + // types of the arguments provided at creation time. + // + // The kernel has a name kernel_name, and is based from provided PTX in ptx, + // and (optional) compiled PTX in cubin_data. + // The canonical storage for both ptx and cubin_data should outlive the + // lifetime of the kernel. + template + tsl::StatusOr>> CreateTypedKernel( + absl::string_view kernel_name, absl::string_view ptx, + absl::Span cubin_data); + + // Warning: use Stream::ThenLaunch instead, this method is not for general + // consumption. However, this is the only way to launch a kernel for which + // the type signature is only known at runtime; say, if an application + // supports loading/launching kernels with arbitrary type signatures. + // In this case, the application is expected to know how to do parameter + // packing that obeys the contract of the underlying platform implementation. + // + // Launches a data parallel kernel with the given thread/block + // dimensionality and already-packed args/sizes to pass to the underlying + // platform driver. + // + // This is called by Stream::Launch() to delegate to the platform's launch + // implementation in StreamExecutorInterface::Launch(). + tsl::Status Launch(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, const KernelBase& kernel, + const KernelArgsArrayBase& args); + + // Submits command buffer for execution to the underlying platform driver. + tsl::Status Submit(Stream* stream, const CommandBuffer& command_buffer); + + // Gets-or-creates (creates with memoization) a FftSupport datatype that can + // be used to execute FFT routines on the current platform. + // + // Ownership and user-facing is the same as AsBlas() below. + // + // Returns null if there was an error initializing the FFT support for the + // underlying platform. + fft::FftSupport* AsFft(); + + // Gets-or-creates (creates with memoization) a DnnSupport datatype that can + // be used for neural network routines on the current platform. + // + // Ownership and user-facing is the same as AsBlas() below. + // + // Returns null if there was an error initializing the DNN support for the + // underlying platform. + dnn::DnnSupport* AsDnn(); + + // Gets-or-creates (creates with memoization) a BlasSupport datatype that can + // be used to execute BLAS routines on the current platform. This is typically + // not user-facing, as users will use the Stream::ThenBlas* family of routines + // to entrain BLAS operations. See blas.h for additional details. + // + // Ownership is not transferred to the caller -- ownership is retained by this + // object for memoization. This BLAS interface is also only expected to be + // used by a Stream for entraining calls to BLAS functionality. + // + // Returns null if there was an error initializing the BLAS support for the + // underlying platform. + blas::BlasSupport* AsBlas(); + + // Registers a trace listener to receive callbacks for only a single + // StreamExecutor instance. + // To register a listener for all executors for a given platform, see + // Platform::RegisterTraceListener(). + // Does not take ownership of listener. + void RegisterTraceListener(TraceListener* listener); + + // Removes a TraceListener from this StreamExecutor instance. + // Returns false (and logs) in cases where the argument listener was not + // previously registered. + bool UnregisterTraceListener(TraceListener* listener); + + // Return allocator statistics. + std::optional GetAllocatorStats(); + + // Clears the internal stats except for the `in_use` fields + // and sets the `peak_bytes_in_use` to be equal to the `bytes_in_use`. + bool ClearAllocatorStats(); + + // Return an allocator which delegates to this stream executor for memory + // allocation. + StreamExecutorMemoryAllocator* GetAllocator() { return &allocator_; } + + // Returns a stream allocated by this executor, or nullptr if not found. + // Performs linear search over alive GPU streams. + Stream* FindAllocatedStream(void* gpu_stream); + + private: + template + friend class ScopedTracer; + friend class Event; + friend class Stream; + template + friend class TypedKernel; + template + friend struct ThenBlasImpl; + + // Synchronously allocates size bytes on the underlying platform and returns + // a DeviceMemoryBase representing that allocation. In the case of failure, + // nullptr is returned. + DeviceMemoryBase Allocate(uint64_t size, int64_t memory_space); + + void* GetUntypedSubBuffer(DeviceMemoryBase* parent, uint64_t offset, + uint64_t size); + + // Causes the host code to synchronously wait for operations entrained + // onto stream to complete. Effectively a join on the asynchronous device + // operations enqueued on the stream before this program point. + tsl::Status BlockHostUntilDone(Stream* stream); + + // Without blocking the device, retrieve the current stream status. + tsl::Status GetStatus(Stream* stream); + + // Finds and retrieves device memory for the symbol on the underlying + // platform. + bool GetSymbol(const std::string& symbol_name, ModuleHandle module_handle, + void** mem, size_t* bytes); + + // Entrains a memcpy operation onto stream, with a host destination location + // host_dst and a device memory source, with target size size. + bool Memcpy(Stream* stream, void* host_dst, + const DeviceMemoryBase& device_src, uint64_t size); + + // Entrains a memcpy operation onto stream, with a device destination location + // and a host memory source, with target size size. + bool Memcpy(Stream* stream, DeviceMemoryBase* device_dst, + const void* host_src, uint64_t size); + + // Entrains a memcpy operation onto stream, with a device destination location + // and a device source location, with target size size. Peer access should + // have been enabled between the StreamExecutors owning the device memory + // regions. + bool MemcpyDeviceToDevice(Stream* stream, DeviceMemoryBase* device_dst, + const DeviceMemoryBase& device_src, uint64_t size); + + // Entrains on a stream a user-specified function to be run on the host. + // See Stream::ThenDoHostCallback for full details. + // This is the preferred form for a callback that may return an error. + bool HostCallback(Stream* stream, + absl::AnyInvocable callback); + + // Performs platform-specific allocation and initialization of an event. + tsl::Status AllocateEvent(Event* event); + + // Performs platform-specific deallocation and cleanup of an event. + tsl::Status DeallocateEvent(Event* event); + + // Inserts the specified event at the end of the specified stream. + tsl::Status RecordEvent(Stream* stream, Event* event); + + // Wait for the specified event at the end of the specified stream. + tsl::Status WaitForEvent(Stream* stream, Event* event); + + // Wait for the specified event at the end of the raw platform-specific + // stream. Currently only implemented for GPU, where stream is a + // GpuStreamHandle (e.g. cudaStream_t). + tsl::Status WaitForEventOnExternalStream(std::intptr_t stream, Event* event); + + // Requests the current status of the event from the underlying platform. + Event::Status PollForEventStatus(Event* event); + + // Allocates stream resources on the underlying platform and initializes its + // internals. + bool AllocateStream(Stream* stream); + + // Deallocates stream resources on the underlying platform. + void DeallocateStream(Stream* stream); + + // Causes dependent to not begin execution until other has finished its + // last-enqueued work. + bool CreateStreamDependency(Stream* dependent, Stream* other); + + // Allocates a new metadata object, appropriately populated, on the heap, with + // ownership transfer to caller. + std::unique_ptr CreateDeviceDescription() const; + + // Adds a task to the tsl::thread::ThreadPool work queue. These tasks must be + // fire-and-forget and have no external data or timing dependencies; their + // execution order and completion time have no guarantees. + // For an example of an appropriate task, see HostBlas::DoBlasGemmInternal; + // there, temporary internal buffers are freed using this method. + void EnqueueOnBackgroundThread(std::function task); + + // Calls the relevant TraceListener routine to begin tracing for the specified + // asynchronous method. + template + void SubmitTrace(TraceCallT trace_call, ArgsT&&... args); + + // Reader/writer lock for class-static StreamExecutor members. + static absl::Mutex static_mu_; + + // Reader/writer lock for mutable data structures on this StreamExecutor. + // + // Mutable so that caching functions (like DeviceDescription, AsBlas, etc.) + // can acquire the lock on their first (mutating) call as well. + mutable absl::Mutex mu_; + + // Reference to the platform that created this executor. + const Platform* platform_; + + // Pointer to the platform-specific-interface implementation. This is + // delegated to by the interface routines in pointer-to-implementation + // fashion. + std::unique_ptr implementation_; + + // Memoized BLAS support object -- we only want to create this once when asked + // for a BLAS interface. + std::unique_ptr blas_ ABSL_GUARDED_BY(mu_); + + // Memoized DNN support object -- we only want to create this once when asked + // for an DNN interface. + std::unique_ptr dnn_ ABSL_GUARDED_BY(mu_); + + // Memoized FFT support object -- we only want to create this once when asked + // for a FFT interface. + std::unique_ptr fft_; + + // Slot to cache the owned DeviceDescription for the underlying device + // once it has been queried from DeviceDescription(). + mutable std::unique_ptr device_description_ + ABSL_GUARDED_BY(mu_); + + // The device ordinal that this object was initialized with. + // + // Immutable post-initialization. + int device_ordinal_; + + // Executor for handling host callback work that cannot be performed + // by a host callback thread - for example, cleanup after a host BLAS routine + // (which may make device API calls). This work cannot block the host + // callback thread, will be completed asynchronously, and should be treated + // as fire-and-forget. Assume no ordering guarantees WRT the tasks enqueued + // here. + // + // Immutable post-initialization. Object is thread-safe. + std::unique_ptr background_threads_; + + // Counter for the current number of live streams. This is used to check + // for accidentally-outstanding streams at StreamExecutor teardown time, as + // well + // as to indicate leaks (via a large outstanding count being logged) in the + // case we can't allocate more streams. + std::atomic_int_fast32_t live_stream_count_; + + // Only one worker thread is needed; little work will be done by the + // executor. + static constexpr int kNumBackgroundThreads = 1; + + // Indicates if StreamExecutor operation tracing should be performed. + bool tracing_enabled_; + + // The set of TraceListeners registered for this StreamExecutor. + std::set listeners_ ABSL_GUARDED_BY(mu_); + + // Memory limit in bytes. Value less or equal to 0 indicates there is no + // limit. + int64_t memory_limit_bytes_; + + StreamExecutorMemoryAllocator allocator_; + + StreamExecutor(const StreamExecutor&) = delete; + void operator=(const StreamExecutor&) = delete; +}; + +// A wrapper around ModuleHandle that uses RAII to manage its lifetime. +class ScopedModuleHandle { + public: + explicit ScopedModuleHandle(StreamExecutor* executor, + ModuleHandle module_handle) + : executor_(executor), module_handle_(module_handle) {} + + ScopedModuleHandle(ScopedModuleHandle&& other) { + executor_ = other.executor_; + module_handle_ = other.module_handle_; + other.executor_ = nullptr; + other.module_handle_ = ModuleHandle(); + } + + ScopedModuleHandle& operator=(ScopedModuleHandle&& other) { + executor_ = other.executor_; + module_handle_ = other.module_handle_; + other.executor_ = nullptr; + other.module_handle_ = ModuleHandle(); + return *this; + } + + ~ScopedModuleHandle() { + if (static_cast(module_handle_)) { + CHECK(executor_->UnloadModule(module_handle_)); + } + } + + private: + StreamExecutor* executor_; + ModuleHandle module_handle_; + + ScopedModuleHandle(const ScopedModuleHandle&) = delete; + void operator=(const ScopedModuleHandle&) = delete; +}; + +//////////// +// Inlines + +template +inline tsl::StatusOr>> +StreamExecutor::CreateTypedKernel(absl::string_view kernel_name, + absl::string_view ptx, + absl::Span cubin_data) { + auto kernel_base = std::make_unique>(this); + MultiKernelLoaderSpec loader_spec(kernel_base->kNumberOfParameters); + loader_spec.AddCudaPtxInMemory(ptx, kernel_name); + + if (!cubin_data.empty()) { + loader_spec.AddCudaCubinInMemory( + reinterpret_cast(cubin_data.data()), kernel_name); + } + + TF_RETURN_IF_ERROR(GetKernel(loader_spec, kernel_base.get())); + return std::move(kernel_base); +} + +template +inline DeviceMemory StreamExecutor::AllocateArray(uint64_t element_count, + int64_t memory_space) { + uint64_t bytes = sizeof(T) * element_count; + return DeviceMemory(Allocate(bytes, memory_space)); +} + +template +ScopedDeviceMemory::ScopedDeviceMemory(StreamExecutor* parent, + DeviceMemoryBase value) + : wrapped_(value), + device_ordinal_(parent->device_ordinal()), + allocator_(parent->GetAllocator()) {} + +template +ScopedDeviceMemory::ScopedDeviceMemory( + StreamExecutor* parent, std::initializer_list values) + : ScopedDeviceMemory(parent, parent->AllocateArray(values.size())) { + if (ptr() != nullptr) { + std::vector local(values); + if (!parent->SynchronousMemcpy(ptr(), const_cast(&local[0]), + ptr()->size())) { + TF_CHECK_OK(Free()); + } + } +} + +template +DeviceMemory StreamExecutor::GetSubBuffer(DeviceMemory* parent, + uint64_t element_offset, + uint64_t element_count) { + if (element_offset + element_count > parent->ElementCount()) { + LOG(ERROR) << "requested sub-buffer allocation (offset + size) is greater " + << "than parent allocation size: (" << element_offset << " + " + << element_count << ") vs. (" << parent->ElementCount() << ")"; + return DeviceMemory{}; + } + + void* opaque = GetUntypedSubBuffer(parent, sizeof(T) * element_offset, + sizeof(T) * element_count); + if (opaque == nullptr) { + return DeviceMemory{}; + } + return DeviceMemory(DeviceMemoryBase(opaque, sizeof(T) * element_count)); +} + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_STREAM_EXECUTOR_PIMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_device_memory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_device_memory.h new file mode 100644 index 0000000000000000000000000000000000000000..b12fd2efceb2c49809511d7a632fbc519bcee2a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_device_memory.h @@ -0,0 +1,136 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Temporary memories are used to allocate scratch space required by an +// operation about to be enqueued onto a stream. +// +// std::unique_ptr> temporary_memory = +// stream.AllocateTemporaryArray(1024).value(); +// // ... enqueue stuff onto the stream using the temporary memory ... +// // Note that the memory is accessible via +// // temporary_memory->device_memory() and similar. +// +// // Finalize the temporary memory. The underlying device memory may +// // be released any time after this program point, as another thread may +// // call Stream::BlockHostUntilDone, causing synchronization. This +// // finalization also happens automatically for the user if the unique_ptr +// // goes out of scope. +// temporary_memory.Finalize(); +// +// WARNING: do NOT hold onto the device memory associated with temporary_memory +// after finalization. If temporary_memory->device_memory() is used after the +// temporary memory is finalized, it will cause a DCHECK failure. +// +// Note that standard usage takes advantage of the type-safe wrapper, +// TemporaryDeviceMemory, defined below. +// +// Also see tests for executable sample usage. + +#ifndef XLA_STREAM_EXECUTOR_TEMPORARY_DEVICE_MEMORY_H_ +#define XLA_STREAM_EXECUTOR_TEMPORARY_DEVICE_MEMORY_H_ + +#include "xla/stream_executor/device_memory.h" + +namespace stream_executor { + +class Stream; +namespace internal { +class TemporaryMemoryManager; +} + +// Untyped base class (analogous to a void*) for temporary device memory +// allocations associated with a stream. +class TemporaryDeviceMemoryBase { + public: + // Marks the temporary memory as finalized if it is not already marked as + // such. + ~TemporaryDeviceMemoryBase(); + + // Precondition: !IsFinalized() + DeviceMemoryBase* mutable_device_memory(); + + // Precondition: !IsFinalized() + const DeviceMemoryBase& device_memory() const; + + // "Finalizes" this temporary memory, making it acceptable to release at the + // next stream synchronization point -- the device memory can be reclaimed at + // any time after the temporary memory is marked as finalized (e.g. if a + // separate thread is calls Stream::BlockHostUntilDone). This may only be + // called once -- see the precondition below. + // + // Precondition: !IsFinalized() + void Finalize(); + + // Returns true iff the temporary memory is finalized (that is, the user is + // done referring to the temporary device memory, and thus it can be released + // at the next stream synchronization point). + bool IsFinalized() const; + + // Returns true iff the temporary memory is still allocated. + // + // Note: this is a polling call, no guarantee is made that the temporary + // memory is still allocated after the call has completed. + bool IsAllocated() const; + + private: + friend class internal::TemporaryMemoryManager; + friend class TemporaryDeviceMemoryTest; + + // Note: construction DCHECKs that the memory is known-allocated in the + // stream's temporary-allocation-manager. + TemporaryDeviceMemoryBase(Stream* parent, DeviceMemoryBase device_memory, + uint64_t allocation_generation); + + // The device memory region that has allocated. + DeviceMemoryBase device_memory_; + + // The generation counter value for the temporary memory record in the + // temporary memory manager. + uint64_t allocation_generation_; + + // The stream that this temporary memory was allocated for. + Stream* parent_; +}; + +// Type-safe wrapper around the base type (which is analogous to a void*). +template +class TemporaryDeviceMemory : public TemporaryDeviceMemoryBase { + public: + // Type-safe wrapper around TemporaryDeviceMemoryBase::mutable_device_memory. + DeviceMemory* mutable_device_memory() { + StaticSlicingAssertionDummy(); + return reinterpret_cast*>( + TemporaryDeviceMemoryBase::mutable_device_memory()); + } + + // Type-safe wrapper around TemporaryDeviceMemoryBase::device_memory. + const DeviceMemory& device_memory() const { + StaticSlicingAssertionDummy(); + return reinterpret_cast&>( + TemporaryDeviceMemoryBase::device_memory()); + } + + private: + static void StaticSlicingAssertionDummy() { + static_assert( + sizeof(TemporaryDeviceMemory) == sizeof(TemporaryDeviceMemoryBase), + "derived class is simply a wrapper, no members may be added due to " + "slicing"); + } +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TEMPORARY_DEVICE_MEMORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_memory_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_memory_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..6a82fe0667235a5b3da7fc4a8624fa3e11d96066 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/temporary_memory_manager.h @@ -0,0 +1,153 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// The temporary-memory-manager is a helper class for a Stream to keep track of +// temporary allocations. These allocations defer their deallocation to the next +// Stream::BlockHostUntilDone call for efficiency purposes (as deallocation +// itself generally forces synchronization to occur). + +#ifndef XLA_STREAM_EXECUTOR_TEMPORARY_MEMORY_MANAGER_H_ +#define XLA_STREAM_EXECUTOR_TEMPORARY_MEMORY_MANAGER_H_ + +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/synchronization/mutex.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/temporary_device_memory.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { +namespace internal { + +// Record used inside the TemporaryMemoryManager as metadata for a given device +// memory region. +struct TemporaryMemoryRecord { + // What "generation" this record was allocated in. + // + // Currently the generation counter is bumped for every allocation, but this + // could be made coarser if necessary. + uint64_t allocation_generation; + + // Notes whether the temporary memory has been marked as finalized, such that + // we can release the DeviceMemory associated with this record at + // synchronization time. + bool finalized; +}; + +// Manages temporary memories associated with a stream -- keeps records of +// outstanding temporaries and their state, and can deallocate them +// appropriately at points in the Stream lifecycle (e.g. BlockHostUntilDone, +// destruction). +class TemporaryMemoryManager { + public: + explicit TemporaryMemoryManager(Stream* stream) : stream_(stream) {} + + // Allocates a temporary array that is then managed by this object. + template + tsl::StatusOr>> AllocateArray( + uint64_t element_count); + + // Forces deallocation of all managed temporary memory regions. + // + // Called, for example, when the Stream owning this temporary memory manager + // is destroyed. + // + // Note: These calls to Deallocate will likely force synchronization. + void ForceDeallocateAll(); + + // Marks the given memory region as finalized. + // + // If must_exist is set, this will check-fail if the temporary memory record + // is not found. + void MarkFinalized(const DeviceMemoryBase& device_memory, uint64_t generation, + bool must_exist); + + // Deallocates temporary memories that have been finalized. + // + // Note: These calls to Deallocate will likely force synchronization, so it is + // meant to be called before a "BlockHostUntilDone" is about to be performed. + void DeallocateFinalizedTemporaries(); + + // Returns whether the provided device_memory is finalized. + // + // In the vacuous case where the device memory doesn't appear in the temporary + // memory records, it is either not a temporary at all, or has already been + // deallocated, and thus returns true. + bool IsFinalized(const DeviceMemoryBase& device_memory, + uint64_t allocation_generation) const; + + // Returns whether the manager has a live allocation record for the given + // device memory pointer with the given generation counter. + // + // Note: this is a polling call -- there is no guarantee that the region is + // still allocated once the call has completed. + bool HasAllocated(const DeviceMemoryBase& device_memory, + uint64_t generation) const; + + private: + // Allocates an array without type parameterization, so that the + // implementation can live in the source file. Without this base allocation + // method, we incur a circular dependency between the StreamExecutor + // definition and this class' definition. + tsl::StatusOr> AllocateArrayBase( + uint64_t element_count, uint64 element_size); + + // Mutex to guard temporary record state. + mutable absl::Mutex mutex_; + + // Mapping from device memory to the current (live) temporary memory record. + // + // If a device memory is not in this mapping, it is not a temporary currently + // allocated and owned by this temporary memory manager. + std::map records_ + ABSL_GUARDED_BY(mutex_); + + // Allocation generation -- we bump this counter to distinguish temporary + // memory handles that have been deallocated and later reallocated at the same + // device memory address. + uint64_t generation_ ABSL_GUARDED_BY(mutex_); + + // The stream (parent object) for this temporary memory manager -- allocations + // are performed through this stream handle. + Stream* stream_; + + TemporaryMemoryManager(const TemporaryMemoryManager&) = delete; + void operator=(const TemporaryMemoryManager&) = delete; +}; + +//////////// +// Inlines + +template +tsl::StatusOr>> +TemporaryMemoryManager::AllocateArray(uint64_t element_count) { + tsl::StatusOr> temporary_memory = + AllocateArrayBase(element_count, sizeof(T)); + if (!temporary_memory.ok()) { + return temporary_memory.status(); + } + + return std::unique_ptr>( + reinterpret_cast*>(temporary_memory->release())); +} + +} // namespace internal +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TEMPORARY_MEMORY_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tf_allocator_adapter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tf_allocator_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..5293e4639dc82de48a8d730cd051c984ebb81242 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tf_allocator_adapter.h @@ -0,0 +1,156 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TF_ALLOCATOR_ADAPTER_H_ +#define XLA_STREAM_EXECUTOR_TF_ALLOCATOR_ADAPTER_H_ + +#include +#include +#include +#include + +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/stream.h" +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/platform/statusor.h" + +namespace stream_executor { + +// Adapter class that wraps a Tensorflow allocator. +// +// Assumes that the Tensorflow allocator permits asynchronous deallocation: +// see comment on `AllowsAsynchronousDeallocation()`. +class TfAllocatorAdapter : public DeviceMemoryAllocator { + public: + // stream: a Stream on which the allocator can only be used. If non-null, the + // allocator can not be used on any other stream. + TfAllocatorAdapter(tsl::Allocator *wrapped, Stream *stream); + + // Constructor for the cases where `stream` can not be provided. + TfAllocatorAdapter(tsl::Allocator *wrapped, Platform *platform); + + ~TfAllocatorAdapter() override; + + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure, + int64_t memory_space) override; + + tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) override; + + // The Tensorflow BFC allocator used on GPU allows host-side deallocation + // before GPU execution takes place. Tensorflow uses the ordering of the main + // compute stream to enforce a happens-before relationship between a memory + // allocation and code that reuses the same memory. If Tensorflow adds + // support for multiple GPU streams or allocators with different ordering + // requirements, this code may need to change. + // (This attribute has no effect on CPU.) + bool AllowsAsynchronousDeallocation() const override { return true; } + + tsl::StatusOr GetStream(int device_ordinal) override; + + tsl::StatusOr GetAllocator(int device_ordinal); + + private: + tsl::Allocator *wrapped_; + Stream *stream_; +}; + +// Adapter class that wraps per-device TF allocators with corresponding streams +// as a TfAllocatorAdapter. Assumes that the Tensorflow allocator permits +// asynchronous deallocation; see comment on `AllowsAsynchronousDeallocation()`. +class MultiDeviceAdapter : public DeviceMemoryAllocator { + public: + using AllocatorWithStream = + std::pair, Stream *>; + using AllocatorWithLogicalIdAndStream = + std::tuple, int, Stream *>; + + MultiDeviceAdapter(const Platform *platform, + std::vector tf_allocators) + : DeviceMemoryAllocator(platform) { + tf_allocators_.reserve(tf_allocators.size()); + for (AllocatorWithStream &p : tf_allocators) { + int device_ordinal = p.second->parent()->device_ordinal(); + if (per_device_allocators_.size() <= device_ordinal) { + per_device_allocators_.resize(device_ordinal + 1); + } + CHECK(!per_device_allocators_[device_ordinal]); + per_device_allocators_[device_ordinal] = + std::make_unique(p.first.get(), p.second); + tf_allocators_.push_back(std::move(p.first)); + } + } + + MultiDeviceAdapter(const Platform *platform, + std::vector tf_allocators) + : DeviceMemoryAllocator(platform) { + tf_allocators_.reserve(tf_allocators.size()); + for (AllocatorWithLogicalIdAndStream &t : tf_allocators) { + const int device_ordinal = std::get<1>(t); + Stream *stream = std::get<2>(t); + if (per_device_allocators_.size() <= device_ordinal) { + per_device_allocators_.resize(device_ordinal + 1); + } + CHECK(!per_device_allocators_[device_ordinal]); + per_device_allocators_[device_ordinal] = + std::make_unique(std::get<0>(t).get(), stream); + tf_allocators_.push_back(std::move(std::get<0>(t))); + } + } + + tsl::StatusOr Allocate(int device_ordinal, uint64_t size, + bool retry_on_failure, + int64_t memory_space) override { + CHECK_LT(device_ordinal, per_device_allocators_.size()); + return per_device_allocators_[device_ordinal]->Allocate( + device_ordinal, size, retry_on_failure, memory_space); + } + + tsl::Status Deallocate(int device_ordinal, DeviceMemoryBase mem) override { + CHECK_LT(device_ordinal, per_device_allocators_.size()); + return per_device_allocators_[device_ordinal]->Deallocate(device_ordinal, + mem); + } + + // The Tensorflow BFC allocator used on GPU allows host-side deallocation + // before GPU execution takes place. Tensorflow uses the ordering of the main + // compute stream to enforce a happens-before relationship between a memory + // allocation and code that reuses the same memory. If Tensorflow adds + // support for multiple GPU streams or allocators with different ordering + // requirements, this code may need to change. + // (This attribute has no effect on CPU.) + bool AllowsAsynchronousDeallocation() const override { return true; } + + tsl::StatusOr GetStream(int device_ordinal) override { + return per_device_allocators_[device_ordinal]->GetStream(device_ordinal); + } + + tsl::StatusOr GetAllocator(int device_ordinal) { + return per_device_allocators_[device_ordinal]->GetAllocator(device_ordinal); + } + + private: + std::vector> per_device_allocators_; + // The wrapped TF allocators backing per_device_allocators_ + // (TfAllocatorAdapter does not take ownership of its underlying Allocator). + std::vector> tf_allocators_; +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TF_ALLOCATOR_ADAPTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_conversions.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_conversions.h new file mode 100644 index 0000000000000000000000000000000000000000..47b9f99551dcd24315bef12fee9a2655fcf722bb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_conversions.h @@ -0,0 +1,161 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_C_API_CONVERSIONS_H_ +#define XLA_STREAM_EXECUTOR_TPU_C_API_CONVERSIONS_H_ + +#include +#include +#include + +#include "xla/executable_run_options.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/literal.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/maybe_owning_device_memory.h" +#include "xla/service/shaped_buffer.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/tpu/c_api_decl.h" + +// APIs for converting between internal and external versions of +// XLA/StreamExecutor data structures. +namespace ApiConverter { + +absl::Span MakeSpan(const FloatList& src_list); +void CreateVector(absl::Span src, FloatList* dst); +void Destroy(FloatList* float_list); + +absl::Span MakeSpan(const Int64List& src_list); +void CreateVector(absl::Span src, Int64List* dst); + +absl::Span MakeSpan(const IntList& src_list); +void CreateVector(absl::Span src, IntList* dst); + +absl::Span MakeSpan(const BoolList& src_list); +void CreateVector(absl::Span src, BoolList* dst); + +void CreateVector(absl::Span src, IntList* dst); + +// se::DeviceMemoryBase +SE_DeviceMemoryBase ToC(const stream_executor::DeviceMemoryBase& base); +void ToC(const stream_executor::DeviceMemoryBase& base, + SE_DeviceMemoryBase* se_base); +stream_executor::DeviceMemoryBase FromC(const SE_DeviceMemoryBase& se_base); +void Destroy(SE_DeviceMemoryBase*); + +// xla::Tile +xla::Tile FromC(const XLA_Tile* c_tile); +void ToC(const xla::Tile& xla_tile, XLA_Tile* c_tile); +void Destroy(XLA_Tile* c_tile); + +// xla::Layout +xla::Layout FromC(const XLA_Layout* c_layout); +void ToC(const xla::Layout& xla_layout, XLA_Layout* c_layout); +void Destroy(XLA_Layout* c_layout); + +// xla::Shape +xla::Shape FromC(const XLA_Shape* c_shape); +void ToC(const xla::Shape& xla_shape, XLA_Shape* c_shape); +void Destroy(XLA_Shape* c_shape); + +// xla::ShapeIndex +XLA_ShapeIndex ToC(const xla::ShapeIndex& xla_shape); +xla::ShapeIndex FromC(XLA_ShapeIndex* c_shape); +void Destroy(XLA_ShapeIndex*); + +// Literal +void ToC(const xla::LiteralSlice& literal, XLA_Literal* c_literal); +xla::MutableBorrowingLiteral FromC(XLA_Literal* c_literal); +void Destroy(XLA_Literal* c_literal); + +// ShapedBuffer +void ToC(const xla::ShapedBuffer& buffer, XLA_ShapedBuffer* c_device_buffer); +xla::ShapedBuffer FromC(XLA_ShapedBuffer* c_buffer); +void Destroy(XLA_ShapedBuffer* c_buffer); + +// se::DeviceMemoryBase +SE_DeviceMemoryBase ToC(const stream_executor::DeviceMemoryBase& base); +stream_executor::DeviceMemoryBase FromC(const SE_DeviceMemoryBase& se_base); +void Destroy(SE_DeviceMemoryBase*); + +// Literal +void ToC(const xla::LiteralSlice& literal, XLA_Literal* c_literal); +xla::MutableBorrowingLiteral FromC(XLA_Literal* c_literal); +void Destroy(XLA_Literal* c_literal); + +// ShapedBuffer +void ToC(const xla::ShapedBuffer& buffer, XLA_ShapedBuffer* c_device_buffer); +xla::ShapedBuffer FromC(XLA_ShapedBuffer* c_buffer); +void Destroy(XLA_ShapedBuffer* c_buffer); + +// TpuEmbeddingEngineParametersData +struct TpuEmbeddingEngineParametersData { + // Backing vector for struct + std::array, 8> vectors; + TpuEmbeddingEngineParameters c_params; +}; + +std::unique_ptr Create(int num_tables); + +xla::MaybeOwningDeviceMemory FromC( + SE_MaybeOwningDeviceMemory* se_mem, + stream_executor::DeviceMemoryAllocator* allocator); + +// DeviceMemoryAllocator +SE_DeviceMemoryAllocator ToC(stream_executor::DeviceMemoryAllocator* allocator); + +// OwningDeviceMemory +SE_MaybeOwningDeviceMemory ToC(stream_executor::OwningDeviceMemory* mem); +// mem.HasOwnership() may be true if the buffer is aliased and shouldn't be +// released. 'aliased' should be true in this case. 'aliased' has no effect if +// 'mem' is unowned. +SE_MaybeOwningDeviceMemory ToC(xla::MaybeOwningDeviceMemory& mem, bool aliased); + +// HloModule +XLA_HloModule ToC(const xla::HloModule& module); +xla::StatusOr> FromC( + const XLA_HloModule& c_module); +void Destroy(XLA_HloModule* c_module); + +// HloModuleConfig +XLA_HloModuleConfig ToC(const xla::HloModuleConfig& config); +xla::HloModuleConfig FromC(const XLA_HloModuleConfig& c_config); +void Destroy(XLA_HloModuleConfig* c_config); + +// Helper for managing stack based C -> C++ conversions. +template +struct StackHelper { + explicit StackHelper() {} + + template + explicit StackHelper(const CppType& t) { + ::ApiConverter::ToC(t, &value); + } + ~StackHelper() { ::ApiConverter::Destroy(&value); } + + template + CppType AsCpp() const { + return ::ApiConverter::FromC(&value); + } + + mutable CType value; +}; + +} // namespace ApiConverter + +#endif // XLA_STREAM_EXECUTOR_TPU_C_API_CONVERSIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_decl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_decl.h new file mode 100644 index 0000000000000000000000000000000000000000..bbeb12472ea8b00490928e453830d1ddb1ad4350 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_decl.h @@ -0,0 +1,362 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_C_API_DECL_H_ +#define XLA_STREAM_EXECUTOR_TPU_C_API_DECL_H_ + +#include +#include + +#include "xla/stream_executor/tpu/libtftpu.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct TSL_Status TF_Status; + +// Maximum number of array elements to inline into structs for performance. +#define TPU_C_API_MAX_INLINED 6 + +typedef enum TpuCoreTypeEnum { + kTensorCore, + kEmbeddingV1, + kEmbeddingV2, +} TpuCoreTypeEnum; + +typedef enum TpuVersionEnum { + kUnknownTpuVersion, + kTpuV2, + kTpuV3, + kTpuV4, + // BEGIN-INTERNAL + // reserved for internal use + // END-INTERNAL +} TpuVersionEnum; + +typedef struct TpuRuntimeVersion { + // The three version numbers are: major, minor, patch + int version[3]; + const char* metadata; + size_t metadata_size; +} TpuRuntimeVersion; + +typedef struct SE_Platform SE_Platform; +typedef struct SE_StreamExecutor SE_StreamExecutor; +typedef struct SE_Stream SE_Stream; +typedef struct SE_Event SE_Event; + +typedef struct TpuSerializedProto { + const char* bytes; + size_t size; +} TpuSerializedProto; + +typedef struct SE_PlatformId { + void* id; // aka stream_executor::Platform::Id +} SE_PlatformId; +typedef struct SE_StreamExecutorConfig SE_StreamExecutorConfig; +typedef struct SE_DeviceOptions SE_DeviceOptions; +typedef TF_Status* (*SE_StatusCallback)(void*); + +typedef struct SE_DeviceMemoryBase { + void* opaque; + uint64_t size; + uint64_t payload; +} SE_DeviceMemoryBase; + +typedef struct SE_ScopedDeviceMemory { + SE_DeviceMemoryBase wrapped; + int device_ordinal; +} SE_ScopedDeviceMemory; + +typedef struct SE_AllocatorStats { + int64_t num_allocs; + int64_t bytes_in_use; + int64_t peak_bytes_in_use; + int64_t largest_alloc_size; + + bool has_bytes_limit; + int64_t bytes_limit; + + int64_t bytes_reserved; + int64_t peak_bytes_reserved; + + bool has_bytes_reservable_limit; + int64_t bytes_reservable_limit; + + int64_t largest_free_block_bytes; +} SE_AllocatorStats; + +// Note, due to the... odd way in which DeviceMemoryAllocator is used in TF, we +// cannot simply wrap an underlying pointer. Instead, we reverse the call +// direction and request memory via a callback. +typedef void (*SE_AllocateFn)(void* ctx, int device_ordinal, uint64_t size, + bool retry_on_failure, int64_t memory_space, + SE_ScopedDeviceMemory* result, TF_Status* status); + +typedef void (*SE_DeallocateFn)(void* ctx, SE_DeviceMemoryBase* base, + int device_ordinal, TF_Status* status); + +typedef struct SE_DeviceMemoryAllocator { + SE_Platform* platform; + void* ctx; + SE_AllocateFn allocate; + SE_DeallocateFn deallocate; +} SE_DeviceMemoryAllocator; + +typedef struct SE_DeviceDescription { + char* device_vendor; + char* platform_version; + char* driver_version; + char* runtime_version; + char* pci_bus_id; + char* name; + + int64_t thread_dim_limit_x; + int64_t thread_dim_limit_y; + int64_t thread_dim_limit_z; + int64_t block_dim_limit_x; + int64_t block_dim_limit_y; + int64_t block_dim_limit_z; + + int64_t threads_per_core_limit; + int64_t threads_per_block_limit; + int64_t threads_per_warp; + + int64_t registers_per_core_limit; + int64_t registers_per_block_limit; + + int64_t device_address_bits; + int64_t device_memory_size; + int64_t memory_bandwidth; + + int64_t shared_memory_per_core; + int64_t shared_memory_per_block; + + float clock_rate_ghz; + + int cuda_compute_capability_major; + int cuda_compute_capability_minor; + + int numa_node; + int core_count; + bool ecc_enabled; +} SE_DeviceDescription; + +typedef struct Tpu_Compiler Tpu_Compiler; +typedef struct SE_Executable SE_Executable; + +typedef struct SE_ExecutableRunOptions { + SE_DeviceMemoryAllocator allocator; + int device_ordinal; + SE_Stream* stream; + SE_Stream* host_to_device_stream; + TpuSerializedProto device_assignment; + int rng_seed; + int64_t run_id; + int launch_id; +} SE_ExecutableRunOptions; + +typedef struct SE_ExecutableSerializationHandle + SE_ExecutableSerializationHandle; + +typedef struct SE_MaybeOwningDeviceMemory { + SE_DeviceMemoryBase memory; + bool owned; + + // Set if owned + int device_ordinal; + SE_DeviceMemoryAllocator allocator; +} SE_MaybeOwningDeviceMemory; + +typedef struct IntList { + union { + int* heap; // owned + int inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} IntList; + +typedef struct Int64List { + union { + int64_t* heap; // owned + int64_t inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} Int64List; + +typedef struct FloatList { + union { + float* heap; // owned + float inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} FloatList; + +typedef struct BoolList { + union { + bool* heap; // owned + bool inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} BoolList; + +typedef struct FloatListRef { + float* ptr; // not owned + int64_t size; +} FloatListRef; + +typedef struct TpuEmbeddingEngineParameters { + FloatListRef** parameters[8]; + size_t num_tables; +} TpuEmbeddingEngineParameters; + +typedef struct XLA_Tile { + Int64List dimensions; +} XLA_Tile; + +typedef struct TileList { + union { + XLA_Tile* heap; // owned + XLA_Tile inlined[TPU_C_API_MAX_INLINED]; + }; + int64_t size; +} TileList; + +typedef struct XLA_Layout { + Int64List minor_to_major; + IntList dim_level_types; + IntList dim_unique; + IntList dim_ordered; + TileList tiles; + int index_primitive_type; + int pointer_primitive_type; + int64_t element_size_in_bits; + int64_t memory_space; + int64_t dynamic_shape_metadata_prefix_bytes; +} XLA_Layout; + +// Represents an XLA shape tree. +typedef struct XLA_Shape { + int element_type; + Int64List dimensions; + BoolList dynamic_dimensions; + struct XLA_Shape* tuple_shapes; // owned + int ntuple_shapes; + bool has_layout; + XLA_Layout layout; +} XLA_Shape; + +// Represents a leaf node for a XLA shaped buffer. +typedef struct XLA_ShapedBuffer { + XLA_Shape on_device_shape; + int device_ordinal; + + SE_DeviceMemoryBase* bases; + size_t count; +} XLA_ShapedBuffer; + +// Represents a leaf XLA literal. +typedef struct XLA_Literal { + char** buffers; + size_t* sizes; + size_t count; + XLA_Shape shape; +} XLA_Literal; + +typedef struct XLA_MaybeOwningDeviceMemoryShapeTree { + XLA_Shape shape; + SE_MaybeOwningDeviceMemory* buffers; +} XLA_MaybeOwningDeviceMemoryShapeTree; + +typedef struct XLA_ShapeIndex { + int64_t indices[8]; + int64_t count; +} XLA_ShapeIndex; + +typedef struct SE_ExecutionInput { + XLA_MaybeOwningDeviceMemoryShapeTree shape_tree; + XLA_ShapeIndex* unowned_indices; + int unowned_indices_size; + XLA_Shape dynamic_shape; +} SE_ExecutionInput; + +typedef struct SE_ExecutionOutput { + XLA_ShapedBuffer result; + SE_MaybeOwningDeviceMemory* to_be_released; + int to_be_released_size; + XLA_ShapeIndex* aliased_indices; + int aliased_indices_size; +} SE_ExecutionOutput; + +typedef struct XLA_ComputationLayout { + int parameter_count; + XLA_Shape* parameter_layouts; + XLA_Shape result_layout; +} XLA_ComputationLayout; + +typedef struct XLA_HloModuleConfig { + uint64_t seed; + int32_t launch_id; + int64_t replica_count; + int64_t num_partitions; + bool use_spmd_partitioning; + bool use_auto_spmd_partitioning; + Int64List auto_spmd_partitioning_mesh_shape; + Int64List auto_spmd_partitioning_mesh_ids; + TpuSerializedProto debug_options; + bool has_static_device_assignment; + TpuSerializedProto static_device_assignment; + bool has_entry_computation_layout; + XLA_ComputationLayout entry_computation_layout; + BoolList allow_spmd_sharding_propagation_to_output; +} XLA_HloModuleConfig; + +typedef struct SE_HloExecutionProfile SE_HloExecutionProfile; + +typedef struct SE_StreamExecutorList { + SE_StreamExecutor** exec; + int count; +} SE_StreamExecutorList; + +typedef struct XLA_HloModuleGroup { + TpuSerializedProto proto; + XLA_HloModuleConfig* module_config; +} XLA_HloModuleGroup; + +typedef struct XLA_HloModule { + TpuSerializedProto proto; + XLA_HloModuleConfig module_config; +} XLA_HloModule; + +typedef struct XLA_TransferManager XLA_TransferManager; +typedef struct XLA_TpuMeshState XLA_TpuMeshState; + +typedef struct XLA_ComputationPlacer XLA_ComputationPlacer; + +typedef void (*XLA_CallbackFn)(void*); +typedef void (*XLA_StatusCallbackFn)(void*, TF_Status*); + +typedef struct SE_TpuTopology SE_TpuTopology; +typedef struct SE_TpuTopology_Core SE_TpuTopology_Core; +typedef struct SE_TpuTopology_Core SE_TpuTopology_Host; + +typedef struct SE_OutsideCompilationParams SE_OutsideCompilationParams; + +#ifdef __cplusplus +} +#endif + +#endif // XLA_STREAM_EXECUTOR_TPU_C_API_DECL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_defn.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_defn.h new file mode 100644 index 0000000000000000000000000000000000000000..8e4707fcbbda044df8c5e21e103f0fdd717824b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/c_api_defn.h @@ -0,0 +1,66 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_C_API_DEFN_H_ +#define XLA_STREAM_EXECUTOR_TPU_C_API_DEFN_H_ + +#include "xla/stream_executor/device_options.h" +#include "xla/stream_executor/event.h" +#include "xla/stream_executor/stream.h" +#include "xla/stream_executor/stream_executor.h" + +// Definitions for XLA API data structures. Any underlying C++ data structures +// are implementation details and should only be used from within the stream +// executor implementation. + +namespace stream_executor { +class Platform; +class StreamExecutor; +} // namespace stream_executor + +struct SE_Platform { + stream_executor::Platform* platform; +}; + +struct SE_StreamExecutor { + stream_executor::StreamExecutor* executor; +}; + +struct SE_Stream { + explicit SE_Stream(stream_executor::StreamExecutor* parent) + : stream(parent) {} + stream_executor::Stream stream; +}; + +struct SE_Event { + explicit SE_Event(stream_executor::StreamExecutor* parent) : event(parent) {} + stream_executor::Event event; +}; + +struct SE_StreamExecutorConfig { + stream_executor::StreamExecutorConfig config; +}; + +struct SE_DeviceOptions { + stream_executor::DeviceOptions options; +}; + +// Ignored -- these are just used to enforce the interface types +struct XLA_TransferManager {}; +struct XLA_ComputationPlacer {}; +struct SE_TpuTopology {}; +struct SE_TpuTopology_Core {}; + +#endif // XLA_STREAM_EXECUTOR_TPU_C_API_DEFN_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/libtftpu.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/libtftpu.h new file mode 100644 index 0000000000000000000000000000000000000000..c5e3fb59a4a5dfab04dcf07227e0a753433bd936 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/libtftpu.h @@ -0,0 +1,59 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include + +#ifndef XLA_STREAM_EXECUTOR_TPU_LIBTFTPU_H_ +#define XLA_STREAM_EXECUTOR_TPU_LIBTFTPU_H_ + +#ifndef __cplusplus +#define decltype(expr) __typeof__(expr) +#endif + +// Unfortunately we have to add an Fn suffix because we cannot have the same +// name for both a function and a element within a struct in the global +// namespace in gcc. This restriction doesn't exist in clang. +#define TFTPU_ADD_FN_IN_STRUCT(FnName) decltype(FnName)* FnName##Fn; + +#ifdef SWIG +#define TFTPU_CAPI_EXPORT +#else +#if defined(_WIN32) +#ifdef TF_COMPILE_LIBRARY +#define TFTPU_CAPI_EXPORT __declspec(dllexport) +#else +#define TFTPU_CAPI_EXPORT __declspec(dllimport) +#endif // TF_COMPILE_LIBRARY +#else +#define TFTPU_CAPI_EXPORT __attribute__((visibility("default"))) +#endif // _WIN32 +#endif // SWIG + +#ifdef __cplusplus +extern "C" { +#endif + +TFTPU_CAPI_EXPORT void TfTpu_Initialize(bool init_library, int num_args, + const char** args); + +#ifdef __cplusplus +} +#endif + +struct TfTpu_BaseFn { + TFTPU_ADD_FN_IN_STRUCT(TfTpu_Initialize); +}; + +#endif // XLA_STREAM_EXECUTOR_TPU_LIBTFTPU_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/proto_helper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/proto_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..b4f505ed135d84a004e06c500adc66d3fcc29c73 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/proto_helper.h @@ -0,0 +1,83 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_PROTO_HELPER_H_ +#define XLA_STREAM_EXECUTOR_TPU_PROTO_HELPER_H_ + +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "tsl/platform/logging.h" // IWYU pragma: keep + +extern "C" { + +void StreamExecutor_Tpu_FreeSerializedProto(const TpuSerializedProto* proto); + +} // extern "C" + +namespace stream_executor { +namespace tpu { + +using SerializedProto = TpuSerializedProto; + +// Serializes a `proto` and put the result in the given `SerializedProtoType*` +// argument. +// +// Users should call SerializedProto_Free on `serialized_proto` afterwards. +template +inline void SerializeProto(const ProtoType& proto, + SerializedProtoType* serialized_proto) { + auto size = proto.ByteSizeLong(); + auto bytes = new char[size]; + CHECK(proto.SerializeToArray(bytes, size)); + serialized_proto->size = size; + serialized_proto->bytes = bytes; +} + +// Serializes a proto and return the result as a SerializedProto value. +// +// Users should call SerializedProto_Free on the return value afterwards. +template +inline SerializedProto SerializeProto(const ProtoType& proto) { + SerializedProto serialized_proto; + SerializeProto(proto, &serialized_proto); + return serialized_proto; +} + +// Deserializes a buffer and return the corresponding proto. If the buffer is +// empty, return an empty proto. +template +inline ProtoType DeserializeProto(const SerializedProtoType& serialized_proto) { + ProtoType proto; + if (serialized_proto.bytes != nullptr) { + CHECK_GT(serialized_proto.size, 0); + CHECK(proto.ParseFromArray(serialized_proto.bytes, serialized_proto.size)) + << "Invalid buffer, failed to deserialize buffer."; + } + return proto; +} + +// Releases the memory allocated for serialized protos. +template +inline void SerializedProto_Free(const SerializedProtoType& serialized_proto) { + CHECK_NE(serialized_proto.bytes, nullptr); + CHECK_GT(serialized_proto.size, 0); + delete[] serialized_proto.bytes; +} + +} // namespace tpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TPU_PROTO_HELPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_api.h new file mode 100644 index 0000000000000000000000000000000000000000..9a3cf2b330abc9bd48cd545fc43b8ca4a3ae7397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_api.h @@ -0,0 +1,36 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_TPU_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_API_H_ + +#include "xla/stream_executor/tpu/libtftpu.h" +#include "xla/stream_executor/tpu/tpu_executor_api.h" +#include "xla/stream_executor/tpu/tpu_ops_c_api.h" +#include "xla/stream_executor/tpu/tpu_profiler_c_api.h" + +namespace stream_executor { +namespace tpu { + +TfTpu_BaseFn* InitializeApiFn(); + +const TfTpu_OpsApiFn* OpsApiFn(); + +const TfTpu_ProfilerApiFn* ProfilerApiFn(); + +} // namespace tpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_api.h new file mode 100644 index 0000000000000000000000000000000000000000..34989709c31a64d09762f259539a43611fa3e602 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_api.h @@ -0,0 +1,38 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_API_H_ + +#include "xla/stream_executor/tpu/libtftpu.h" +#include "xla/stream_executor/tpu/tpu_executor_c_api.h" + +namespace stream_executor { +namespace tpu { + +TfTpu_ExecutorApiFn* ExecutorApiFn(); + +// Returns whether function pointers in `executor_api_fn` have been set and +// stream_executor is enabled. +bool IsStreamExecutorEnabled(TfTpu_ExecutorApiFn* executor_api_fn); + +// Returns whether function pointers in `executor_api_fn` have been set. If +// false, it probably means an appropriate initializer needs to be linked in. +bool IsInitialized(TfTpu_ExecutorApiFn* executor_api_fn); + +} // namespace tpu +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..f2dc3e3918948d90f6adae094ae838ef995bd0fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_executor_c_api.h @@ -0,0 +1,532 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_C_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_C_API_H_ + +#include +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "xla/stream_executor/tpu/libtftpu.h" + +extern "C" { + +SE_Platform* TpuPlatform_New(); +void TpuPlatform_Free(SE_Platform* platform); +void TpuPlatform_Initialize(SE_Platform* platform, size_t options_size, + const char** options_key, + const char** options_value, TF_Status* status); +bool TpuPlatform_Initialized(SE_Platform* platform); +SE_StreamExecutor* TpuPlatform_GetExecutor(SE_Platform* platform, + SE_StreamExecutorConfig* config, + TF_Status* status); +SE_PlatformId TpuPlatform_Id(SE_Platform* platform); +int64_t TpuPlatform_VisibleDeviceCount(SE_Platform* platform); +bool TpuPlatform_ShouldRegisterTpuDeviceToDeviceCopy(SE_Platform* platform); +SE_TpuTopology* TpuPlatform_GetTopologyPtr(SE_Platform* platform); +SE_TpuTopology_Host* TpuPlatform_GetHostLocation(SE_Platform* platform); +TpuRuntimeVersion TpuPlatform_GetRuntimeVersion(SE_Platform* platform); + +void TpuExecutor_Init(SE_StreamExecutor* executor, int device_ordinal, + SE_DeviceOptions* device_options, TF_Status* status); +void TpuExecutor_Free(SE_StreamExecutor* executor); + +SE_DeviceMemoryBase TpuExecutor_Allocate(SE_StreamExecutor* executor, + uint64_t size, int64_t memory_space); +void TpuExecutor_Deallocate(SE_StreamExecutor* executor, + SE_DeviceMemoryBase* memory); +bool TpuExecutor_GetAllocatorStats(SE_StreamExecutor* executor, + SE_AllocatorStats* stats); +bool TpuExecutor_DeviceMemoryUsage(SE_StreamExecutor* executor, int64_t* free, + int64_t* total); + +bool TpuExecutor_AllocateStream(SE_StreamExecutor* executor, SE_Stream* stream); +void TpuExecutor_DeallocateStream(SE_StreamExecutor* executor, + SE_Stream* stream); +bool TpuExecutor_CreateStreamDependency(SE_StreamExecutor* executor, + SE_Stream* dependent, SE_Stream* other); +void TpuExecutor_GetStatus(SE_StreamExecutor* executor, SE_Stream* stream, + TF_Status* status); + +SE_TpuTopology_Core* TpuExecutor_GetCoreLocation(SE_StreamExecutor* executor); + +void TpuExecutor_AllocateEvent(SE_StreamExecutor* executor, SE_Event* event, + TF_Status* status); +void TpuExecutor_DeallocateEvent(SE_StreamExecutor* executor, SE_Event* event, + TF_Status* status); +int TpuExecutor_PollForEventStatus(SE_StreamExecutor* executor, + SE_Event* event); +void TpuExecutor_RecordEvent(SE_StreamExecutor* executor, SE_Stream* stream, + SE_Event* event, TF_Status* status); +void TpuExecutor_WaitForEvent(SE_StreamExecutor* executor, SE_Stream* stream, + SE_Event* event, TF_Status* status); + +void TpuExecutor_SynchronousMemcpyToHost(SE_StreamExecutor* executor, + void* host_dst, + const SE_DeviceMemoryBase* device_src, + uint64_t size, TF_Status* status); +void TpuExecutor_SynchronousMemcpyFromHost(SE_StreamExecutor* executor, + SE_DeviceMemoryBase* device_dst, + const void* host_src, uint64_t size, + TF_Status* status); +bool TpuExecutor_MemcpyToHost(SE_StreamExecutor* executor, SE_Stream* stream, + void* host_dst, + const SE_DeviceMemoryBase* device_src, + uint64_t size); + +bool TpuExecutor_MemcpyFromHost(SE_StreamExecutor* executor, SE_Stream* stream, + SE_DeviceMemoryBase* device_dst, + const void* host_src, uint64_t size); + +void TpuExecutor_EnqueueInfeed(SE_StreamExecutor* executor, + int32_t infeed_queue_index, const uint8_t* data, + int64_t size, TF_Status* status); +void TpuExecutor_DequeueOutfeed(SE_StreamExecutor* executor, + int32_t outfeed_queue_index, uint8_t* data, + int64_t size, TF_Status* status); +void TpuExecutor_WaitForInfeedReady(SE_StreamExecutor* executor, + int32_t infeed_queue_index, + TF_Status* status); +void TpuExecutor_WaitForOutfeedReady(SE_StreamExecutor* executor, + int32_t outfeed_queue_index, + TF_Status* status); + +void TpuExecutor_BlockHostUntilDone(SE_StreamExecutor* executor, + SE_Stream* stream, TF_Status* status); +void TpuExecutor_BlockUntilDoneOrFailed(SE_StreamExecutor* executor, + TF_Status* status); +void TpuExecutor_SyncAndForgetFailedStreams(SE_StreamExecutor* executor); +bool TpuExecutor_SynchronizeAllActivity(SE_StreamExecutor* executor); + +void TpuExecutor_UnloadAllPrograms(SE_StreamExecutor* executor, + TF_Status* status); +void TpuExecutor_EnqueueCompactionOnStreamForHbm(SE_StreamExecutor* executor, + SE_Stream* compaction_stream, + TF_Status* status); + +SE_Stream* TpuStream_New(SE_StreamExecutor* parent); +void TpuStream_Free(SE_Stream*); +void* TpuStream_Stream(SE_Stream*); +bool TpuStream_Status(SE_Stream*); +bool TpuStream_IsSameSharedMemoryLocation(SE_Stream*, SE_Stream*); +void TpuStream_EnqueueTransferHostToDevice(SE_Stream* stream, + SE_DeviceMemoryBase device_dst, + void* host_src, uint64_t size, + TF_Status* status); +void TpuStream_EnqueueTransferDeviceToHost(SE_Stream* stream, + SE_DeviceMemoryBase device_src, + void* host_dst, uint64_t size, + TF_Status* status); +void TpuStream_TpuEnqueueOnDeviceSendRecvLocal(SE_Stream* stream, + SE_DeviceMemoryBase send_buffer, + SE_DeviceMemoryBase recv_buffer, + TF_Status* status); + +SE_Event* TpuEvent_New(SE_StreamExecutor* parent); +void TpuEvent_Free(SE_Event*); + +TF_Status* TpuStatus_New(); +TF_Status* TpuStatus_Create(int32_t code, const char* msg); +void TpuStatus_Set(TF_Status* status, int32_t code, const char* msg, + int32_t len); +void TpuStatus_Free(TF_Status* status); +const char* TpuStatus_Message(TF_Status* status); +int TpuStatus_Code(TF_Status* status); +bool TpuStatus_Ok(TF_Status* status); + +SE_StreamExecutorConfig* TpuStreamExecutorConfig_Default(); +void TpuStreamExecutorConfig_SetOrdinal(SE_StreamExecutorConfig*, int ordinal); +void TpuStreamExecutorConfig_Free(SE_StreamExecutorConfig*); + +SE_DeviceDescription* TpuDeviceDescription_New(); +void TpuDeviceDescription_Free(SE_DeviceDescription* description); +void TpuExecutor_CreateDeviceDescription(SE_StreamExecutor* executor, + SE_DeviceDescription* description, + TF_Status* status); + +SE_DeviceOptions* TpuExecutor_NewDeviceOptions(unsigned flags); +void TpuExecutor_FreeDeviceOptions(SE_DeviceOptions* options); + +bool TpuExecutor_HostCallback(SE_StreamExecutor* executor, SE_Stream* stream, + SE_StatusCallback callback_fn, void* ctx); + +XLA_TransferManager* TpuTransferManager_New(); +void TpuTransferManager_Free(XLA_TransferManager* manager); +SE_PlatformId TpuTransferManager_PlatformId(XLA_TransferManager* manager); +void TpuTransferManager_HostShapeToDeviceShape(XLA_TransferManager* manager, + XLA_Shape* host_shape, + XLA_Shape* device_shape); +void TpuTransferManager_TransferLiteralToDeviceAsync( + XLA_TransferManager* manager, SE_Stream* stream, XLA_Literal* literal, + XLA_ShapedBuffer* device_buffer, TF_Status* status); +void TpuTransferManager_TransferLiteralFromDevice( + XLA_TransferManager* manager, SE_Stream* stream, + XLA_ShapedBuffer* device_buffer, XLA_Literal* literal, + XLA_StatusCallbackFn callback, void* ctx); +int64_t TpuTransferManager_GetByteSizeRequirement(XLA_TransferManager* manager, + XLA_Shape* shape); +void TpuTransferManager_ChooseCompactLayoutForShape( + XLA_TransferManager* manager, XLA_Shape* host_shape, XLA_Shape* output, + TF_Status* status); +bool TpuTransferManager_CanShapedBufferBeAccessedNow( + XLA_TransferManager* manager, SE_StreamExecutor* executor, + XLA_ShapedBuffer* device_buffer); +bool TpuTransferManager_CanBufferBeAccessedNow( + XLA_TransferManager* manager, SE_StreamExecutor* executor, + SE_DeviceMemoryBase* device_buffer); +void TpuTransferManager_WriteSingleTupleIndexTable( + XLA_TransferManager* manager, SE_Stream* stream, + SE_DeviceMemoryBase* elements, size_t elements_len, XLA_Shape* shape, + SE_DeviceMemoryBase* region, TF_Status* status); +void TpuTransferManager_GetInfeedLayout(XLA_Shape* shape, + XLA_Shape* infeed_shape); +void TpuTransferManager_LinearizeToBuffers( + XLA_TransferManager* manager, XLA_Literal* c_literal, + XLA_Shape* c_device_shape, char*** buffers_array, int64_t** buffers_size, + int64_t* buffers_array_size, TF_Status* status); +void TpuTransferManager_FreeBuffers(char** buffers_array, int64_t* buffers_size, + int64_t buffers_array_size); +void TpuTransferManager_TransferLiteralToInfeed(XLA_TransferManager* manager, + SE_StreamExecutor* executor, + XLA_Literal* c_literal, + TF_Status* status); +void TpuTransferManager_TransferBuffersToInfeed(XLA_TransferManager* manager, + SE_StreamExecutor* executor, + uint32_t** buffers_array, + int64_t* buffers_size_in_uint32, + int64_t buffers_array_size, + TF_Status* status); +void TpuTransferManager_TransferLiteralFromOutfeed( + XLA_TransferManager* manager, SE_StreamExecutor* executor, + XLA_Shape* shape /*deprecated*/, XLA_Literal* c_literal, TF_Status* status); +void TpuTransferManager_ResetDevices(XLA_TransferManager* manager, + SE_StreamExecutor** executors, + int64_t num_executors, TF_Status* status); +void TpuTransferManager_ReadDynamicShapes(SE_Stream* stream, + XLA_ShapedBuffer* buffer, + const XLA_Shape& original_shape, + XLA_Shape* updated_shape, + TF_Status* status); + +XLA_ComputationPlacer* TpuComputationPlacer_New(); +void TpuComputationPlacer_Free(XLA_ComputationPlacer* placer); +// `assignment` should be a preallocated array of size `replicate_count` * +// `computation_count`. The assignment will be constructed as a 2D array where +// assignment[replica][computation] = device_id. +void TpuComputationPlacer_AssignDevices(XLA_ComputationPlacer* placer, + int replica_count, + int computation_count, int* assignment, + TF_Status* status); +void TpuComputationPlacer_AssignLocalDevices(SE_TpuTopology_Host* host, + int replica_count, + int computation_count, + int* assignment, + TF_Status* status); + +int TpuTopology_LogicalDevicesPerHost(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type); +int TpuTopology_LogicalDevicesPerChip(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type); +int TpuTopology_HostCount(SE_TpuTopology* tpu_topology); +int TpuTopology_ChipsPerHost(SE_TpuTopology* tpu_topology); + +int TpuTopology_ChipBounds_X(SE_TpuTopology* tpu_topology); +int TpuTopology_ChipBounds_Y(SE_TpuTopology* tpu_topology); +int TpuTopology_ChipBounds_Z(SE_TpuTopology* tpu_topology); +bool TpuTopology_HasChip(SE_TpuTopology* tpu_topology, int x, int y, int z); +SE_TpuTopology_Core* TpuTopology_CoreForId(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type, + int id); +SE_TpuTopology_Core* TpuTopology_Core(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type, int x, + int y, int z, int index); +int TpuTopology_NumCores(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type); +// 'cores' should be a preallocated array of size TpuTopology_NumCores. +void TpuTopology_Cores(SE_TpuTopology* tpu_topology, + TpuCoreTypeEnum tpu_core_type, + SE_TpuTopology_Core** cores); +int TpuTopology_IdForHost(SE_TpuTopology* tpu_topology, int x, int y, int z); +TpuVersionEnum TpuTopology_Version(SE_TpuTopology* tpu_topology); +void TpuCoreLocation_ChipCoordinates(SE_TpuTopology_Core* tpu_core_location, + int* x, int* y, int* z); +void TpuCoreLocation_HostCoordinates(SE_TpuTopology_Core* tpu_core_location, + int* x, int* y, int* z); +int TpuCoreLocation_Index(SE_TpuTopology_Core* tpu_core_location); +int TpuCoreLocation_Id(SE_TpuTopology_Core* tpu_core_location); + +int TpuHostLocation_Id(SE_TpuTopology_Host* tpu_host_location); +int TpuHostLocation_NumCores(SE_TpuTopology_Host* tpu_host_location, + TpuCoreTypeEnum tpu_core_type); +// 'cores' should be a preallocated array of size TpuHostLocation_NumCores. +void TpuHostLocation_Cores(SE_TpuTopology_Host* tpu_host_location, + TpuCoreTypeEnum tpu_core_type, + SE_TpuTopology_Core** cores); + +// Async collective offloading. +// Safe to call multiple times. +void TpuAsyncCollectiveOffloadHelper_Init(); +// Must be called after TpuAsyncCollectiveOffloadHelper_Init. +void TpuAsyncCollectiveOffloadHelper_Shutdown(); + +// C API for XLA::Compiler interface + +TFTPU_CAPI_EXPORT Tpu_Compiler* TpuCompiler_New(); +TFTPU_CAPI_EXPORT void TpuCompiler_Free(Tpu_Compiler* compiler); + +TFTPU_CAPI_EXPORT void TpuCompiler_RunHloPasses( + Tpu_Compiler* compiler, XLA_HloModule* se_hlo_module, + SE_StreamExecutor* stream_executor, SE_DeviceMemoryAllocator* allocator, + XLA_HloModule* result, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuCompiler_RunBackend( + Tpu_Compiler* compiler, XLA_HloModule* se_hlo_module, + SE_StreamExecutor* stream_executor, SE_DeviceMemoryAllocator* allocator, + SE_Executable** result, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuCompiler_Compile( + Tpu_Compiler* compiler, XLA_HloModuleGroup* se_hlo_module_group, + SE_StreamExecutorList* stream_exec_lists, int num_lists, + SE_DeviceMemoryAllocator* allocator, SE_Executable** executables, + TF_Status* status); + +TFTPU_CAPI_EXPORT int64_t TpuCompiler_ShapeSize(Tpu_Compiler* compiler, + XLA_Shape* c_shape); + +TFTPU_CAPI_EXPORT void TpuCompiler_DefaultDeviceShapeRepresentation( + Tpu_Compiler* compiler, XLA_Shape* host_shape, XLA_Shape* device_shape); + +TFTPU_CAPI_EXPORT void TpuExecutable_ExecuteAsyncOnStream( + SE_Executable* executable, SE_ExecutableRunOptions* se_options, + SE_ExecutionInput** se_arguments, int se_arguments_size, + SE_HloExecutionProfile* hlo_execution_profile, + SE_ExecutionOutput* se_output, TF_Status* status); + +// This frees the XLA_ShapeIndex* array allocated when se_output is returned by +// TpuExecutable_ExecuteAsyncOnStream. +TFTPU_CAPI_EXPORT void TpuExecutable_FreeXlaShapeIndexArray( + XLA_ShapeIndex* array); + +// This frees the SE_MaybeOwningDeviceMemory* array allocated when se_output is +// returned by TpuExecutable_ExecuteAsyncOnStream. +// Note that this only frees the heap-allocated array itself, and does not +// free any of the underlying device memory. +TFTPU_CAPI_EXPORT void TpuExecutable_FreeMaybeOwningDeviceMemoryArray( + SE_MaybeOwningDeviceMemory* array); + +TFTPU_CAPI_EXPORT void TpuExecutable_Fingerprint(SE_Executable* executable, + const char** fingerprint, + size_t* size); + +// The serialization format is not guaranteed to be stable over time and has no +// compatibility guarantees (i.e. this is not a suitable long-term storage +// format). TpuExecutableSerialize_FreeHandle should be called after 'handle' is +// no longer needed. 'handle' is set to nullptr on error. +TFTPU_CAPI_EXPORT void TpuExecutable_Serialize( + SE_Executable* executable, SE_ExecutableSerializationHandle** handle, + TF_Status* status); + +// Returns the size of the serialized executable in bytes, i.e. the size of the +// array that should be passed to TpuExecutableSerialize_WriteToArray. `handle` +// must be non-null. +TFTPU_CAPI_EXPORT size_t +TpuExecutableSerialize_GetByteSize(SE_ExecutableSerializationHandle* handle); + +// Writes the serialized executable to `serialized`, which must be of size +// `serialized_size`. `serialized_size` should must be at least +// `TpuExecutableSerialize_GetByteSize(handle)`. `handle` must be non-null. +TFTPU_CAPI_EXPORT void TpuExecutableSerialize_WriteToArray( + SE_ExecutableSerializationHandle* handle, int serialized_size, + uint8_t* serialized, TF_Status* status); + +// Safe to call if 'handle' is null. +TFTPU_CAPI_EXPORT void TpuExecutableSerialize_FreeHandle( + SE_ExecutableSerializationHandle* handle); + +TFTPU_CAPI_EXPORT void TpuExecutable_Deserialize(int serialized_size, + const uint8_t* serialized, + SE_Executable** executable, + TF_Status* status); + +// Caller is responsible for freeing the returned module's proto and its +// config's proto. +TFTPU_CAPI_EXPORT XLA_HloModule +TpuExecutable_HloModule(SE_Executable* executable); + +TFTPU_CAPI_EXPORT void TpuExecutable_Free(SE_Executable*); + +// Converts an XLA `Shape` into its equivalent TPU `Shape` representation. +TFTPU_CAPI_EXPORT void XlaShapeToTpuShapeRepresentation( + XLA_Shape* serialized_xla_shape, int data_type, bool use_fast_memory, + XLA_Shape* serialized_tpu_shape, TF_Status* status); + +TFTPU_CAPI_EXPORT void XlaShapeToTpuPaddedShape(XLA_Shape* serialized_xla_shape, + XLA_Shape* padded_shape, + TF_Status* status); + +struct TfTpu_ExecutorApiFn { + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_New); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Initialize); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Initialized); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetExecutor); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_Id); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_VisibleDeviceCount); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_ShouldRegisterTpuDeviceToDeviceCopy); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetTopologyPtr); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetHostLocation); + TFTPU_ADD_FN_IN_STRUCT(TpuPlatform_GetRuntimeVersion); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Init); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Allocate); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_Deallocate); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_GetAllocatorStats); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DeviceMemoryUsage); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_AllocateStream); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DeallocateStream); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_CreateStreamDependency); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_GetStatus); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_GetCoreLocation); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_AllocateEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DeallocateEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_PollForEventStatus); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_RecordEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_WaitForEvent); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_SynchronousMemcpyToHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_SynchronousMemcpyFromHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_MemcpyToHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_MemcpyFromHost); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_EnqueueInfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_DequeueOutfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_BlockHostUntilDone); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_SynchronizeAllActivity); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_UnloadAllPrograms); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_EnqueueCompactionOnStreamForHbm); + + TFTPU_ADD_FN_IN_STRUCT(TpuStream_New); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_Stream); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_Status); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_IsSameSharedMemoryLocation); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_EnqueueTransferHostToDevice); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_EnqueueTransferDeviceToHost); + TFTPU_ADD_FN_IN_STRUCT(TpuStream_TpuEnqueueOnDeviceSendRecvLocal); + + TFTPU_ADD_FN_IN_STRUCT(TpuEvent_New); + TFTPU_ADD_FN_IN_STRUCT(TpuEvent_Free); + + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_New); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Set); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Message); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Code); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Ok); + + TFTPU_ADD_FN_IN_STRUCT(TpuStreamExecutorConfig_Default); + TFTPU_ADD_FN_IN_STRUCT(TpuStreamExecutorConfig_SetOrdinal); + TFTPU_ADD_FN_IN_STRUCT(TpuStreamExecutorConfig_Free); + + TFTPU_ADD_FN_IN_STRUCT(TpuDeviceDescription_New); + TFTPU_ADD_FN_IN_STRUCT(TpuDeviceDescription_Free); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_CreateDeviceDescription); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_NewDeviceOptions); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_FreeDeviceOptions); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutor_HostCallback); + + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_New); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_PlatformId); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_HostShapeToDeviceShape); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralToDeviceAsync); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralFromDevice); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_GetByteSizeRequirement); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_ChooseCompactLayoutForShape); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_CanShapedBufferBeAccessedNow); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_CanBufferBeAccessedNow); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_WriteSingleTupleIndexTable); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_GetInfeedLayout); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_LinearizeToBuffers); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_FreeBuffers); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralToInfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferBuffersToInfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_TransferLiteralFromOutfeed); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_ResetDevices); + TFTPU_ADD_FN_IN_STRUCT(TpuTransferManager_ReadDynamicShapes); + + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_New); + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_AssignDevices); + TFTPU_ADD_FN_IN_STRUCT(TpuComputationPlacer_AssignLocalDevices); + + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_LogicalDevicesPerHost); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_LogicalDevicesPerChip); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_HostCount); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipsPerHost); + + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipBounds_X); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipBounds_Y); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_ChipBounds_Z); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_HasChip); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_CoreForId); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_Core); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_NumCores); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_Cores); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_IdForHost); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_Version); + + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_ChipCoordinates); + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_HostCoordinates); + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_Index); + TFTPU_ADD_FN_IN_STRUCT(TpuCoreLocation_Id); + + TFTPU_ADD_FN_IN_STRUCT(TpuHostLocation_Id); + TFTPU_ADD_FN_IN_STRUCT(TpuHostLocation_NumCores); + TFTPU_ADD_FN_IN_STRUCT(TpuHostLocation_Cores); + + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_New); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_RunHloPasses); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_RunBackend); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_Compile); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_ShapeSize); + TFTPU_ADD_FN_IN_STRUCT(TpuCompiler_DefaultDeviceShapeRepresentation); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_ExecuteAsyncOnStream); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_FreeXlaShapeIndexArray); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_FreeMaybeOwningDeviceMemoryArray); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Fingerprint); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Serialize); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutableSerialize_GetByteSize); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutableSerialize_WriteToArray); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutableSerialize_FreeHandle); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Deserialize); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_HloModule); + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_Free); + + TFTPU_ADD_FN_IN_STRUCT(XlaShapeToTpuShapeRepresentation); + TFTPU_ADD_FN_IN_STRUCT(XlaShapeToTpuPaddedShape); + + TFTPU_ADD_FN_IN_STRUCT(TpuAsyncCollectiveOffloadHelper_Init); + TFTPU_ADD_FN_IN_STRUCT(TpuAsyncCollectiveOffloadHelper_Shutdown); +}; +} + +// extern "C" + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_EXECUTOR_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_ops_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_ops_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..65bfbabeb15f7641dba58616fd6c463a10ee10b8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_ops_c_api.h @@ -0,0 +1,828 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_STREAM_EXECUTOR_TPU_TPU_OPS_C_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_OPS_C_API_H_ + +#include + +#include +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "xla/stream_executor/tpu/libtftpu.h" + +typedef struct TpuSerializedProto TpuSerializedProto; + +namespace tensorflow { + +class TpuMeshCommonState; +class TpuEmbeddingEngineState; +class ResourceMgr; + +} // namespace tensorflow + +extern "C" { + +typedef struct XLA_TpuProgram XLA_TpuProgram; + +// Enum for choosing sharding/unsharding program from a `XLA_TpuProgram` obj. +enum TpuProgramShardingType { kInvalid = 0, kMain, kSharding, kUnsharding }; + +struct TpuProgramFingerprint { + const char* bytes; + size_t size; +}; + +struct TpuExecutableSerializedProto { + const char* bytes; + size_t size; +}; + +struct CompilerMetadataSerializedProto { + const char* bytes; + size_t size; +}; + +struct HostComputeMetadataSerializedProto { + const char* bytes; + size_t size; +}; + +typedef struct XLA_TpuMeshState XLA_TpuMeshState; + +typedef struct XLA_TpuEmbeddingEngineState XLA_TpuEmbeddingEngineState; + +typedef struct TpuEmbedding_TensorBatchFixedState + TpuEmbedding_TensorBatchFixedState; + +typedef struct XLA_DeviceAssignment { + const char* bytes; + size_t size; +} XLA_DeviceAssignment; + +// Property for creating compilation cache key. +struct CompilationCacheKeyProperty { + const char* config_prefix; + const char* shapes_prefix; + const char* function_name; + uint64_t mlir_module_fingerprint; + const int32_t* device_ids; + size_t device_ids_size; + int32_t guaranteed_constants_size; + uint64_t function_library_fingerprint; + int32_t num_cores_per_replica; + int32_t num_replicas; + const XLA_TpuMeshState* mesh_state; + uint64_t session_id; + tensorflow::ResourceMgr* resource_mgr; +}; + +// Compilation cache key result returning both the key and a more verbose debug +// version. +struct CompilationCacheKeyResult { + const char* key; + const char* debug_string; +}; + +typedef struct XLA_TpuNodeContext XLA_TpuNodeContext; + +typedef struct TfTpu_OrdinalSelector TfTpuOrdinalSelector; + +struct TpuPartitionedCall_Params { + bool input_shape_opt; + bool group_tensors_for_packing; + int32_t minimum_input_tensors_packing; + int32_t minimum_output_tensors_packing; + + // Whether to attempt to automatically shard inputs by adding an + // XlaSharding op after each input. + bool enable_auto_xla_input_sharding; + + // The dimension of each input to shard if + // enable_auto_xla_input_sharding is set to true. Negative numbers are + // allowed and refers to dimensions starting from the end. + int32_t auto_xla_input_sharding_dim; + + // If true, only create one variable on the TPU for each variable on the CPU. + bool enable_variable_deduplication; +}; + +// Compiles Mlir or TF function computation by lowering into HLO IR and returns +// `count` number of TPU programs ready for execution. +// The API allocates the `XLA_TpuProgram*[]` array `tpu_programs` and creates +// `XLA_TpuProgram` object(s) using the `TpuProgram_New` API. The caller is +// responsible to deallocate both the `XLA_TpuProgram*[]` array and the +// `XLA_TpuProgram` object(s) using `TpuProgram_FreeArray` and `TpuProgram_Free` +// API respectively. +TFTPU_CAPI_EXPORT void TpuCompile_CompileAndBuild( + TpuSerializedProto compilation_request, const XLA_TpuMeshState* mesh_state, + XLA_TpuProgram** tpu_programs[], size_t* count, TF_Status* status); + +// Compiles a HLO IR and returns `count` number of TPU programs ready for +// execution. The API allocates the `XLA_TpuProgram*[]` array `tpu_programs` and +// creates `XLA_TpuProgram` object(s) using the `TpuProgram_New` API. The caller +// is responsible to deallocate both the `XLA_TpuProgram*[]` array and the +// `XLA_TpuProgram` object(s) using `TpuProgram_FreeArray` and `TpuProgram_Free` +// API respectively. +TFTPU_CAPI_EXPORT void TpuCompile_XrtCompileAndBuild( + TpuSerializedProto xrt_computation, const XLA_TpuMeshState* mesh_state, + XLA_TpuProgram** tpu_programs[], size_t* count, TF_Status* status); + +// Creates a new TPU mesh state object. +TFTPU_CAPI_EXPORT XLA_TpuMeshState* TpuMeshState_Create(); + +// Deletes the given TPU `mesh_state` object. Once deleted the object is +// unusable. +TFTPU_CAPI_EXPORT void TpuMeshState_Free(XLA_TpuMeshState* mesh_state); + +// Returns a pointer to an opaque mesh data structure used internally. +TFTPU_CAPI_EXPORT void* TpuMeshState_MeshCommonState( + XLA_TpuMeshState* mesh_state); + +// Creates a new TPU embedding engine state object. +TFTPU_CAPI_EXPORT XLA_TpuEmbeddingEngineState* TpuEmbeddingEngineState_Create(); + +// Delete the given TPU embedding engine state object. Once deleted the object +// is unusable. +TFTPU_CAPI_EXPORT void TpuEmbeddingEngineState_Free( + XLA_TpuEmbeddingEngineState* engine_state); + +// Returns a pointer to an opaque embedding engine state data structure used +// internally. +TFTPU_CAPI_EXPORT void* TpuEmbeddingEngineState_GetState( + XLA_TpuEmbeddingEngineState* engine_state); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_Create( + TfTpuOrdinalSelector** ordinal_selector, int num_cores_per_replica); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_Destroy( + TfTpuOrdinalSelector* ordinal_selector); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_GetOrdinal( + TfTpuOrdinalSelector* ordinal_selector, std::optional key, + int64_t* req_id, int64_t* ordinal); + +TFTPU_CAPI_EXPORT void TfTpuOrdinalSelector_DequeueFromCoreSelector( + TfTpuOrdinalSelector* ordinal_selector, int32_t device_ordinal, + int64_t req_id); + +TFTPU_CAPI_EXPORT void TfTpu_GetTpuPartitionedCallParams( + TpuPartitionedCall_Params* params); + +typedef struct TpuExecutable_LoadProgramAndEnqueueToStream_Params { + int32_t struct_size; + void* priv; + + const XLA_TpuProgram* program; + SE_DeviceMemoryBase* arguments; + size_t arguments_len; + SE_DeviceMemoryBase* result; + size_t cross_program_prefetch_addrs_len; + SE_DeviceMemoryBase* cross_program_prefetch_addrs; + size_t cross_program_prefetch_offsets_len; + const uint32_t* cross_program_prefetch_offsets; + int32_t rng_seed; + XLA_DeviceAssignment* device_assignment; + SE_Stream* stream; + SE_OutsideCompilationParams* outside_compilation_params; + + TF_Status* status; // out +} TpuExecutable_LoadProgramAndEnqueueToStream_Params; + +#define TpuExecutable_LoadProgramAndEnqueueToStream_Params_SIZE \ + (sizeof(struct TpuExecutable_LoadProgramAndEnqueueToStream_Params)) + +TFTPU_CAPI_EXPORT void TpuExecutable_LoadProgramAndEnqueueToStream( + TpuExecutable_LoadProgramAndEnqueueToStream_Params* params); + +TFTPU_CAPI_EXPORT void HardwareLayout_HostShapeToDeviceShape( + XLA_Shape* host_shape, XLA_Shape* device_shape); +TFTPU_CAPI_EXPORT int64_t HardwareLayout_ShapeSize(XLA_Shape* shape); +TFTPU_CAPI_EXPORT int64_t HardwareLayout_ShapeSizeCompact(XLA_Shape* shape); +TFTPU_CAPI_EXPORT int64_t HardwareLayout_ShapeSizeCompactRaw(XLA_Shape* shape); + +typedef struct TpuExecute_RuntimeInputToPaddedData_Params { + int32_t struct_size; + void* priv; + + uint32_t* runtime_input_ptr; + size_t runtime_input_size; + int8_t* padded_data_ptr; + size_t padded_data_size; + XLA_Shape* runtime_shape; + XLA_Shape* compile_time_shape; + + TF_Status* status; // out +} TpuExecute_RuntimeInputToPaddedData_Params; + +#define TpuExecute_RuntimeInputToPaddedData_Params_SIZE \ + (sizeof(struct TpuExecute_RuntimeInputToPaddedData_Params)) + +TFTPU_CAPI_EXPORT void TpuExecute_RuntimeInputToPaddedData( + TpuExecute_RuntimeInputToPaddedData_Params* params); + +TFTPU_CAPI_EXPORT void TpuExecute_GetTpuEmbeddingMemoryAllocations( + int device_ordinal, SE_DeviceMemoryBase** addrs, size_t* addrs_count, + TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuExecute_FreeTpuEmbeddingMemoryAllocations( + int device_ordinal, SE_DeviceMemoryBase* addrs); + +typedef struct ConfigureDistributedTpuOp_DoWork_Params { + int32_t struct_size; + void* priv; + + size_t num_cores_per_host_size; + const int32_t* num_cores_per_host; + size_t server_address_size; + const char* server_address; + + size_t* host_config_output_size; // out + char** host_config_output; // out + TF_Status* status; // out +} ConfigureDistributedTpuOp_DoWork_Params; + +#define ConfigureDistributedTpuOp_DoWork_Params_SIZE \ + (sizeof(struct ConfigureDistributedTpuOp_DoWork_Params)) + +TFTPU_CAPI_EXPORT void ConfigureDistributedTpuOp_DoWork( + ConfigureDistributedTpuOp_DoWork_Params* params); + +typedef struct WaitForDistributedTpuOp_DoWork_Params { + int32_t struct_size; + void* priv; + + size_t num_hosts; + size_t num_cores_per_host; + const int32_t** host_ordinal_to_global_core_id_map; + tensorflow::TpuMeshCommonState* tpu_mesh_common_state; + + size_t* tpu_topology_output_size; // out + char** tpu_topology_output; // out + TF_Status* status; // out +} WaitForDistributedTpuOp_DoWork_Params; + +#define WaitForDistributedTpuOp_DoWork_Params_SIZE \ + (sizeof(struct WaitForDistributedTpuOp_DoWork_Params)) + +TFTPU_CAPI_EXPORT void WaitForDistributedTpuOp_DoWork( + WaitForDistributedTpuOp_DoWork_Params* params); + +typedef struct InitializeHostForDistributedTpuOp_DoWork_Params { + int32_t struct_size; + void* priv; + + size_t tpu_host_config_size; + const char* tpu_host_config; + bool enable_whole_mesh_compilations; + bool is_master_worker; + + size_t* core_id_output_size; // out + int32_t** core_id_output; // out + TF_Status* status; // out +} InitializeHostForDistributedTpuOp_DoWork_Params; + +#define InitializeHostForDistributedTpuOp_DoWork_Params_SIZE \ + (sizeof(struct InitializeHostForDistributedTpuOp_DoWork_Params)) + +TFTPU_CAPI_EXPORT void InitializeHostForDistributedTpuOp_DoWork( + InitializeHostForDistributedTpuOp_DoWork_Params* params); + +TFTPU_CAPI_EXPORT void SetGlobalTPUArrayOp_DoWork( + const size_t tpu_topology_size, const char* tpu_topology, + TF_Status* status); + +TFTPU_CAPI_EXPORT void DisconnectDistributedTpuChipsOp_DoWork( + int32_t* number_of_chips_output, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuConfigurationApi_FreeCharArray(char* output); +TFTPU_CAPI_EXPORT void TpuConfigurationApi_FreeInt32Array(int32_t* output); + +TFTPU_CAPI_EXPORT bool TpuConfigurationApi_HasTPUPodState(); + +TFTPU_CAPI_EXPORT void TpuConfigurationApi_TpusPerHost(int32_t* tpus, + TF_Status* status); +TFTPU_CAPI_EXPORT void TpuConfigurationApi_TpuMemoryLimit(int64_t* memory_limit, + TF_Status* status); +TFTPU_CAPI_EXPORT void TpuConfigurationApi_RemoteCompilationCacheSizeInBytes( + int64_t* cache_size_in_bytes); + +typedef struct TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params { + int32_t struct_size; + void* priv; + + size_t tpu_host_config_size; + const char* tpu_host_config; + + size_t* server_address_output_size; // out + char** server_address_output; // out + TF_Status* status; // out +} TpuConfigurationApi_CompilationCacheServerAddressFromConfig_Params; + +#define TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params_SIZE \ + (sizeof( \ + struct TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params)) + +TFTPU_CAPI_EXPORT +void TpuConfigurationApi_CompilationCacheServerAddressFromConfig( + TpuConfigurationApi_CompilationCacheServerAddrFromConfig_Params* params); + +typedef struct TpuConfigurationApi_GetServerAddressAndPort_Params { + int32_t struct_size; + void* priv; + + size_t* server_address_output_size; // out + char** server_address_output; // out + int* port_output; // out + TF_Status* status; // out +} TpuConfigurationApi_GetServerAddressAndPort_Params; + +#define TpuConfigurationApi_GetServerAddressAndPort_Params_SIZE \ + (sizeof(struct TpuConfigurationApi_GetServerAddressAndPort_Params)) + +TFTPU_CAPI_EXPORT void TpuConfigurationApi_GetServerAddressAndPort( + TpuConfigurationApi_GetServerAddressAndPort_Params* params); + +// Creates a new TPU program. +TFTPU_CAPI_EXPORT XLA_TpuProgram* TpuProgram_New(); + +// Destroys the `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_Free(XLA_TpuProgram* tpu_program); + +// Creates an array of `XLA_TpuProgram*`. +TFTPU_CAPI_EXPORT XLA_TpuProgram** TpuProgram_NewArray(size_t count); + +// Destroys an array of `XLA_TpuProgram*`. +TFTPU_CAPI_EXPORT void TpuProgram_FreeArray(XLA_TpuProgram* tpu_program[]); + +// Unloads and destroys the `tpu_program`. Once the TPU program is unloaded and +// destroyed, it is in an unusable state. +TFTPU_CAPI_EXPORT void TpuProgram_UnloadAndDestroy(XLA_TpuProgram* tpu_program, + TF_Status* status); + +// Gets TPU program size in bytes from the `tpu_program`. +TFTPU_CAPI_EXPORT int64_t +TpuProgram_GetProgramSize(const XLA_TpuProgram* tpu_program); + +// Logs the summary of current memory state snapshot of the `tpu_program`. +TFTPU_CAPI_EXPORT bool TpuProgram_LogProgramMemorySummary( + const XLA_TpuProgram* tpu_program); + +// Gets TPU program executable info from the `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_GetExecutableInfo( + const XLA_TpuProgram* tpu_program, TpuSerializedProto* executable_info, + TF_Status* status); + +// Gets host transfer info proto. +TFTPU_CAPI_EXPORT void TpuProgram_GetHostTransferInfo( + const XLA_TpuProgram* tpu_program, TpuSerializedProto* host_transfer_info, + TF_Status* status); + +// Gets HLO metadata proto. +TFTPU_CAPI_EXPORT void TpuProgram_GetHloMetadata( + const XLA_TpuProgram* tpu_program, TpuSerializedProto* hlo_metadata, + TF_Status* status); + +// Gets may modify variables boolean value. +TFTPU_CAPI_EXPORT void TpuProgram_GetMayModifyVariables( + const XLA_TpuProgram* tpu_program, bool* may_modify_variables); + +// Checks if TPU program has sharding. +TFTPU_CAPI_EXPORT bool TpuProgram_HasSharding( + const XLA_TpuProgram* tpu_program); + +// Gets TPU program by sharding type. Return value is valid only when the +// `status.status()` returns `OK`. +TFTPU_CAPI_EXPORT XLA_TpuProgram* TpuProgram_GetTpuProgram( + XLA_TpuProgram* tpu_program, TpuProgramShardingType type); + +// Gets TPU executable proto from a `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_SerializeTpuExecutable( + const XLA_TpuProgram* tpu_program, TpuExecutableSerializedProto* executable, + TF_Status* status); + +// Gets compilation metadata proto from a `tpu_program`. +TFTPU_CAPI_EXPORT void TpuProgram_SerializeCompilerMetadata( + const XLA_TpuProgram* tpu_program, + CompilerMetadataSerializedProto* compiler_metadata, TF_Status* status); + +// Deserializes the `GetTpuProgramResponse` proto into an `XLA_TpuProgram`. +TFTPU_CAPI_EXPORT void TpuProgram_DeserializeFromGetTpuProgramResponseProto( + TpuSerializedProto get_tpu_program_response, XLA_TpuProgram* tpu_program, + TF_Status* status); + +TFTPU_CAPI_EXPORT TpuProgramFingerprint +TpuProgram_GetFingerprint(const XLA_TpuProgram* tpu_program); + +TFTPU_CAPI_EXPORT void TpuProgram_DestroyFingerprint( + TpuProgramFingerprint fingerprint); + +// Checks if whether a TPU compilation is enabled. +TFTPU_CAPI_EXPORT bool TpuCompile_IsTpuCompilationEnabled(); + +// XLA compilation cannot be cancelled. To avoid hanging the TF worker will exit +// when cancellation is requested for an XLA compile op. Some tests require this +// behavior to be disabled, and we test for this condition with the following +// flag function. +TFTPU_CAPI_EXPORT bool TpuCompile_ShouldTpuCompileOpIgnoreCancellation(); + +// Returns the number of available TPU core count. +TFTPU_CAPI_EXPORT int TpuTopology_AvailableCoreCount( + const XLA_TpuMeshState* mesh_state, TpuCoreTypeEnum tpu_core_type); + +// Recycle unused service port. +TFTPU_CAPI_EXPORT void TpuNetUtil_RecycleUnusedPort(int port); + +// Creates a unique compilation cache `key` used for `put` and `get` operations. +// Returned buffers are heap-allocated and must be owned. +TFTPU_CAPI_EXPORT CompilationCacheKeyResult +TpuCompile_CreateCompilationCacheKey(CompilationCacheKeyProperty property); + +// Destroys the CompilationCacheKeyResult returned by calling the +// `TpuCompile_CreateCompilationCacheKey` API. +TFTPU_CAPI_EXPORT void TpuCompile_DestroyCompilationCacheKey( + CompilationCacheKeyResult result); + +// Creates a guaranteed const fingerprint. Guarantee const is normally used in +// TPU inference to avoid re-copying unchanged variables onto the TPU device. +// It promises the value is identical for every execution in the same session +// even if the actual value changes in later executions. +TFTPU_CAPI_EXPORT uint64_t TpuCompile_CreateGuaranteedConstFingerprint( + uint64_t fingerprint, const char* data, size_t size); + +// Returns a pointer to the TPU topology struct. +TFTPU_CAPI_EXPORT SE_TpuTopology* TpuUtil_GetTopologyPtr(); + +// Returns XLA pad size from TPU topology. +TFTPU_CAPI_EXPORT size_t TpuUtil_GetXlaPadSizeFromTpuTopology(); + +XLA_TpuNodeContext* TpuNodeContext_Create(int device_ordinal, + TF_Status* status); +void TpuNodeContext_Free(XLA_TpuNodeContext* node_context); + +void TpuNodeContext_CloseTpuHost(TF_Status* status); + +void TpuNodeContext_Initialize(int device_ordinal, TF_Status* status); + +bool TpuNodeContext_CompactionSupported(int device_ordinal); + +// Globally initialize the TPU system for inference. +TFTPU_CAPI_EXPORT void TfTpu_InitializeTpuModelServer(); + +typedef struct TpuEmbeddingEngine_ExecutePartitioner_Params { + int32_t struct_size; + void* priv; + TpuSerializedProto tpu_embedding_config; + + // out + size_t* common_config_size; + char** common_config; + TF_Status* status; +} TpuEmbeddingEngine_ExecutePartitioner_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ExecutePartitioner( + TpuEmbeddingEngine_ExecutePartitioner_Params* params); + +typedef struct TpuEmbeddingEngine_ConfigureMemory_Params { + int32_t struct_size; + void* priv; + + int num_inputs; + size_t common_config_size; + const char* common_config; + + // out + size_t* memory_config_size; + char** memory_config; + TF_Status* status; +} TpuEmbeddingEngine_ConfigureMemory_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ConfigureMemory( + TpuEmbeddingEngine_ConfigureMemory_Params* params); + +typedef struct TpuEmbeddingEngine_CollateMemory_Params { + int32_t struct_size; + void* priv; + + size_t memory_configs_size; + const TpuSerializedProto* memory_configs; + + // out + size_t* merged_memory_config_size; + char** merged_memory_config; + TF_Status* status; +} TpuEmbeddingEngine_CollateMemory_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_CollateMemory( + TpuEmbeddingEngine_CollateMemory_Params* params); + +typedef struct TpuEmbeddingEngine_ConfigureHost_Params { + int32_t struct_size; + void* priv; + + int num_inputs; + size_t common_config_size; + const char* common_config; + size_t memory_config_size; + const char* memory_config; + TpuSerializedProto tpu_embedding_config; + + // out + size_t* network_config_size; + char** network_config; + TF_Status* status; +} TpuEmbeddingEngine_ConfigureHost_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ConfigureHost( + TpuEmbeddingEngine_ConfigureHost_Params* params); + +typedef struct TpuEmbeddingEngine_ConnectHosts_Params { + int32_t struct_size; + void* priv; + + size_t network_configs_size; + const TpuSerializedProto* network_configs; + + // out + TF_Status* status; +} TpuEmbeddingEngine_ConnectHosts_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ConnectHosts( + TpuEmbeddingEngine_ConnectHosts_Params* params); + +typedef struct TpuEmbeddingEngine_Finalize_Params { + int32_t struct_size; + void* priv; + const XLA_TpuMeshState* tpu_mesh_state; + + size_t common_config_size; + const char* common_config; + size_t memory_config_size; + const char* memory_config; + + // out + TF_Status* status; +} TpuEmbeddingEngine_Finalize_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_Finalize( + TpuEmbeddingEngine_Finalize_Params* params); + +typedef struct TpuEmbeddingEngine_IsInitialized_Params { + int32_t struct_size; + void* priv; + + size_t config_string_size; + const char* config_string; + + // out + bool* is_tpu_embedding_initialized; + TF_Status* status; +} TpuEmbeddingEngine_IsInitialized_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_IsInitialized( + TpuEmbeddingEngine_IsInitialized_Params* params); + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_WriteParameters( + TpuEmbeddingEngineParameters* params, TF_Status* status); + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_ReadParameters( + TpuEmbeddingEngineParameters* params, TF_Status* status); + +typedef struct TF_Tensor TF_Tensor; + +typedef struct TpuEmbeddingEngine_EnqueueTensorBatch_Params { + int32_t struct_size; + void* priv; + + int32_t mode; + int32_t local_device_ordinal; + TpuEmbedding_TensorBatchFixedState* fixed_state; + + TF_Tensor** sample_indices_tensors; + size_t sample_indices_tensors_size; + TF_Tensor** embedding_indices_tensors; + size_t embedding_indices_tensors_size; + TF_Tensor** aggregation_weights_tensors; + size_t aggregation_weights_tensors_size; + TF_Status* status; +} TpuEmbeddingEngine_EnqueueTensorBatch_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_EnqueueTensorBatch( + TpuEmbeddingEngine_EnqueueTensorBatch_Params* params); + +typedef struct TpuEmbedding_TensorBatchFixedState_Create_Params { + int32_t struct_size; + void* priv; + + size_t combiners_size; + char** combiners; + + // out + TF_Status* status; +} TpuEmbedding_TensorBatchFixedState_Create_Params; + +TFTPU_CAPI_EXPORT TpuEmbedding_TensorBatchFixedState* +TpuEmbeddingTensorBatchFixedState_Create( + TpuEmbedding_TensorBatchFixedState_Create_Params* params); +TFTPU_CAPI_EXPORT void TpuEmbeddingTensorBatchFixedState_Destroy( + TpuEmbedding_TensorBatchFixedState* fixed_state); + +typedef struct TpuEmbeddingEngine_RecvActivationsComputation_Params { + int32_t struct_size; + void* priv; + + TpuSerializedProto tpu_embedding_config; + XLA_Shape* deduplication_data_shape; + TpuSerializedProto* op_sharding; + + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_RecvActivationsComputation_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_RecvActivationsComputation( + TpuEmbeddingEngine_RecvActivationsComputation_Params* params); + +typedef struct + TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation_Params { + int32_t struct_size; + void* priv; + + TpuSerializedProto tpu_embedding_config; + TpuSerializedProto* op_sharding; + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation_Params; + +TFTPU_CAPI_EXPORT void +TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation( + TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation_Params* + params); + +typedef struct TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation_Params { + int32_t struct_size; + void* priv; + + int32_t num_inputs; + TpuSerializedProto tpu_embedding_config; + XLA_Shape* learning_rate_tuple_shape; + XLA_Shape* deduplication_data_shape; + XLA_Shape* gradient_tuple_shape; + TpuSerializedProto* op_sharding; + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation( + TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation_Params* params); + +typedef struct TpuEmbeddingEngine_DedupDataTupleMaskComputation_Params { + int32_t struct_size; + void* priv; + + TpuSerializedProto tpu_embedding_config; + // out + TpuSerializedProto* xla_computation; + TF_Status* status; +} TpuEmbeddingEngine_DedupDataTupleMaskComputation_Params; + +TFTPU_CAPI_EXPORT void TpuEmbeddingEngine_DedupDataTupleMaskComputation( + TpuEmbeddingEngine_DedupDataTupleMaskComputation_Params* params); + +typedef struct SparseCore_GetMaxIdsAndUniques_Params { + size_t struct_size; + void* priv; + const char* program_key; + const char* table_name; + int64_t num_samples_per_sparse_core; + int64_t feature_width; + // out + TF_Status* status; + int64_t max_ids_per_partition; + int64_t max_unique_ids_per_partition; +} SparseCore_GetMaxIdsAndUniques_Params; + +TFTPU_CAPI_EXPORT void SparseCore_GetMaxIdsAndUniques( + SparseCore_GetMaxIdsAndUniques_Params* params); + +struct TfTpu_OpsApiFn { + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_CompileAndBuild); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_XrtCompileAndBuild); + + TFTPU_ADD_FN_IN_STRUCT(TpuMeshState_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuMeshState_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuMeshState_MeshCommonState); + + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngineState_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngineState_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngineState_GetState); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecutable_LoadProgramAndEnqueueToStream); + + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_HostShapeToDeviceShape); + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_ShapeSize); + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_ShapeSizeCompact); + TFTPU_ADD_FN_IN_STRUCT(HardwareLayout_ShapeSizeCompactRaw); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecute_RuntimeInputToPaddedData); + + TFTPU_ADD_FN_IN_STRUCT(TpuExecute_GetTpuEmbeddingMemoryAllocations); + TFTPU_ADD_FN_IN_STRUCT(TpuExecute_FreeTpuEmbeddingMemoryAllocations); + + TFTPU_ADD_FN_IN_STRUCT(ConfigureDistributedTpuOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(WaitForDistributedTpuOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(InitializeHostForDistributedTpuOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(SetGlobalTPUArrayOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(DisconnectDistributedTpuChipsOp_DoWork); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_FreeCharArray); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_FreeInt32Array); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_HasTPUPodState); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_TpusPerHost); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_TpuMemoryLimit); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_RemoteCompilationCacheSizeInBytes); + TFTPU_ADD_FN_IN_STRUCT( + TpuConfigurationApi_CompilationCacheServerAddressFromConfig); + TFTPU_ADD_FN_IN_STRUCT(TpuConfigurationApi_GetServerAddressAndPort); + + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_New); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_NewArray); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_FreeArray); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_UnloadAndDestroy); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetProgramSize); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_LogProgramMemorySummary); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetExecutableInfo); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetHostTransferInfo); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetHloMetadata); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetMayModifyVariables); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_HasSharding); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetTpuProgram); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_SerializeTpuExecutable); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_SerializeCompilerMetadata); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_DeserializeFromGetTpuProgramResponseProto); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_GetFingerprint); + TFTPU_ADD_FN_IN_STRUCT(TpuProgram_DestroyFingerprint); + + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_IsTpuCompilationEnabled); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_ShouldTpuCompileOpIgnoreCancellation); + TFTPU_ADD_FN_IN_STRUCT(TpuTopology_AvailableCoreCount); + TFTPU_ADD_FN_IN_STRUCT(TpuNetUtil_RecycleUnusedPort); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_CreateCompilationCacheKey); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_DestroyCompilationCacheKey); + TFTPU_ADD_FN_IN_STRUCT(TpuCompile_CreateGuaranteedConstFingerprint); + TFTPU_ADD_FN_IN_STRUCT(TpuUtil_GetTopologyPtr); + TFTPU_ADD_FN_IN_STRUCT(TpuUtil_GetXlaPadSizeFromTpuTopology); + + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_CloseTpuHost); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_Initialize); + TFTPU_ADD_FN_IN_STRUCT(TpuNodeContext_CompactionSupported); + + TFTPU_ADD_FN_IN_STRUCT(TfTpu_InitializeTpuModelServer); + + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_Create); + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_Destroy); + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_GetOrdinal); + TFTPU_ADD_FN_IN_STRUCT(TfTpuOrdinalSelector_DequeueFromCoreSelector); + TFTPU_ADD_FN_IN_STRUCT(TfTpu_GetTpuPartitionedCallParams); + + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ExecutePartitioner); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ConfigureMemory); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_CollateMemory); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ConfigureHost); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ConnectHosts); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_Finalize); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_IsInitialized); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_WriteParameters); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_ReadParameters); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingTensorBatchFixedState_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingTensorBatchFixedState_Destroy); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_EnqueueTensorBatch); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_RecvActivationsComputation); + TFTPU_ADD_FN_IN_STRUCT( + TpuEmbeddingEngine_RecvTPUEmbeddingDeduplicationDataComputation); + TFTPU_ADD_FN_IN_STRUCT( + TpuEmbeddingEngine_SendTPUEmbeddingGradientsComputation); + TFTPU_ADD_FN_IN_STRUCT(TpuEmbeddingEngine_DedupDataTupleMaskComputation); + + TFTPU_ADD_FN_IN_STRUCT(SparseCore_GetMaxIdsAndUniques); +}; + +} // extern "C" + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_OPS_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_profiler_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_profiler_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..efb81d37acc14b5ac22f4147d11e4e4186dbdf08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/tpu/tpu_profiler_c_api.h @@ -0,0 +1,84 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef XLA_STREAM_EXECUTOR_TPU_TPU_PROFILER_C_API_H_ +#define XLA_STREAM_EXECUTOR_TPU_TPU_PROFILER_C_API_H_ + +#include + +#include + +#include "xla/stream_executor/tpu/c_api_decl.h" +#include "xla/stream_executor/tpu/libtftpu.h" + +extern "C" { + +typedef struct TpuProfiler TpuProfiler; + +// Creates a TPU profiler that is ready to start profiling. +TFTPU_CAPI_EXPORT void TpuProfiler_Create(TpuProfiler** tpu_profiler, + TF_Status* status); +// Destroys the given TPU profiler. +TFTPU_CAPI_EXPORT void TpuProfiler_Destroy(TpuProfiler* tpu_profiler); +// Starts profiling if not already started, returns an error otherwise. +TFTPU_CAPI_EXPORT void TpuProfiler_Start(TpuProfiler* tpu_profiler, + TF_Status* status); +// Stops profiling if not already stopped, returns an error otherwise. +TFTPU_CAPI_EXPORT void TpuProfiler_Stop(TpuProfiler* tpu_profiler, + TF_Status* status); +// Serializes profiled data into `buffer` and returns the size of `buffer`. The +// profile data held by the TPU driver will be cleared after retrieval. +// +// Step 1. Query the size of buffer required into `size_in_bytes`. +// +// size_t size_in_bytes; +// TpuProfiler_CollectData(profiler, status, nullptr, &size_in_bytes); +// +// Step 2. Retrieve the data into a `buffer` of size `size_in_bytes`. +// Subsequently,The TPU driver clears its copy of the profile data. +// +// uint8_t buffer = new uint8_t[size_in_bytes]; +// TpuProfiler_CollectData(profiler, status, buffer, size_in_bytes); +// +// Step 3. Unpack the data into an XSpace. +// +// tensorflow::profiler::XSpace space; +// space.ParseFromArray(buffer, size_in_bytes); +// +TFTPU_CAPI_EXPORT void TpuProfiler_CollectData(TpuProfiler* tpu_profiler, + TF_Status* status, + uint8_t* buffer, + size_t* size_in_bytes); + +// Status helpers to create TFStatus for Profiler. +TF_Status* TpuStatus_New(); +void TpuStatus_Free(TF_Status* status); +const char* TpuStatus_Message(TF_Status* status); +int TpuStatus_Code(TF_Status* status); + +struct TfTpu_ProfilerApiFn { + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Create); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Destroy); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Start); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_Stop); + TFTPU_ADD_FN_IN_STRUCT(TpuProfiler_CollectData); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_New); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Free); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Message); + TFTPU_ADD_FN_IN_STRUCT(TpuStatus_Code); +}; + +} // extern "C" + +#endif // XLA_STREAM_EXECUTOR_TPU_TPU_PROFILER_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/trace_listener.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/trace_listener.h new file mode 100644 index 0000000000000000000000000000000000000000..5b1340dc7cfbb89f4b725f789e23db9a48e0d77c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/stream_executor/trace_listener.h @@ -0,0 +1,74 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines the StreamExecutor trace listener, used for inserting +// non-device-specific instrumentation into the StreamExecutor. +#ifndef XLA_STREAM_EXECUTOR_TRACE_LISTENER_H_ +#define XLA_STREAM_EXECUTOR_TRACE_LISTENER_H_ + +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/kernel.h" +#include "xla/stream_executor/launch_dim.h" +#include "tsl/platform/status.h" + +namespace stream_executor { + +class Stream; + +// Traces StreamExecutor PIMPL-level events. +// The few StreamExecutor interfaces that are synchronous have both Begin and +// Complete versions of their trace calls. Asynchronous operations only have +// Submit calls, as execution of the underlying operations is device-specific. +// As all tracing calls mirror StreamExecutor routines, documentation here is +// minimal. +// +// All calls have default implementations that perform no work; subclasses +// should override functionality of interest. Keep in mind that these routines +// are not called on a dedicated thread, so callbacks should execute quickly. +// +// Note: This API is constructed on an as-needed basis. Users should add +// support for further StreamExecutor operations as required. By enforced +// convention (see SCOPED_TRACE in stream_executor_pimpl.cc), synchronous +// tracepoints should be named NameBegin and NameComplete. +class TraceListener { + public: + virtual ~TraceListener() {} + + virtual void LaunchSubmit(Stream* stream, const ThreadDim& thread_dims, + const BlockDim& block_dims, + const KernelBase& kernel, + const KernelArgsArrayBase& args) {} + + virtual void SynchronousMemcpyH2DBegin(int64_t correlation_id, + const void* host_src, int64_t size, + DeviceMemoryBase* gpu_dst) {} + virtual void SynchronousMemcpyH2DComplete(int64_t correlation_id, + const tsl::Status* result) {} + + virtual void SynchronousMemcpyD2HBegin(int64_t correlation_id, + const DeviceMemoryBase& gpu_src, + int64_t size, void* host_dst) {} + virtual void SynchronousMemcpyD2HComplete(int64_t correlation_id, + const tsl::Status* result) {} + + virtual void BlockHostUntilDoneBegin(int64_t correlation_id, Stream* stream) { + } + virtual void BlockHostUntilDoneComplete(int64_t correlation_id, + const tsl::Status* result) {} +}; + +} // namespace stream_executor + +#endif // XLA_STREAM_EXECUTOR_TRACE_LISTENER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/attribute_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/attribute_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..cd88cd95010e43805796fa47f6ceb08cefeadc17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/attribute_importer.h @@ -0,0 +1,79 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_ATTRIBUTE_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_ATTRIBUTE_IMPORTER_H_ + +#include +#include + +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Converts an XLA PrecisionConfig to the corresponding MLIR attribute. +mlir::ArrayAttr ConvertPrecisionConfig(const PrecisionConfig* config, + mlir::Builder* builder); + +// Converts the gather dimensions to attributes. +mlir::mhlo::GatherDimensionNumbersAttr ConvertGatherDimensionNumbers( + const xla::GatherDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the scatter dimensions to attributes. +mlir::mhlo::ScatterDimensionNumbersAttr ConvertScatterDimensionNumbers( + const xla::ScatterDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the dot dimensions to attributes. +mlir::mhlo::DotDimensionNumbersAttr ConvertDotDimensionNumbers( + const DotDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the conv dimensions to attributes. +mlir::mhlo::ConvDimensionNumbersAttr ConvertConvDimensionNumbers( + const xla::ConvolutionDimensionNumbers& dnums, mlir::Builder* builder); + +// Converts the output operand aliasing to attributes. +mlir::ArrayAttr ConvertOutputOperandAliasing( + const std::vector>>& aliaInfo, + mlir::Builder* builder); + +StatusOr ConvertFftType(FftType type); +StatusOr ConvertTranspose( + TriangularSolveOptions_Transpose transpose); + +StatusOr ConvertCustomCallApiVersion( + xla::CustomCallApiVersion api_version); + +// Extracts layouts from shapes and converts it into layout attributes (array of +// rank-1 index tensors). Returns an error if any of the shapes is a tuple. +StatusOr ExtractLayoutsFromShapes( + const absl::Span shapes_with_layouts, mlir::Builder* builder); + +// Extracts the layouts of each element from a tuple shape and returns them as +// an array of rank-1 index tensors. Returns an error in presence of nested +// tuple shapes. +StatusOr ExtractLayoutsFromTuple(const xla::Shape shape, + mlir::Builder* builder); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_ATTRIBUTE_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_function_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_function_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..66794a4bf80480637a12005e9c2e71e6ad5c8e74 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_function_importer.h @@ -0,0 +1,301 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_HLO_FUNCTION_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_FUNCTION_IMPORTER_H_ + +#include +#include + +#include "absl/types/optional.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "xla/comparison_util.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/hlo.pb.h" +#include "xla/status.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +class HloModule; +class HloComputation; +class HloInstruction; +class Shape; + +// HLO bounded dynamic shapes can be converted to either MLIR dynamic shapes +// (which lose the bound information) or casted to static shape using the +// bounds. +enum class DynamicShapeHandlingMode { kDynamic, kConvertToStatic }; + +// Helper class for importing HloComputations. +class HloFunctionImporter { + public: + // Imports the given computation as a function in the given symbol table and + // returns the FuncOp. This also imports any computations referred by + // instructions in this computation. + static StatusOr ImportAsFunc( + const xla::HloComputation& computation, mlir::SymbolTable& symbol_table, + std::unordered_map* + function_map, + mlir::Builder* builder, bool is_main); + + // Imports the given hlo computation to the specified region. If + // 'flatten_region_arg_tuple' is true, then flatten the tuple-typed region + // argument(s) and return value(s). + static Status ImportAsRegion(const xla::HloComputation& computation, + mlir::SymbolTable& symbol_table, + mlir::Region* region, mlir::Builder* builder, + bool flatten_region_arg_tuple = false); + + // Imports the given computation to the given place specified by `builder`. + // `arguments` contains values for all parameters. + static StatusOr ImportInstructions( + const xla::HloComputation& computation, + const llvm::SmallVectorImpl& arguments, + mlir::SymbolTable& symbol_table, mlir::OpBuilder* builder); + + static StatusOr ImportInstruction( + const xla::HloInstruction* instr, + const llvm::SmallVectorImpl& operands, + mlir::SymbolTable& symbol_table, mlir::OpBuilder* builder, + DynamicShapeHandlingMode mode = DynamicShapeHandlingMode::kDynamic); + + static void SetLayoutForMlir(mlir::Operation* op, const Shape& shape, + llvm::StringRef attr_name); + + // TODO(b/179166199): move this to attribute_importer.h. + // Converts XLA instruction source target pairs to MLIR attribute. + static mlir::NamedAttribute ConvertSourceTargetPairs( + const std::vector>& source_target_pairs, + mlir::Builder* builder); + + // TODO(b/179166199): move this to attribute_importer.h. + // Converts replica groups to attribute + static mlir::NamedAttribute ConvertReplicaGroups( + absl::Span replica_groups, mlir::Builder* builder); + + // For mlir::IfOp or mlir::CaseOp, replace the uses of their region's block + // arguments with 'implicit_operands'. Here | implicit_operands | == sum of + // the number of arguments in all the regions in IfOp or CaseOp. + void ReplaceBlockArgumentsWithImplicitOperands( + mlir::Operation* op, llvm::ArrayRef implicit_operands); + + // Create a TupleOp using the results of 'op' if 'type' is a mlir::TupleType. + // Otherwise, return 'op'. + mlir::Operation* CreateTupleFromOpResults(mlir::OpBuilder* func_builder, + mlir::Location loc, + mlir::Operation* op, + mlir::Type type); + + // FlattenTupleType flattens the types in (nested) tuple-type 'type' and + // stores them in 'types'. + static void FlattenTupleType( + mlir::Type type, llvm::SmallVectorImpl& flattened_types); + + // FlattenTupleValue flattens the values in (nested) tuple-typed 'value' and + // stores them in 'flattened_values'. + static void FlattenTupleValue( + mlir::OpBuilder* func_builder, mlir::Location loc, mlir::Value value, + llvm::SmallVectorImpl& flattened_values); + + // CreateTupleValue creates a root TupleOp of (nested) tuple-type 'type' using + // the non-tuple-typed values in 'flatten_values'. + // + // e.g., Given 'flatten_values': [V1, V2, V3] &'type': tuple>, + // The function returns %t2 such that: + // %t1 = mhlo.tuple(V2,V3) : (T2,T3) -> tuple + // %t2 = mhlo.tuple(V1,%t1): (T1,tuple) -> tuple> + // + // Note: 1. FlattenTupleValue and CreateTupleValue is a pair of functions to + // resp. flatten and create tuples in the exact same order. + // 2. `flatten_values`, initially storing the flattened values, will be + // mutated to a 0-length array by the end of function invocation. + static mlir::Value CreateTupleValue( + mlir::OpBuilder* func_builder, mlir::Location loc, + llvm::MutableArrayRef& flatten_values, mlir::Type type); + + private: + HloFunctionImporter(mlir::SymbolTable& symbol_table, + std::unordered_map* function_map, + mlir::Builder* builder) + : context_(symbol_table.getOp()->getContext()), + symbol_table_(symbol_table), + builder_(builder), + function_map_(function_map) { + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + } + + // Imports the given computation as a new function, if it hasn't been already + // imported. + StatusOr ImportAsFunc( + const xla::HloComputation& computation, bool is_main); + + // Imports the given computation in the specified region. + Status ImportAsRegion(const HloComputation& computation, mlir::Region* region, + bool flatten_region_arg_tuple = false); + + // Imports instructions from the given computation in the specified block. + // Assumes that the block already has correct arguments populated. + Status ImportInstructions(const HloComputation& computation, + mlir::Block* block, bool flatten_region_arg_tuple); + StatusOr ImportInstructionsImpl( + const xla::HloComputation& computation, + const llvm::SmallVectorImpl& arguments, + mlir::OpBuilder* builder); + + // Imports an instruction. + StatusOr ImportInstructionWithLayout( + const xla::HloInstruction* instruction, + const llvm::SmallVectorImpl& operands, + mlir::OpBuilder* func_builder, + DynamicShapeHandlingMode mode = DynamicShapeHandlingMode::kDynamic); + + StatusOr ImportInstructionImpl( + const HloInstruction* instruction, + const llvm::SmallVectorImpl& operands, + mlir::OpBuilder* func_builder, + DynamicShapeHandlingMode mode = DynamicShapeHandlingMode::kDynamic); + + // Gets the MLIR operand values from an HLO Instruction. + StatusOr> GetOperands( + const xla::HloInstruction* instruction); + + // Converts xla Tensor type to the corresponding MLIR type. + StatusOr ConvertTensorType(const xla::Shape& shape); + + // Converts an XLA shape/layout to the corresponding MLIR layout, in + // flattened_attr, while flattening the tuple layout. + Status ConvertShapeToMlirLayout( + const xla::Shape& shape, + llvm::SmallVectorImpl& flattened_attr); + + // Returns the output type of an HloInstruction. + StatusOr GetReturnType(const xla::HloInstruction* instruction); + + // Takes a list of HloInstructions and generates the list of types used for + // input, bypassing tuples to subsets. + Status GetMlirTypes(absl::Span instructions, + llvm::SmallVectorImpl* types); + + // Returns the Mlir Value for the corresponding HloInstruction. + StatusOr GetMlirValue(const xla::HloInstruction* instruction); + + // Converts an XLA ComparisonDirection to the corresponding MLIR attribute. + mlir::NamedAttribute ConvertComparisonDirection( + ComparisonDirection direction); + + // Converts an XLA Comparison::Type to the corresponding MLIR attribute. + mlir::NamedAttribute ConvertComparisonType(Comparison::Type type); + + // Converts an XLA CustomCallSchedule to the corresponding MLIR attribute. + mlir::NamedAttribute ConvertCustomCallSchedule( + xla::CustomCallSchedule schedule); + + // Converts the dimensions of an HLO instruction into an MLIR attribute. + mlir::DenseIntElementsAttr ConvertDimensions( + absl::Span op_dimensions); + + // Converts Array ref to an DenseIntElementsAttr. + mlir::DenseIntElementsAttr Convert(llvm::ArrayRef elements); + + // Converts Array ref of bools to a DenseIntElementsAttr of I1 type. + mlir::DenseIntElementsAttr Convert(llvm::ArrayRef elements); + + // Converts Array ref to padding attribute. Input is a flattened list of + // padding low and padding high for each of the spatial dimensions. + mlir::NamedAttribute ConvertPadding(llvm::ArrayRef padding); + + // Converts channel id to attribute + mlir::NamedAttribute ConvertChannelHandle(std::optional channel_id); + + // Convert use global device ids flag to attribute + mlir::NamedAttribute ConvertUseGlobalDeviceIds(); + + // Converts channel handle to attribute + mlir::NamedAttribute ConvertChannelHandle(const xla::ChannelHandle& channel); + + // ============ + // Imports an old-style async start op. E.g. an HLO all-gather-start + // instruction is imported as an async-start associated with an all-gather + // computation. + // + // Eventually, old-style async ops (e.g. all-gather-start) and new-style async + // ops (i.e. async-start, async-update and async-done) will converge on the + // HLO side, so we decided to not introduce new MHLO ops for all-gather-start + // and friends. + // + // In the end, there may be new ops added in the old-style because they're not + // compatible with the new-style async semantics, but those should be handled + // on their own, rather than this function which "upgrades" ops to the + // new-style async API. + // ============ + template + StatusOr ImportOldStyleAsyncStart( + llvm::SmallVectorImpl& attributes, + const llvm::SmallVectorImpl& operands, mlir::Location loc, + mlir::Type result_type, mlir::OpBuilder* func_builder, + std::string func_name, std::function mutate_op); + + // Imports an old-style async done op + StatusOr ImportOldStyleAsyncDone( + llvm::SmallVectorImpl& attributes, + const llvm::SmallVectorImpl& operands, mlir::Location loc, + mlir::Type result_type, mlir::OpBuilder* func_builder); + + mlir::MLIRContext* context_; + + // SymbolTable to which new functions should be inserted. + mlir::SymbolTable& symbol_table_; + + mlir::Builder* builder_; + + // Mapping from HloComputation to the created MLIR function. + std::unordered_map* + function_map_; + + // Mapping from HloInstructions to the associative MLIR values. + std::unordered_map + instruction_value_map_; +}; + +// Returns a StringAttr that carries a prettyprinted representation of the +// given HLO C++ sharding. +// Always succeeds and returns a non-empty attribute. +mlir::Attribute ConvertSharding(const xla::HloSharding& sharding, + mlir::Builder* builder); + +// Returns a StringAttr that carries a prettyprinted representation of the +// given HLO proto sharding. +// Will fail and return an empty attribute if the proto sharding cannot be +// converted to the C++ sharding. +mlir::Attribute ConvertSharding(const xla::OpSharding& sharding, + mlir::Builder* builder); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_FUNCTION_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_module_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_module_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..ac42e28f3f2123d946ce40d09011158a6dc72e20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_module_importer.h @@ -0,0 +1,67 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_HLO_MODULE_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_MODULE_IMPORTER_H_ + +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/SymbolTable.h" // from @llvm-project +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/status.h" +#include "xla/xla_data.pb.h" + +namespace xla { +class HloModule; +class HloModuleProto; +class HloComputation; +class HloInstruction; +class Shape; + +// Importer that takes an HloModule and imports it as an MLIR module in the XLA +// dialect. HloModuleImporter does not take ownership. +class HloModuleImporter { + public: + explicit HloModuleImporter(mlir::ModuleOp module, + bool import_all_computation = false); + + // Import the HloModule into the MLIR Module. + Status Import(const xla::HloModule& module); + + // Import the HloModuleProto into the MLIR Module. + Status Import(const xla::HloModuleProto& module); + + private: + void ImportFrontendAttributes(const xla::HloModule& hlo_module, + mlir::ModuleOp module); + + bool import_all_computation_; + mlir::SymbolTable symbol_table_; + mlir::Builder builder_; + + // Map for tracking which MLIR function map to which HLO Computation. This + // tracks functions as they are imported and provides a quick lookup for + // functions invoked by control flow related operations (e.g. while, call). + std::unordered_map + function_map_; +}; + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_MODULE_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h new file mode 100644 index 0000000000000000000000000000000000000000..21b3c1589c0bd7384baa2262f66abb4b719fc320 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_to_mlir_hlo.h @@ -0,0 +1,44 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_HLO_TO_MLIR_HLO_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_TO_MLIR_HLO_H_ + +#include "xla/status.h" + +namespace mlir { +class ModuleOp; +} // namespace mlir + +namespace xla { +class HloModule; +class HloModuleProto; + +// Converts an HLO module proto to a MLIR module in HLO dialect. +// If import_all_computation is set to true, imports all computations +// irrespective if transitively called from entry computation. +Status ConvertHloToMlirHlo(mlir::ModuleOp module, + xla::HloModuleProto const* hlo_module, + bool import_all_computations = false); + +// Converts an HLO module to a MLIR module in HLO dialect. +// If import_all_computation is set to true, imports all computations +// irrespective if transitively called from entry computation. +Status ConvertHloToMlirHlo(mlir::ModuleOp module, xla::HloModule* hlo_module, + bool import_all_computations = false); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_TO_MLIR_HLO_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..42682a251385aeb82b97bb3f64378f1dfc377539 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/hlo_utils.h @@ -0,0 +1,174 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// This file defines helpers useful when creating or manipulating lhlo/hlo. + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_HLO_UTILS_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_HLO_UTILS_H_ + +#include "llvm/ADT/STLExtras.h" +#include "mlir/Dialect/SparseTensor/IR/Enums.h" // from @llvm-project +#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/mlir_hlo/utils/convert_op_folder.h" +#include "xla/util.h" + +namespace xla { + +StatusOr CreateDenseElementsAttrFromLiteral( + const LiteralBase& literal, mlir::Builder builder); + +Status CopyDenseElementsDataToXlaFormat(mlir::DenseElementsAttr data, + std::vector* output); + +StatusOr GetElementTypeBytes(mlir::Type type); + +// Creates an DenseIntElementsAttr using the elements of the vector and the +// optional shape. +mlir::DenseIntElementsAttr CreateDenseIntElementsAttrFromVector( + const llvm::ArrayRef vector, mlir::Builder builder, + llvm::ArrayRef shape = {}); + +StatusOr ConvertPrimitiveTypeToMLIRType(PrimitiveType element_type, + mlir::Builder builder); + +mlir::mhlo::GatherDimensionNumbersAttr CreateGatherDimensionNumbers( + const GatherDimensionNumbers& input, mlir::Builder builder); + +// Converts the given XLA shape for tensors to the template MLIR type. +template +static StatusOr ConvertTensorShapeToType(const Shape& xla_ty, + mlir::Builder builder) { + auto element_type_or = + ConvertPrimitiveTypeToMLIRType(xla_ty.element_type(), builder); + if (!element_type_or.ok()) return element_type_or.status(); + + bool is_dynamic = false; + int64_t rank = xla_ty.rank(); + llvm::SmallVector shape(rank, mlir::ShapedType::kDynamic); + llvm::SmallVector bounds(rank, mlir::ShapedType::kDynamic); + for (int64_t dim = 0; dim < rank; ++dim) { + int64_t dim_size = xla_ty.dimensions(dim); + if (xla_ty.is_dynamic_dimension(dim)) { + bounds[dim] = dim_size; + is_dynamic = true; + } else { + shape[dim] = dim_size; + } + } + using mlir::mhlo::TypeExtensionsAttr; + mlir::Attribute encoding; + if (is_dynamic) { + encoding = TypeExtensionsAttr::get(builder.getContext(), bounds); + } + + using mlir::sparse_tensor::SparseTensorEncodingAttr; + // TODO(b/238903065): We don't yet support bounded dynamism shapes and + // sparsity at the same time, as we can currently only have one `encoding` on + // a RankedTensorType, and we don't currently have a meet of + // SparseTensorEncodingAttr and TypeExtensionsAttr (which holds bounds). + // + // For example, we wouldn't be able to represent the xla type + // `f32[4,<=4]{1,0:D(D,C)}`. + if (xla_ty.has_layout()) { + auto layout = xla_ty.layout(); + if (LayoutUtil::IsSparse(layout)) { + if (is_dynamic) + return Unimplemented( + "MHLO doesn't support bounded dynamic shapes for sparse tensors"); + llvm::SmallVector dlts; + for (size_t i = 0, e = layout.dim_level_types().size(); i < e; ++i) { + auto dlt = layout.dim_level_types()[i]; + bool ordered = + i < layout.dim_ordered().size() ? layout.dim_ordered()[i] : true; + bool unique = + i < layout.dim_unique().size() ? layout.dim_unique()[i] : true; + switch (dlt) { + case DimLevelType::DIM_DENSE: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::Dense, ordered, unique)); + break; + case DimLevelType::DIM_COMPRESSED: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::Compressed, ordered, unique)); + break; + case DimLevelType::DIM_SINGLETON: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::Singleton, ordered, unique)); + break; + case DimLevelType::DIM_LOOSE_COMPRESSED: + dlts.push_back(*mlir::sparse_tensor::buildLevelType( + mlir::sparse_tensor::LevelFormat::LooseCompressed, ordered, + unique)); + break; + default: + return InvalidArgument("Unknown DimLevelType from HLO"); + } + } + auto ordering = layout.minor_to_major(); + llvm::SmallVector major_to_minor = {ordering.rbegin(), + ordering.rend()}; + auto id_map = mlir::AffineMap::getPermutationMap(major_to_minor, + builder.getContext()); + // TODO(atondwal): support sizes other than 32 when XLA does + encoding = SparseTensorEncodingAttr::get( + builder.getContext(), dlts, id_map, mlir::AffineMap(), 32, 32); + } + } + return TypeT::get(shape, element_type_or.value(), encoding); +} + +StatusOr ConvertTensorShapeToMemRefType( + const Shape& shape, mlir::Builder builder); + +template <> +inline StatusOr ConvertTensorShapeToType( + const Shape& shape, mlir::Builder builder) { + if (shape.is_dynamic()) { + return FailedPrecondition( // NOLINT + "MemRefType don't support dynamic shapes"); + } + return ConvertTensorShapeToMemRefType(shape, builder); +} + +// Converts the given XLA shape to the template MLIR type. +template +static StatusOr ConvertShapeToType(const Shape& shape, + mlir::Builder builder) { + if (shape.IsTuple()) { + llvm::SmallVector contents; + contents.reserve(shape.tuple_shapes_size()); + for (const auto& subtype : shape.tuple_shapes()) { + TF_ASSIGN_OR_RETURN(auto mlir_subtype, + ConvertShapeToType(subtype, builder)); + contents.push_back(mlir_subtype); + } + return builder.getTupleType(contents); + } + if (shape.IsToken()) { + return mlir::mhlo::TokenType::get(builder.getContext()); + } + return ConvertTensorShapeToType(shape, builder); +} + +::xla::StatusOr<::xla::HloOpcode> MhloToHloOpcode(mlir::Operation* op); + +} // namespace xla + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_HLO_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/location_importer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/location_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..1cfc4ab39bfde89d19fbcb28de3a4fc3b785d442 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/location_importer.h @@ -0,0 +1,33 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_LOCATION_IMPORTER_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_LOCATION_IMPORTER_H_ + +#include "mlir/IR/Location.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" + +namespace mlir { +namespace mhlo { + +// Returns an MLIR Location generated from HLO Instruction. Uses instruction +// metadata if present or instruction name. +mlir::Location GenerateInstructionLocation( + const xla::HloInstruction* instruction, mlir::MLIRContext* context); + +} // namespace mhlo +} // namespace mlir + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_LOCATION_IMPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/stack_location_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/stack_location_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..298f651ad86531da732e9c0ab252d11f8c4cecde --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/hlo_to_mhlo/stack_location_utils.h @@ -0,0 +1,34 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_HLO_TO_MHLO_STACK_LOCATION_UTILS_H_ +#define XLA_TRANSLATE_HLO_TO_MHLO_STACK_LOCATION_UTILS_H_ + +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "xla/hlo/ir/hlo_module.h" +#include "xla/service/hlo.pb.h" + +namespace mlir { +namespace mhlo { +// Construct MLIR location from frame index. +// Returns unknown location if frame is not presented. +mlir::Location GetLocationFromFrameIndex(int frame_id, mlir::Builder &builder, + const xla::HloModule *hlo_module); + +} // namespace mhlo +} // namespace mlir + +#endif // XLA_TRANSLATE_HLO_TO_MHLO_STACK_LOCATION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/attribute_exporter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/attribute_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..3d58247b6d631807c76dbb810eecb8535df18298 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/attribute_exporter.h @@ -0,0 +1,77 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_ATTRIBUTE_EXPORTER_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_ATTRIBUTE_EXPORTER_H_ + +#include + +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape_util.h" +#include "xla/statusor.h" +#include "xla/stream_executor/dnn.h" +#include "xla/types.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Converts the conv dimensions attribute to XLA HLO. +ConvolutionDimensionNumbers ConvertConvDimensionNumbers( + mlir::mhlo::ConvDimensionNumbersAttr input); + +StatusOr ConvertConvActivationMode( + mlir::lmhlo_gpu::Activation input); + +StatusOr> ConvertReplicaGroups( + mlir::DenseIntElementsAttr input); + +// Convert a (N, 2) dense attribute to a list of tuples. This is the way padding +// and source-target pairs are defined in HLO. +StatusOr>> ConvertNx2Attribute( + std::optional optional_attr); + +StatusOr ConvertFftType(llvm::StringRef type_string); +StatusOr ConvertTranspose( + llvm::StringRef transpose_string); + +StatusOr ConvertCustomCallSchedule( + mlir::mhlo::CustomCallSchedule schedule); + +StatusOr ConvertCustomCallApiVersion( + mlir::mhlo::CustomCallApiVersion api_version); + +StatusOr>>> +ConvertOutputOperandAliasing(mlir::ArrayAttr aliasArrayAttr); + +// Returns an OpSharding that represents the result of parsing the given string: +// first, as serialized protobuf, and then as prettyprinted representation. +// Will fail if both attempts at parsing failed. +std::optional ConvertSharding(mlir::StringRef sharding); + +DotDimensionNumbers ConvertDotDimensionNumbers( + mlir::mhlo::DotDimensionNumbersAttr input); + +DotDimensionNumbers ConvertDotDimensionNumbers( + absl::Span lhs_batch, absl::Span lhs_contract, + absl::Span rhs_batch, + absl::Span rhs_contract); + +StatusOr> ConvertMlirArrayAttrToInt64Array( + const mlir::ArrayAttr& array); +} // namespace xla +#endif // XLA_TRANSLATE_MHLO_TO_HLO_ATTRIBUTE_EXPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/layout_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/layout_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f8f175ba282c476251b8c1d7873897fd0fcc2937 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/layout_util.h @@ -0,0 +1,84 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Utilities for working with XLA layout and shapes. + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_LAYOUT_UTIL_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_LAYOUT_UTIL_H_ + +#include +#include + +#include "xla/client/xla_builder.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/shape.h" +#include "xla/statusor.h" +#include "xla/xla_data.pb.h" + +namespace mlir { + +// XLA Layout preferences. Currently, when it comes to TPU, there are two +// primary layout choices for any XLA argumetns (parameter or resource): (1) +// CompactChunkPadded and (2) Linear. CompactChunkPadded is the native TPU +// layout while Linear is native host (CPU) layout. +// This enum allows the caller of XLA to progogate layout preference to the XLA +// compiler. +// kNoPreference: the generic layout where the XLA compiler has the freedom +// to assign any layout. +// kTpuPreferCompactChunkPaddedLayout: use native TPU layout on TPU. +// kTpuPreferLinearLayout: use native CPU layout on TPU. The compiler may +// insert transformation TPU kernels. +// As the layout of any argument will change from a native host layout to a +// native TPU layout either on host or on device, XLA compiler and TPU runtime +// must be in coordination to transform the parameters in a consistent way. +enum class XlaLayoutPreference { + kNoPreference = 0, + kTpuPreferCompactChunkPaddedLayout = 1, + kTpuPreferLinearLayout = 2 +}; + +// The following defines the layout preference of an xla tensor. +// The return value of LayoutPreferenceFn can be used in +// ShapeRepresentationFn. +typedef std::function( + const xla::Shape& shape)> + LayoutPreferenceFn; + +typedef std::function( + const xla::Shape& shape, bool fast_mem, + XlaLayoutPreference layout_preference)> + ShapeRepresentationFn; + +// Return a LayoutPreferenceFn that always uses kNoPreference layout. +LayoutPreferenceFn UseNoPreferenceLayoutFn(); + +// Rewrites the layout of xla_shape if there is tiled sharding. +xla::Status RewriteLayoutWithShardedShape( + const std::optional& sharding, bool use_fast_memory, + const LayoutPreferenceFn& layout_preference_fn, + const ShapeRepresentationFn& shape_representation_fn, + xla::Shape* xla_shape); + +// Adds reshapes to fix the layout of an output, if a shape_representation_fn or +// sharding is present. +xla::StatusOr ReshapeWithCorrectRepresentationAndSharding( + xla::XlaBuilder* builder, xla::XlaOp original, xla::Shape original_shape, + const LayoutPreferenceFn& layout_preference_fn, + const ShapeRepresentationFn& shape_representation_fn, + std::optional sharding, bool fast_mem); + +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_LAYOUT_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/location_exporter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/location_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..69efa6dbc4f477d705b34f9b2a581cc55237cfd3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/location_exporter.h @@ -0,0 +1,44 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_LOCATION_EXPORTER_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_LOCATION_EXPORTER_H_ + +#include + +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "xla/translate/mhlo_to_hlo/stack_frame_index_builder.h" +#include "xla/xla_data.pb.h" + +namespace mlir { +namespace mhlo { + +// Returns a OpMetadata proto based on the location of the op. If the location +// is unknown, an empty proto is returned. `op_name` are populated with the op +// location (converted). FileLineColLoc locations are populated by taking the +// file name and line number, and populating `source_file` and `source_line` +// respectively. +xla::OpMetadata CreateOpMetadataFromLocation( + Operation* op, StackFrameIndexBuilder* frame_index_builder); + +// Returns a name that can be used for debugging purposes, e.g., naming +// variable names in generated IR or producing logging output. +std::string GetDebugNameFromLocation(Location location); + +} // namespace mhlo +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_LOCATION_EXPORTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h new file mode 100644 index 0000000000000000000000000000000000000000..5cbdfdd398dabc4e46fe51d67d55bf45f874d773 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/mlir_hlo_to_hlo.h @@ -0,0 +1,72 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_MLIR_HLO_TO_HLO_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_MLIR_HLO_TO_HLO_H_ + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "xla/client/xla_builder.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/translate/mhlo_to_hlo/layout_util.h" + +namespace mlir { + +struct MlirToHloConversionOptions { + // Best-effort propagation of the layouts. These layouts serve as performance + // hints to the backend. + // + // Note that non-array shapes are not carrying layouts, and users have to + // figure out the proper layouts of them through context. This is one of the + // reasons why the attribute-based solution is temporary. + // + // TODO(timshen): Investigate the necessity of having layouts in MHLO. + bool propagate_layouts = false; + + // Propagate the source and result layouts from mhlo bitcast op into the + // backend config for the bitcast. This is required for XLA:GPU backend to + // use elemental IR emitters for fused bitcasts without propagating layouts. + bool propagate_bitcast_layouts_to_backend_config = false; + + LayoutPreferenceFn layout_preference_fn; + ShapeRepresentationFn shape_representation_fn; +}; + +// Converts a MLIR module in HLO dialect into a HloModuleProto. If +// use_tuple_args is set, then the entry computations's arguments are converted +// to a tuple and passed as a single parameter. +// Similarly, if return tuple is true, then the entry function's return values +// are converted to a tuple even when there is only a single return value. +// Multiple return values are always converted to a tuple and returned as a +// single value. +xla::Status ConvertMlirHloToHlo(mlir::ModuleOp module, + ::xla::HloProto* hlo_proto, bool use_tuple_args, + bool return_tuple, + MlirToHloConversionOptions options = {}); + +// Transforms a Block into HLO, where the HLO is represented as calls into an +// XlaBuilder. Callee functions are allowed in the Block's ancestor ModuleOp. +// xla_params are inputs to block. returns are the returned XlaOps. +xla::Status BuildHloFromMlirHlo(mlir::Block& block, xla::XlaBuilder& builder, + llvm::ArrayRef xla_params, + std::vector& returns, + MlirToHloConversionOptions options = {}); + +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_MLIR_HLO_TO_HLO_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..804795eb83f62e5725a863076646136749820df6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/stack_frame_index_builder.h @@ -0,0 +1,48 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_STACK_FRAME_INDEX_BUILDER_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_STACK_FRAME_INDEX_BUILDER_H_ + +#include +#include +#include + +#include "mlir/IR/Location.h" // from @llvm-project +#include "xla/service/hlo.pb.h" + +namespace mlir { +class StackFrameIndexBuilder { + public: + constexpr static int kInvalidIndex = 0; + + xla::StackFrameIndexProto Build() const; + + int AddCallStackAndGetFirstFrameId(const mlir::Location &root_loc); + + private: + int AddStackFrameLocation(const mlir::NameLoc &name_location, + int parent_frame_id); + + xla::StackFrameIndexProto indexes_; + + std::map function_name_to_id_; + std::map file_name_to_id_; + std::map, int> file_location_to_id_; + std::map, int> frame_to_id_; +}; +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_STACK_FRAME_INDEX_BUILDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/type_to_shape.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/type_to_shape.h new file mode 100644 index 0000000000000000000000000000000000000000..39bfb6c5b409185a0a3a198f1c8052b99d97573c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_hlo/type_to_shape.h @@ -0,0 +1,35 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_MHLO_TO_HLO_TYPE_TO_SHAPE_H_ +#define XLA_TRANSLATE_MHLO_TO_HLO_TYPE_TO_SHAPE_H_ + +#include "llvm/ADT/STLExtras.h" +#include "mlir/IR/Types.h" // from @llvm-project +#include "xla/shape.h" +#include "xla/xla_data.pb.h" + +namespace xla { + +// Returns a XLA Shape equivalent of a MLIR Type, else returns empty shape. +Shape TypeToShape(mlir::Type type); + +// Returns a XLA PrimitiveType equivalent of a MLIR Type that represents a +// primitive type (e.g., i8, f32), else returns PRIMITIVE_TYPE_INVALID. +PrimitiveType TypeToPrimitiveType(mlir::Type type); + +} // namespace xla + +#endif // XLA_TRANSLATE_MHLO_TO_HLO_TYPE_TO_SHAPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h new file mode 100644 index 0000000000000000000000000000000000000000..c355cb132fa63d0af79cc3e5fedc5de0f226bc61 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/compiler/xla/translate/mhlo_to_lhlo_with_xla/mhlo_to_lhlo_with_xla.h @@ -0,0 +1,337 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef XLA_TRANSLATE_MHLO_TO_LHLO_WITH_XLA_MHLO_TO_LHLO_WITH_XLA_H_ +#define XLA_TRANSLATE_MHLO_TO_LHLO_WITH_XLA_MHLO_TO_LHLO_WITH_XLA_H_ + +#include +#include +#include +#include + +#include "absl/types/optional.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/ir/hlo_instructions.h" +#include "xla/mlir_hlo/lhlo/IR/lhlo_ops.h" +#include "xla/mlir_hlo/lhlo_gpu/IR/lhlo_gpu_ops.h" +#include "xla/service/buffer_assignment.h" +#include "xla/shape_util.h" +#include "tsl/platform/status.h" +#include "tsl/platform/statusor.h" + +namespace mlir { + +// This class will process an HloModule with the supplied BufferAssignment and +// populate the MLIR ModuleOp with the computation converted in the LHLO +// dialect. +class LhloDialectEmitter : public xla::ConstDfsHloVisitorWithDefault { + public: + // Initializes internal data structures. It must be called before calling any + // of the visitors. + tsl::Status Initialize(); + + LhloDialectEmitter(const xla::BufferAssignment& assignment, + const xla::HloComputation& computation, ModuleOp module) + : assignment_(assignment), + computation_(computation), + module_(module), + symbol_table_(module), + builder_(module.getContext()), + i8_type_(builder_.getIntegerType(8)) {} + + tsl::StatusOr EmitOp(const xla::HloInstruction* instr); + + static tsl::StatusOr + GetScatterDimensionNumbers(const xla::HloInstruction* instr, + mlir::MLIRContext* context); + + absl::flat_hash_map + ConsumeLhloToHloMap() { + return std::move(lhlo_to_hlo_); + } + + private: + tsl::StatusOr EmitSortOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitFusionOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitScatterOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitSelectAndScatterOp( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitCustomCallOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitCholesky( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitGemm( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitCublasLtMatmul( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitCublasLtMatmulF8( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitDnnConvolution( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitDnnConvolutionReorderVectorized( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitDnnBatchNorm( + const xla::HloCustomCallInstruction* custom_call); + xla::StatusOr EmitDnnfMHA( + const xla::HloCustomCallInstruction* custom_call); + xla::StatusOr EmitDnnfMHABackward( + const xla::HloCustomCallInstruction* custom_call); + tsl::StatusOr EmitConstant( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitInfeedOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitOutfeedOp( + const xla::HloInstruction* instr); + + template + tsl::StatusOr EmitDoneOp(const xla::HloInstruction* instr); + + tsl::StatusOr EmitAllToAllStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllToAllDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllGatherStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllGatherDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllReduceStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAllReduceDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAsyncStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitAsyncDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitReduceScatterStartOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitReduceScatterDoneOp( + const xla::HloInstruction* instr); + tsl::StatusOr + EmitCollectivePermuteStartOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitCollectivePermuteDoneOp( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitRngGetAndUpdateStateOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitFftOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitTriangularSolveOp( + const xla::HloInstruction* instr); + tsl::StatusOr EmitBitcast(const xla::HloInstruction* instr); + + tsl::StatusOr EmitCaseOp(const xla::HloInstruction* instr); + + tsl::StatusOr EmitWhileOp(const xla::HloInstruction* instr); + + tsl::StatusOr EmitSendOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitSendDoneOp( + const xla::HloInstruction* instr); + + tsl::StatusOr EmitRecvOp(const xla::HloInstruction* instr); + tsl::StatusOr EmitRecvDoneOp( + const xla::HloInstruction* instr); + + tsl::Status ImportAsLmhloRegion(xla::HloComputation* computation, + mlir::Region* region); + + // Since LMHLO dialect does not define token types, this enum controls how + // token operand/results from XLA:HLO are lowered to MLIR. + enum class TokenLoweringMode { + kFailToLower, // Fail lowering if token inputs are encountered. + kUseNull, // Use a null Value in the operand list for each token. + // kSkip, // Skip any token inputs or outputs (not yet needed) + }; + + // Create LHLO operation operands given an XLA HLO instruction. By default, + // all XLA HLO operands and results are converted to MLIR and appended to + // `operands`. If `num_operands` is specified, only the first `num_operand` + // operands of the instruction are converted to MLIR. The function returns the + // actual number of operands and results generated for MLIR in `num_arguments` + // and `num_results`. + tsl::Status CreateOperands(const xla::HloInstruction* instr, + std::optional num_operands, + TokenLoweringMode token_mode, + SmallVectorImpl& operands, + size_t& num_arguments, size_t& num_results); + + template + tsl::StatusOr CreateOpWithoutAttrs( + const xla::HloInstruction* instr, + std::optional num_operands = std::nullopt) { + size_t unused; + return CreateOpWithoutAttrs(instr, unused, unused, num_operands); + } + + template + tsl::StatusOr CreateOpWithoutAttrs( + const xla::HloInstruction* instr, size_t& num_arguments, + size_t& num_results, std::optional num_operands = std::nullopt); + + template + OpType CreateOpWithoutAttrs(const xla::HloInstruction* instr, + ValueRange operands); + + template + DenseIntElementsAttr GetI64DenseElementsAttr(const T& container) { + return builder_.getI64TensorAttr( + {container.data(), static_cast(container.size())}); + } + + DenseIntElementsAttr GetWindowElements( + const xla::Window& window, + std::function getter) { + llvm::SmallVector elements; + elements.reserve(window.dimensions_size()); + for (const xla::WindowDimension& dim : window.dimensions()) { + elements.push_back(getter(dim)); + } + return GetI64DenseElementsAttr(elements); + } + + static mlir::DenseIntElementsAttr GetLayoutAttribute( + const xla::Layout& layout, Builder* builder); + + tsl::Status DefaultAction(const xla::HloInstruction* instr) final; + + // Computation parameters don't need any specific handling when they are + // visited, they are already processed when we enter a new computation. + tsl::Status HandleParameter(const xla::HloInstruction* instr) final { + return ::tsl::OkStatus(); + } + + // Helper function that recursively visits the tuple structure in + // `current_shape`, and reconstruct a matching lmhlo::TupleOp. + // Each leaf node is converted to an std.view op with corresponding offsets. + // If no tuple presents, it simply returns a view of the buffer. + tsl::Status GetOrCreateViewImpl(const xla::HloInstruction* instr, + const xla::Shape& current_shape, + xla::ShapeIndex* current_shape_index, + SmallVectorImpl* values, + TokenLoweringMode token_mode); + + // Helper function to create view/tuple of views to a buffer for a given + // instruction result. `result_subset` can be used to for instructions that + // have a tuple result and MLIR conversion needs to convert only one of the + // tuple elements. Note that if needed, this can be extended to take a list of + // ShapeIndex values in case we need finer control on what elements of the + // output tuple to be converted to MLIR. + tsl::Status GetOrCreateView( + const xla::HloInstruction* instr, SmallVectorImpl* values, + const xla::ShapeIndex& result_subset = {}, + TokenLoweringMode token_mode = TokenLoweringMode::kFailToLower); + + tsl::StatusOr GetOrCreateArrayView( + const xla::HloInstruction* instr, const xla::Shape& current_shape, + const xla::ShapeIndex& current_shape_index); + + tsl::StatusOr RewriteFusionOperand(const xla::HloInstruction* root, + const xla::Shape& shape, + xla::ShapeIndex* shape_index, + OpBuilder* b, Location loc); + + // Return an MLIR location for an HLO instruction. + Location getLocation(const xla::HloInstruction* inst) { + return NameLoc::get(builder_.getStringAttr(inst->name())); + } + + // This map provides access to MLIR buffers for each HLO buffer allocation. + // The MLIR buffers are all `memref<{size}xi8>` and correspond to function + // parameters. It is populated at the beginning of the processing with all + // the buffer allocations and is unchanged afterward. Every HLOInstruction + // is using a "slice" of the buffer allocation and providing shape, layout, + // and Dtype. An MLIR view is used separately to model slices into the + // allocations (see below). + llvm::DenseMap allocations_; + + // This map provides access to MLIR buffers constructed from memref arguments + // (allocations) using memref.view operation at the given offset (defined by + // slice) and result type (defined by shape). By using this cache we guarantee + // that we have a unique memref.view operation corresponding to each + // allocation slice. + absl::flat_hash_map, + Value> + allocation_slices_; + + // This map provides access to MLIR buffers for each HLO instruction, keyed + // instruction identity. A slice is contained in a BufferAllocation, and has + // an offset and a size. + // + // As for why we don't use HloInstruction*, see GetOrCreateView(), but + // mostly we want to leverage better of the aliased buffers. + // + // If the HloInstruction is a tuple, all leaf nodes are stored flattened. + // Otherwise, there will be a single buffer. + // + // An MLIR buffer is either an input parameter, or a ViewOp in the case + // where the slice is only part of its allocation. + // + // `instr_slices_` is populated lazily in the `GetOrCreateView()` helper as we + // process every instruction. + absl::flat_hash_map, + Value> + instr_slices_; + + // The BufferAssignment computed by XLA ahead of time. + const xla::BufferAssignment& assignment_; + + // The HLO module that will be converted. + const xla::HloComputation& computation_; + + // This is the MLIR module in which a function will be created for every HLO + // computation. + ModuleOp module_; + + // SymbolTable associated with the module. New functions should be added using + // this to avoid name conflicts. + mlir::SymbolTable symbol_table_; + + // The builder keeps track of the current insertion point in the MLIR + // module. + OpBuilder builder_; + // Convenient "cached" access to this widely used MLIR type (i8). + Type i8_type_; + + // Map ops returning tokens to their output (async collectives start ops, and + // point-to-point communication ops), to connect the correct done op. + absl::flat_hash_map ret_tokens_; + + // Maps each LHLO op created directly by this emitter to the corresponding HLO + // instruction. + // Note: this does not contain ops that are inside the bodies of fusions. + absl::flat_hash_map + lhlo_to_hlo_; +}; + +// Populate the MLIR `module` with the computation from the `hlo_module` using +// the provided buffer `assignment`. The returned `Status` indicates success +// or failure in the conversion. +// `lhlo_to_hlo_map`, if non-null, is populated with a mapping from generated +// top-level MLIR operations to the original HLO instructions. "top-level" means +// that ops inside the bodies of fusions are not included (but all fusions are). +tsl::Status HloToLhloModule( + const xla::BufferAssignment& assignment, const xla::HloModule& hlo_module, + ModuleOp module, + absl::flat_hash_map* + lhlo_to_hlo_map = nullptr); + +OwningOpRef HloTextToLhloTranslateFunction( + llvm::StringRef input, MLIRContext* context); + +} // namespace mlir + +#endif // XLA_TRANSLATE_MHLO_TO_LHLO_WITH_XLA_MHLO_TO_LHLO_WITH_XLA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/activity_watcher/activity.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/activity_watcher/activity.h new file mode 100644 index 0000000000000000000000000000000000000000..334a58d45190baf7d659b6809a8a2a6562b57401 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/activity_watcher/activity.h @@ -0,0 +1,186 @@ +/* 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_ACTIVITY_WATCHER_ACTIVITY_H_ +#define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tsl/platform/macros.h" +#include "tsl/platform/types.h" + +namespace tsl { +class CoordinationServiceAgent; +} + +namespace tensorflow { + +namespace activity_watcher { + +using ActivityId = tsl::uint64; +constexpr ActivityId kActivityNotRecorded = 0; +constexpr int kWatcherDisabled = 0; + +enum ActivityCategory { + kCollective = 0, + kRemoteFunction = 1, + kMisc = 2, + kDatasetOp = 3, + kTpuOp = 4, + kRendezvous = 5, +}; + +static tsl::string ToString(ActivityCategory category) { + switch (category) { + case ActivityCategory::kCollective: + return "Collective"; + case ActivityCategory::kRemoteFunction: + return "Remote Function"; + case ActivityCategory::kMisc: + return "Miscellaneous"; + case ActivityCategory::kDatasetOp: + return "Dataset Op"; + case ActivityCategory::kTpuOp: + return "TPU Op"; + case ActivityCategory::kRendezvous: + return "Rendezvous"; + } +} + +// An activity to be recorded. +struct Activity { + using Attributes = absl::flat_hash_map; + // A human readable title of the activity. + tsl::string title; + // The category of the activity. + ActivityCategory category = ActivityCategory::kMisc; + // Key/value pairs that are attached to the activity. + Attributes attributes; + Activity() = default; + Activity(tsl::string title, ActivityCategory category) + : title(std::move(title)), category(category) {} + Activity(tsl::string title, ActivityCategory category, Attributes attributes) + : title(std::move(title)), + category(category), + attributes(std::move(attributes)) {} +}; + +// Enable activity wathcer to send own workers activities to coordination +// service and also fetch all workers' activities. +void MaybeEnableMultiWorkersWatching(tsl::CoordinationServiceAgent* agent); + +namespace tfw_internal { + +#if defined(TF_ENABLE_ACTIVITY_WATCHER) + +// Records an activity start without checking whether the watcher is enabled. +ActivityId RecordActivityStart(std::unique_ptr activity); +// Records an activity end without checking whether the activity_id is valid. +void RecordActivityEnd(ActivityId activity_id); + +TF_EXPORT extern std::atomic g_watcher_level; + +// Returns whether the activitity watcher is enabled. +inline bool WatcherEnabled(int level = 1) { + return g_watcher_level.load(std::memory_order_acquire) >= level; +} + +#endif + +// NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not +// available in Android NDK. +template +struct is_invocable_r + : std::is_constructible< + std::function, + std::reference_wrapper::type>> {}; + +} // namespace tfw_internal + +template +constexpr bool is_activity_generator = + tfw_internal::is_invocable_r, F>::value; + +// Records an activity explicitly. Useful when the start and end of an activity +// happen in different threads. Generates the Activity only if activity +// watching is enabled, useful for avoiding expensive operations when activity +// watching is disabled. +// Example Usage: +// auto aid = ActivityStart([&]() { +// return std::make_unique( +// op_name, category, +// Activity::Attributes{{"key1", value1}, {"key2", value2}}); +// }, /*level=*/2); +// DoSomething(); +// ActivityEnd(aid); +template < + typename ActivityGenerator, + std::enable_if_t, bool> = true> +inline ActivityId ActivityStart(ActivityGenerator&& gen, int level = 1) { +#if defined(TF_ENABLE_ACTIVITY_WATCHER) + if (TF_PREDICT_FALSE(tfw_internal::WatcherEnabled(level))) { + return tfw_internal::RecordActivityStart( + std::forward(gen)()); + } +#endif + return kActivityNotRecorded; +} + +inline void ActivityEnd(ActivityId id) { +#if defined(TF_ENABLE_ACTIVITY_WATCHER) + if (TF_PREDICT_FALSE(id != kActivityNotRecorded)) { + tfw_internal::RecordActivityEnd(id); + } +#endif +} + +// ActivityScope marks a scope as an activity and record it with a global +// ActivityRecorder. +// Example Usage: +// { +// ActivityScope activity_scope([&]() { +// return std::make_unique( +// op_name, ActivityCategory::kMisc, +// Activity::Attributes{{"key1", value1}, {"key2", value2}}); +// }, /*level=*/2); +// DoSomething(); +// } +class ActivityScope { + public: + template < + typename ActivityGenerator, + std::enable_if_t, bool> = true> + explicit ActivityScope(ActivityGenerator&& gen, int level = 1) { + activity_id_ = ActivityStart(std::forward(gen), level); + } + ActivityScope(ActivityScope&& activity) { + activity_id_ = activity.activity_id_; + activity.activity_id_ = kActivityNotRecorded; + } + ~ActivityScope() { ActivityEnd(activity_id_); } + + private: + ActivityId activity_id_; + ActivityScope(const ActivityScope&) = delete; + void operator=(const ActivityScope&) = delete; +}; + +} // namespace activity_watcher +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/activity_watcher/activity_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/activity_watcher/activity_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..745b1c88565ed5e6a8dbb2a7410693b3986cca0e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/activity_watcher/activity_utils.h @@ -0,0 +1,37 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_UTILS_H_ +#define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_UTILS_H_ + +#include + +#include "tensorflow/core/activity_watcher/activity.h" + +namespace tensorflow { + +class OpKernelContext; + +namespace activity_watcher { + +// A convenient way to create an activity. Writes OpKernelContext information +// and given attributes to a new activity and returns. +std::unique_ptr ActivityFromContext( + OpKernelContext* context, tsl::string name, ActivityCategory category, + Activity::Attributes additional_attributes = Activity::Attributes()); + +} // namespace activity_watcher +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/all_to_all.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/all_to_all.h new file mode 100644 index 0000000000000000000000000000000000000000..0c9716da6a108b876fd5fd619b9eddbafc593bce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/all_to_all.h @@ -0,0 +1,69 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_ALL_TO_ALL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_ALL_TO_ALL_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/base_collective_executor.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device.h" + +namespace tensorflow { + +// Implementation of collective all-to-all. +class AllToAll : public CollectiveImplementationInterface { + public: + AllToAll(); + + void Run(StatusCallback done) override; + + Status InitializeCollectiveParams(CollectiveParams* col_params) override { + return OkStatus(); + } + + // Initializes members of CollectiveContext not yet initialized, i.e. device + // and device_locality. Also saves the CollectiveContext in this object. + Status InitializeCollectiveContext( + std::shared_ptr col_ctx) override; + + private: + std::shared_ptr col_ctx_; + const CollectiveParams* col_params_; // Not owned + std::vector input_chunks_; + Tensor output_buffer_; + std::vector output_chunks_; + StatusCallback done_; + mutex mu_; + Status status_ TF_GUARDED_BY(mu_); + int counter_ TF_GUARDED_BY(mu_); + + void DispatchSend(int src_rank, int target_rank, const Tensor* tensor, + const StatusCallback& done); + + void DispatchRecv(int src_rank, int target_rank, Tensor* tensor, + const StatusCallback& done); + + // Atomically increments counter_ by one for sending, one for receiving. + // Invokes done when counter_ reaches 2. + // The purpose of checking counter_ is to ensure that done_ is called once. + StatusCallback CheckCounterAndCallDone(); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_ALL_TO_ALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/allocator_retry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/allocator_retry.h new file mode 100644 index 0000000000000000000000000000000000000000..44ff25aee27aa44ed41a52b0d68335d5016992f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/allocator_retry.h @@ -0,0 +1,28 @@ +/* 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_COMMON_RUNTIME_ALLOCATOR_RETRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_ALLOCATOR_RETRY_H_ + +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/framework/allocator_retry.h" + +namespace tensorflow { +using tsl::AllocatorRetry; // NOLINT +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_ALLOCATOR_RETRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/arg_ret_placement.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/arg_ret_placement.h new file mode 100644 index 0000000000000000000000000000000000000000..4f00d18e3bb6ca801e7281d85c74d53efd009f6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/arg_ret_placement.h @@ -0,0 +1,158 @@ +/* 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_COMMON_RUNTIME_ARG_RET_PLACEMENT_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_ARG_RET_PLACEMENT_H_ + +#include +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow::full_type { + +// Set the contents of memory_types for args (inputs to functions, "_Arg" ops) +// based on dtype. Raises an error if an int32 arg does not have +// expected full_type information. If an error raised about bad full +// time information causes a breakage, changing `SetMemoryTypeForArgs` to +// `WeakSetMemoryTypeForArgs` is a possible work around. +Status SetMemoryTypeForArgs(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + MemoryTypeVector& memory_types); + +// TODO(b/258849883) Delete the `Weak...` versions of these functions once +// everything is working with the version without `Weak`. + +// Set the contents of memory_types for args (inputs to functions, "_Arg" ops) +// based on dtype. Logging of warnings if an int32 arg does not have +// expected full_type information can be enabled. +Status WeakSetMemoryTypeForArgs(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + MemoryTypeVector& memory_types); + +// Set the contents of memory_types for rets (outputs from functions, "_Retval" +// ops) based on dtype. Raises an error if an int32 ret does not have +// expected full_type information (i.e. if the source of the input to the ret +// does not have expected full type information). If an error raised about bad +// full time information causes a breakage, changing `SetMemoryTypeForRets` to +// `WeakSetMemoryTypeForRets` is a possible work around. +Status SetMemoryTypeForRets(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + MemoryTypeVector& memory_types); + +// Set the contents of memory_types for rets (outputs from functions, "_Retval" +// ops) based on dtype. Logging of warnings if an int32 ret does not have +// expected full_type information (i.e. if the source of the input to the ret +// does not have expected full type information) can be enabled. +Status WeakSetMemoryTypeForRets(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + MemoryTypeVector& memory_types); + +// Set the contents of alloc_attrs for args (inputs to functions, "_Arg" ops) +// based on dtype. Raises an error if an int32 arg does not have +// expected full_type information. If an error raised about bad full +// time information causes a breakage, changing `SetAllocAttrsForArgs` to +// `WeakSetAllocAttrsForArgs` is a possible work around. +Status SetAllocAttrsForArgs(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for args (inputs to functions, "_Arg" ops) +// based on dtype. Logging of warnings if an int32 arg does not have +// expected full_type information can be enabled. +Status WeakSetAllocAttrsForArgs(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for rets (outputs from functions, "_Retval" +// ops) based on dtype. Raises an error if an int32 ret does not have +// expected full_type information (i.e. if the source of the input to the ret +// does not have expected full type information). If an error raised about bad +// full time information causes a breakage, changing `SetAllocAttrsForRets` to +// `WeakSetAllocAttrsForRets` is a possible work around. +Status SetAllocAttrsForRets(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for rets (outputs from functions, "_Retval" +// ops) based on dtype. Logging of warnings if an int32 ret does not have +// expected full_type information (i.e. if the source of the input to the ret +// does not have expected full type information) can be enabled. +Status WeakSetAllocAttrsForRets(const gtl::InlinedVector& nodes, + const DataTypeVector& dtypes, + std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for args (inputs to functions, "_Arg" ops) +// for a single device funtion based on dtype. Raises an error if an int32 arg +// does not have expected full_type information. If an error raised about bad +// full time information causes a breakage, changing +// `SingleDeviceSetAllocAttrsForArgs` to `WeakSingleDeviceSetAllocAttrsForArgs` +// is a possible work around. The DataType specified by the "T" attr of input +// nodes is used. +Status SingleDeviceSetAllocAttrsForArgs( + std::vector> arg_nodes, + bool ints_on_device, std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for args (inputs to functions, "_Arg" ops) +// for a single device based on dtype. Logging of warnings if an int32 arg does +// not have expected full_type information can be enabled. The DataType +// specified by the "T" attr of input nodes is used. +Status WeakSingleDeviceSetAllocAttrsForArgs( + std::vector> arg_nodes, + bool ints_on_device, std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for rets (outputs from functions, "_Retval" +// ops) for a single device based on dtype. Raises an error if an int32 ret does +// not have expected full_type information (i.e. if the source of the input to +// the ret does not have expected full type information). If an error raised +// about bad full time information causes a breakage, changing +// `SingleDeviceSetAllocAttrsForRets` to `WeakSingleDeviceSetAllocAttrsForRets` +// is a possible work around. The DataType specified by the "T" attr of input +// nodes is used. +Status SingleDeviceSetAllocAttrsForRets( + std::vector> ret_nodes, bool ints_on_device, + std::vector& alloc_attrs); + +// Set the contents of alloc_attrs for rets (outputs from functions, "_Retval" +// ops) for a single device based on dtype. Logging of warnings if an int32 ret +// does not have expected full_type information (i.e. if the source of the input +// to the ret does not have expected full type information) can be enabled. The +// DataType specified by the "T" attr of input nodes is used. +Status WeakSingleDeviceSetAllocAttrsForRets( + std::vector> ret_nodes, bool ints_on_device, + std::vector& alloc_attrs); + +// Given a FullTypeId, return the corresponding MemoryTypes (i.e. return +// HOST_MEMORY for TFT_SHAPE_TENSOR, DEVICE_MEMORY othersize). +MemoryType MemoryTypeFromFullTypeId(FullTypeId id); + +// Check that use_host_memory is true iff FT has type_id TFT_SHAPE_TENSOR +// and logging of a warning if not can be enabled. Returns true if check passes. +// Note the FT is expected to be the full type information for a tensor, not for +// the whole ouput of an op, i.e. it should not have an outer TFT_PRODUCT. +bool LogMemoryTypeMismatch(bool use_host_memory, const FullTypeDef& ft); + +// Check that use_host_memory is true iff FT has type_id TFT_SHAPE_TENSOR +// and raise an error if not. Note the FT is expected to be the full type +// information for a tensor, not for the whole ouput of an op, i.e. it should +// not have an outer TFT_PRODUCT. +Status CheckMemoryType(bool use_host_memory, const FullTypeDef& ft); + +} // namespace tensorflow::full_type + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_ARG_RET_PLACEMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/base_collective_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/base_collective_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..242b92b2e749f74a0223ff87e7058866d7b226b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/base_collective_executor.h @@ -0,0 +1,164 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_BASE_COLLECTIVE_EXECUTOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_BASE_COLLECTIVE_EXECUTOR_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/buf_rendezvous.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/platform/unbounded_work_queue.h" + +namespace tensorflow { +class CollectiveImplementation; +class DeviceMgr; +class Device; + +// Helper interface that aliases regular subfields of a Tensor as separate +// Tensors for in-place update. +class CollectiveAdapter { + public: + virtual ~CollectiveAdapter() {} + + // Move the backing tensor to 'output' with its original storage and + // shape. After this call this CollectiveAdapter object should be + // deleted immediately without calling any of its other methods. + virtual void ConsumeFinalValue(Tensor* output) = 0; + + // const access to entire intermediate value for debugging + virtual const Tensor& Value() const = 0; + + // Returns tensor for chunk i which aliases the backing buffer. + virtual Tensor ChunkAlias(int i) = 0; + + // Returns tensor allocated on the same device but with its own + // separate backing buffer. Will have same type and size as + // chunk i. + virtual Tensor TempChunk(int i) const = 0; + + // Bytes in chunk i + virtual int64_t ChunkBytes(int i) const = 0; + + // Generate a CPU RAM scalar tensor of the same DataType as the + // backing tensor with the given integer value. + virtual Tensor Scalar(int v) const = 0; + + // Generate a scalar tensor of same DataType and on the same device + // as the backing tensor. + virtual Tensor Scalar(Allocator* a, + const AllocationAttributes& attr) const = 0; + + // Debugging string describing buffer location + virtual string TBounds(const Tensor& t) const = 0; + + virtual string DebugString() const = 0; + + // Computes the number of elements per alias chunk tensor. + // + // A CHECK in tensor.cc expects that the memory buffer backing a + // Tensor will be aligned according to EIGEN_MAX_ALIGN_BYTES. To + // ensure that all chunk aliasing Tensors maintain this alignment we + // need to pick a chunk size that preserves it. Note than in extreme + // cases (impractical, but possible with very small tensors) one or + // more tail chunks can end up emptby. + static int64_t AlignedChunkElts(int64_t elt_bytes, int64_t total_elts, + int64_t num_chunks); +}; + +// Create a CollectiveAdaptor wrapping 'output', specialized to its +// data-type and shape. If align_chunks == true then chunk size may +// be larger than output->NumElements() / num_chunks and one or more +// of the suffix chunks may be empty. Chunks will be arranged to start +// and end on alignment boundaries. If align_chunks == false then +// output->NumElements() % num_chunks must be 0 and all chunks will +// have exactly the same size, ignoring alignment issues. +CollectiveAdapter* MakeCollectiveAdapter(Tensor* output, int num_chunks, + Allocator* allocator, + bool align_chunks = true); + +// Default implementation of CollectiveExecutor. Delegates the actual +// work of moving data to a class specialized for the operation type, +// arguments and device+interconnect topology. +class BaseCollectiveExecutor : public CollectiveExecutor { + public: + BaseCollectiveExecutor(CollectiveExecutorMgrInterface* cem, + CollectiveRemoteAccess* remote_access, int64_t step_id, + const DeviceMgr* dev_mgr, + std::shared_ptr work_queue) + : CollectiveExecutor(cem), + step_id_(step_id), + dev_mgr_(dev_mgr), + remote_access_(remote_access), + work_queue_(std::move(work_queue)) {} + + ~BaseCollectiveExecutor() override; + + void StartAbort(const Status& s) override TF_LOCKS_EXCLUDED(status_mu_); + + void ExecuteAsync(OpKernelContext* ctx, const CollectiveParams* col_params, + const string& exec_key, StatusCallback done) override; + + void CompleteParamsAsync(const DeviceAttributes& device, CollectiveParams* cp, + CancellationManager* cancel_mgr, + StatusCallback done) override; + + CollectiveRemoteAccess* remote_access() override { + return remote_access_.get(); + } + + void RunClosure(std::function closure) override { + work_queue_->Schedule(std::move(closure)); + } + + // If we need to enforce an ordering on any portion of collective + // implementation, and the ordering is encoded via attribute on the collective + // op, this function will block until all dependencies for this collective + // have completed. + void WaitForDependencies(const CollectiveParams& col_params) override; + // Record that this collective has completed the portion of the implementation + // that needs to be ordered wrt other collectives, to unblock any of its + // dependent ops. + void UnblockDependencies(const CollectiveParams& col_params) override; + + protected: + const int64_t step_id_; + const DeviceMgr* dev_mgr_; // Not owned. + std::unique_ptr remote_access_; + // Ownership of `work_queue_` is shared between `this` and + // `CollectiveExecutorMgr`. + std::shared_ptr work_queue_; + mutex launch_mu_; + condition_variable launch_cv_; + // collective instance key -> number of local devices for which NCCL ops have + // been launched. + std::unordered_map launched_ TF_GUARDED_BY(launch_mu_); + mutex status_mu_; + Status status_ TF_GUARDED_BY(status_mu_); + + private: + Status CreateCollective(const CollectiveParams& col_params, + CollectiveImplementationInterface** col_impl); + // Check if all ops on which this collective depends on have launched. + bool CheckDependencies(const CollectiveParams& col_params) + TF_EXCLUSIVE_LOCKS_REQUIRED(launch_mu_); + // Tries to return the status that is the original error. It returns the + // aborted status if the collective executor is aborted. + Status GetStatus(const Status& s) TF_LOCKS_EXCLUDED(status_mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_BASE_COLLECTIVE_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/bfc_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/bfc_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..efd2a0c7480d8448b395477a7fc39263cc3ecff0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/bfc_allocator.h @@ -0,0 +1,45 @@ +/* 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_COMMON_RUNTIME_BFC_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_BFC_ALLOCATOR_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/common_runtime/allocator_retry.h" +#include "tensorflow/core/common_runtime/shared_counter.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/lib/strings/numbers.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/framework/bfc_allocator.h" + +namespace tensorflow { + +class MemoryDump; // NOLINT +using tsl::BFCAllocator; // NOLINT + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_BFC_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/buf_rendezvous.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/buf_rendezvous.h new file mode 100644 index 0000000000000000000000000000000000000000..0ee6099eea54943cd44f66a54bf4be101d1d04a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/buf_rendezvous.h @@ -0,0 +1,134 @@ +/* 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_COMMON_RUNTIME_BUF_RENDEZVOUS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_BUF_RENDEZVOUS_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { +class Device; +class DeviceContext; +class DeviceMgr; +class Tensor; + +// EXPERIMENTAL: RDMA oriented producer/consumer rendezvous on a local +// Tensor value for which DMAHelper::CanUseDMA() is true, i.e. dense +// numeric types. Similar to Rendezvous but never owns a Ref on the +// tensor, instead it uses an explicit callback to the producer when +// the consumer side is finished with the value. This allows the +// producer to perform in-place updates on the source buffer or to take +// other actions that depend on knowing the consumer has passed a certain +// execution point. +class BufRendezvous { + public: + explicit BufRendezvous(uint64 step_id, const DeviceMgr* dev_mgr) + : step_id_(step_id), dev_mgr_(dev_mgr) {} + + virtual ~BufRendezvous(); + + // Inform all waiting parties that this BufRendezvous is defunct because of + // an error Status interrupting the Step. + void StartAbort(const Status& s); + + struct Hook; + // Provided by the consumer to be called when access to the buffer + // is available. If the Status arg is not OK, then hook will not + // be populated. Ownership of Hook passes to consumer with the + // callback. + typedef std::function ConsumerCallback; + // Provided by the producer to be called when the consumer has finished + // reading the buffer and will no longer access it. + typedef std::function ProducerCallback; + + struct Hook { + Device* prod_dev; + DeviceContext* prod_ctx; + const Tensor* prod_value; + AllocatorAttributes prod_attr; + ProducerCallback prod_cb; + ConsumerCallback cons_cb; + CancellationManager* cancellation_manager; + CancellationToken cancellation_token; + explicit Hook(CancellationManager* cancellation_manager, + CancellationToken cancellation_token) + : prod_dev(nullptr), + prod_ctx(nullptr), + prod_value(nullptr), + prod_cb(nullptr), + cons_cb(nullptr), + cancellation_manager(cancellation_manager), + cancellation_token(cancellation_token) {} + string DebugString() const; + }; + + // Called to advertise availability of a Tensor value corresponding + // to key. That value must stay valid until done is called. + // + // If a non-null cancellation manager is provided, this function registers a + // callback to delete the hook and invoke provider/consumer callbacks with + // cancelled error. + void ProvideBuf(const string& key, Device* dev, DeviceContext* dev_ctx, + const Tensor* v, const AllocatorAttributes& attr, + const ProducerCallback& done, + CancellationManager* cancellation_manager); + + // Called to request access to a Tensor value corresponding to key. + // Consumer is provided with a Hook as soon as available. + // + // This function also checks that the current incarnation number of the + // `device` that produced this value matches the `incarnation` expected by the + // consumer, and invokes `done` with `FailedPrecondition` status and + // `nullptr` hook if it does not match. + // + // If a non-null cancellation manager is provided, this function registers a + // callback to delete the hook and invoke provider/consumer callbacks with + // cancelled error. + virtual void ConsumeBuf(const string& key, const string& device, + const uint64 incarnation, + const ConsumerCallback& done, + CancellationManager* cancellation_manager); + + // Cancel the rendezvous entry corresponding to `key`. Triggered by the + // cancellation manager. No-op if the rendezvous was already successful. + void CancelHook(const string& key); + + // Consumer must call this function when it's done reading the Hook provided + // by the ConsumerCallback. This function will invoke the producer callback + // and then delete h. + static void DoneWithHook(Hook* h); + + // Write the current contents of the table to the INFO log. + void LogContents(); + + protected: + const uint64 step_id_; + const DeviceMgr* const dev_mgr_; // Not owned. + mutex mu_; + Status status_ TF_GUARDED_BY(mu_); + typedef absl::flat_hash_map HookTable; + HookTable hook_table_ TF_GUARDED_BY(mu_); + + void PurgeTable(const Status& s, HookTable* table); +}; +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_BUF_RENDEZVOUS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/build_graph_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/build_graph_options.h new file mode 100644 index 0000000000000000000000000000000000000000..f33d43fbc3cfd6f1f6deffc94cc606502c377e44 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/build_graph_options.h @@ -0,0 +1,48 @@ +/* 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_COMMON_RUNTIME_BUILD_GRAPH_OPTIONS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_BUILD_GRAPH_OPTIONS_H_ + +#include + +#include "tensorflow/core/graph/collective_order.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +struct BuildGraphOptions { + CallableOptions callable_options; + + // If `true`, uses Arg/Retval to implement feeds/fetches; otherwise + // uses Recv/Send to implement feeds/fetches. + // TODO(mrry): Remove this when the distributed runtime supports Arg/Retval. + bool use_function_convention = false; + + static constexpr int64_t kNoCollectiveGraphKey = 0; + int64_t collective_graph_key = kNoCollectiveGraphKey; + + // If not `kNone`, order all CollectiveReduce operations statically and + // deterministically. If `kEdges`, encode dependencies as explicit control + // edges, if `kAttrs` encode as attribute on collective op. + GraphCollectiveOrder collective_order = GraphCollectiveOrder::kNone; + + string DebugString() const; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_BUILD_GRAPH_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_executor_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_executor_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..d480db03a466094f83764b9f88700b2d371aa5fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_executor_mgr.h @@ -0,0 +1,96 @@ +/* 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_COMMON_RUNTIME_COLLECTIVE_EXECUTOR_MGR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_EXECUTOR_MGR_H_ + +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/lib/gtl/flatmap.h" +#include "tensorflow/core/platform/unbounded_work_queue.h" + +namespace tensorflow { +class ConfigProto; +class DeviceMgr; + +class CollectiveExecutorMgr : public CollectiveExecutorMgrInterface { + public: + CollectiveExecutorMgr( + const ConfigProto& config, const DeviceMgr* dev_mgr, + std::unique_ptr dev_resolver, + std::unique_ptr param_resolver, + std::unique_ptr nccl_communicator); + + virtual ~CollectiveExecutorMgr(); + + CollectiveExecutor* FindOrCreate(int64_t step_id) override; + + void Cleanup(int64_t step_id) override; + + ParamResolverInterface* GetParamResolver() const override { + return param_resolver_.get(); + } + + DeviceResolverInterface* GetDeviceResolver() const override { + return dev_resolver_.get(); + } + + NcclCommunicatorInterface* GetNcclCommunicator() const override { + return nccl_communicator_.get(); + } + + void GetStepSequenceAsync(const GetStepSequenceRequest* request, + GetStepSequenceResponse* response, + const StatusCallback& done) override; + + void RefreshStepIdSequenceAsync(int64_t graph_key, + const StatusCallback& done) override; + + int64_t NextStepId(int64_t graph_key) override { + return CollectiveExecutor::kInvalidId; + } + + void RetireStepId(int64_t graph_key, int64_t step_id) override {} + + protected: + // Called by FindOrCreate when table entry does not yet exist. + virtual CollectiveExecutor* Create(int64_t step_id); + + const DeviceMgr* dev_mgr_; + std::unique_ptr dev_resolver_; + std::unique_ptr param_resolver_; + string gpu_ring_order_; + std::unique_ptr nccl_communicator_; + // Unbounded work queue for scheduling potentially-blocking work during + // collective op execution. Ownership is shared between `this` and + // `CollectiveRemoteAccessLocal`. + std::shared_ptr work_queue_; + + private: + mutex exec_mu_; + // Map from step_id to CollectiveExecutor + gtl::FlatMap executor_table_ + TF_GUARDED_BY(exec_mu_); +}; + +// Creates a local CollectiveExecutorMgr with production implementations of each +// components. Cases that need to inject other implementations of these +// components should call CollectiveExecutorMgr constructor directly. This only +// supports a single host. For distributed use case, use +// CreateProdRpcCollectiveExecutorMgr() instead. +std::unique_ptr CreateProdLocalCollectiveExecutorMgr( + const ConfigProto& config, const DeviceMgr* device_mgr, + std::unique_ptr nccl_communicator); + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_EXECUTOR_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_param_resolver_local.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_param_resolver_local.h new file mode 100644 index 0000000000000000000000000000000000000000..6a702e237c171c4a128e5cf230f9fea1a262baff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_param_resolver_local.h @@ -0,0 +1,215 @@ +/* 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_COMMON_RUNTIME_COLLECTIVE_PARAM_RESOLVER_LOCAL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_PARAM_RESOLVER_LOCAL_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/lib/gtl/flatmap.h" +#include "tensorflow/core/platform/thread_annotations.h" + +namespace tensorflow { +class CompleteGroupRequest; +class CompleteGroupResponse; +class CompleteInstanceRequest; +class CompleteInstanceResponse; +class ConfigProto; +class DeviceMgr; + +// Implements ParamResolverInterface for a single-task context. +// It also implements the functionality necessary to serve as the +// group leader for param resolution in a multi-task context. +class CollectiveParamResolverLocal : public ParamResolverInterface { + public: + CollectiveParamResolverLocal(const ConfigProto& config, + const DeviceMgr* dev_mgr, + DeviceResolverInterface* dev_resolver, + NcclCommunicatorInterface* nccl_communicator, + const string& task_name); + + ~CollectiveParamResolverLocal() override {} + + void CompleteParamsAsync(const DeviceAttributes& device, CollectiveParams* cp, + CancellationManager* cancel_mgr, + const StatusCallback& done) override; + + void CompleteGroupAsync(const DeviceAttributes& device, + CollGroupParams* group_params, + CancellationManager* cancel_mgr, + const StatusCallback& done) override; + + void CompleteInstanceAsync(const CompleteInstanceRequest* request, + CompleteInstanceResponse* response, + CancellationManager* cancel_mgr, + const StatusCallback& done) override; + + Status LookupGroup(int32_t group_key, CollGroupParams* group) override; + + void StartAbort(const Status& s) override; + + protected: + // For access to InstanceRec and CompleteDefaultRanking. + friend class CollectiveParamResolverLocalTest; + + // Used to complete/verify CollGroup. + struct GroupRec { + mutable mutex mu; + CollGroupParams group TF_GUARDED_BY(mu); + Status status TF_GUARDED_BY(mu); + std::unordered_map incarnations_by_device_name + TF_GUARDED_BY(mu); + std::vector pending_params TF_GUARDED_BY(mu); + std::vector pending_done TF_GUARDED_BY(mu); + }; + + // Finds the GroupRec that corresponds to group_params->group_key. + // Also populates group_params from that group_rec. + // Will wait until GroupRec is fully populated or an error arises before + // calling done. Callback GroupRec* arg is only valid if status is ok. + // Ownership of GroupRec stays with this object and does not pass to the + // callback. + void CompleteGroupLocal(const DeviceAttributes& device, + CollGroupParams* group_params, + CancellationManager* cancel_mgr, StatusCallback done) + TF_LOCKS_EXCLUDED(group_mu_); + + // Finishes the group parameters once all members of the group are there. + void FinishGroup(GroupRec* gr) TF_EXCLUSIVE_LOCKS_REQUIRED(gr->mu); + + // Cancels the group if it's still pending. + void CancelGroup(int32 group_key) TF_LOCKS_EXCLUDED(group_mu_); + + // Lookup and populate parameters from an already initialized group. + Status LookupAndPopulateGroupParams(CollGroupParams* group_params); + + // Used to complete/verify CollInstance. + struct InstanceRec; + + typedef std::function IRConsumer; + struct InstanceRec { + mutex mu; + // Values to be shared by all instances, constant after initialization. + CollectiveParams* shared; + // If an error occurs during initialization this structure stays in the + // table with a non-OK status. Purging the table and restarting needs to be + // done at a higher level. + Status status TF_GUARDED_BY(mu); + + // These fields are used to count the instances that have called + // in and become known while resolving broadcast source identity and + // communicator key. + int source_rank TF_GUARDED_BY(mu); + string communicator_key TF_GUARDED_BY(mu); + int known_count TF_GUARDED_BY(mu); + std::vector known TF_GUARDED_BY(mu); + std::vector known_waiters TF_GUARDED_BY(mu); + + InstanceRec() + : shared(new CollectiveParams()), source_rank(-1), known_count(0) {} + ~InstanceRec() { shared->Unref(); } + }; + + // Find the InstanceRec with the same instance_key as cp. If it doesn't + // already exist, create and initialize from gr and cp. + // created is set to true if a new IRec is created, false otherwise. + // + // Precondition: *gr must be a complete GroupRec, i.e. the value set + // by CompleteGroupLocal. *cp must be populated with all the fields + // required by InitInstanceSharedParams. Ownership of InstanceRec stays + // with this object and does not pass to the callback. + InstanceRec* GetOrCreateInstanceRec(CollectiveParams* cp, bool* created) + TF_LOCKS_EXCLUDED(instance_mu_, group_mu_); + + // Populate *ir with device membership from gr, then initialize to be specific + // to cp->instance_key, i.e. order the devices and tasks. + // + // Preconditions: + // cp is populated with all DeviceLocalities + void InitInstanceSharedParams(const CollectiveParams* cp, InstanceRec* ir); + + // Establishes the final order of gp->device_names and gp->task_names by + // considering localities of all devices. + void CompleteDefaultRanking(CollGroupParams* gp); + + // Finish populating *cp. + // Precondition: *gr has been fully populated by CompleteGroupLocal. + void CompleteInstanceLocal(const string& device, CollectiveParams* cp, + const StatusCallback& done) + TF_LOCKS_EXCLUDED(instance_mu_, group_mu_); + + // Finish populating *cp from fully initialized *ir. + // Precondition: *gr and *ir are fully populated. + void CompleteInstanceFromInitializedIRec(const string& device, + CollectiveParams* cp, + InstanceRec* ir, + const StatusCallback& done) + TF_LOCKS_EXCLUDED(ir->mu); + + // Complete instance params after waiting for group. + // Precondition: *cp has complete group data and default_rank. + void WaitForGroup(InstanceRec* ir, CollectiveParams* cp, const IRConsumer& f) + TF_LOCKS_EXCLUDED(ir->mu); + + // If cp.device_names contains only devices local to this process + // populates *localities, else returns an error. + Status GetLocalDeviceLocalities(const CollectiveParams& cp, + std::vector* localities); + + // Sets cp->instance_default_rank according to location of device in + // current ordering of cp->instance.device_names. + void SetDefaultRank(const string& device, CollectiveParams* cp); + + // Sets cp->instance.type based on collective op type, and attempts to assign + // best implementation. + void AssignCollectiveType(CollectiveParams* cp); + + void StartAbortLocal(const Status& s) + TF_LOCKS_EXCLUDED(status_mu_, group_mu_, instance_mu_); + + const bool nccl_; + const DeviceMgr* dev_mgr_; + DeviceResolverInterface* dev_resolver_; // Not owned. + NcclCommunicatorInterface* nccl_communicator_; // Not owned. + string task_name_; + string gpu_ring_order_; + mutex group_mu_; + gtl::FlatMap> group_table_ + TF_GUARDED_BY(group_mu_); + struct TupleHash { + std::size_t operator()(const std::tuple x) const { + // The hash does not need to be unique and a value of 20 is picked + // arbitrarily as an effort to reduce probability of conflicts. + return (std::get<0>(x) << 20) + std::get<1>(x); + } + }; + mutex instance_mu_; + gtl::FlatMap, + std::unique_ptr, TupleHash>> + instance_table_ TF_GUARDED_BY(instance_mu_); + mutex status_mu_; + Status status_ TF_GUARDED_BY(status_mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_PARAM_RESOLVER_LOCAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_rma_local.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_rma_local.h new file mode 100644 index 0000000000000000000000000000000000000000..5c12ed413d9594361ec02dbb06623c5e206d73cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_rma_local.h @@ -0,0 +1,82 @@ +/* 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_COMMON_RUNTIME_COLLECTIVE_RMA_LOCAL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_RMA_LOCAL_H_ + +#include "tensorflow/core/common_runtime/buf_rendezvous.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/rendezvous.h" + +namespace tensorflow { + +// Basic implementation of PerStepCollectiveRemoteAccess. +class CollectiveRemoteAccessLocal : public CollectiveRemoteAccess { + public: + CollectiveRemoteAccessLocal(const DeviceMgr* dev_mgr, + DeviceResolverInterface* dev_resolver, + int64_t step_id) + : dev_mgr_(dev_mgr), + dev_resolver_(dev_resolver), + buf_rendezvous_(step_id, dev_mgr), + step_id_(step_id) {} + + ~CollectiveRemoteAccessLocal() override = default; + + void StartAbort(const Status& s) override; + + void RecvFromPeer(const string& peer_device, const string& peer_task, + bool peer_is_local, const string& key, Device* to_device, + DeviceContext* to_device_ctx, + const AllocatorAttributes& to_alloc_attr, Tensor* to_tensor, + const DeviceLocality& client_locality, + int dev_to_dev_stream_index, + CancellationManager* cancellation_manager, + const StatusCallback& done) override; + + void PostToPeer(const string& peer_device, const string& peer_task, + const string& key, Device* from_device, + DeviceContext* from_device_ctx, + const AllocatorAttributes& from_alloc_attr, + const Tensor* from_tensor, + const DeviceLocality& client_locality, + CancellationManager* cancellation_manager, + const StatusCallback& done) override; + + void CheckPeerHealth(const string& peer_task, int64_t timeout_in_ms, + const StatusCallback& done) override; + + BufRendezvous* buf_rendezvous() override { return &buf_rendezvous_; } + + // Copy utility that always copies bytes from src to dst even if + // they are on the same device, unlike CopyTensor::ViaDMA which will + // just change the dst buffer pointer in that case. + static void MemCpyAsync(DeviceContext* src_dev_ctx, + DeviceContext* dst_dev_ctx, Device* src_dev, + Device* dst_dev, const AllocatorAttributes& src_attr, + const AllocatorAttributes& dst_attr, + const Tensor* src, Tensor* dst, + int dev_to_dev_stream_index, + const StatusCallback& done); + + protected: + const DeviceMgr* dev_mgr_; // not owned + DeviceResolverInterface* dev_resolver_; // not owned + BufRendezvous buf_rendezvous_; + int64_t step_id_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_RMA_LOCAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_util.h new file mode 100644 index 0000000000000000000000000000000000000000..01fb8b8c81cd2f4dc390c2b6467d7c54c7753bf0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/collective_util.h @@ -0,0 +1,59 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_UTIL_H_ + +#include + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +namespace collective_util { + +Status InitializeDeviceAndLocality(const DeviceMgr* dev_mgr, + const string& device_name, Device** device, + DeviceLocality* device_locality); +string SubdivPermDebugString(const CollectiveParams& col_params); + +// Used for executing a sub-operation, e.g. a merge_op instance, with +// an OpKernelContext based on the one passed into this Op. +class SubContext { + public: + OpKernelContext::Params sub_params_; + gtl::InlinedVector sub_inputs_; + gtl::InlinedVector sub_input_attr_; + gtl::InlinedVector sub_input_dc_; + // Used only for Binary and Unary Ops for which we require + // the calculation to be in-place on the first input. + int forward_from_ = 0; + std::unique_ptr sub_ctx_; + SubContext(OpKernelContext* ctx, OpKernelContext::Params* params, + OpKernel* op, Tensor* output, Tensor* input); + ~SubContext() = default; +}; + +Status ComputeBinOp(OpKernelContext* op_ctx, OpKernelContext::Params* params, + Device* device, OpKernel* op, Tensor* output, + Tensor* input); + +} // namespace collective_util +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COLLECTIVE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/colocation_graph.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/colocation_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..e6362b47334949c12f5a070c6e1d6b33a6215f2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/colocation_graph.h @@ -0,0 +1,393 @@ +/* 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_COMMON_RUNTIME_COLOCATION_GRAPH_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COLOCATION_GRAPH_H_ + +#include +#include + +#include "absl/strings/str_join.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/inspecting_placer.h" +#include "tensorflow/core/common_runtime/placer_inspection_required_ops_utils.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/util/device_name_utils.h" +#include "tensorflow/core/util/port.h" + +namespace tensorflow { + +// Represents a node in the disjoint node forest and the +// accumulated constraints on the device used by that node. +class Member { + public: + Member() = default; + + Status SetParentAndSupportedDevices( + const Node& node, const std::vector& types, + const DeviceNameUtils::ParsedName* local_address_spec); + + const DeviceNameUtils::ParsedName& requested_device_name() const { + return requested_device_name_; + } + + Status SetAssignedDeviceName(const string& device_name); + Status SetResourceDeviceName(const Node& node); + Status SetRequestedDeviceName(const Node& node); + + Status FillPossibleDevices(PossibleDevices* possible_device) const; + + // Returns whether `src_root` is assigned to a CompositeDevice and `this` is + // assigned to a physical device. + bool IsEdgeFromCompositeDeviceToPhysicalDevice(const Member& src_root) const; + + Status EnsureCompatibilityAcrossResourceEdge( + const Node& src, const Member& src_root, + const Node& dst, /*dst_root is this*/ + bool log_device_placement); + + const PrioritizedDeviceTypeVector& supported_device_types() const { + return supported_device_types_; + } + + // If `dry_run` is true, just sets `new_root` and `old_root` and does not + // actually modify anything in the `tree`. + static void Merge(std::vector* tree, int x_root, int y_root, + Member** new_root, Member** old_root, bool dry_run); + + // Returns the root node of the disjoint tree to which the node with the + // given id is connected. + // FindRoot should be called only for debugging or after the members have + // been updated with direct root pointers because it does not update + // root pointers and can traverse many links. It exists to have + // a const version of FindAndUpdateRoot + static int FindRoot(const std::vector& tree, int node_id); + static int FindAndUpdateRoot(std::vector* tree, int node_id); + + Status MergeDeviceNames(const Member& other, bool allow_soft_placement); + + // Updates this to contain the intersection of the device types in + // this and "other". If the intersection is empty, returns false and does + // not update this. Else returns true and updates this. + bool MergeSupportedDevices(const Member& other); + + Status AssignDevice(const Node& node); + + // If user does not explicitly request XLA device and non-XLA device is + // supported for this node, use only the non-XLA device. See b/140896502. + void MaybeExcludeXlaDevices(); + + // Limit the possible devices of this (should be a root) to the device + // specifications in `devices`. + Status LimitToPossibleDevices(const PossibleDevices& devices, + bool allow_soft_placement); + + void set_possible_devices(std::vector&& devices) { + possible_devices_ = devices; + } + const std::vector& possible_devices() { return possible_devices_; } + + // Returns a (parsed) device name that is based on requested_device_name() + // but with potentially cleared device type and ID fields. A field is cleared + // if the assigned_device_name does not specify it. If it does, the field + // is not cleared because soft placement cannot violate assigned device names. + DeviceNameUtils::ParsedName GetSoftDeviceName() const; + + // Same as GetSoftDeviceName but device type and device ID fields are not + // cleared if resource device has them set. + DeviceNameUtils::ParsedName GetPreferredSoftDeviceName() const; + + string DebugString() const; + + bool has_assigned_device_name() const { return assigned_device_name_.has_id; } + + private: + // Updates this to contain the intersection of the device types in + // this and `other_devices`. + bool MergeSupportedDevices(const PrioritizedDeviceTypeVector& other_devices); + + // The id of the node that is the parent of this one, or its own + // id if it is a root. parent <= 0 indicates that this member is invalid. + int parent_ = -1; + + // A proxy for the depth of the tree that is used to prefer + // connecting smaller trees to larger trees when merging disjoint + // sets. + int rank_ = 0; + + // Once colocation groups have been formed, the Placer starts actually + // choosing devices. All nodes in a group must be assigned to the same + // device. Once we assigned the first device to some node in this group, + // we set assigned_device_name_index to this device name's index in the + // graph. + // The `*_device_name_` fields will contain the parsed name of this device + // and `possible_devices`, if computed, will contain just this device. + // `assigned_device_name_index` is an optimization to avoid parsing and + // comparing device names. The value of -1 signals that a single device + // has not been chosen yet. + int assigned_device_name_index_ = -1; + + // The merged form of the device requested for this node, with those of all of + // its children. requested_device_name_ is always kept a specialization (i.e. + // DeviceNameUtils::IsSpecification) of assigned_device_name_. When no device + // is requested, this field is set to assigned_device_name_. As a + // specialization of assigned_device_name_, requested_device_name_ represents + // the most specific form of all assigned and requested devices of this node + // and its children, if this node is a root. requested_device_name_ is used + // to finally select devices for nodes. We can override requested devices due + // to resource colocation constraints but not assigned devices (unless soft + // placement is on). + // INVARIANT: requested_device_name_ is always kept a + // DeviceNameUtils::IsSpecification of assigned_device_name_ and + // resource_device_name_. This makes requested_device_name_ the "accumulation + // of all wishes" about the device. + DeviceNameUtils::ParsedName requested_device_name_; + + // The merged form of the device assigned for this node, with + // those of all of its children. + // This field is used to raise errors due to unsatisfiable constraints. + // Can be a partial specification. + DeviceNameUtils::ParsedName assigned_device_name_; + + // The merged form of the requested resource device assigned for this node, + // with those of all of its children. + // This field is used to raise errors due to unsatisfiable constraints. + // Can be a partial specification. + // resource_device_name_ is initialized with user-requested device on nodes + // producing resources, e.g. VarHandleOp. + // For historical reasons, with soft placement enabled, Placer can "move" + // resources (place resource producing ops on a device different from what + // the user explicitly requested) when the colocation group of a resource + // producing op contains ops that are not supported on the user-requested + // resource device. A classic example of this is a sparse optimizer (only + // supported on CPU) used on a GPU variable. In this case, the whole group + // will be assigned to some device supported by all ops in the colocation + // group. This is a surprising and unfortunate behavior because: + // 1. Since soft_placement is on by default, users don't know that their + // variables are created on a different device than what they requested. + // Among other things, this can lead to surprising poor performance. + // 2. Eager runtime cannot "move" resources. The same code can "work" when + // wrapped in tf.function but will fail when run eagerly. + // 3. Extra complexity here to preserve these resource moving capabilities. + DeviceNameUtils::ParsedName resource_device_name_; + + // The intersection of all device types supported by this node, + // and those of all of its children, in priority order + // of the preferred device. + // It is possible that supported_device_types_ has an empty intersection with + // requested/assigned/resource devices. We could have detected such cases + // as soon as they happen and raise an error. Instead, for historical reasons, + // we leave such error detection to the final device picking stage. + PrioritizedDeviceTypeVector supported_device_types_; + + // If this node is a root, stores a list of Devices to which this node + // and all of its children can be assigned. + // `possible_devices` is empty if they have not yet been computed. + std::vector possible_devices_; +}; + +// This class maintains the connected components of a colocation +// constraint graph, and uses this information to assign a satisfying +// device placement to the nodes of the graph. +// +// This implementation uses the Union-Find algorithm to efficiently maintain the +// connected components and incrementally adds edges via +// ColocationGraph::ColocateNodes() invocations. +// +// ColocationGraph does not assign any devices to graph nodes. The +// `log_device_placement` argument is used to log messages when requested +// device is ignored. +class ColocationGraph { + public: + // graph, flib_def, and device_set must not be null and must outlive + // this ColocationGraph. default_local_device can be null. If not, must + // outlive this. + ColocationGraph(const Graph* graph, const FunctionStack& stack, + const FunctionLibraryDefinition* flib_def, + const DeviceSet* device_set, + const Device* default_local_device, bool allow_soft_placement, + bool log_device_placement); + + Status Initialize(); + + const std::vector& members() const { return members_; } + + // Limit the group containing `node` to the device specifications in + // `devices`. + Status LimitToPossibleDevices(const Node& node, + const PossibleDevices& devices); + + // Limits the possible devices of `node`'s colocation group to the device + // to which `node` is assigned. This makes sure that all nodes in this + // colocation group will be assigned to the same device. Without this + // explicit restriction, heuristics can choose a different possible device + // for other nodes in the group. + Status LimitToAssignedDevice(const Node& node); + + // Returns the root node of the disjoint tree to which the node with the + // given id is connected. + // Updates the internal pointers so that future calls will returns faster. + int FindAndUpdateRoot(int node_id) { + return Member::FindAndUpdateRoot(&members_, node_id); + } + + // For the given node, subject to the constraints previously given + // to this ColocationGraph, set its assigned_device_name. Returns OK + // if a satisfying device can be found, otherwise an error. + // + // Note: This method returns a pointer to a field within members_. + // The caller must not use the returned pointer after there is any possibility + // that the members_[i].possible_devices field has been modified. + Status GetDevicesForNode(Node* node, + const std::vector** possible_devices); + + // Returns debugging info for the node referred to by 'node_root'. + string DebugInfo(const int node_root) const; + + string DebugString() const; + + // Returns a list of devices having type in supported_device_types. The + // returned list is sorted by preferred type (higher numeric type is + // preferred). + static std::vector FilterSupportedDevices( + const std::vector& devices, + const PrioritizedDeviceTypeVector& supported_device_types, + const Device* default_local_device); + + private: + // Adds each node of the Graph to this ColocationGraph as a singleton. + // + // NOTE: The implementation assumes that the ids of nodes passed to + // this method are dense and zero-based; the memory used will be linear in + // the largest node ID. + // NOTE: If this method returns an error, *this is left in an undefined + // state. + Status ColocateAllNodes(); + + Status ColocateResourceOrRefEdge(const Node* src, const Node* dst); + + // Adds colocation constraints to data types known not to support copying. + Status ColocateUncopiableTypeEdges( + std::unordered_set* inspection_required); + + // Updates this ColocationGraph by making sure that all nodes + // touching resource and/or ref tensors are colocated. + // As it iterates over the edges, fills the `inspection_required` set with + // the nodes that + // PlacerInspectionRequiredOpChecker::IsPlacerInspectionRequired + // deems as requiring deep inspection by placer. This is an optimization. + // TODO(mdan): Deprecate in favor of ColocateUncopiableTypeEdges. + Status ColocateResourceAndRefEdges( + std::unordered_set* inspection_required); + + // Updates this ColocationGraph by making sure that all nodes having inputs of + // a DT_VARIANT data type with a host-only underlying types (e.g. strings) can + // be placed only on CPU device. We do that by reverse-DFS traversal from all + // nodes that take variant inputs to the node that produces that variant. + // TODO(ezhulenev): This function does not yet support "deep op" inspection, + // that we have for DT_RESOURCE edges. + Status AddHostOnlyDataTypesConstraints(); + + Status AddInspectionConstraints( + const std::unordered_set& inspection_required); + + // Applies colocation groups for `node`'s inputs and outputs to this + // ColocationGraph. + // `groups` are the colocation groups to which `nodes`'s inputs and outputs + // belong. + // `node` is a node requiring deep inspection (e.g. a node calling + // a function) + // + // For example, consider a `node` taking two inputs and producing one output + // a b + // | | + // v v + // node + // | + // v + // c + // + // `groups` can tell us that `a` and `c` must be colocated and their device + // must be a GPU. `b` might be in a group by itself without any device + // restrictions. + // + // ApplyIOColocationGroups will have an effect of calling + // ColocateNodes(a, c) and LimitToPossibleDevices(`a`, "GPU"). The colocation + // group of the `node` itself is not directly impacted. + // + Status ApplyIOColocationGroups(const IOColocationGroups& groups, + const Node& node); + + Status ColocateNodeToGroup( + std::unordered_map* + colocation_group_root, + const Node* node, StringPiece colocation_group); + + // Merge the (possibly disjoint) sets containing nodes "x" and + // "y". Returns OK if the all nodes in the union of these sets can + // be placed on the same device type. + // + // If this method returns an error, *this is unchanged. + Status ColocateNodes(const Node& x, const Node& y); + + // This overload of ColocateNodes() allows a caller to provide the root node + // ids for the two nodes. For large graphs, this noticeably reduces the + // graph load time. + // If this method returns an error, *this is unchanged. + Status ColocateNodes(const Node& x, int x_root, const Node& y, int y_root); + + void GetSoftDeviceCandidates(const Node& node, const Member& root_member, + int root_id, + std::vector* possible_devices); + + Status InitializeMembers(); + + Status InitializeMemberWithAssignedDevice(const string& assigned_device_name, + const string& node_type, + Member* member); + + Status InitializeMember(const Node& node, Member* member); + + // Returns the root node of the disjoint tree to which the node with the + // given id is connected. + // FindRoot should be called only for debugging or after the members have + // been updated with direct root pointers because it does not update + // root pointers and can traverse many links. It exists to have + // a const version of FindAndUpdateRoot + int FindRoot(int node_id) const { + return Member::FindRoot(members_, node_id); + } + + const Graph& graph_; + const FunctionStack stack_; + std::vector members_; + InspectingPlacer inspecting_placer_; + PlacerInspectionRequiredOpChecker inspection_required_checker_; + const DeviceSet& device_set_; + const std::vector device_types_; + const DeviceNameUtils::ParsedName local_address_spec_; + const Device* default_local_device_; + const bool allow_soft_placement_; + const bool log_device_placement_; + + ColocationGraph(const ColocationGraph&) = delete; + void operator=(const ColocationGraph&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COLOCATION_GRAPH_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/composite_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/composite_device.h new file mode 100644 index 0000000000000000000000000000000000000000..800a24f34117d709e8db455fd0fbb8e93b44e169 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/composite_device.h @@ -0,0 +1,72 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_COMPOSITE_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COMPOSITE_DEVICE_H_ + +#include "absl/strings/string_view.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +extern const char* const kCompositeDeviceType; + +// A virtual device which represents a set of devices. We don't execute any +// op on this virtial device. +class CompositeDevice : public Device { + public: + Status Sync() override { + return errors::Internal( + "Sync() should never been invoked on CompositeDevice."); + } + + Allocator* GetAllocator(AllocatorAttributes) override { return nullptr; } + + const std::vector* underlying_devices() const { + return &underlying_devices_; + } + + // Helper for creating a CompositeDevice on the same task as the given host + // CPU. + static std::unique_ptr MakeDevice( + const std::vector& underlying_devices, const int unique_device_id, + const DeviceNameUtils::ParsedName& host_name, Status* status); + + // Helper for creating a CompositeDevice with the given device name. + static std::unique_ptr MakeDevice( + const std::vector& underlying_devices, const string& device_name, + Status* status); + + bool IsRemoteCallAllowed() const override { return false; } + + private: + CompositeDevice(const DeviceAttributes& device_attributes, + const std::vector& underlying_devices) + : Device(/*env=*/nullptr, device_attributes), + underlying_devices_(underlying_devices) {} + + const std::vector underlying_devices_; + + CompositeDevice(const CompositeDevice&) = delete; + void operator=(const CompositeDevice&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COMPOSITE_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/constant_folding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/constant_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..64441f73db4b868f23805739e3b1170083fffb3a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/constant_folding.h @@ -0,0 +1,70 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_CONSTANT_FOLDING_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_CONSTANT_FOLDING_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/env.h" + +// TODO(skyewm): can this be combined with EvaluateConstantTensor? + +namespace tensorflow { + +// This generator type is used to generate a name for the newly folded node +// based on the node's old name. +using ConstantFoldNameGenerator = + std::function; + +// Options specific to constant folding optimizations. +struct ConstantFoldingOptions { + // If "consider" is not a nullptr, then only constant fold a node "n" if + // consider(n) returns true. + std::function consider = nullptr; + // If shape_map is not a nullptr, it is a map from node n to a + // vector of the (potentially partially-known) shapes of its + // outputs. + const std::unordered_map>* shape_map = + nullptr; // not owned + // The maximum size of each constant created during constant folding + // optimization. + int64_t max_constant_size_in_bytes = 10 * 1024 * 1024; + + // A generator for the name suffix of constant folded nodes. A + // default id generator that monotonically increases is used if nullptr is + // passed. + ConstantFoldNameGenerator generate_new_name = nullptr; +}; + +// Perform constant folding optimization on "graph". +// Looks for nodes in "graph" that can be completely evaluated statically, i.e., +// that are only dependent on constants. Evaluates those nodes on a CPU device +// and replaces those nodes with the result of the evaluation. +// "partition_device", if non-null, is the device where all the graph nodes are +// assumed to execute. +// Sets `was_mutated` to true if and only if "graph" has been mutated. +// The status is only set to a non-OK state if an unexpected error is hit +// running the graph. +Status ConstantFold(const ConstantFoldingOptions& opts, + FunctionLibraryRuntime* function_library, Env* env, + const Device* partition_device, Graph* graph, + bool* was_mutated); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_CONSTANT_FOLDING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/copy_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/copy_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..0bbbee2421b284b6181a0c1b8f4c4f178651e142 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/copy_tensor.h @@ -0,0 +1,78 @@ +/* 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_COMMON_RUNTIME_COPY_TENSOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COPY_TENSOR_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +class CopyTensor { + public: + typedef void (*CopyFunction)( + DeviceContext* send_dev_context, DeviceContext* recv_dev_context, + Device* src, Device* dst, const AllocatorAttributes src_alloc_attr, + const AllocatorAttributes dst_alloc_attr, const Tensor* input, + Tensor* output, int dev_to_dev_stream_index, StatusCallback done); + + // Copies "input" to "output" between devices accessible to the + // local process via some DMA-like method. "edge_name" is the name + // of the tensor being copied, for debugging purposes. Depending on + // the type of devices and memory in use, the copy may be performed + // synchronously or asynchronously. 'done' will be invoked only + // after the copy is actually complete. + static void ViaDMA(StringPiece edge_name, DeviceContext* send_dev_context, + DeviceContext* recv_dev_context, Device* src, Device* dst, + const AllocatorAttributes src_alloc_attr, + const AllocatorAttributes dst_alloc_attr, + const Tensor* input, Tensor* output, + int dev_to_dev_stream_index, StatusCallback done, + bool sync_dst_compute = true); + + // Object used to call Register() at static-initialization time. + // Note: This should only ever be used as a global-static object; no stack + // or heap instances. + class Registration { + public: + Registration(DeviceType sender_device_type, DeviceType receiver_device_type, + CopyFunction copy_function) { + TF_QCHECK_OK(Register(sender_device_type, receiver_device_type, + copy_function, /*is_pluggable_device=*/false)); + } + }; + + // Register a function for copying between two specific DeviceTypes. + // Note: This should only be called via the constructor of + // CopyTensor::Registration or from PluggableDevice implementation. + static Status Register(DeviceType sender_device_type, + DeviceType receiver_device_type, + CopyFunction copy_function, bool is_pluggable_device); +}; + +void CopyDeviceToHost(const Tensor* input, Allocator* cpu_allocator, + Allocator* out_allocator, StringPiece edge_name, + Device* src, Tensor* output, + DeviceContext* send_dev_context, StatusCallback done); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COPY_TENSOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_constants.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..d580a95370bfd7cf3f069bf6db9e6716b18a23e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_constants.h @@ -0,0 +1,42 @@ +/* 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_COMMON_RUNTIME_COST_CONSTANTS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COST_CONSTANTS_H_ + +namespace tensorflow { + +// Types of per-request cost. +inline constexpr char kTpuCostName[] = "tpu"; +inline constexpr char kGcuCostName[] = "gcu"; +inline constexpr char kNoOpCostName[] = "no_op"; + +// Each type of per-request cost could have the following versions. +// +// A server may have costs that cannot be directly attributed to a specific +// query. Each request will be assigned a portion of it, and the cost ends with +// '_with_smear" includes this part. +inline constexpr char kWithSmearSuffix[] = "_with_smear"; +inline constexpr char kNoSmearSuffix[] = "_no_smear"; + +// Full names of per-request cost. +inline constexpr char kTpuWithSmearCostName[] = "tpu_with_smear"; +inline constexpr char kTpuNoSmearCostName[] = "tpu_no_smear"; +inline constexpr char kGcuWithSmearCostName[] = "gcu_with_smear"; +inline constexpr char kGcuNoSmearCostName[] = "gcu_no_smear"; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COST_CONSTANTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_measurement.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_measurement.h new file mode 100644 index 0000000000000000000000000000000000000000..3da322e5dbcba91fb4bcbeae76d9ccea36bb52a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_measurement.h @@ -0,0 +1,45 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_COST_MEASUREMENT_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COST_MEASUREMENT_H_ + +#include "absl/strings/string_view.h" +#include "absl/time/time.h" + +namespace tensorflow { + +// An interface for cost measurement. +class CostMeasurement { + public: + // Context of the CostMeasurement. + struct Context { + // Whether this CostMeasurement is running within a per-query context (e.g. + // rpc handler) or not (e.g. batching). + bool is_per_query = false; + }; + + explicit CostMeasurement(const Context& context) {} + + virtual ~CostMeasurement() {} + + virtual absl::Duration GetTotalCost() = 0; + + virtual absl::string_view GetCostType() const = 0; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COST_MEASUREMENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_measurement_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_measurement_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..b2f1727325235ee24afdd3c3c89dfecfc56282b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_measurement_registry.h @@ -0,0 +1,72 @@ +/* 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_COMMON_RUNTIME_COST_MEASUREMENT_REGISTRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COST_MEASUREMENT_REGISTRY_H_ + +#include +#include +#include +#include + +#include "absl/memory/memory.h" +#include "absl/strings/string_view.h" +#include "tensorflow/core/common_runtime/cost_measurement.h" + +namespace tensorflow { + +// CostMeasurementRegistry allows to +// - register a CostMeasurement type to the global map +// - create an instance of registered CostMeasurement. +class CostMeasurementRegistry { + public: + // Creates an instance of registered CostMeasurement by name. If the named + // CostMeasurement is not registered yet, returns nullptr. Any returned + // std::unique_ptr should not be moved. + // TODO(b/185852990): create a non-moveable wrapper class for the returned + // unique_ptr. + static std::unique_ptr CreateByNameOrNull( + const std::string& name, const CostMeasurement::Context& context); + + using Creator = std::function( + const CostMeasurement::Context&)>; + + // Registers a CostMeasurement type to the global map. Registering different + // types of CostMeasurement with the same name is prohibited. + static void RegisterCostMeasurement(absl::string_view name, Creator creator); +}; + +// Registers a CostMeasurement type to the global map. Registering different +// types of CostMeasurement with the same name is prohibited. +class CostMeasurementRegistrar { + public: + explicit CostMeasurementRegistrar(absl::string_view name, + CostMeasurementRegistry::Creator creator) { + CostMeasurementRegistry::RegisterCostMeasurement(name, std::move(creator)); + } +}; + +#define REGISTER_COST_MEASUREMENT(name, MyCostMeasurementClass) \ + namespace { \ + static ::tensorflow::CostMeasurementRegistrar \ + MyCostMeasurementClass##_registrar( \ + (name), [](const CostMeasurement::Context& context) { \ + return std::make_unique(context); \ + }); \ + } // namespace + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COST_MEASUREMENT_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_util.h new file mode 100644 index 0000000000000000000000000000000000000000..aa1102c1c43e96451bf91df266c7872c456b6397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/cost_util.h @@ -0,0 +1,39 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_COST_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COST_UTIL_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/cost_measurement.h" +#include "tensorflow/core/common_runtime/request_cost_accessor.h" + +namespace tensorflow { + +// Creates instances of CostMeasurement. The types to create are determined by +// env. +std::vector> CreateCostMeasurements( + const CostMeasurement::Context& context); + +// Creates an instance of RequestCostAccessor. The type to create is determined +// by env. Returns nullptr if the type is not specified in env, or the type of +// CostMeasurement is unregistered.. +std::unique_ptr CreateRequestCostAccessor(); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COST_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/costmodel_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/costmodel_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..770d44287269da27130cacd0c8a9c8946fd48040 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/costmodel_manager.h @@ -0,0 +1,55 @@ +/* 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_COMMON_RUNTIME_COSTMODEL_MANAGER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_COSTMODEL_MANAGER_H_ + +#include + +#include "tensorflow/core/framework/cost_graph.pb.h" +#include "tensorflow/core/graph/costmodel.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/iterator_range.h" + +namespace tensorflow { + +// Used to manage all the cost models for a session. +class CostModelManager { + public: + ~CostModelManager(); + + typedef std::unordered_map CostModelMap; + typedef CostModelMap::iterator CostModelMapIter; + + void ExportCostModels(CostModelMap* cost_models) { + mutex_lock l(mu_); + *cost_models = cost_models_; + } + + CostModel* FindOrCreateCostModel(const Graph* graph); + + bool RemoveCostModelForGraph(const Graph* graph); + + Status AddToCostGraphDef(const Graph* graph, CostGraphDef* cost_graph); + + private: + mutex mu_; + CostModelMap cost_models_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_COSTMODEL_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/debugger_state_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/debugger_state_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..e4815cca4f3c597dce273500c6527f71aceac344 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/debugger_state_interface.h @@ -0,0 +1,122 @@ +/* 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_COMMON_RUNTIME_DEBUGGER_STATE_INTERFACE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEBUGGER_STATE_INTERFACE_H_ + +#include + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/protobuf/debug.pb.h" + +namespace tensorflow { + +// Returns a summary string for the list of debug tensor watches. +const string SummarizeDebugTensorWatches( + const protobuf::RepeatedPtrField& watches); + +// An abstract interface for storing and retrieving debugging information. +class DebuggerStateInterface { + public: + virtual ~DebuggerStateInterface() {} + + // Publish metadata about the debugged Session::Run() call. + // + // Args: + // global_step: A global step count supplied by the caller of + // Session::Run(). + // session_run_index: A chronologically sorted index for calls to the Run() + // method of the Session object. + // executor_step_index: A chronologically sorted index of invocations of the + // executor charged to serve this Session::Run() call. + // input_names: Name of the input Tensors (feed keys). + // output_names: Names of the fetched Tensors. + // target_names: Names of the target nodes. + virtual Status PublishDebugMetadata( + const int64_t global_step, const int64_t session_run_index, + const int64_t executor_step_index, const std::vector& input_names, + const std::vector& output_names, + const std::vector& target_nodes) = 0; +}; + +class DebugGraphDecoratorInterface { + public: + virtual ~DebugGraphDecoratorInterface() {} + + // Insert special-purpose debug nodes to graph and dump the graph for + // record. See the documentation of DebugNodeInserter::InsertNodes() for + // details. + virtual Status DecorateGraph(Graph* graph, Device* device) = 0; + + // Publish Graph to debug URLs. + virtual Status PublishGraph(const Graph& graph, + const string& device_name) = 0; +}; + +typedef std::function( + const DebugOptions& options)> + DebuggerStateFactory; + +// Contains only static methods for registering DebuggerStateFactory. +// We don't expect to create any instances of this class. +// Call DebuggerStateRegistry::RegisterFactory() at initialization time to +// define a global factory that creates instances of DebuggerState, then call +// DebuggerStateRegistry::CreateState() to create a single instance. +class DebuggerStateRegistry { + public: + // Registers a function that creates a concrete DebuggerStateInterface + // implementation based on DebugOptions. + static void RegisterFactory(const DebuggerStateFactory& factory); + + // If RegisterFactory() has been called, creates and supplies a concrete + // DebuggerStateInterface implementation using the registered factory, + // owned by the caller and return an OK Status. Otherwise returns an error + // Status. + static Status CreateState(const DebugOptions& debug_options, + std::unique_ptr* state); + + private: + static DebuggerStateFactory* factory_; + + DebuggerStateRegistry(const DebuggerStateRegistry&) = delete; + void operator=(const DebuggerStateRegistry&) = delete; +}; + +typedef std::function( + const DebugOptions& options)> + DebugGraphDecoratorFactory; + +class DebugGraphDecoratorRegistry { + public: + static void RegisterFactory(const DebugGraphDecoratorFactory& factory); + + static Status CreateDecorator( + const DebugOptions& options, + std::unique_ptr* decorator); + + private: + static DebugGraphDecoratorFactory* factory_; + + DebugGraphDecoratorRegistry(const DebugGraphDecoratorRegistry&) = delete; + void operator=(const DebugGraphDecoratorRegistry&) = delete; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEBUGGER_STATE_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device.h new file mode 100644 index 0000000000000000000000000000000000000000..83785e3341be5980f989a2db554beb496b747823 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device.h @@ -0,0 +1,20 @@ +/* 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_COMMON_RUNTIME_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_H_ + +#include "tensorflow/core/framework/device.h" + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_event_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_event_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..00b300466805b69fef87ad9dcde7c5f6546362ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_event_mgr.h @@ -0,0 +1,142 @@ +/* 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_COMMON_RUNTIME_DEVICE_DEVICE_EVENT_MGR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_EVENT_MGR_H_ + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// TODO(annarev): Check if we can use a more general option representation here +// that could work for other device types as well. +class GPUOptions; + +// The callback provided to EventMgr::ThenExecute must not block or take a long +// time. If it does, performance may be impacted and device memory may be +// exhausted. This macro is for checking that an EventMgr thread is not +// accidentally entering blocking parts of the code, e.g. the RPC subsystem. +// +// Intended use is something like +// +// void RespondToAnRPC(Params* params) { +// WARN_IF_IN_EVENT_MGR_THREAD; +// if (params->status.ok()) { ... +// +namespace device_event_mgr { +// Logs a stack trace if current execution thread belongs to this EventMgr +// object. If f is not nullptr, executes instead of logging the stack trace. +// trace. +void WarnIfInCallback(std::function f); +} // namespace device_event_mgr +#define WARN_IF_IN_EVENT_MGR_THREAD \ + ::tensorflow::device_event_mgr::WarnIfInCallback(nullptr) + +// EventMgr lets you register a callback to be executed when a given +// StreamExecutor stream completes all the work that's thus-far been enqueued on +// the stream. +class EventMgr { + public: + virtual ~EventMgr(); + + // Execute `func` when all pending stream actions have completed. func must + // be brief and non-blocking since it executes in the one thread used for all + // such callbacks and also buffer deletions. + void ThenExecute(se::Stream* stream, std::function func) { + mutex_lock l(mu_); + EnqueueCallback(stream, std::move(func)); + PollEvents(stream); + } + + private: + friend class TEST_EventMgr; + friend class TEST_EventMgrHelper; + friend class EventMgrFactory; + + se::StreamExecutor* const exec_; + const int32 polling_active_delay_usecs_; + mutex mu_; + condition_variable events_pending_ TF_GUARDED_BY(mu_); + + EventMgr(se::StreamExecutor* se, const GPUOptions& gpu_options); + + // Set up `func` to be called once `stream` completes all its outstanding + // work. + void EnqueueCallback(se::Stream* stream, std::function func) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + // This function should be called at roughly the same tempo as QueueTensors() + // to check whether pending events have recorded, and then retire them. + // + // If `stream` is not null, we only poll events for that stream. Otherwise we + // poll events for all streams. + void PollEvents(se::Stream* stream = nullptr) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + // An internal polling loop that runs at a low frequency to clear straggler + // Events. + void PollLoop(); + + // Setup/Teardown functions for the polling loop. + void StartPollingLoop(); + void StopPollingLoop(); + + // A stack of unused events + std::vector> free_events_ TF_GUARDED_BY(mu_); + + // Callbacks waiting on their events to complete. + absl::flat_hash_map< + se::Stream*, + std::deque, std::function>>> + callbacks_ TF_GUARDED_BY(mu_); + + bool stop_polling_ TF_GUARDED_BY(mu_); + std::unique_ptr polling_stopped_; + + // The main PollLoop for the event manager runs in this threadpool. + thread::ThreadPool threadpool_; +}; + +// Manages all the EventMgr instances. +class EventMgrFactory { + public: + static EventMgrFactory* Singleton(); + + EventMgr* GetEventMgr(se::StreamExecutor* se, const GPUOptions& gpu_options); + + private: + mutex mu_; + + // Maintain one EventMgr per physical device (StreamExecutor is + // per-physical-device). + absl::flat_hash_map event_mgr_map_ + TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_EVENT_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_host_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_host_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..4111fc909631cea0b57a95396d0555bcd24aebf6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_host_allocator.h @@ -0,0 +1,28 @@ +/* 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_COMMON_RUNTIME_DEVICE_DEVICE_HOST_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_HOST_ALLOCATOR_H_ + +#include "xla/stream_executor/device_host_allocator.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/stream_executor.h" + +namespace tensorflow { +using stream_executor::DeviceHostAllocator; // NOLINT +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_HOST_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_id.h new file mode 100644 index 0000000000000000000000000000000000000000..382c40aacfacdb5e4999ec1f9461735f47a65ae4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_id.h @@ -0,0 +1,91 @@ +/* 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_COMMON_RUNTIME_DEVICE_DEVICE_ID_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_ID_H_ + +#include "tensorflow/core/lib/gtl/int_type.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/framework/device_id.h" + +namespace tensorflow { + +// There are three types of device ids: +// - *physical* device id: this is the integer index of a device in the +// physical machine, it can be filtered (for e.g. using environment variable +// CUDA_VISIBLE_DEVICES when using CUDA). Note that this id is not visible to +// Tensorflow, but result after filtering is visible to TF and is called +// platform device id as below. +// For CUDA, see +// http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars +// for more details. +// - *platform* device id (also called *visible* device id in +// third_party/tensorflow/core/protobuf/config.proto): this is the id that is +// visible to Tensorflow after filtering (for e.g. by CUDA_VISIBLE_DEVICES). +// For CUDA, this id is generated by the CUDA GPU driver. It starts from 0 +// and is used for CUDA API calls like cuDeviceGet(). +// - TF device id (also called *virtual* device id in +// third_party/tensorflow/core/protobuf/config.proto): this is the id that +// Tensorflow generates and exposes to its users. It is the id in the +// field of the device name "/device:GPU:", and is also the identifier of +// a BaseGPUDevice. Note that the configuration allows us to create multiple +// BaseGPUDevice per GPU hardware in order to use multi CUDA streams on the +// hardware, so the mapping between TF GPU id and platform GPU id is not a 1:1 +// mapping, see the example below. +// +// For example, assuming that in the machine we have GPU device with index 0, 1, +// 2 and 3 (physical GPU id). Setting "CUDA_VISIBLE_DEVICES=1,2,3" will create +// the following mapping between platform GPU id and physical GPU id: +// +// platform GPU id -> physical GPU id +// 0 -> 1 +// 1 -> 2 +// 2 -> 3 +// +// Note that physical GPU id 0 is invisible to TF so there is no mapping entry +// for it. +// +// Assuming we configure the Session to create one BaseGPUDevice per GPU +// hardware, then setting GPUOptions::visible_device_list to "2,0" will create +// the following mapping between TF device id and platform device id: +// +// TF GPU id -> platform GPU ID +// 0 (i.e. /device:GPU:0) -> 2 +// 1 (i.e. /device:GPU:1) -> 0 +// +// Note that platform device id 1 is filtered out by +// GPUOptions::visible_device_list, so it won't be used by the TF process. +// +// On the other hand, if we configure it to create 2 BaseGPUDevice per GPU +// hardware, then setting GPUOptions::visible_device_list to "2,0" will create +// the following mapping between TF device id and platform device id: +// +// TF GPU id -> platform GPU ID +// 0 (i.e. /device:GPU:0) -> 2 +// 1 (i.e. /device:GPU:1) -> 2 +// 2 (i.e. /device:GPU:2) -> 0 +// 3 (i.e. /device:GPU:3) -> 0 +// +// We create strong-typed integer classes for both TF device id and platform +// device id to minimize programming errors and improve code readability. Except +// for the StreamExecutor interface (as we don't change its API), whenever we +// need a TF device id (or platform device id) we should use TfDeviceId (or +// PlatformDeviceId) instead of a raw integer. +using tsl::PlatformDeviceId; // NOLINT +using tsl::TfDeviceId; // NOLINT + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_id_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_id_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..1e9232c270f18726a08e0a189dcfdad7f6f5b023 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_id_manager.h @@ -0,0 +1,28 @@ +/* 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_COMMON_RUNTIME_DEVICE_DEVICE_ID_MANAGER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_ID_MANAGER_H_ + +#include "tensorflow/core/common_runtime/device/device_id.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tsl/framework/device_id_manager.h" + +namespace tensorflow { +using tsl::DeviceIdManager; // NOLINT +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_ID_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_mem_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_mem_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..4ba97a5b68cfbe8a5fdd168be696eec433b99f1b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_mem_allocator.h @@ -0,0 +1,28 @@ +/* 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_COMMON_RUNTIME_DEVICE_DEVICE_MEM_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_MEM_ALLOCATOR_H_ + +#include "xla/stream_executor/device_mem_allocator.h" +#include "tensorflow/core/common_runtime/device/device_id.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/stream_executor.h" + +namespace tensorflow { +using stream_executor::DeviceMemAllocator; // NOLINT +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_MEM_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..91c93a64e46b6621e086059ef9d23a8c36172842 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device/device_utils.h @@ -0,0 +1,41 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_UTILS_H_ + +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/stringpiece.h" + +namespace tensorflow { +namespace device_utils { + +// Validate device type. Device type must start with a capital letter and +// consist of capital letters and underscores. Reasoning behind this decision: +// * At the minimum we want to disallow '/' and ':' since +// these characters are used in device spec, for e.g. +// /job:foo/replica:12/device:GPU:1. +// * Underscores seem useful, for e.g. XLA_GPU uses underscores. +// * Allowing lowercase might get confusing. For example, say someone +// registers a new type called "Gpu". It might be confusing for users that +// "Gpu" is not the same device type as "GPU". +// Note that lowercase "cpu" and "gpu" are currently supported only for +// legacy reasons: +// https://cs.opensource.google/tensorflow/tensorflow/+/master:tensorflow/python/framework/device_spec.py;l=46;drc=d3a378f9665d8eee827c74cb9ecbee81e4c288dd +Status ValidateDeviceType(StringPiece type); + +} // namespace device_utils +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_DEVICE_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_factory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..1b5a662639acbf2fbb249a675807fd2c82d3d943 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_factory.h @@ -0,0 +1,20 @@ +/* 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_COMMON_RUNTIME_DEVICE_FACTORY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_FACTORY_H_ + +#include "tensorflow/core/framework/device_factory.h" + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_FACTORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..6e8420de1733cbe085fa25f8d1d84f925b57bb36 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_mgr.h @@ -0,0 +1,178 @@ +/* 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_COMMON_RUNTIME_DEVICE_MGR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_MGR_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/lib/core/arena.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +class DeviceAttributes; + +// Represents a set of devices. +class DeviceMgr { + public: + DeviceMgr() = default; + virtual ~DeviceMgr(); + + // Returns attributes of all devices. + virtual void ListDeviceAttributes( + std::vector* devices) const = 0; + + // Returns raw pointers to the underlying devices. + virtual std::vector ListDevices() const = 0; + + // Returns a string listing all devices. + virtual string DebugString() const = 0; + + // Returns a string of all the device mapping. + virtual string DeviceMappingString() const = 0; + + // Assigns *device with pointer to Device of the given name. + // Accepts either a full device name, or just the replica-local suffix. + virtual Status LookupDevice(StringPiece name, Device** device) const = 0; + + // Check if the current device manager contains device with the given + // incarnation ID. Looking up by incarnation IDs because they are randomly + // generated and not intentionally reused (unlike device pointers). + virtual bool ContainsDevice(int64_t device_incarnation) const = 0; + + // Clears given containers of all devices if 'container' is + // non-empty. Otherwise, clears default containers of all devices. + virtual void ClearContainers(gtl::ArraySlice containers) const = 0; + + virtual int NumDeviceType(const string& type) const = 0; + + virtual int NumDevices() const = 0; + + // Returns an arbitrary CPU device if one is present, otherwise return + // nullptr. + virtual Device* HostCPU() const = 0; + + DeviceMgr(const DeviceMgr&) = delete; + void operator=(const DeviceMgr&) = delete; +}; + + +// Size of stale device buffer for temporary storage of removed devices. +static const size_t kStaleDeviceBufferSize = 8192; + +// Represents a dynamic set of devices +class DynamicDeviceMgr : public DeviceMgr { + public: + // Constructs an empty DynamicDeviceMgr. + DynamicDeviceMgr(); + + // Constructs a DynamicDeviceMgr from a list of devices. + explicit DynamicDeviceMgr(std::vector>&& devices); + explicit DynamicDeviceMgr(std::unique_ptr&& device); + + ~DynamicDeviceMgr() override; + + void ListDeviceAttributes( + std::vector* devices) const override; + std::vector ListDevices() const override; + string DebugString() const override; + string DeviceMappingString() const override; + Status LookupDevice(StringPiece name, Device** device) const override; + bool ContainsDevice(int64_t device_incarnation) const override; + void ClearContainers(gtl::ArraySlice containers) const override; + int NumDeviceType(const string& type) const override; + int NumDevices() const override; + Device* HostCPU() const override; + + // Add devices to device manager. Returns error for repeated device names. + Status AddDevices(std::vector> devices); + + // Remove devices from device manager. + // Returns error for non-existing devices or if the HostCPU() device is in the + // input list. If an error is returned, the device list is not modified. + Status RemoveDevices(const std::vector& devices); + + // Remove devices from device manager by their names. Returns error for + // non-existing devices or if the HostCPU() device is given in the input list. + // If an error is returned, the device list is not modified. + Status RemoveDevicesByName(const std::vector& device_names); + + private: + mutable mutex devices_mu_; + + // Using an ordered map to ensure deterministic ordering of devices. + // Not a set, because we need to do find(Device*) and own the devices + // at the same time. + // We still have to override C++'s default pointer ordering. + struct DereferenceDevicePtrLess { + bool operator()(const Device* a, const Device* b) const { + return Device::LessByParsedName(*a, *b); + } + }; + std::map, DereferenceDevicePtrLess> + dynamic_devices_ TF_GUARDED_BY(devices_mu_); + + absl::flat_hash_set device_incarnation_set_ + TF_GUARDED_BY(devices_mu_); + std::unordered_map device_map_ TF_GUARDED_BY(devices_mu_); + + std::unordered_map device_type_counts_ + TF_GUARDED_BY(devices_mu_); + + mutable std::atomic cpu_device_; // memoize `HostCPU` result + + class DeviceCircularBuffer { + public: + DeviceCircularBuffer() : index_(0) { + devices_.resize(kStaleDeviceBufferSize); + } + void add(std::unique_ptr device) { + devices_[index_] = std::move(device); + index_ = (index_ + 1) % kStaleDeviceBufferSize; + } + + private: + int index_; + std::vector> devices_; + }; + + // Buffer to temporarily store the removed devices. Raw device pointers are + // accessible to DeviceSet, and if the function instantiation process directly + // access fields through the device set, the underlying device object must + // still be available to avoid segmentation fault. We keep the devices in this + // buffer only for that purpose. + DeviceCircularBuffer stale_devices_ TF_GUARDED_BY(devices_mu_); + + DynamicDeviceMgr(const DynamicDeviceMgr&) = delete; + void operator=(const DynamicDeviceMgr&) = delete; +}; + +// TODO(b/183966398): Remove StaticDeviceMgr since there's no usage. +using StaticDeviceMgr = DynamicDeviceMgr; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_resolver_local.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_resolver_local.h new file mode 100644 index 0000000000000000000000000000000000000000..adb859abc1fd9e3450cb546af53fa26d1d591802 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_resolver_local.h @@ -0,0 +1,47 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_RESOLVER_LOCAL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_RESOLVER_LOCAL_H_ + +#include +#include + +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +class DeviceMgr; + +// Implements DeviceResolverInterface in a single-task context. +class DeviceResolverLocal : public DeviceResolverInterface { + public: + explicit DeviceResolverLocal(const DeviceMgr* dev_mgr) : dev_mgr_(dev_mgr) {} + + Status GetDeviceAttributes(const string& device, + DeviceAttributes* attributes) override; + + Status GetAllDeviceAttributes( + const string& task, std::vector* attributes) override; + + Status UpdateDeviceAttributes( + const std::vector& attributes) override; + + protected: + const DeviceMgr* dev_mgr_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_RESOLVER_LOCAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_set.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_set.h new file mode 100644 index 0000000000000000000000000000000000000000..16dcd0ad6e5a442c2687522c3a2e97a02cf30000 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/device_set.h @@ -0,0 +1,139 @@ +/* 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_COMMON_RUNTIME_DEVICE_SET_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_SET_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace tensorflow { + +typedef std::vector> PrioritizedDeviceVector; + +// DeviceSet is a container class for managing the various types of +// devices used by a model. +class DeviceSet { + public: + DeviceSet(); + ~DeviceSet(); + + // Does not take ownership of 'device'. + void AddDevice(Device* device) TF_LOCKS_EXCLUDED(devices_mu_); + + // Set the device designated as the "client". This device + // must also be registered via AddDevice(). + void set_client_device(Device* device) { + DCHECK(client_device_ == nullptr); + client_device_ = device; + } + + // Returns a pointer to the device designated as the "client". + Device* client_device() const { return client_device_; } + + // Return the list of devices in this set. + const std::vector& devices() const { return devices_; } + + // Given a DeviceNameUtils::ParsedName (which may have some + // wildcards for different components), fills "*devices" with all + // devices in "*this" that match "spec". + void FindMatchingDevices(const DeviceNameUtils::ParsedName& spec, + std::vector* devices) const; + + // Finds the device with the given "fullname". Returns nullptr if + // not found. + Device* FindDeviceByName(const string& fullname) const; + + // Return the list of unique device types in this set, ordered + // with more preferable devices earlier. + std::vector PrioritizedDeviceTypeList() const; + + // Return the prioritized list of devices in this set. + // Devices are prioritized first by `DeviceTypeOrder`, then by name. + const PrioritizedDeviceVector& prioritized_devices() const + TF_LOCKS_EXCLUDED(devices_mu_); + + // Return the prioritized list of unique device types in this set. + // + // The list will be ordered by decreasing priority. The priorities (the second + // element in the list's `std::pair`) will be initialized + // to the value of `DeviceTypeOrder` for the device types. + const PrioritizedDeviceTypeVector& prioritized_device_types() const + TF_LOCKS_EXCLUDED(devices_mu_); + + // An order to sort by device types according to system-determined + // priority. + // + // Higher result implies higher priority. + static int DeviceTypeOrder(const DeviceType& d); + + // Sorts a PrioritizedDeviceVector according to devices and explicit + // priorities. + // + // After a call to this function, the argument vector will be sorted by + // explicit priority (the second element in the `std::pair`), then by `DeviceTypeOrder` of the device type, then by device + // locality, and lastly by device name. + static void SortPrioritizedDeviceVector(PrioritizedDeviceVector* vector); + + // Sorts a PrioritizedDeviceTypeVector according to types and explicit + // priorities. + // + // After a call to this function, the argument vector will be sorted by + // explicit priority (the second element in the `std::pair`), then by `DeviceTypeOrder` of the device type. + static void SortPrioritizedDeviceTypeVector( + PrioritizedDeviceTypeVector* vector); + + private: + mutable mutex devices_mu_; + + mutable absl::flat_hash_map> + matching_device_cache_; + + // Not owned. + std::vector devices_; + + // Cached prioritized vector, created on-the-fly when + // prioritized_devices() is called. + mutable PrioritizedDeviceVector prioritized_devices_ + TF_GUARDED_BY(devices_mu_); + + // Cached prioritized vector, created on-the-fly when + // prioritized_device_types() is called. + mutable PrioritizedDeviceTypeVector prioritized_device_types_ + TF_GUARDED_BY(devices_mu_); + + // Fullname -> device* for device in devices_. + std::unordered_map device_by_name_; + + // client_device_ points to an element of devices_ that we consider + // to be the client device (in this local process). + Device* client_device_ = nullptr; + + DeviceSet(const DeviceSet&) = delete; + void operator=(const DeviceSet&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DEVICE_SET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/direct_session.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/direct_session.h new file mode 100644 index 0000000000000000000000000000000000000000..a81a3079345117ee1b0c8b8e1588ccfed9e307d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/direct_session.h @@ -0,0 +1,450 @@ +/* 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_COMMON_RUNTIME_DIRECT_SESSION_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DIRECT_SESSION_H_ + +#include +#include +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/costmodel_manager.h" +#include "tensorflow/core/common_runtime/debugger_state_interface.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/executor.h" +#include "tensorflow/core/common_runtime/graph_execution_state.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/common_runtime/rendezvous_mgr.h" +#include "tensorflow/core/common_runtime/session_factory.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/session_state.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session.h" + +namespace tensorflow { + +class CostModel; +class DebugGateway; +class Device; +class DirectSessionFactory; + +class DirectSession : public Session { + public: + typedef std::function CloseCallback; + + // Takes ownership of 'device_mgr'. + // 'factory' is used to unregister the DirectSession with 'factory' when its + // closed. This ensures that Reset requests from the 'factory' don't get sent + // to sessions that are already closed. + DirectSession(const SessionOptions& options, const DeviceMgr* device_mgr, + DirectSessionFactory* factory); + ~DirectSession() override; + + typedef std::vector> NamedTensorList; + typedef std::unordered_map NameNodeMap; + + ::tensorflow::Status Create(const GraphDef& graph) override; + ::tensorflow::Status Create(GraphDef&& graph) override; + ::tensorflow::Status Extend(const GraphDef& graph) override; + ::tensorflow::Status Extend(GraphDef&& graph) override; + ::tensorflow::Status Run(const NamedTensorList& inputs, + const std::vector& output_names, + const std::vector& target_nodes, + std::vector* outputs) override; + + // NOTE: Experimental and subject to change. + ::tensorflow::Status Run(const ::tensorflow::RunOptions& run_options, + const NamedTensorList& inputs, + const std::vector& output_names, + const std::vector& target_nodes, + std::vector* outputs, + RunMetadata* run_metadata) override; + + // NOTE: Experimental and subject to change. + ::tensorflow::Status Run( + const ::tensorflow::RunOptions& run_options, + const NamedTensorList& inputs, const std::vector& output_names, + const std::vector& target_nodes, std::vector* outputs, + RunMetadata* run_metadata, + const thread::ThreadPoolOptions& threadpool_options) override; + + // NOTE: PRunSetup and PRun are added to support partial execution. This + // feature is experimental and subject to change. + ::tensorflow::Status PRunSetup(const std::vector& input_names, + const std::vector& output_names, + const std::vector& target_nodes, + string* handle) override; + ::tensorflow::Status PRun(const string& handle, const NamedTensorList& inputs, + const std::vector& output_names, + std::vector* outputs) override; + + // Reset clears 'containers' from the device_mgr of the DirectSession. + // If 'containers' is empty, then Reset clears the default container. + ::tensorflow::Status Reset(const std::vector& containers); + + ::tensorflow::Status ListDevices( + std::vector* response) override; + ::tensorflow::Status Close() override; + ::tensorflow::Status LocalDeviceManager(const DeviceMgr** output) override { + *output = device_mgr_.get(); + return OkStatus(); + } + + void ExportCostModels(CostModelManager::CostModelMap* cost_models) { + cost_model_manager_.ExportCostModels(cost_models); + } + + ::tensorflow::Status MakeCallable(const CallableOptions& callable_options, + CallableHandle* out_handle) override; + + ::tensorflow::Status RunCallable(CallableHandle handle, + const std::vector& feed_tensors, + std::vector* fetch_tensors, + RunMetadata* run_metadata) override; + + ::tensorflow::Status RunCallable( + CallableHandle handle, const std::vector& feed_tensors, + std::vector* fetch_tensors, RunMetadata* run_metadata, + const thread::ThreadPoolOptions& threadpool_options) override; + + ::tensorflow::Status ReleaseCallable(CallableHandle handle) override; + + ::tensorflow::Status Finalize() override; + + const SessionOptions& options() const { return options_; } + + private: + // For access to collective_graph_key_. + friend class DirectSessionCollectiveTest; + + // We create one executor and its dependent library runtime for + // every partition. + struct PerPartitionExecutorsAndLib { + std::unique_ptr graph = nullptr; + Device* device = nullptr; // not owned. + FunctionLibraryRuntime* flib = nullptr; // not owned. + std::unique_ptr executor; + }; + + // An ExecutorsAndKeys is created for a given set of feeds/fetches. + // 'step_count' is the number of times this graph is executed. + // 'graph' is the entire graph being executed. 'name_to_node' + // maps node name to node. We keep 'graph' and 'name_to_node' only in + // the case of partial runs. Each item in 'items' is the executor for + // a partition of the graph bundled with its dependent library runtime. + // 'input_keys' are the rendezvous keys for the feeds and 'output_keys' + // are rendezvous keys for the fetches. + struct ExecutorsAndKeys { + ExecutorsAndKeys() : step_count(0) {} + + std::atomic_int_fast64_t step_count; + std::unique_ptr graph; + NameNodeMap name_to_node; + std::vector items; + std::unordered_map input_name_to_index; + std::unordered_map input_name_to_rendezvous_key; + std::unordered_map output_name_to_index; + std::unordered_map output_name_to_rendezvous_key; + + DataTypeVector input_types; + DataTypeVector output_types; + + CallableOptions callable_options; + + int64_t collective_graph_key = BuildGraphOptions::kNoCollectiveGraphKey; + }; + + // A FunctionInfo object is created for every unique set of feeds/fetches. + // This info could be folded into the ExecutorsAndKeys object but we would + // like to maintain a deletion order in which the OpKernels (owned by the + // executor) should be destroyed first, followed by the resources in the + // device and then followed by the function stuff. + // TODO(rohanj): Consolidate function library definitions so that we can + // instantiate only one ProcFLR and lib_def and make this just a member + // variable and not a vector. + // 'flib_def' is the function library used. + // 'proc_flr' is the collection of FunctionLibraryRuntime objects, one per + // device. + struct FunctionInfo { + std::unique_ptr flib_def; + std::unique_ptr proc_flr; + }; + + // For each live Run() call, the session maintains a RunState. + // 'status' is the current status of the execution. + struct RunState { + mutex mu; + Status status TF_GUARDED_BY(mu); + std::unique_ptr collective_executor; + std::unique_ptr collector; + TensorStore tensor_store; + ScopedStepContainer step_container; + + RunState(int64_t step_id, const std::vector* devices); + }; + + // For each live partial execution, the session maintains a PartialRunState. + // 'executor_done' is "notified" when all executors are done. 'pending_inputs' + // are the set of pending feeds and 'pending_outputs' are the set of pending + // fetches. + struct PartialRunState : public RunState { + Notification executors_done; + std::unordered_map pending_inputs; // true if fed + std::unordered_map pending_outputs; // true if fetched + core::RefCountPtr rendez = nullptr; + + PartialRunState(const std::vector& pending_input_names, + const std::vector& pending_output_names, + int64_t step_id, const std::vector* devices); + + // Returns true if all pending inputs and outputs have been completed. + bool PendingDone() const; + + ~PartialRunState(); + }; + + struct RunStateArgs { + explicit RunStateArgs(const DebugOptions& options) + : debug_options(options) {} + + bool is_partial_run = false; + string handle; + std::unique_ptr graph; + const DebugOptions& debug_options; + int64_t collective_graph_key = BuildGraphOptions::kNoCollectiveGraphKey; + }; + + // Retrieves an already existing set of executors to run 'inputs' and + // 'outputs', or creates and caches them for future use. + ::tensorflow::Status GetOrCreateExecutors( + gtl::ArraySlice inputs, gtl::ArraySlice outputs, + gtl::ArraySlice target_nodes, + ExecutorsAndKeys** executors_and_keys, RunStateArgs* run_state_args); + + // Creates a set of executors to run the subgraph defined by + // `callable_options`. + ::tensorflow::Status CreateExecutors( + const CallableOptions& callable_options, + std::unique_ptr* out_executors_and_keys, + std::unique_ptr* out_func_info, + RunStateArgs* run_state_args); + + // Creates several graphs given the existing graph_def_ and the + // input feeds and fetches, given 'devices'. The graphs share a common + // function library 'flib_def'. + ::tensorflow::Status CreateGraphs( + const BuildGraphOptions& options, + std::unordered_map>* outputs, + std::unique_ptr* flib_def, + RunStateArgs* run_state_args, DataTypeVector* input_types, + DataTypeVector* output_types, int64_t* collective_graph_key); + + ::tensorflow::Status RunInternal( + int64_t step_id, const RunOptions& run_options, + CallFrameInterface* call_frame, ExecutorsAndKeys* executors_and_keys, + RunMetadata* run_metadata, + const thread::ThreadPoolOptions& threadpool_options); + + // Returns whether inter-op execution uses a global pool or the input + // `run_options` requests being run on inter_op_thread_pool = 0 in case + // multiple pools are configured. + bool ShouldUseRunHandlerPool(const RunOptions& run_options) const; + + ::tensorflow::Status ExtendLocked(GraphDef&& graph) + TF_EXCLUSIVE_LOCKS_REQUIRED(graph_state_lock_); + + ::tensorflow::Status ResourceHandleToInputTensor( + const Tensor& resource_tensor, Tensor* retrieved_tensor); + + // Feeds more inputs to the executors, triggering further execution. + ::tensorflow::Status SendPRunInputs( + const std::vector>& inputs, + const ExecutorsAndKeys* executors_and_keys, + IntraProcessRendezvous* rendez); + + // Fetches more outputs from the executors. It waits until the output + // tensors are computed. + ::tensorflow::Status RecvPRunOutputs( + const std::vector& output_names, + const ExecutorsAndKeys* executors_and_keys, PartialRunState* run_state, + std::vector* outputs); + + // Check if the specified fetches can be computed from the feeds + // that we have already provided. + ::tensorflow::Status CheckFetch( + const std::vector>& feeds, + const std::vector& fetches, + const ExecutorsAndKeys* executors_and_keys, + const PartialRunState* run_state); + + // Use the appropriate WaitForNotification function based on whether + // operation_timeout_in_ms is greater than 0. + // + // If the timeout expires, the `cm->StartCancel()` will be called. + ::tensorflow::Status WaitForNotification(Notification* n, + int64_t timeout_in_ms); + void WaitForNotification(Notification* n, RunState* run_state, + CancellationManager* cm, int64_t timeout_in_ms); + + ::tensorflow::Status CheckNotClosed() { + mutex_lock l(closed_lock_); + if (closed_) return errors::Cancelled("Session has been closed."); + return OkStatus(); + } + + ::tensorflow::Status CheckGraphCreated(const char* method) { + mutex_lock l(graph_state_lock_); + if (!graph_created_) { + return errors::InvalidArgument( + "Session was not created with a graph before ", method, "!"); + } + return OkStatus(); + } + + ::tensorflow::Status CreateDebuggerState( + const CallableOptions& options, int64_t global_step, + int64_t session_run_index, int64_t executor_step_index, + std::unique_ptr* debugger_state); + + ::tensorflow::Status DecorateAndPublishGraphForDebug( + const DebugOptions& debug_options, Graph* graph, Device* device); + + const SessionOptions options_; + + // Device structures. + const std::unique_ptr device_mgr_; + std::vector devices_; // not owned + DeviceSet device_set_; + + // Unique session identifier. + string session_handle_; + mutex graph_state_lock_; + bool graph_created_ TF_GUARDED_BY(graph_state_lock_) = false; + bool finalized_ TF_GUARDED_BY(graph_state_lock_) = false; + + // The thread-pools to use for running ops, with a bool indicating if the pool + // is owned. + std::vector> thread_pools_; + + Status init_error_; // Set to an error if construction failed. + + // If true, blocks until device has finished all queued operations in a step. + bool sync_on_finish_ = true; + + std::vector> functions_ + TF_GUARDED_BY(executor_lock_); + + mutex executor_lock_; // protects executors_ + // Holds mappings from signature to the executors that process + // it. The reason for a level of indirection around mapped_type is + // to guarantee address stability. + // The map value is a shared_ptr since multiple map keys can point to the + // same ExecutorsAndKey object. + std::unordered_map> executors_ + TF_GUARDED_BY(executor_lock_); + + class RunCallableCallFrame; + struct Callable { + std::shared_ptr executors_and_keys; + std::shared_ptr function_info; + ~Callable(); + }; + mutex callables_lock_; + int64_t next_callable_handle_ TF_GUARDED_BY(callables_lock_) = 0; + std::unordered_map callables_ + TF_GUARDED_BY(callables_lock_); + + // Holds mappings from handle to partial run state. + std::unordered_map> partial_runs_ + TF_GUARDED_BY(executor_lock_); + + // This holds all the tensors that are currently alive in the session. + SessionState session_state_; + + DirectSessionFactory* const factory_; // not owned + CancellationManager* cancellation_manager_; + std::unique_ptr collective_executor_mgr_; + + // Map of placed stateful nodes, i.e. nodes for which is_stateful() + // is true, such as "params" and "queue" nodes. Once placed these + // nodes can not be moved to a different device. Maps node names to + // device names. + std::unordered_map stateful_placements_ + TF_GUARDED_BY(graph_state_lock_); + + // Execution_state; used when placing the entire graph. + std::unique_ptr execution_state_ + TF_GUARDED_BY(graph_state_lock_); + + // The function library, before any rewrites or optimizations have been + // performed. In particular, CreateGraphs() may need to modify the function + // library; it copies and modifies the function library. + std::unique_ptr flib_def_; + + // true if the Session has been Closed. + mutex closed_lock_; + bool closed_ TF_GUARDED_BY(closed_lock_) = false; + + // For generating unique names for this session instance. + std::atomic edge_name_counter_ = {0}; + std::atomic handle_name_counter_ = {0}; + + // For generating step ids that are unique among all sessions. + static std::atomic_int_fast64_t step_id_counter_; + + // Global timeout for all blocking operations in this session. + const int64_t operation_timeout_in_ms_ = 0; + + // Manages all the cost models for the graphs executed in this session. + CostModelManager cost_model_manager_; + + // For testing collective graph key generation. + mutex collective_graph_key_lock_; + int64_t collective_graph_key_ TF_GUARDED_BY(collective_graph_key_lock_) = -1; + + // Run in caller's thread if RunOptions.inter_op_thread_pool is negative or + // all of following conditions are met: + // 1. This session doesn't own any thread pool. + // 2. RunOptions.inter_op_thread_pool is unspecified or 0. + // 3. This session has a single executor. + // 4. config.inter_op_parallelism_threads is specified to negative explicitly + // or through environment variable TF_NUM_INTEROP_THREADS. + // 5. RunOptions.experimental.use_run_handler_pool is unspecified or false. + // Otherwise run in global thread pool, session owned thread pool or handler + // pool according to other specifications of RunOptions and ConfigProto. + bool run_in_caller_thread_ = false; + + DirectSession(const DirectSession&) = delete; + void operator=(const DirectSession&) = delete; + + // EXPERIMENTAL: debugger (tfdbg) related + friend class DebugGateway; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DIRECT_SESSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/dma_helper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/dma_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..4a76cff1e340b6386b7455b7a3288faa2e341984 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/dma_helper.h @@ -0,0 +1,38 @@ +/* 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_COMMON_RUNTIME_DMA_HELPER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_DMA_HELPER_H_ + +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { + +// For TensorFlow internal use only. +class DMAHelper { + public: + static bool CanUseDMA(const Tensor* t) { return t->CanUseDMA(); } + static const void* base(const Tensor* t) { return t->base(); } + static void* base(Tensor* t) { return t->base(); } + static TensorBuffer* buffer(Tensor* t) { return t->buf_; } + static const TensorBuffer* buffer(const Tensor* t) { return t->buf_; } + static void UnsafeSetShape(Tensor* t, const TensorShape& s) { + t->set_shape(s); + } +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_DMA_HELPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/attr_builder.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/attr_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..6fc817039cc214df4d6d56ccc8e5787d85e805a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/attr_builder.h @@ -0,0 +1,223 @@ +/* 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_COMMON_RUNTIME_EAGER_ATTR_BUILDER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_ATTR_BUILDER_H_ + +// Support for eager execution of TensorFlow kernels. + +#include +#include +#include + +#include "tensorflow/c/eager/abstract_op_attrs.h" +#include "tensorflow/c/tf_attrtype.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op_kernel.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/gtl/inlined_vector.h" +#include "tensorflow/core/platform/fingerprint.h" +#include "tensorflow/core/util/tensor_slice_reader_cache.h" + +namespace tensorflow { + +// Maps attribute name to an encoding of the type of the attribute value. +// If the type is not a list type, the value is the same as the TF_AttrType type +// of the value. Else, the highest order bit is on, and the rest of the bits +// represent the TF_AttrType type of the values in the list. +typedef std::unordered_map AttrTypeMap; + +// Look up OpDef for `op_name`. +Status OpDefForOp(const string& op_name, const OpDef** op_def); + +// Returns the AttrTypeMap for the TensorFlow operation named op_name. +// If op_name is not registered in global op registry, AttrTypeMapForOp assumes +// the op to be a function and returns the default attributes for a function. +// `is_function` is set to true in this case. +Status AttrTypeMapForOp(const char* op_name, const AttrTypeMap** out, + bool* is_function); + +// Looks for 'attr_name' in 'm' and sets 'out' and 'is_list'. +Status AttrTypeByName(const AttrTypeMap& m, const string& attr_name, + TF_AttrType* out, unsigned char* is_list); + +// KernelAndDevice::Init needs a NodeDef only to pass the attribute map through. +// An AttrBuilder is a convenience class to help with that - providing a smaller +// interface than NodeDefBuilder and avoiding expensive (unnecessary?) sanity +// checks (like number of inputs matching the OpDef - we only care about +// attributes here). +// +// TODO(ashankar): Take a closer look at checks in NodeDefBuilder and see which +// ones make sense to replicate. + +// This is a helper class for creating a NodeDef. Additionally, this class +// allows computing a cache key based on fingerprinting the attributes of this +// NodeDef. +// +// Example usage: +// AttrBuilder a; +// a.NumInputs(2); +// a.Set("T", TF_FLOAT); +// tensorflow::Fprint128 cache_key = a.CacheKey("cpu:0"); +// const NodeDef& n = a.BuildNodeDef(); +// +// Calls to NumInputs or Set between multiple invocations to CacheKey may cause +// different values to be returned by CacheKey. +// +// If NumInputs or Set is called, BuildNodeDef should be called again to update +// the NodeDef. +// +// For performance reasons, the class internally delays the actual construction +// of the NodeDef till BuildNodeDef is called, or Set is called with certain +// uncommon types (see template specializations of Set to see which types +// trigger a NodeDef creation). +// +// Setting attributes via `Set` may cause arena-allocated protocol buffer +// messages to be destructed, which is not thread safe. This means that it is +// currently not safe to set attributes on *different* AttrBuilder objects from +// multiple threads. This does not apply to `CopyAttributes`. +class AttrBuilder : public AbstractOpAttrs { + public: + AttrBuilder() + : AbstractOpAttrs(AbstractOpAttrs::AbstractOpAttrsKind::kEager) {} + + ~AttrBuilder() override = default; + explicit AttrBuilder(const char* op) + : AbstractOpAttrs(AbstractOpAttrs::AbstractOpAttrsKind::kEager) { + Reset(op); + } + + void Reset(const char* op) { + op_name_ = op; + num_inputs_ = 0; + encoded_attrs_.clear(); + node_def_finalized_ = false; + cached_cache_key_ = std::nullopt; + device_for_cached_cache_key_.clear(); + } + + const string& op_name() const { return op_name_; } + void set_op_name(const string& name) { op_name_ = name; } + + // Needed to work around call to ValidateNodeDef in CreateOpKernel. + AttrBuilder& NumInputs(int n); + + template + AttrBuilder& Set(StringPiece attr_name, T&& value) { + SetAttrValue(value, &attr_tmp_); + AddAttrIfNotPresent(attr_name, attr_tmp_); + node_def_finalized_ = false; + cached_cache_key_ = std::nullopt; + return *this; + } + + size_t NumAttributes() const { return encoded_attrs_.size(); } + + AttrBuilder& Set(StringPiece attr_name, const AttrValue& value) { + AddAttrIfNotPresent(attr_name, value); + cached_cache_key_ = std::nullopt; + return *this; + } + + // Retrieves the attribute value. + // Note that Get() can involve a linear scan of all attributes with the same + // value type in this Node. This is not an issue, because Get is used rarely + // and nodes have a small number of attributes. + template + Status Get(StringPiece attr_name, T* value) const { + // Common attributes are stored in AttrVecs. This Get() template + // is specialized for them below. If we end up here, the type must be + // among those that we store in the node_def_. + if (!node_def_finalized_) { + return errors::NotFound("No attr named'", attr_name, + "' found in AttrBuilder for ", op_name_); + } + return GetNodeAttr(AttrSlice(node_def_), attr_name, value); + } + + tensorflow::Fprint128 CacheKey(StringPiece device); + + // Fill `m` with the attr-value pairs set via AttrBuilder::Set() so far, as + // well as any default attr-value pairs from the associated op_def, if there + // is one. + void FillAttrValueMap(AttrValueMap* m) const; + + // Fill `m` with the attr-value pairs set via AttrBuilder::Set() so far except + // when the value matches the default for this attr. + // More precisely, if the global op registry contains an OpDef for this op + // and if an attribute value is the same as the default (according to the + // OpDef), this attr-value pair is not added to `m`. + void FillAttrValueMapWithoutDefaults(AttrValueMap* m) const; + const NodeDef& BuildNodeDef(); + + // Transfers the attributes from `other` to this AttrBuilder. Does not + // overwrite existing attributes. Since it does not require deserializing and + // re-serializing attributes, it is much more efficient than going through an + // AttrValueMap. + void CopyAttributes(const AttrBuilder& other); + + void GetNameAttrList(tensorflow::NameAttrList* name_and_attrs) const override; + + bool GetInt(absl::string_view attr_name, int64_t* result) const override; + bool GetFloat(absl::string_view attr_name, float* result) const override; + bool GetBool(absl::string_view attr_name, bool* result) const override; + bool GetType(absl::string_view attr_name, + tensorflow::DataType* result) const override; + Status GetTypeList( + absl::string_view attr_name, + absl::InlinedVector* type_list) const override; + + private: + tensorflow::Fprint128 BuildCacheKeyForDevice(StringPiece device) const; + + template + void SetInAttrValueMap(AttrValueMap* m, const string& attr_name, + T&& value) const { + DCHECK(!node_def_finalized_) + << "Calling SetInAttrValueMap after BuildNodeDef."; + // If attribute is set more than once, its first value prevails + m->insert({attr_name, value}); + } + + void AddAttrIfNotPresent(StringPiece attr_name, const AttrValue& value); + + gtl::FlatMap encoded_attrs_; + mutable AttrValue attr_tmp_; // For encoding + + string op_name_; + int num_inputs_; + NodeDef node_def_; + bool node_def_initialized_; + bool node_def_finalized_; + + std::optional cached_cache_key_; + string device_for_cached_cache_key_; +}; + +template <> +Status AttrBuilder::Get(StringPiece attr_name, int* value) const; +template <> +Status AttrBuilder::Get(StringPiece attr_name, float* value) const; +template <> +Status AttrBuilder::Get(StringPiece attr_name, bool* value) const; +template <> +Status AttrBuilder::Get(StringPiece attr_name, + tensorflow::DataType* value) const; +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_ATTR_BUILDER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/context.h new file mode 100644 index 0000000000000000000000000000000000000000..e45ce40735506c7ec06a49535a2badebaa629068 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/context.h @@ -0,0 +1,914 @@ +/* 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_COMMON_RUNTIME_EAGER_CONTEXT_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/types/optional.h" +#include "tensorflow/c/eager/immediate_execution_context.h" +#include "tensorflow/core/common_runtime/composite_device.h" +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/eager/custom_device.h" +#include "tensorflow/core/common_runtime/eager/custom_device_op_handler.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/kernel_and_device.h" +#include "tensorflow/core/common_runtime/eager/rendezvous_cache.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/common_runtime/rendezvous_mgr.h" +#include "tensorflow/core/example/example.pb.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/log_memory.h" +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/lib/gtl/flatmap.h" +#include "tensorflow/core/lib/gtl/flatset.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/lib/gtl/map_util.h" +#include "tensorflow/core/platform/casts.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/fingerprint.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/platform.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/threadpool.h" +#include "tensorflow/core/public/session_options.h" +#include "tensorflow/core/public/version.h" +#include "tensorflow/core/util/device_name_utils.h" +#include "tsl/platform/refcount.h" + +// "tensorflow/core/platform/platform.h" must be included first before using +// IS_MOBILE_PLATFORM. +#if !defined(IS_MOBILE_PLATFORM) +#include "tensorflow/core/distributed_runtime/eager/eager_client.h" +#include "tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h" +#include "tensorflow/core/distributed_runtime/server_lib.h" +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/distributed_runtime/worker_env.h" +#endif // !IS_MOBILE_PLATFORM + +namespace tensorflow { + +namespace eager { +// We need this forward declaration because we have circular dependency: +// Context -> RemoteMgr -> TensorHandle -> Context. +// TODO(fishx): Remove this once we remove Context dependency in TensorHandle. +class RemoteMgr; +} // namespace eager + +class EagerContext : public ImmediateExecutionContext, public core::RefCounted { + public: + static constexpr uint64 kInvalidContextId = 0; + + static uint64 NewContextId() { + uint64 context_id = random::New64(); + while (context_id == kInvalidContextId) { + context_id = random::New64(); + } + return context_id; + } + + EagerContext( + const SessionOptions& opts, + ContextDevicePlacementPolicy default_device_placement_policy, bool async, + /*const*/ DeviceMgr* device_mgr, bool device_mgr_owned, + /*const*/ tsl::core::RefCountPtr rendezvous, + DistributedFunctionLibraryRuntime* cluster_flr = nullptr, + CollectiveExecutorMgrInterface* collective_executor_mgr = nullptr, + bool run_eager_op_as_function = false, bool jit_compile_rewrite = false); + + void Release() override { Unref(); } + + AbstractTensorInterface* CreateInt64Scalar(int64_t value) override; + AbstractTensorInterface* CreateUint64Scalar(uint64 value) override; + AbstractTensorInterface* CreateInt32Scalar(int32_t value) override; + AbstractTensorInterface* CreateFloatScalar(float value) override; + AbstractTensorInterface* CreateDoubleScalar(double value) override; + AbstractTensorInterface* CreateHalfScalar(Eigen::half value) override; + AbstractTensorInterface* CreateStringScalar( + tensorflow::tstring value) override; + AbstractTensorInterface* CreateComplex128Scalar( + tensorflow::complex128 value) override; + AbstractTensorInterface* CreateBoolScalar(bool value) override; + + AbstractTensorInterface* CreateTensor( + DataType dtype, absl::Span dim_sizes) override; + AbstractTensorInterface* CreateTensor(DataType dtype, const int64_t* dims, + int num_dims, void* data, size_t len, + MemoryReleaser memory_releaser, + void* memory_releaser_arg) override; + + ImmediateExecutionTensorHandle* CreateLocalHandle( + AbstractTensorInterface* t) override; + // Create an abstract tensor handle from tensorflow::Tensor. + ImmediateExecutionTensorHandle* CreateLocalHandleFromTFTensor( + tensorflow::Tensor& t, const char* d_name) override; + ImmediateExecutionTensorHandle* CopyTensorHandleToDevice( + ImmediateExecutionTensorHandle* handle, const char* device_name, + Status* status) override; + ImmediateExecutionOperation* CreateOperation() override; + + // This is a virtual helper function to convert TFRT TensorHandle to + // tensorflow::TensorHandle. In current runtime EagerContext, just forward + // the input since the input tensor handle is already a + // tensorflow::TensorHandle. + ImmediateExecutionTensorHandle* TFTensorHandleFromInterface( + ImmediateExecutionTensorHandle* handle) override; + + Status RegisterFunction(AbstractFunction* f) override; + + bool UsesTFRT() override; + + bool RunEagerOpAsFunction() const; + + void SetRunEagerOpAsFunction(bool enable) override; + + bool JitCompileRewrite() const; + + void SetJitCompileRewrite(bool enable) override; + + void ListDevices(std::vector* device_attributes) override; + + Status AddDevices(std::vector> devices) override; + + thread::ThreadPool* GetThreadPool() { return thread_pool_.get(); } + + // Returns the function library runtime for the given device. + FunctionLibraryRuntime* func_lib(const Device* d) const { + return pflr_->GetFLR(d->name()); + } + + ProcessFunctionLibraryRuntime* pflr() const { return pflr_.get(); } + + std::function)>* runner() { return &runner_; } + + // Specify a executor for this thread. + void SetExecutorForThread(EagerExecutor* executor) override; + + std::shared_ptr> prioritized_device_type_list() + const { + mutex_lock l(device_type_list_mu_); + return prioritized_device_type_list_; + } + + // Clear pending nodes in thread executors and kernel caches. + void ClearCachesAndThreadExecutors() override; + // Clear pending nodes in default executor and kernel caches. + void ClearCachesAndDefaultExecutor(); + + // Sets the device placement policy for the current thread. + void SetThreadLocalDevicePlacementPolicy( + ContextDevicePlacementPolicy policy) override; + + // Returns the device placement policy for the current thread. + ContextDevicePlacementPolicy GetDevicePlacementPolicy() const override; + + // Select an appropriate device for an operation. + // + // Given the preferred device for the operation, and the node_def, finds the + // best suitable device for the operation in this context. + // + // The preferred device is specified as a `ParsedName` containing the elements + // (details) that the resulting device should match. If there are no such + // devices, and the context currently allows soft device placement, a suitable + // device not matching `preferred` will be chosen. + // + // The chosen device is stored in the `device` argument. The argument is not + // modified unless this method returns `OkStatus()`. + Status SelectDevice(DeviceNameUtils::ParsedName preferred, + const NodeDef& ndef, Device** out) const; + + // TODO(mdan): Rename to ContainsFunction. + bool FindFunctionByName(const string& name) const; + + Status FindFunctionOpData(const string& name, + const tensorflow::OpRegistrationData** op_data); + + const FunctionDef* FindFunctionDef(const string& name) const override; + core::RefCountPtr FindRecord( + const string& name) const override; + + Device* HostCPU() const { return host_cpu_device_; } + Device* CanonicalDevice(Device* d) const { + return HostCPU() == d ? nullptr : d; + } + const DeviceNameUtils::ParsedName& HostCPUParsedName() const override { + return HostCPU()->parsed_name(); + } + + const string& HostCPUName() const override { return HostCPU()->name(); } + + GraphCollector* GetGraphCollector() { return &graph_collector_; } + + EagerExecutor& Executor() override; + + // Add the given `fdef` to the local FunctionLibraryDefinition. And add an + // entry to the KernelAndDevice cache for it if it's not exist. + Status AddFunctionDef(const FunctionDef& fdef) override; + + Status AddFunctionDefWithStackTraces( + const FunctionDef& fdef, const StackTracesMap& stack_traces) override; + + // `library` contains all FunctionDefs and GradientDefs to expand `fdef`. Add + // it to the local FunctionLibraryDefinition as well, but no need to add it + // to the KernelAndDevice cache since they won't be executed as + // KernelAndDevices. + Status AddFunctionDef(const FunctionDef& fdef, + const FunctionDefLibrary& library, + bool add_to_local_only = false, + const StackTracesMap& stack_traces = {}); + + const FunctionDef* GetFunctionDef(const string& function_name); + + std::vector ListFunctionNames() override; + tensorflow::ImmediateExecutionContext::CacheStats GetCacheStats() override; + + Status RemoveFunction(const string& func) override; + Status AddRemoveFunctionNotifier(const string& func, + std::function notifier) override; + + // Wait for pending nodes to be finished in local executors (including context + // default executor and thread executors) and executors on remote workers. + // Return combined status of remote executors. If there are multiple errors, + // the Status code will be the same as the first remote executor that has + // errors, and the error message will be combined from all executors. + Status SyncExecutors(); + + Status AsyncWait() override { return SyncExecutors(); } + + core::RefCountPtr GetCachedKernel(Fprint128 cache_key); + Device* GetCachedDevice(Fprint128 device_cache_key); + + void AddKernelToCache(Fprint128 cache_key, KernelAndDevice* kernel); + void AddDeviceToCache(Fprint128 device_cache_key, Device* device); + + bool LogDevicePlacement() const { return log_device_placement_; } + void SetLogDevicePlacement(bool enable) override { + log_device_placement_ = enable; + } + + bool AllowSoftPlacement() const { return allow_soft_placement_; } + void SetAllowSoftPlacement(bool enable) override { + allow_soft_placement_ = enable; + } + bool LogMemory() const { return log_memory_; } + + // Returns a borrowed pointer to the global rendezvous. The rendezvous may + // become invalid if this Context is destroyed. + Rendezvous* GetRendezvous() const { return rendezvous_.get(); } + + void ResetGlobalRendezvousForFunction() override { + mutex_lock l(global_rendezvous_mu_); + // Remove the global rendezvous instance from the local rendezvous table + // if it uses local rendezvous type, which forces EagerContext to create a + // new local rendezvous instance in the table. + // TODO(b/274683676) Why can't we abort the old rendezvous here? + local_rendezvous_cache_.Remove(-1); + TF_CHECK_OK(CreateRendezvousFactory()(-1, nullptr, + &global_rendezvous_for_functions_)); + } + + // Returns the global_rendezvous_for_functions' underlying LocalRendezvous' + // status. If the underlying Rendezvous is not in the local_rendezvous_cache_ + // returns OK. + Status GetGlobalRendezvousForFunctionLocalRendezvousStatus(); + + // Returns a factory which maps from step_id to rendezvous. + // + // When tensor transfer across functions/eager executions using send/recv ops + // are required, `reuse_rendezvous_for_functions` can be set to true so that + // function executions and eager executions use the same rendezvous instance, + // instead of creating new instance per function calls. + // + // The caller of the returned function owns a reference to the resulting + // Rendezvous. + Rendezvous::Factory RendezvousFactory( + bool reuse_rendezvous_for_functions = false) { + // There is an implicit assumption that the global_rendezvous_for_functions_ + // is always an IntraProcessRendezvous to match the behaviour of the + // EagerContext's rendezvous. + // Ref: tensorflow/c/eager/c_api.cc;l=143;rcl=396387348 + // If a cross process kernel needs a rendezvous a new InterProcessRendezvous + // should be created. + if (reuse_rendezvous_for_functions && rendezvous_creator_ == nullptr && +#if !defined(IS_MOBILE_PLATFORM) + worker_env_ == nullptr && +#endif + remote_device_mgr() == nullptr) { + return Rendezvous::Factory{[this](const int64_t step_id, + const DeviceMgr* device_mgr, + tsl::core::RefCountPtr* r) { + mutex_lock l(global_rendezvous_mu_); + *r = global_rendezvous_for_functions_.GetNewRef(); + return OkStatus(); + }}; + } else { + return CreateRendezvousFactory(); + } + } + + CollectiveExecutorMgrInterface* collective_executor_mgr() { + return collective_executor_mgr_.Get(); + } + std::unique_ptr GetCollectiveExecutorHandle() { + return std::make_unique( + + collective_executor_mgr()->FindOrCreate(0), true /*inherit_ref*/); + } + + void SetCollectiveExecutorMgr(CollectiveExecutorMgrInterface* mgr) { + collective_executor_mgr_.Reset(mgr); + } + tensorflow::DeviceMgr* local_device_mgr() const { + return local_device_manager_.Get(); + } + const tensorflow::DynamicDeviceMgr* remote_device_mgr() const { + return remote_device_manager_.Get(); + } + + tensorflow::DynamicDeviceMgr* GetOwnedRemoteDeviceMgr() { + return remote_device_manager_.GetOwned(); + } + + std::vector ListLocalTfDevices() override { + return local_device_mgr()->ListDevices(); + } + + std::vector ListAllTfDevices() override; + + // TODO(apassos) clean up RunMetadata storage. + mutex* MetadataMu() TF_LOCK_RETURNED(metadata_mu_) { return &metadata_mu_; } + bool ShouldStoreGraphs() TF_LOCKS_EXCLUDED(metadata_mu_); + void SetShouldStoreGraphs(bool value) override; + RunMetadata* RunMetadataProto() TF_EXCLUSIVE_LOCKS_REQUIRED(metadata_mu_) { + return run_metadata_.get(); + } + std::unique_ptr ExportRunMetadata() override + TF_LOCKS_EXCLUDED(metadata_mu_); + + void StartStep() override; + void EndStep() override; + ScopedStepContainer* StepContainer(); + + FunctionLibraryDefinition* FuncLibDef() override { return &func_lib_def_; } + +#if !defined(IS_MOBILE_PLATFORM) + // Assign the EagerClient pointer to `client` based on the given device / task + // name, and increment the refcount of the client. The reference ownership is + // transferred to the caller, and the unref should automatically happen when + // destructing the RefCountPtr object at the caller's side. + // `client` must not be initialized or holding a reference of another object + // before calling this method. + Status GetClient(Device* device, + core::RefCountPtr* client); + Status GetClient(const DeviceNameUtils::ParsedName& device_name, + core::RefCountPtr* client); + Status GetClient(const string& remote_task, + core::RefCountPtr* client); + + uint64 GetContextId() const; + uint64 GetContextViewId() const; + void IncrementContextViewId(); + + Status EnableCollectiveOps(const ServerDef& server_def) override; + + // TODO(nareshmodi): Encapsulate remote state into a separate + // class/struct. + // + // Enables the eager context to communicate with remote devices. When + // initializing with this method, this context will be the primary context, + // which will kill all its remote contexts in shutdown. + // + // - server: A ServerInterface that exports the tensorflow.WorkerService. + // Note that this class expects the server to already have been started. + // - remote_eager_workers: A cache from which we can get "EagerClient"s to + // communicate with remote eager services. + // - remote_device_mgr: A DeviceMgr* which contains all remote devices + // (should contain no local devices). + // - remote_contexts: A vector containing task names. + // TODO(b/184375824): clean up parameter order for better readability. + Status InitializeRemoteMaster( + std::unique_ptr server, WorkerEnv* worker_env, + std::shared_ptr worker_session, + std::unique_ptr remote_eager_workers, + std::unique_ptr remote_device_manager, + const std::vector& remote_contexts, uint64 context_id, + tsl::core::RefCountPtr r, + /*const*/ DeviceMgr* local_device_mgr, int keep_alive_secs, + DistributedFunctionLibraryRuntime* cluster_flr, + std::unique_ptr> + remote_mgr); + + // Update an existing master context with a new set of remote workers (i.e., a + // new "view" of cluster membership. Similar to InitializeRemoteMaster but + // this will keep the current context_id and increment a context_view_id, will + // keep the current resource manager so that resources from the previous view + // can still be accessed, and will automatically register existing functions + // if there are newly added hosts. + Status UpdateRemoteMaster( + uint64 context_id, + std::unique_ptr remote_eager_workers, + const std::vector& add_remote_contexts, + const std::vector& remove_remote_contexts); + + // Similar with InitializeRemoteMaster but this context will not kill remote + // contexts in shutdown. + Status InitializeRemoteWorker( + std::unique_ptr remote_eager_workers, + DynamicDeviceMgr* remote_device_mgr, + const std::vector& remote_contexts, uint64 context_id, + uint64 context_view_id, + std::function(const int64_t)> + rendezvous_creator, + DistributedFunctionLibraryRuntime* cluster_flr, + std::unique_ptr> + remote_mgr, + std::function resource_deallocator); + + // Similar with InitializeRemoteWorker but will reuse existing context and + // increment context_view_id. + Status UpdateRemoteWorker( + std::unique_ptr remote_eager_workers, + const std::vector& remote_contexts, uint64 context_id); + + Status StoreCollectiveOpsServer( + std::unique_ptr new_server, DeviceMgr* device_mgr, + CollectiveExecutorMgrInterface* rpc_collective_executor_mgr); + + // For the specified remote worker, preprocess and set its device filters. + Status SetRemoteDeviceFilters(const string& remote_worker, + const std::vector& device_filters); + + // For the specified remote worker, apply the stored device filters to the + // list of device attributes following these rules: + // (1) if the remote worker does not have device filters, all devices are + // visible to the worker; + // (2) if the device is on the remote worker, then it is visible; + // (3) if the device matches at least one device filter, then it is visible. + // The result is saved as a boolean vector of the same length (i.e., + // filtered_device_mask) indicating whether each of the devices is visible to + // the remote worker. + void FilterDevicesForRemoteWorkers( + const string& remote_worker, + const protobuf::RepeatedPtrField& device_attrs, + std::vector* filtered_device_mask); + + // TODO(fishx): Remove the custom deleter once we remove forward declaration. + const std::unique_ptr>& + RemoteMgr() { + return remote_mgr_; + } + + // If true, then tensors should be shipped across processes via the + // EagerService.Enqueue(SendTensorOp). If false, _Send/_Recv ops should be + // used instead (which in-turn use WorkerService.RecvTensor RPCs). + bool UseSendTensorRPC() { return use_send_tensor_rpc_; } + + tensorflow::ServerInterface* GetServer() { return server_.get(); } + + // For LLVM style RTTI. + static bool classof(const AbstractContext* ptr) { + return ptr->getKind() == kEager; + } + + // Function to support distributed C API. + void SetDistributedManager( + std::unique_ptr distributed) + override { + distributed_manager_ = std::move(distributed); + } + ImmediateExecutionDistributedManager* GetDistributedManager() override { + return distributed_manager_.get(); + } + + // May only be used during multi-client setup so that a RemoteRendezvous + // can be initialized instead of defaulting to the IntraProcessRendezvous. + void SetWorkerEnv(WorkerEnv* worker_env, + std::shared_ptr worker_session); +#endif // IS_MOBILE_PLATFORM + + // Closes remote eager contexts, waits for all RPCs to finish, and + // destroys the EagerClientCache. No RPCs can be made through this context + // after this method has been called. + // This method exists to aid a clean shutdown. It causes all RPCs to finish + // and remote TensorHandles to release their references to this context. + // To avoid deadlocks, this method must not be called on the thread + // processing RPCs because it makes RPCs and waits for their completion. + // + // On mobile, it just cleans the caches. + void WaitForAndCloseRemoteContexts(); + + bool PinSmallOpsToCPU() const { return pin_small_ops_to_cpu_; } + + tensorflow::Env* TFEnv() const { return env_; } + + Status FindDeviceFromName(const char* device_name, Device** device) const; + + Status FindCompositeDeviceFromName(StringPiece device_name, + CompositeDevice** device) const; + + bool IsCustomDevice(const string& device_name) override; + + Status RegisterCustomDevice(const string& name, + std::unique_ptr device) override; + + CustomDeviceOpHandler& GetCustomDeviceOpHandler() override { + return custom_device_op_handler_; + }; + + // Find or create a composite device with the given `underlying_devices` and + // `device_name` (if not empty). + Status FindOrCreateCompositeDevice( + const std::vector& underlying_devices, const string& device_name, + CompositeDevice** composite_device); + + bool OnSameTask(const Device* first, const Device* second) const; + // Gets the CPU device on the task of device. + Status CPUDeviceOnTask(const Device* device, Device** cpu_device) const; + + const SessionOptions& session_options() const { return opts_; } + void InitPrioritizedDeviceTypeList(); + + // Re-assign cluster-FLR and re-initialize devices and FLR in process-FLR + void UpdateClusterFLRAndInitDevices( + DistributedFunctionLibraryRuntime* cluster_flr); + + // A constant representing the step id used for the global rendezvous. + // This is used to distibguish whether a user-specified step id should be set. + // Step id value of kGlobalRendezvous is reserved and should not be specified + // by the user. + static const int64_t kGlobalRendezvousId; + + private: + // The class for caching Rendezvous instances per step_id. + // If the Rendezvous object is destroyed for the step, a new one will be + // created on demand. + class LocalRendezvousCache { + public: + LocalRendezvousCache() + : cache_(new RendezvousCache) {} + + tsl::core::RefCountPtr FindOrCreate( + int64_t step_id, DeviceMgr* device_mgr); + + tsl::core::RefCountPtr Find(int64_t step_id) const { + return cache_->Find(step_id); + } + + std::vector GetActiveStepIds() const { + return cache_->GetActiveStepIds(); + } + + void Remove(int64_t step_id) { cache_->Remove(step_id); } + + private: + tsl::core::RefCountPtr> cache_; + }; + + Rendezvous::Factory CreateRendezvousFactory() { + if (rendezvous_creator_ != nullptr) { + return Rendezvous::Factory{[this](const int64_t step_id, + const DeviceMgr* device_mgr, + tsl::core::RefCountPtr* r) { + VLOG(6) << "Creating rendezvous using the rendezvous_creator_."; + *r = rendezvous_creator_(step_id); + return OkStatus(); + }}; + } + +#if !defined(IS_MOBILE_PLATFORM) + if (worker_env_ != nullptr && worker_env_->rendezvous_mgr != nullptr) { + return Rendezvous::Factory{[this](const int64_t step_id, + const DeviceMgr* device_mgr, + tsl::core::RefCountPtr* r) { + VLOG(6) << "Creating rendezvous using the worker_env's rendezvous_mgr."; + // TODO(hhb): Add a Create method and use it here. + auto remote_r = worker_env_->rendezvous_mgr->Find(step_id); + remote_r->Initialize(worker_session_.get()).IgnoreError(); + *r = std::move(remote_r); + return OkStatus(); + }}; + } +#endif + + if (remote_device_mgr() == nullptr) { + return Rendezvous::Factory{[this](const int64_t step_id, + const DeviceMgr* device_mgr, + tsl::core::RefCountPtr* r) { + VLOG(6) << "Creating rendezvous using local_device_mgr."; + *r = local_rendezvous_cache_.FindOrCreate(step_id, local_device_mgr()); + return OkStatus(); + }}; + } + + return Rendezvous::Factory(); + } + + ~EagerContext() override; + + Status MaybeRegisterFunctionRemotely(const FunctionDef& fdef); + Status MaybeRemoveFunctionRemotely(const string& function_name); + Status RegisterExistingFunctionsOnRemoteWorkers( + const std::vector& remote_workers); + + void ResetPFLR(const DeviceMgr* device_mgr, Env* env, + const ConfigProto* config, int graph_def_version, + const FunctionLibraryDefinition* lib_def, + const OptimizerOptions& optimizer_options, + thread::ThreadPool* thread_pool = nullptr, + DistributedFunctionLibraryRuntime* cluster_flr = nullptr); + + void ResetClusterFLR(DistributedFunctionLibraryRuntime* cluster_flr); + void UpdateGlobalRendezvousDeviceManager(tensorflow::DeviceMgr* device_mgr); + + void ClearResourceContainer(const string& name); + + template + struct OwnedOrUnownedHelper { + public: + OwnedOrUnownedHelper() = default; + explicit OwnedOrUnownedHelper(T* object, const bool owned = false) { + Reset(object, owned); + } + + void Reset(std::unique_ptr object) { + owned_object = std::move(object); + unowned_object_ptr = nullptr; + } + + void Reset(T* object, const bool owned = false) { + if (owned) { + owned_object.reset(object); + unowned_object_ptr = nullptr; + } else { + owned_object.reset(nullptr); + unowned_object_ptr = object; + } + } + + bool Owned() const { return owned_object != nullptr; } + + T* GetOwned() const { return owned_object.get(); } + T* Get() const { + return owned_object ? owned_object.get() : unowned_object_ptr; + } + + std::unique_ptr owned_object = nullptr; + T* unowned_object_ptr = nullptr; + }; + + SessionOptions opts_; + const ContextDevicePlacementPolicy default_device_placement_policy_; + + // Note: we cannot use C++11 thread_local here as there is no concept of a + // thread-local-object-local variable in C++11. + mutable mutex policy_map_mu_; + std::unordered_map + device_placement_policy_ TF_GUARDED_BY(policy_map_mu_); + + // This device manager maintains only the local devices on this worker. + OwnedOrUnownedHelper local_device_manager_; + // Maintain copy of all previously created local device managers. + std::vector> old_local_device_managers_; + + // Unowned DynamicDeviceMgr is set on remote worker to allow running + // multi-device function on remote worker. + // This device manager maintains all the devices (including both local and + // remote to this worker) in the cluster. + OwnedOrUnownedHelper remote_device_manager_; + + Device* host_cpu_device_; // Owned by device_manager + mutable mutex device_type_list_mu_; + std::shared_ptr> prioritized_device_type_list_ + TF_GUARDED_BY(device_type_list_mu_); + tsl::core::RefCountPtr rendezvous_; + std::function(const int64_t)> + rendezvous_creator_; + CustomDeviceOpHandler custom_device_op_handler_; + + mutable mutex composite_devices_mu_; + // Maps from the fingerprint of a set of device names to a virtual + // CompositeDevice. + // TODO(b/145922293): Consider taking device names as keys. + absl::flat_hash_map> + composite_devices_ ABSL_GUARDED_BY(composite_devices_mu_); + + FunctionLibraryDefinition func_lib_def_{OpRegistry::Global(), {}}; + + std::unique_ptr thread_pool_; + + // EagerContext owns the DistributedFunctionLibraryRuntime( + // EagerClusterFunctionLibraryRuntime) if using EagerService for remote + // function execution (lazy_copy_function_remote_inputs_=true). + OwnedOrUnownedHelper cluster_flr_; + // One FunctionLibraryRuntime per device. + // func_libs[i] is the FunctionLibraryRuntime corresponding to + // session->devices[i]. + std::unique_ptr pflr_; + + std::function)> runner_; + + mutex cache_mu_; + mutex device_cache_mu_; + mutex remove_function_notifiers_mu_; + struct RegisteredFunction : public core::RefCounted { + ~RegisteredFunction() override = default; + + std::unique_ptr> cached_kernel_keys; + }; + std::unordered_map, + Fprint128Hasher> + kernel_cache_ TF_GUARDED_BY(cache_mu_); + std::unordered_map registered_functions_ + TF_GUARDED_BY(cache_mu_); + absl::flat_hash_map device_cache_ + TF_GUARDED_BY(device_cache_mu_); + std::unordered_map>> + remove_function_notifiers_ TF_GUARDED_BY(remove_function_notifiers_mu_); + + // Whether we should compute RunMetadata. + std::atomic should_store_graphs_{false}; + mutex metadata_mu_; + std::unique_ptr run_metadata_ TF_GUARDED_BY(metadata_mu_); + GraphCollector graph_collector_; + std::atomic log_device_placement_; + std::atomic allow_soft_placement_; + + // Information related to step containers. + std::atomic num_active_steps_; + std::unique_ptr step_container_ + TF_GUARDED_BY(metadata_mu_); + + EagerExecutor default_executor_; + mutable mutex executor_map_mu_; + // Not owned. + std::unordered_map thread_local_executor_ + TF_GUARDED_BY(executor_map_mu_); + std::unordered_map> + has_cleanup_ TF_GUARDED_BY(executor_map_mu_); + + const bool log_memory_; + + // The table of local rendezvous instances for intra-process communication. + // This make sures only one local rendezvous instance exists per step id. + LocalRendezvousCache local_rendezvous_cache_; + + // Whether to use same rendezvous instance across function/eager executions. + std::atomic reuse_rendezvous_for_functions_{false}; + mutable mutex global_rendezvous_mu_; + + // Keeps alive the global rendezvous object. + core::RefCountPtr global_rendezvous_for_functions_ + TF_GUARDED_BY(global_rendezvous_mu_); + + Env* const env_; + + OwnedOrUnownedHelper collective_executor_mgr_; + +#if !defined(IS_MOBILE_PLATFORM) + std::vector GetRemoteContexts() TF_LOCKS_EXCLUDED(remote_state_mu_); + bool IsRemoteContextsEmpty() TF_LOCKS_EXCLUDED(remote_state_mu_); + void CloseAndClearAllRemoteContexts(); + void CloseRemoteContexts(const std::vector& remote_contexts, + uint64 context_id, uint64 context_view_id); + + // TODO(b/184375824): clean up parameter order for better readability. + Status SetMasterContextState( + std::unique_ptr server, WorkerEnv* worker_env, + std::shared_ptr worker_session, + std::unique_ptr remote_eager_workers, + std::unique_ptr remote_device_manager, + uint64 context_id, uint64 context_view_id, + tsl::core::RefCountPtr r, + /*const*/ DeviceMgr* local_device_mgr, int keep_alive_secs, + DistributedFunctionLibraryRuntime* cluster_flr, + std::unique_ptr> + remote_mgr); + + // The server_ is not const since we release it when the context is destroyed. + // Therefore the server_ object is not marked as const (even though it should + // be). + std::unique_ptr server_; + WorkerEnv* worker_env_ = nullptr; + std::shared_ptr worker_session_; + + mutable mutex remote_state_mu_; + + uint64 context_id_ TF_GUARDED_BY(remote_state_mu_); + // The view id of an eager context should be set to 0 when context is created, + // and continuously incremented when context with the same context_id gets + // updated. The view id should be consistent between master and workers. + uint64 context_view_id_ TF_GUARDED_BY(remote_state_mu_); + std::vector remote_contexts_ TF_GUARDED_BY(remote_state_mu_); + std::unique_ptr remote_eager_workers_ + TF_GUARDED_BY(remote_state_mu_); + + int keep_alive_secs_ TF_GUARDED_BY(remote_state_mu_); + std::atomic sleep_for_secs_; + + std::unique_ptr keep_alive_thread_; + mutex keep_alive_thread_shutdown_mu_; + condition_variable keep_alive_thread_cv_; + bool shutting_down_ TF_GUARDED_BY(keep_alive_thread_shutdown_mu_) = false; + + std::unique_ptr> + remote_mgr_; + bool is_master_ TF_GUARDED_BY(remote_state_mu_); + + // Maps from a remote worker to a list of parsed device filters. + std::unordered_map> + cluster_device_filters_ TF_GUARDED_BY(remote_state_mu_); + + // A distributed manager that helps setup, update, and check liveness of + // member tasks in the cluster. + std::unique_ptr distributed_manager_; + +#endif // IS_MOBILE_PLATFORM + + // For a multi device function, the target device of each input is unknown + // until the function is instantiated on the default function device. + // If false, eagerly copy all remote inputs to the default function device; + // if true, lazily copy remote inputs to their target devices to avoid + // redundant copies. + bool lazy_copy_function_remote_inputs_ = false; + bool use_send_tensor_rpc_; + const bool pin_small_ops_to_cpu_; + + // Function that will be invoked in destructor to deallocate resources related + // to this context. + std::function resource_deallocator_ = nullptr; + bool run_eager_op_as_function_; + bool jit_compile_rewrite_; +}; + +inline EagerContext* ContextFromInterface(ImmediateExecutionContext* context) { + return down_cast(context); +} + +namespace internal { +struct EagerContextDeleter { + void operator()(EagerContext* p) const { + if (p != nullptr) { + p->Release(); + } + } +}; +} // namespace internal + +using EagerContextPtr = + std::unique_ptr; + +// Sets the EagerContext owned by the current Python eager Context (see +// TFE_Py_SetEagerContext in python/eager/pywrap_tfe.h). This is always called +// in tandem with TFE_Py_SetEagerContext (but not called by it, because its +// py_context argument is opaque). +// +// Do not use this function in production. It is only intended for testing. +// (see _reset_context in context.py). +// +// Not thread-safe. +void SetCEagerContext(EagerContext* ctx); + +// Returns the EagerContext owned by the current Python eager Context (see +// TFE_Py_SetEagerContext in pywrap_tfe.h). +// +// Not thread-safe. +EagerContext* GetCEagerContext(); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/context_distributed_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/context_distributed_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..b6344827f44ba4665d14ef21f4135e8c38b5c05d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/context_distributed_manager.h @@ -0,0 +1,79 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_DISTRIBUTED_MANAGER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_DISTRIBUTED_MANAGER_H_ + +#include +#include +#include + +#include "tensorflow/c/eager/immediate_execution_context.h" +#include "tensorflow/c/eager/immediate_execution_distributed_manager.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/platform/status.h" + +#if !defined(IS_MOBILE_PLATFORM) +#include "tsl/distributed_runtime/coordination/coordination_service_agent.h" +#include "tsl/distributed_runtime/preemption/preemption_notifier.h" +#endif // !IS_MOBILE_PLATFORM + +namespace tensorflow { +#if !defined(IS_MOBILE_PLATFORM) +class EagerContext; +class ServerDef; + +class EagerContextDistributedManager + : public ImmediateExecutionDistributedManager { + public: + explicit EagerContextDistributedManager(EagerContext* context) + : context_(context) {} + + // When running in a distributed context, `init_timeout_in_ms` requests the + // amount of time to wait for remote workers to respond. + + Status SetOrUpdateServerDef(const ServerDef& server_def, bool reset_context, + int keep_alive_secs, int64_t init_timeout_in_ms, + int retries) override; + + Status InitializeLocalOnlyContext(const ServerDef& server_def, + int keep_alive_secs) override; + + Status EnableCollectiveOps(const ServerDef& server_def) override; + + Status CheckRemoteAlive(const std::string& remote_task_name, + bool* is_alive) override; + + tsl::CoordinationServiceAgent* GetCoordinationServiceAgent() override { + return coordination_service_agent_; + } + void SetCoordinationServiceAgent(tsl::CoordinationServiceAgent* agent) { + coordination_service_agent_ = agent; + } + void SetPreemptionNotifier( + std::unique_ptr notifier) { + preemption_notifier_ = std::move(notifier); + } + + private: + EagerContext* context_; + // Owned by context_->GetServer()->worker_env()->session_mgr. + tsl::CoordinationServiceAgent* coordination_service_agent_ = nullptr; + std::unique_ptr preemption_notifier_; +}; +#endif // !IS_MOBILE_PLATFORM +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CONTEXT_DISTRIBUTED_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/copy_to_device_node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/copy_to_device_node.h new file mode 100644 index 0000000000000000000000000000000000000000..6cbc7b87dd41d1abcd0397d198f1094d510c4672 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/copy_to_device_node.h @@ -0,0 +1,95 @@ +/* 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_COMMON_RUNTIME_EAGER_COPY_TO_DEVICE_NODE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_COPY_TO_DEVICE_NODE_H_ + +#include + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/profiler/lib/scoped_memory_debug_annotation.h" + +namespace tensorflow { + +class CopyToDeviceNode : public EagerNode { + public: + CopyToDeviceNode(TensorHandle* src, TensorHandle* dst, Device* dstd, + const EagerContext& ctx, bool async, bool mirror) + : EagerNode(), + src_(src), + dst_(dst), + dstd_(dstd), + ctx_(ctx), + async_(async), + mirror_(mirror) { + if (async_) { + src_->Ref(); + dst_->Ref(); + } + } + + ~CopyToDeviceNode() override { + if (async_) { + src_->Unref(); + dst_->Unref(); + } + } + + Status Run() override { + tensorflow::Tensor tensor; + profiler::ScopedMemoryDebugAnnotation op_annotation( + "eager::CopyToDeviceNode", "dynamic", tensor.dtype(), + [&tensor]() { return tensor.shape().DebugString(); }); + TF_RETURN_IF_ERROR(src_->CopyToDevice(ctx_, dstd_, &tensor)); + if (!async_ && mirror_) { + Status s = dst_->AddLocalMirror(std::move(tensor), dstd_); + // If a mirror was added since we called HasLocalMirror then just return + // and ignore the error. + if (s.ok() || (s.code() == error::Code::ALREADY_EXISTS)) { + return OkStatus(); + } + return s; + } else { + return dst_->SetTensor(std::move(tensor), dstd_); + } + } + + void Abort(Status status) override { dst_->Poison(status, dstd_); } + + string DebugString() const override { + string out = "[CopyToDeviceNode]"; + strings::StrAppend(&out, " src_tensor: ", src_->DebugString()); + strings::StrAppend(&out, ", dst_tensor: ", dst_->DebugString()); + strings::StrAppend(&out, ", dst_device: ", dstd_ ? dstd_->name() : "[]"); + return out; + } + + TensorHandle* dst() { return dst_; } + + private: + TensorHandle* src_; + TensorHandle* dst_; + Device* dstd_; + const EagerContext& ctx_; + bool async_; + bool mirror_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_COPY_TO_DEVICE_NODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/custom_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/custom_device.h new file mode 100644 index 0000000000000000000000000000000000000000..ed8716fb4b298a9005deec5a92403e37765de55a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/custom_device.h @@ -0,0 +1,134 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CUSTOM_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CUSTOM_DEVICE_H_ + +#include +#include +#include + +#include "tensorflow/c/eager/immediate_execution_context.h" +#include "tensorflow/c/eager/immediate_execution_operation.h" +#include "tensorflow/c/eager/immediate_execution_tensor_handle.h" +#include "tensorflow/core/framework/full_type.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace tensorflow { + +class TensorHandle; +class EagerOperation; +class CustomDeviceTensorHandle; + +// Custom devices intercept the execution of operations (the `Execute` method), +// typically implemented with one or more of the custom device's own executions. +class CustomDevice { + public: + virtual ~CustomDevice() = default; + virtual const string& name() = 0; + virtual Status CopyTensorToDevice( + ImmediateExecutionTensorHandle* tensor, + ImmediateExecutionTensorHandle** result) = 0; + + virtual Status CopyTensorFromDevice( + ImmediateExecutionTensorHandle* tensor, const string& target_device_name, + ImmediateExecutionTensorHandle** result) = 0; + + virtual Status Execute(const ImmediateExecutionOperation* op, + ImmediateExecutionTensorHandle** retvals, + int* num_retvals) = 0; + + // Creates a packed TensorHandle from a group of custom device TensorHandles, + // one of which is on this custom device. + virtual Status Pack(absl::Span handles, + ImmediateExecutionTensorHandle** result) = 0; + + // Returns true signifying to pin to the current custom device. + // Returns false to pin to the physical device. + virtual StatusOr ShallPinToThisDevice( + const ImmediateExecutionOperation* op) = 0; +}; + +// Custom devices do many of the same things as physical Devices, but have a +// much more restricted interface. We pass around ambiguous pointers since +// operations may be placed either on custom or physical devices. +using VariantDevice = std::variant; + +// Indicates either HostCPU or an unset physical device. We never set a null +// CustomDevice*. +const VariantDevice kVariantDeviceNull = static_cast(nullptr); + +// A tensor handle produced by a custom device. Generally they can only be +// consumed by executing an operation on the same custom device that produced it +// originally, or by attempting to copy the handle off the custom device. +// +// TODO(allenl): Currently custom devices are tied to the eager C API. They +// should be renamed op handlers and subclass AbstractTensorHandle instead so +// they are eager/graph agnostic. +// +// full_type_ is not set by the constructor (because it is not currently +// needed). If full type information is needed in the future, the constructor +// could use map_dtype_to_child_of_tensor() from core/framework/types.h to set +// it based on dtype. Update test CustomDevice.TestTensorHandle in +// custom_device_test.cc if this changes. +class CustomDeviceTensorHandle : public ImmediateExecutionTensorHandle { + public: + CustomDeviceTensorHandle(ImmediateExecutionContext* context, + CustomDevice* device, tensorflow::DataType dtype) + : ImmediateExecutionTensorHandle(kCustomDevice), + context_(context), + device_(device), + dtype_(dtype) {} + + // TODO(allenl): Should this be a generic method of + // ImmediateExecutionTensorHandle to support TFE_TensorHandleDevicePointer? + virtual void* DevicePointer() const = 0; + + tensorflow::DataType DataType() const override { return dtype_; } + tensorflow::FullTypeDef FullType() const override { return full_type_; } + Status Shape(PartialTensorShape* shape) const override; + Status NumElements(int64_t* num_elements) const override; + + const char* DeviceName(Status* status) const override { + return device_->name().c_str(); + } + const char* BackingDeviceName(Status* status) const override { + return device_->name().c_str(); + } + CustomDevice* device() const { return device_; } + const char* DeviceType(Status* status) const override; + int DeviceId(Status* status) const override; + + AbstractTensorInterface* Resolve(Status* status) override; + + // For LLVM style RTTI. + static bool classof(const AbstractTensorHandle* ptr) { + return ptr->getKind() == kCustomDevice; + } + + protected: + const DeviceNameUtils::ParsedName* ParsedName(Status* status) const; + + ImmediateExecutionContext* const context_; + CustomDevice* const device_; + const tensorflow::DataType dtype_; + tensorflow::FullTypeDef full_type_; + + mutable std::optional parsed_name_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CUSTOM_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/custom_device_op_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/custom_device_op_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..2f60726566f4411c3758df0741538a0e9fa75f1c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/custom_device_op_handler.h @@ -0,0 +1,59 @@ +/* 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_COMMON_RUNTIME_EAGER_CUSTOM_DEVICE_OP_HANDLER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CUSTOM_DEVICE_OP_HANDLER_H_ + +#include +#include + +#include "tensorflow/c/eager/immediate_execution_operation.h" +#include "tensorflow/c/eager/immediate_execution_tensor_handle.h" +#include "tensorflow/core/common_runtime/eager/custom_device.h" +#include "tensorflow/core/lib/core/status.h" +namespace tensorflow { + +// TODO(tfrt-devs): Figure out a way to unify it with OpHandler in TFRT. +class CustomDeviceOpHandler { + public: + ~CustomDeviceOpHandler() = default; + // Register a new custom device. + Status RegisterCustomDevice(const string& device_name, + std::unique_ptr device); + + // Find the custom device from given name. Return true if it finds one. + bool FindCustomDeviceFromName(const string& name, + CustomDevice** device) const; + + Status Execute(ImmediateExecutionOperation* op, + ImmediateExecutionTensorHandle** retvals, int* num_retvals); + + ImmediateExecutionTensorHandle* CopyTensorHandleToDevice( + ImmediateExecutionContext* context, + ImmediateExecutionTensorHandle* handle, const char* device_name, + Status* status); + + // Determine whether to place an op on a custom device. This method is + // exposed as public for test only. + Status MaybePinToCustomDevice(CustomDevice** device, + const ImmediateExecutionOperation& op) const; + + void Clear(); + + private: + std::unordered_map> custom_devices_; +}; +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_CUSTOM_DEVICE_OP_HANDLER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_executor.h new file mode 100644 index 0000000000000000000000000000000000000000..63e9dedc4fa8eca676b931e2497f0170255b9340 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_executor.h @@ -0,0 +1,290 @@ +/* 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_COMMON_RUNTIME_EAGER_EAGER_EXECUTOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EAGER_EXECUTOR_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/rendezvous_mgr.h" +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/lib/gtl/map_util.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { + +class AsyncEagerNode; +class AsyncRemoteExecuteNode; +namespace eager { +class EagerClient; +} + +// A unit of execution for the EagerExecutor class below. Example subclasses +// encapsulate execution of a TFE_Op, or copying a TFE_TensorHandle from one +// device to another. +class EagerNode { + public: + EagerNode() = default; + + virtual ~EagerNode() = default; + + // Prepares the node when adding it into EagerExecutor. If any errors happens, + // EagerExecutor will abort the node immediately. + virtual Status Prepare() { return OkStatus(); } + + // Runs the computation corresponding to this node and blocks till the + // execution is done. + virtual Status Run() = 0; + + // Called when this node will not be run due to some error contained in + // `status`. `status` must not be OK. + // For example, if the node would have computed some tensors in the Run(), + // it should poison the corresponding tensor handles in this method. + virtual void Abort(Status status) = 0; + + // Returns nullptr iff this Eager node is synchronous. + virtual AsyncEagerNode* AsAsync() { return nullptr; } + virtual AsyncRemoteExecuteNode* AsAsyncRemoteExecuteNode() { return nullptr; } + + virtual string DebugString() const = 0; + + // Indicates whether a node failure should make the executor unusable. + virtual bool Fatal() const { return true; } +}; + +class AsyncEagerNode : public EagerNode { + public: + using EagerNode::EagerNode; // Lift EagerNode constructors. + + // This node will be cleaned up once the done callback is called. + virtual void RunAsync(StatusCallback done) = 0; + + AsyncEagerNode* AsAsync() final { return this; } + + Status Run() final { + return errors::Unimplemented("Don't call AsyncEagerNode::Run()."); + } +}; + +class AsyncRemoteExecuteNode : public AsyncEagerNode { + public: + AsyncRemoteExecuteNode* AsAsyncRemoteExecuteNode() final { return this; } + + virtual const eager::EagerClient* eager_client() const = 0; + virtual bool needs_remote_inputs() const = 0; + virtual bool allow_multiple_pending_requests() const = 0; + virtual Status SyncExecutors() = 0; +}; + +// A class for handling async execution (see TFE_ContextSetAsync). +// Note that this class is thread-safe. +// TODO(agarwal): TFE_OpAddInput may currently block if it tries to access the +// device of the input handle. Fix that. +// TODO(agarwal): Implement support for control dependencies. +// TODO(agarwal): Support out-of-order execution and dispatching multiple +// EagerNode in parallel. +// TODO(agarwal): Implement optimizations over EagerNode traces. +class EagerExecutor { + public: + explicit EagerExecutor(bool async, bool enable_streaming_enqueue = true, + int in_flight_nodes_limit = 0); + + ~EagerExecutor(); + + // Puts this in a shutdown state. In this state, AddOrExecute() will return an + // error and not add new EagerNodes. After putting this in the shutdown state, + // blocks until all pendings nodes have finished running. + // Returns the status of executing pending nodes. + // If async was not enabled, aborts and destroys all pending nodes. + Status ShutDown(); + + bool Async() const; + + bool StreamingEnqueue() const; + + // Inline execute node if executor is in sync mode. + Status SyncExecute(EagerNode* node); + + // - Async Mode: schedules `node` for execution. + // - Sync Mode: inline execute the 'node' directly. + // If an error occurs (e.g. EagerExecutor has already been shut down), the + // `node` is not added to this executor and its Abort() method is called. + Status AddOrExecute(std::unique_ptr node); + + // Blocks till all currently pending ops are done. + // In particular, if EnableAsync() has not beed called, it will not return + // until that happens (and pendings, at the time of call, nodes finish + // running). If this executor has already been shut down, its final status is + // returned. + Status WaitForAllPendingNodes(); + + // Clears all currently set errors which re-enables async execution. + void ClearError(); + + // Returns Status based on any errors that occurred during async execution. + Status status() const { + if (ok()) return OkStatus(); + + tf_shared_lock l(node_queue_mutex_); + return status_; + } + + bool ok() const TF_NO_THREAD_SAFETY_ANALYSIS { return ok_; } + + // On destruction, runs `callback`. Used by the EagerContext for clearing + // thread-local executors. + void AddCleanup(intptr_t key, std::function callback); + // If `key` (e.g. a context) is destroyed before the executor, the associated + // callbacks are no longer safe to run. + void RemoveCleanups(intptr_t key); + + private: + // Possible states for this executor. + // Executor starts in kActive state. When Shutdown() is called, Executor + // is put in the kShuttingDown state. In this state, the executor thread + // continues to run, but no new nodes are accepted. Finally, when all nodes + // are drained, the executor is put in the kShutDown state, which causes the + // thread to exit. + // If this executor is destroyed without calling shutdown first, it + // transitions to kShutDown state immediately which causes the thread to exit + // without running pending nodes. + enum class ExecutorState { + kActive, + kShuttingDown, + kShutDown, + }; + + enum class NodeState { + kPENDING, + kSCHEDULED, + kDONE, + }; + + struct NodeItem : core::RefCounted { + // Unique id generated in EagerExecutor::Add(). If item1.id < item2.id, it + // means item1.node is added before item2.node. + uint64 id; + std::unique_ptr node; + NodeState state; + }; + + const char* StateStringLocked() + TF_EXCLUSIVE_LOCKS_REQUIRED(node_queue_mutex_); + + void NodeDone(const core::RefCountPtr& item, const Status& status, + bool from_queue); + void NotifyWaiters(uint64 id) TF_EXCLUSIVE_LOCKS_REQUIRED(node_queue_mutex_); + + // Starts execution of pending EagerNodes. This function loops till executor + // state_ is set to kShutDown. If any errors are encountered, these are set + // inside `status_`. The loop blocks anytime there are no pending nodes, or if + // `status_` is not ok. + void Run(); + + Status RunItem(core::RefCountPtr item, bool from_queue); + Status MoveToUnfinished(core::RefCountPtr item, bool from_queue); + + // The impl of WaitForAllPendingNodes + // `lock` is the lock that holds node_queue_mutex_. + Status WaitForAllPendingNodesLocked(mutex_lock* lock) + TF_EXCLUSIVE_LOCKS_REQUIRED(node_queue_mutex_); + + Status WaitImpl(bool wait_all, uint64 node_id); + + std::atomic next_node_id_; + + mutable mutex node_queue_mutex_; + + // Used to signal that some EagerNodes are pending execution. + condition_variable nodes_pending_ TF_GUARDED_BY(node_queue_mutex_); + // Used to signal that some EagerNodes are done. + condition_variable nodes_done_ TF_GUARDED_BY(node_queue_mutex_); + + // Queue of pending NodeItems. Ordered by NodeItem::id. + std::queue> node_queue_ + TF_GUARDED_BY(node_queue_mutex_); + + // Ordered by NodeItem::id. + std::map, std::less> + unfinished_nodes_ TF_GUARDED_BY(node_queue_mutex_); + + // `status_` is set based on any errors raised during execution of a + // EagerNode. It remains set until ClearError is called. + Status status_ TF_GUARDED_BY(node_queue_mutex_); + std::atomic ok_ TF_GUARDED_BY(node_queue_mutex_); + + // Map from id of a EagerNode to condition_variables (not owned by the map). + // These condition_variables are notified and removed when that EagerNode is + // done executing, or if an error is found in execution of any EagerNode. + // The map is ordered by id. + std::multimap> + node_done_notifications_ TF_GUARDED_BY(node_queue_mutex_); + + // thread_exited_notification_ is notified by the `thread_` right before it + // exits. + Notification thread_exited_notification_; + + // When state_ is set to kShutDown, it indicates that `thread_` should stop as + // soon as it is done executing the current EagerNode. + ExecutorState state_ TF_GUARDED_BY(node_queue_mutex_) = + ExecutorState::kActive; + + // Thread object that calls the `Run` method in async mode.This thread runs + // until state_ is set to kShuttingDown. It is `nullptr` in sync mode. + const std::unique_ptr thread_; + + // Last device where remote function with remote inputs was executed. + const eager::EagerClient* last_eager_client_; + + const bool enable_async_wait_for_remote_function_; + + // Enable sending remote executions through streaming enqueue. + const bool enable_streaming_enqueue_; + + // Callbacks to run on destruction. + absl::flat_hash_map>> cleanups_; + + // Limit the number of in-flight nodes. When the number of in-flight eager + // async nodes reach this number, enqueuing to the eager async queue is + // blocked. + const int64_t in_flight_nodes_limit_; +}; + +inline bool EagerExecutor::Async() const { return thread_ != nullptr; } + +inline bool EagerExecutor::StreamingEnqueue() const { + return enable_streaming_enqueue_; +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EAGER_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_op_rewrite_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_op_rewrite_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..a70877b57114a2399ddd37d75dfe9ae978d008d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_op_rewrite_registry.h @@ -0,0 +1,109 @@ +/* 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_COMMON_RUNTIME_EAGER_EAGER_OP_REWRITE_REGISTRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EAGER_OP_REWRITE_REGISTRY_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/eager/eager_operation.h" + +namespace tensorflow { + +// Eager op rewrites should inherit from this class and +// implement the Run method. +class EagerOpRewrite { + public: + EagerOpRewrite(string name, string file, string line) { + debug_info_.name = name; + debug_info_.file = file; + debug_info_.line = line; + } + + virtual ~EagerOpRewrite() = default; + + // To be implemented by an Eager op rewrite pass. + virtual Status Run(EagerOperation* orig_op, + std::unique_ptr* out_op) = 0; + + // Holds information about the rewrite registration. + struct DebugInfo { + string name, file, line; + }; + + // Returns information about the registered Eager op rewrite. + DebugInfo GetDebugInfo() const { return debug_info_; } + + private: + DebugInfo debug_info_; +}; + +class EagerOpRewriteRegistry { + public: + // Phases at which the Eager op rewrite pass should run. + enum Phase { + PRE_EXECUTION = 0, // right before executing an eager op + POST_PLACEMENT = 1 // after device placement + }; + + // Add a rewrite pass to the registry. + void Register(Phase phase, int32_t ordinal, + std::unique_ptr pass); + + // Run the rewrite pass registered for a given phase. + Status RunRewrite(Phase phase, EagerOperation* orig_op, + std::unique_ptr* out_op); + + // Returns the global registry of rewrite passes. + static EagerOpRewriteRegistry* Global(); + + private: + static constexpr int32_t kNumPhases = 2; + // Holds all the registered Eager op rewrites and their ordinal numbers. + std::array, int32>>, + kNumPhases> + rewrites_; +}; + +namespace eager_rewrite_registration { + +// This class is used to register a new Eager Op rewrite. +class EagerRewriteRegistration { + public: + EagerRewriteRegistration(EagerOpRewriteRegistry::Phase phase, int32_t ordinal, + std::unique_ptr pass) { + EagerOpRewriteRegistry::Global()->Register(phase, ordinal, std::move(pass)); + } +}; + +} // namespace eager_rewrite_registration + +#define REGISTER_REWRITE(phase, ordinal, rewrite) \ + REGISTER_REWRITE_UNIQ_HELPER(__COUNTER__, __FILE__, __LINE__, phase, \ + ordinal, rewrite) + +#define REGISTER_REWRITE_UNIQ_HELPER(ctr, file, line, phase, ordinal, rewrite) \ + REGISTER_REWRITE_UNIQ(ctr, file, line, phase, ordinal, rewrite) + +#define REGISTER_REWRITE_UNIQ(ctr, file, line, phase, ordinal, rewrite) \ + static ::tensorflow::eager_rewrite_registration::EagerRewriteRegistration \ + register_rewrite_##ctr(phase, ordinal, \ + ::std::unique_ptr<::tensorflow::EagerOpRewrite>( \ + new rewrite(#rewrite, file, #line))) + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EAGER_OP_REWRITE_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_operation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_operation.h new file mode 100644 index 0000000000000000000000000000000000000000..ccde391e8dc53da0f3a4a84c417163ebfc690e42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/eager_operation.h @@ -0,0 +1,323 @@ +/* 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_COMMON_RUNTIME_EAGER_EAGER_OPERATION_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EAGER_OPERATION_H_ + +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/types/optional.h" +#include "absl/types/span.h" +#include "absl/types/variant.h" +#include "tensorflow/c/eager/abstract_tensor_handle.h" +#include "tensorflow/c/eager/immediate_execution_operation.h" +#include "tensorflow/core/common_runtime/eager/attr_builder.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/kernel_and_device.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/op_def.pb.h" +#include "tensorflow/core/util/device_name_utils.h" +#include "tensorflow/core/util/managed_stack_trace.h" + +namespace tensorflow { + +class EagerOperation : public ImmediateExecutionOperation { + public: + explicit EagerOperation(tensorflow::EagerContext* ctx) + : ImmediateExecutionOperation(kEager), ctx_(*ctx), is_function_(false) {} + ~EagerOperation() override { + for (ImmediateExecutionTensorHandle* h : inputs_) { + h->Unref(); + } + } + + void Release() override { delete this; } + + void Clear() override; + Status Reset(const char* op, const char* raw_device_name) override { + return Reset(op, raw_device_name, false, nullptr); + } + + const string& Name() const override { return attrs_.op_name(); } + + const string& DeviceName() const override { return device_name_; } + + ImmediateExecutionContext* GetContext() const override { return &ctx_; } + + const DeviceNameUtils::ParsedName& GetDeviceParsedName() const { + return device_parsed_name_; + } + + // Replaces the previous device name with the given one (see + // AbstractOperation::SetDeviceName for more details). + // + // This also resets the internal device pointer, unless the given name refers + // to a known custom device, in which case the internal device pointer is + // updated to that device. + Status SetDeviceName(const char* name) override; + + void SetDevice(VariantDevice device) { + device_ = device; + device_name_ = std::visit( + [](auto* device) { return device == nullptr ? "" : device->name(); }, + device); + DeviceNameUtils::ParseFullName(device_name_, &device_parsed_name_); + // TODO(b/154133594): Due to intricacies of external logic, we can not + // set this do device_name_ as it would be natural, because we need the + // next call to SetDeviceName to reset the device pointer. + last_set_device_name_ = "\177"; // DEL (an invalid value) + } + + Status SetAttrValue(const char* attr_name, const AttrValue& value); + + Status AddInput(AbstractTensorHandle* input) override; + Status AddInputList(absl::Span inputs) override; + Status SetInput(size_t index, ImmediateExecutionTensorHandle* input) override; + absl::Span GetInputs() const override; + bool HasCustomDeviceInput() const override { + return custom_device_tensor_handles_count_ > 0; + } + Status Execute(absl::Span retvals, + int* num_retvals) override; + const tensorflow::OpDef* OpDef() const override { return op_def_; }; + + Status SetAttrString(const char* attr_name, const char* data, + size_t length) override; + Status SetAttrInt(const char* attr_name, int64_t value) override; + Status SetAttrFloat(const char* attr_name, float value) override; + Status SetAttrBool(const char* attr_name, bool value) override; + Status SetAttrType(const char* attr_name, DataType value) override; + Status SetAttrShape(const char* attr_name, const int64_t* dims, + int num_dims) override; + Status SetAttrFunction(const char* attr_name, + const AbstractOperation* value) override; + Status SetAttrFunctionName(const char* attr_name, const char* data, + size_t length) override; + Status SetAttrTensor(const char* attr_name, + AbstractTensorInterface* tensor) override; + Status SetAttrStringList(const char* attr_name, const void* const* values, + const size_t* lengths, int num_values) override; + Status SetAttrFloatList(const char* attr_name, const float* values, + int num_values) override; + Status SetAttrIntList(const char* attr_name, const int64_t* values, + int num_values) override; + Status SetAttrTypeList(const char* attr_name, const DataType* values, + int num_values) override; + Status SetAttrBoolList(const char* attr_name, const unsigned char* values, + int num_values) override; + Status SetAttrShapeList(const char* attr_name, const int64_t** dims, + const int* num_dims, int num_values) override; + Status SetAttrFunctionList( + const char* attr_name, + absl::Span values) override; + + Status InputLength(const char* input_name, int* length) override; + Status OutputLength(const char* output_name, int* length) override; + + const AbstractOpAttrs* GetOpAttrs() const override; + void AddAttrs(const AbstractOpAttrs* op_attrs) override; + + void SetStackTrace(ManagedStackTrace stack_trace) override { + stack_trace_ = stack_trace; + } + + std::optional GetStackTrace() override { + return stack_trace_; + } + + Status Reset( + const char* op, const char* device_name, bool remote, + EagerExecutor* executor, + absl::optional eager_func_params = std::nullopt); + + bool is_function() const { return is_function_; } + bool colocation_exempt() const { return colocation_exempt_; } + + tensorflow::EagerContext& EagerContext() const { return ctx_; } + + AttrBuilder* MutableAttrs() { return &attrs_; } + const AttrBuilder& Attrs() const { return attrs_; } + + // TensorHandleInputs and MutableTensorHandleInputs first check that all + // inputs are TensorHandles, i.e. that there are no custom device inputs. They + // return a bad status otherwise. + Status TensorHandleInputs( + const absl::InlinedVector** inputs) const; + Status MutableTensorHandleInputs( + absl::InlinedVector** inputs); + + const absl::InlinedVector& Inputs() + const { + return inputs_; + } + + void UpdateInput(int i, TensorHandle* h); + + // This is useful if we want the EagerOperation to point to a different + // function. + void UpdateName(const string& name) { + op_name_ = name.c_str(); + attrs_.set_op_name(name); + } + + // Like TensorHandles, EagerOperations may be placed either on a virtual + // CustomDevice or on a physical Device. + VariantDevice Device() const { return device_; } + + // Indicates whether the op is assigned to a device that is local to the + // current host. + bool IsLocal() const; + + CancellationManager* GetCancellationManager() const { + return cancellation_manager_; + } + void SetCancellationManager( + CancellationManager* cancellation_manager) override { + cancellation_manager_ = cancellation_manager; + } + + // Assign step_id value only if op has valid step id. + // When eager_func_params.has_value() returns true, we can directly overwrite + // its step id according to Op's step id (if not default value). However, when + // eager_func_params.has_value() returns false, we need to first create a new + // EagerFuncParams object for it before assigning step_id; otherwise, + // directly assigning step_id in this case leaves eager_func_params to be + // in a weird state where: + // (1) eager_func_params.has_value() returns false, but + // (2) eager_func_params->step_id.has_value() returns true. + void SetStepId(int64_t step_id) override { + assert(is_function()); + if (step_id != EagerContext::kGlobalRendezvousId) { + if (eager_func_params_.has_value()) { + eager_func_params_->step_id = step_id; + } else { + eager_func_params_ = EagerFunctionParams{ + kInvalidOpId, /*is_component_function=*/false, step_id}; + } + } else { + LOG(WARNING) << "SetStepId() should not receive a gloabl rendezvous id."; + } + } + + EagerExecutor& Executor() { return *executor_; } + + string DebugString() const; + + const absl::optional& eager_func_params() const { + return eager_func_params_; + } + + // Op name recorded for memory debugging purpose. + const char* op_name() const { return op_name_; } + + // For LLVM style RTTI. + static bool classof(const AbstractOperation* ptr) { + return ptr->getKind() == kEager; + } + + private: + void AddTensorHandle(ImmediateExecutionTensorHandle* h); + + const tensorflow::OpDef* GetOpDef(Status* status); + + void ClearInferenceState() { + op_def_ = nullptr; + inference_arg_idx_ = 0; + inference_attrs_.clear_no_resize(); + } + + Status MaybeInferSingleInputAttrs(ImmediateExecutionTensorHandle* handle); + Status InferInputListAttrs(int num_inputs); + + void InferSingleTypeInputListAttrs(const OpDef::ArgDef& input_def, + DataType dtype, int num_inputs); + void InferMixedTypeInputListAttrs(const OpDef::ArgDef& input_def, + const std::vector& dtypes); + + tensorflow::EagerContext& ctx_; + const char* op_name_ = nullptr; + AttrBuilder attrs_; + const AttrTypeMap* attr_types_; + + // The number of custom device TensorHandle inputs. These inputs need to be + // processed by CustomDeviceOpHandler first. + int custom_device_tensor_handles_count_ = 0; + absl::InlinedVector inputs_; + + // The last device name given to SetDeviceName. + // This is used to avoid having to re-process the same device in repeated + // calls to SetDeviceName. + string last_set_device_name_; + + // The operation's device name. + // This contains the named passed to SetDeviceName until device_ is set, + // at which point it contains the device_ name. + string device_name_; + + // The parsed device name. + // This will always contain the result of + // DeviceNameUtils::ParseFullName(device_name_). + DeviceNameUtils::ParsedName device_parsed_name_; + + // The operation's device. + // This is set by the execution device placement logic, and should conform + // with the contents of device_name_. Once it is set, the device_name_ is + // updated accordingly. + VariantDevice device_; + + std::optional stack_trace_; + bool is_function_; // Conceptually const, but can't be because of Reset + bool colocation_exempt_; + CancellationManager* cancellation_manager_ = nullptr; // Not owned. + EagerExecutor* executor_; // Not owned. + + std::optional eager_func_params_; + + // Inference information + const tensorflow::OpDef* op_def_; // op definition from protobuf + int inference_arg_idx_; // arg definition index for the next input to be + // added + gtl::FlatSet inference_attrs_; // attributes inferred so far +}; + +inline void EagerOperation::UpdateInput(int i, TensorHandle* h) { + ImmediateExecutionTensorHandle** slot = &inputs_[i]; + ImmediateExecutionTensorHandle* existing = *slot; + if (existing != h) { + h->Ref(); + existing->Unref(); + *slot = h; // Update inputs_[i] to h + } +} + +inline EagerOperation* OperationFromInterface( + ImmediateExecutionOperation* operation) { + return down_cast(operation); +} + +inline const EagerOperation* OperationFromInterface( + const ImmediateExecutionOperation* operation) { + return down_cast(operation); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EAGER_OPERATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/execute.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/execute.h new file mode 100644 index 0000000000000000000000000000000000000000..5cba8cf0243207a7ae59920141dae52b4e768163 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/execute.h @@ -0,0 +1,90 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EXECUTE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EXECUTE_H_ + +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/common_runtime/eager/eager_operation.h" +#include "tensorflow/core/common_runtime/eager/kernel_and_device.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/framework/step_stats.pb.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Utility function that executes a fully constructed EagerOperation. +// There are a few possible different combinations of how things can be +// executed: +// - Async (the op context is configured to schedule asynchronously) +// Eager execute should return quickly after scheduling this operation to +// execute. +// - Remote (the op device is on a remote task) +// Eager execute will send an RPC to execute the op on a remote device. +// Note that in the Async + Remote case, EagerExecute should still return +// quickly, but it will schedule the op to be executed remotely. +// +// 'retvals' must point to a pre-allocated array of TensorHandle* and +// '*num_retvals' should be set to the size of this array. It is an error if +// the size of 'retvals' is less than the number of outputs. This call sets +// *num_retvals to the number of outputs. +Status EagerExecute(EagerOperation* op, TensorHandle** retvals, + int* num_retvals); + +// Low-level utility to execute the kernel specified by `kernel` on +// `kernel->device()`, with the inputs op_inputs, in the context 'ctx'. +Status EagerKernelExecute( + EagerContext* ctx, const absl::InlinedVector& op_inputs, + const absl::optional& eager_func_params, + const core::RefCountPtr& kernel, + GraphCollector* graph_collector, CancellationManager* cancellation_manager, + absl::Span retvals, + const absl::optional& stack_trace = {}); + +// Low-level utility to copy a tensor handle from one device to another. If +// successful, result TensorHandle will be populated. If the caller requests for +// the mirror flag, EagerCopyToDevice will attempt to add a mirror to the +// original handle and update *result to point to h. Since this is not +// guaranteed, callers should always use the value in *result. +Status EagerCopyToDevice(TensorHandle* h, EagerContext* ctx, + EagerExecutor* executor, Device* device, bool mirror, + TensorHandle** result); + +// Utility function that executes a fully constructed EagerOperation +// asynchronously on the local task. This function works differently from +// EagerExecute in several ways: +// - It supports local execution only. +// - It returns after launching the eager operation to run asynchronously. +// Different from EagerExecute with async context that apends the operation +// to the end of the eager executor schedule queue, this call bypasses the +// executor logic and directly launches op execution. Ops running through +// this call does NOT have an ordering and can be executed in parallel. +// - It takes a StatusCallback which will be triggered after execution with the +// execution status. +// +// Does not support custom device. +// +// 'retvals' must point to a pre-allocated array of TensorHandle* and +// '*num_retvals' should be set to the size of this array. It is an error if +// the size of 'retvals' is less than the number of outputs. This call sets +// *num_retvals to the number of outputs. +void EagerLocalExecuteAsync(EagerOperation* op, TensorHandle** retvals, + int* num_retvals, StatusCallback done); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EXECUTE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/execute_node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/execute_node.h new file mode 100644 index 0000000000000000000000000000000000000000..8fbe075c34ce1a069e5aa8cfe7680bfc4280322d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/execute_node.h @@ -0,0 +1,249 @@ +/* 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_COMMON_RUNTIME_EAGER_EXECUTE_NODE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EXECUTE_NODE_H_ + +// clang-format off +// Required for IS_MOBILE_PLATFORM +#include +#include +#include +#include +#include +#include +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/platform.h" +// clang-format on + +#include "absl/container/inlined_vector.h" +#include "absl/memory/memory.h" +#include "absl/types/optional.h" +#include "absl/types/span.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/execute.h" +#include "tensorflow/core/common_runtime/eager/kernel_and_device.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/framework/step_stats.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/strcat.h" +#if !defined(IS_MOBILE_PLATFORM) +#include "tensorflow/core/distributed_runtime/eager/remote_mgr.h" +#include "tensorflow/core/protobuf/remote_tensor_handle.pb.h" +#endif // IS_MOBILE_PLATFORM + +namespace tensorflow { + +class ExecuteNodeArgs : public EagerKernelArgs { + public: + explicit ExecuteNodeArgs(int count) : EagerKernelArgs(count) {} + + Status Init(EagerContext* ctx, + const absl::InlinedVector& op_inputs, + const core::RefCountPtr& kernel); + + Status GetLocalArg(const FunctionArgIndex& index, Tensor* val) const override; + + bool HasRemoteOrPackedInputs() const override { + return has_remote_inputs_ || has_packed_inputs_; + }; + +#if !defined(IS_MOBILE_PLATFORM) + Status GetRemoteArg(const FunctionArgIndex& index, + eager::RemoteTensorHandle* val) const override { + return serialize_remote_handle_(index, val); + } +#endif // IS_MOBILE_PLATFORM + + private: +#if !defined(IS_MOBILE_PLATFORM) + // Returns whether `handle` is a remote handle or has a remote mirror on + // `input_device` + bool IsRemote(EagerContext* ctx, Device* input_device, TensorHandle* handle); +#endif // IS_MOBILE_PLATFORM + + // Initialize a packed TensorHandle which is the `index`-th argument. + Status InitPackedHandle(int index, EagerContext* ctx, Device* input_device, + TensorHandle* packed_handle); + + bool has_remote_inputs_ = false; + bool has_packed_inputs_ = false; + // Maps from the index of a packed arg to a list of sub-args. + absl::flat_hash_map> packed_args_; +#if !defined(IS_MOBILE_PLATFORM) + std::function + serialize_remote_handle_; +#endif // IS_MOBILE_PLATFORM +}; + +class ExecuteNode : public EagerNode { + public: + ExecuteNode(EagerContext* ctx, + const absl::InlinedVector& inputs, + const absl::optional& eager_func_params, + const core::RefCountPtr& kernel, + GraphCollector* graph_collector, + CancellationManager* cancellation_manager, + absl::Span retvals, + std::optional stack_trace) + : EagerNode(), + ctx_(ctx), + inputs_(inputs), + eager_func_params_(eager_func_params), + kernel_(kernel), + graph_collector_(graph_collector), + cancellation_manager_(cancellation_manager), + retvals_(retvals), + stack_trace_(stack_trace) {} + + Status Run() override { + int i = 0; + for (TensorHandle* h : inputs_) { + if (h->RefCountIsOne()) { + const Device* d = ctx_->CanonicalDevice(kernel_->InputDevice(i)); + Status s = h->Unprotect(d); + if (!s.ok()) { + VLOG(1) << "Unable to unprotect tensor: " << s; + } + } + ++i; + } + return EagerKernelExecute(ctx_, inputs_, eager_func_params_, kernel_, + graph_collector_, cancellation_manager_, retvals_, + stack_trace_); + } + + void Abort(Status status) override {} + + std::string DebugString() const override { + std::string out = "[ExecuteNode]"; + strings::StrAppend(&out, " kernel: ", kernel_->name()); + return out; + } + + private: + EagerContext* ctx_; + const absl::InlinedVector& inputs_; + const absl::optional& eager_func_params_; + const core::RefCountPtr& kernel_; + GraphCollector* graph_collector_; + CancellationManager* const cancellation_manager_; + absl::Span retvals_; + std::optional stack_trace_; +}; + +class AsyncExecuteNode : public EagerNode { + public: + AsyncExecuteNode(EagerContext* ctx, + const absl::InlinedVector& inputs, + const absl::optional& eager_func_params, + core::RefCountPtr kernel, + GraphCollector* graph_collector, + CancellationManager* cancellation_manager, + absl::Span retvals, + std::optional stack_trace) + : EagerNode(), + ctx_(ctx), + inputs_(inputs), + eager_func_params_(eager_func_params), + kernel_(std::move(kernel)), + graph_collector_(graph_collector), + cancellation_manager_(cancellation_manager), + stack_trace_(stack_trace) { + // Copy the output handles, since the container for them might get + // destroyed. + for (auto handle : retvals) { + handle->Ref(); + retvals_.push_back(handle); + } + + // This is required to ensure that the tensor handles stay alive across + // the execution. + for (auto handle : inputs_) { + handle->Ref(); + } + } + + ~AsyncExecuteNode() override { + for (auto handle : retvals_) { + handle->Unref(); + } + + for (auto handle : inputs_) { + handle->Unref(); + } + } + + Status Run() override { + int i = 0; + for (TensorHandle* h : inputs_) { + if (h->RefCountIsOne()) { + const Device* d = ctx_->CanonicalDevice(kernel_->InputDevice(i)); + Status s = h->Unprotect(d); + if (!s.ok()) { + VLOG(1) << "Unable to unprotect tensor: " << s; + } + } + ++i; + } + Status status = EagerKernelExecute( + ctx_, inputs_, eager_func_params_, kernel_, graph_collector_, + cancellation_manager_, absl::MakeSpan(retvals_), stack_trace_); + if (!status.ok()) { + if (stack_trace_.has_value()) { + errors::SetStackTrace( + status, stack_trace_->ToStackFrames( + {}, {}, /*reverse_traversal=*/false, /*limit=*/-1)); + } + Abort(status); + return status; + } + // If status is ok, EagerKernelExecute would have called SetTensor on + // all the output handles. + return OkStatus(); + } + + void Abort(Status status) override { + int i = 0; + for (auto handle : retvals_) { + handle->Poison(status, ctx_->CanonicalDevice(kernel_->OutputDevice(i))); + ++i; + } + } + + std::string DebugString() const override { + std::string out = "[AsyncExecuteNode]"; + strings::StrAppend(&out, " kernel: ", kernel_->name()); + return out; + } + + private: + EagerContext* ctx_; + absl::InlinedVector inputs_; + const absl::optional eager_func_params_; + core::RefCountPtr kernel_; + GraphCollector* graph_collector_; + CancellationManager* const cancellation_manager_; + std::optional stack_trace_; + absl::InlinedVector retvals_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_EXECUTE_NODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/kernel_and_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/kernel_and_device.h new file mode 100644 index 0000000000000000000000000000000000000000..a98427a9e04d27186fda17578225032f240a888f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/kernel_and_device.h @@ -0,0 +1,412 @@ +/* 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_COMMON_RUNTIME_EAGER_KERNEL_AND_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_KERNEL_AND_DEVICE_H_ + +// Support for eager execution of TensorFlow kernels. + +#include +#include +#include +#include +#include +#include +#include + +// clang-format off +// Required for IS_MOBILE_PLATFORM +#include "absl/memory/memory.h" +#include "tensorflow/core/platform/platform.h" +// clang-format on + +#include "absl/container/flat_hash_map.h" +#include "absl/types/optional.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op_kernel.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/gtl/inlined_vector.h" +#include "tensorflow/core/platform/fingerprint.h" +#include "tensorflow/core/util/managed_stack_trace.h" +#include "tensorflow/core/util/tensor_slice_reader_cache.h" +#if !defined(IS_MOBILE_PLATFORM) +#include "tensorflow/core/protobuf/remote_tensor_handle.pb.h" +#endif // IS_MOBILE_PLATFORM + +namespace tensorflow { + +static constexpr const char* const kOutputsOnOpDevice = "_OutputsOnOpDevice"; + +class ProcessFunctionLibraryRuntime; +class FunctionLibraryRuntime; + +const int64_t kInvalidOpId = -1; + +// This struc is used for: +// 1. setting op_id and step_id, is_component_function for single-client +// remote function scenario, +// 2. setting step_id for multi-client parallel_device scenario. +struct EagerFunctionParams { + int64_t op_id = kInvalidOpId; + bool is_component_function; + std::optional step_id = std::nullopt; +}; + +class EagerKernelArgs : public FunctionArgsInterface { + public: + EagerKernelArgs() = default; + + explicit EagerKernelArgs(int count) : tensor_args_(count) {} + + explicit EagerKernelArgs(gtl::InlinedVector&& tensor_args) + : tensor_args_(std::move(tensor_args)) {} + + ~EagerKernelArgs() override = default; + + bool HasRemoteOrPackedInputs() const override { return false; }; + TensorValue* MutableInput(int i) { return &tensor_args_[i]; } + + Status GetLocalArg(const FunctionArgIndex& index, Tensor* val) const override; + + std::vector GetLocalTensors() const override; + + const gtl::InlinedVector* GetTensorValues() const { + return &tensor_args_; + } + + protected: + gtl::InlinedVector tensor_args_; +}; + +typedef std::variant EagerKernelRet; + +// KernelAndDevice encapsulates the logic needed to run a computation eagerly. +// The computation can be a single instantiated kernel (implemented by +// KernelAndDeviceOp below) or a multi-device function (implemented by +// KernelAndDeviceFunc below). +// +// Also see: +// https://www.tensorflow.org/code/tensorflow/core/common_runtime/kernel_benchmark_testlib.h +// and +// https://www.tensorflow.org/code/tensorflow/core/kernels/ops_testutil.h +class KernelAndDevice : public core::RefCounted { + public: + // Populates this with a kernel appropriate for 'ndef'. + // + // The provided FunctionLibraryRuntime MUST outlive all calls to + // Run() on the returned KernelAndDevice. + virtual Status Init(bool log_device_placement, const NodeDef& ndef, + GraphCollector* graph_collector) = 0; + + // Non-multi-device functions are run using regular CallOp and look like + // primitive operations from KernelAndDevice perspective. + // `flr` can be nullptr if the operation is not run on any specific device + // (currently can happen only for multi-device functions). + KernelAndDevice( + FunctionLibraryRuntime* flr, + std::function)>* runner, + std::unique_ptr collective_executor, + Device* host_cpu_device) + : device_(flr == nullptr ? nullptr : flr->device()), + host_cpu_device_(host_cpu_device), + flr_(flr), + collective_executor_(std::move(collective_executor)), + runner_(runner) {} + + // Not thread safe. + ~KernelAndDevice() override = default; + + virtual bool IsFunction() { return false; } + + virtual bool IsCrossProcess() { return false; } + + // TODO(ashankar): Handle list-valued inputs. + virtual Status Run( + ScopedStepContainer* step_container, const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + const absl::optional& stack_trace, + tsl::CoordinationServiceAgent* coordination_service_agent) = 0; + + // Execute kernel asynchronously when applicable. Different from `Run` which + // blocks the caller thread and waits for the execution of the op/function, + // `RunAsync` could return before finishing the execution. The `done` callback + // will be triggered once the op/function execution finishes. + // Currently, calling RunAsync on ops might not honor the asynchronicity when + // it is called on an instance with only sync implementation, execute the + // kernel synchronously and then call the callback with the return status + // from sync execution. + virtual void RunAsync( + ScopedStepContainer* step_container, const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + tsl::CoordinationServiceAgent* coordination_service_agent, + StatusCallback done) = 0; + + virtual Device* InputDevice(int i) const = 0; + virtual Device* OutputDevice(int idx) const = 0; + // If idx'th output is a resource, returns the device backing the resource. + // Else, returns nullptr. + virtual Device* OutputResourceDevice(int idx) const = 0; + + // Returns the kernel that will be used to run this. + // Returns nullptr if this will be run using function library runtime. + virtual const OpKernel* kernel() const = 0; + + // Returns the device on which this kernel will run. In the case of + // multi-device functions, this is the default device that is passed to the + // placer but actual computation can happen on a different set of devices. + // Also, outputs can be produced on devices different from what this method + // returns. + Device* device() const { return device_; } + + virtual const DataTypeVector& input_dtypes() const = 0; + virtual const DataTypeVector& output_dtypes() const = 0; + + virtual int num_inputs() const = 0; + virtual int num_outputs() const = 0; + virtual const string& name() const = 0; + + protected: + std::function)>* get_runner() const; + + Device* const device_; // can be null + Device* const host_cpu_device_; // non-null + FunctionLibraryRuntime* const flr_; // can be null + const std::unique_ptr collective_executor_; + + private: + std::function)>* const runner_; // can be null +}; + +// Represents an op kernel and the device it will be run on. +class KernelAndDeviceOp final : public KernelAndDevice { + public: + KernelAndDeviceOp( + tensorflow::Rendezvous* rendezvous, bool log_memory, + FunctionLibraryRuntime* flr, + std::function)>* runner, + std::unique_ptr collective_executor, + Device* host_cpu_device) + : KernelAndDevice(flr, runner, std::move(collective_executor), + host_cpu_device), + rendezvous_(rendezvous), + log_memory_(log_memory) {} + + ~KernelAndDeviceOp() override = default; + + Status Init(bool log_device_placement, const NodeDef& ndef, + GraphCollector* graph_collector) override; + + Status Run( + ScopedStepContainer* step_container, const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + const absl::optional& stack_trace, + tsl::CoordinationServiceAgent* coordination_service_agent) override; + + void RunAsync(ScopedStepContainer* step_container, + const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + tsl::CoordinationServiceAgent* coordination_service_agent, + StatusCallback done) override { + // Trivial async implementation on top of the sync version + done(Run(step_container, inputs, outputs, cancellation_manager, + eager_func_params, {}, coordination_service_agent)); + } + + const OpKernel* kernel() const override { return kernel_.get(); } + + Device* InputDevice(int i) const override; + Device* OutputDevice(int idx) const override; + Device* OutputResourceDevice(int idx) const override; + + const DataTypeVector& input_dtypes() const override { + return kernel_->input_types(); + } + const DataTypeVector& output_dtypes() const override { + return kernel_->output_types(); + } + int num_inputs() const override { return kernel_->num_inputs(); } + int num_outputs() const override { return kernel_->num_outputs(); } + const string& name() const override { return kernel_->name(); } + + private: + std::unique_ptr kernel_; + bool is_distributed_communication_op_; + gtl::InlinedVector input_alloc_attrs_; + std::vector input_devices_; + gtl::InlinedVector output_alloc_attrs_; + Rendezvous* const rendezvous_; + checkpoint::TensorSliceReaderCacheWrapper slice_reader_cache_; + const bool log_memory_; +}; + +// Represents a multi-device function. Functions can also be run using +// various function-calling kernels including CallOp and PartitionedCallOp. +// In such cases, KernelAndDeviceOp is used. +class KernelAndDeviceFunc : public KernelAndDevice { + public: + // `flr` can be nullptr. + // `pflr` must not be nullptr. + // `host_cpu_device` must not be nullptr. + KernelAndDeviceFunc( + FunctionLibraryRuntime* flr, ProcessFunctionLibraryRuntime* pflr, + std::vector input_devices, + absl::flat_hash_map*> composite_devices, + std::unordered_map + input_resource_dtypes_and_shapes, + std::function)>* runner, + std::unique_ptr collective_executor, + Device* host_cpu_device, const string& name, + const bool outputs_on_op_device, + const bool allow_small_function_optimizations, + const bool allow_control_flow_sync_execution, + const bool shape_inference_on_tfe_dialect_import, + const bool int_args_and_retvals_on_device, + std::optional xla_compile_device_type, + const bool allow_soft_placement, Rendezvous::Factory rendezvous_factory, + std::function get_op_id) + : KernelAndDevice(flr, runner, std::move(collective_executor), + host_cpu_device), + pflr_(pflr), + handle_(kInvalidHandle), + outputs_on_op_device_(outputs_on_op_device), + allow_small_function_optimizations_(allow_small_function_optimizations), + allow_control_flow_sync_execution_(allow_control_flow_sync_execution), + shape_inference_on_tfe_dialect_import_( + shape_inference_on_tfe_dialect_import), + int_args_and_retvals_on_device_(int_args_and_retvals_on_device), + xla_compile_device_type_(xla_compile_device_type), + allow_soft_placement_(allow_soft_placement), + input_devices_(std::move(input_devices)), + composite_devices_(std::move(composite_devices)), + input_resource_dtypes_and_shapes_( + std::move(input_resource_dtypes_and_shapes)), + name_(name), + rendezvous_factory_(std::move(rendezvous_factory)), + get_op_id_(std::move(get_op_id)) {} + + ~KernelAndDeviceFunc() override; + + bool IsFunction() override { return true; }; + + bool IsCrossProcess() override { return is_cross_process_; } + + Status InstantiateFunc(bool log_device_placement, const NodeDef& ndef, + GraphCollector* graph_collector); + + Status Init(bool log_device_placement, const NodeDef& ndef, + GraphCollector* graph_collector) override; + + Status Run( + ScopedStepContainer* step_container, const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + const absl::optional& stack_trace, + tsl::CoordinationServiceAgent* coordination_service_agent) override; + + void RunAsync(ScopedStepContainer* step_container, + const EagerKernelArgs& inputs, + std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + tsl::CoordinationServiceAgent* coordination_service_agent, + StatusCallback done) override; + + const OpKernel* kernel() const override { return nullptr; } + + Device* InputDevice(int i) const override; + Device* OutputDevice(int idx) const override; + Device* OutputResourceDevice(int idx) const override; + + const DataTypeVector& input_dtypes() const override { return input_dtypes_; } + const DataTypeVector& output_dtypes() const override { + return output_dtypes_; + } + int num_inputs() const override { return input_dtypes_.size(); } + int num_outputs() const override { return output_dtypes_.size(); } + const string& name() const override { return name_; }; + + private: + std::shared_ptr PrepareForRun( + ScopedStepContainer* step_container, std::vector* outputs, + CancellationManager* cancellation_manager, + const absl::optional& eager_func_params, + const absl::optional& stack_trace, + tsl::CoordinationServiceAgent* coordination_service_agent, + tsl::core::RefCountPtr* rendezvous); + + ProcessFunctionLibraryRuntime* const pflr_; // non-null + FunctionLibraryRuntime::Handle handle_; + // Indicates whether the function needs to execute cross process. + bool is_cross_process_; + + // If true, function outputs are explicitly assigned to the default device; + // if false, the output devices are inferred by pflr_. + bool outputs_on_op_device_; + + // If True, allow optimizations which should be targeted at a limited + // set of small functions. (For example, running kernels synchronously can + // be faster under some conditions.) + const bool allow_small_function_optimizations_; + + // If True, allows control nodes to run on the single threaded executor. + const bool allow_control_flow_sync_execution_; + + // TODO(b/176491312): Remove this if shape inference on import flag is + // removed. If True, allows mlir roundtrip to run shape inference on import. + const bool shape_inference_on_tfe_dialect_import_; + + const bool int_args_and_retvals_on_device_; + + const absl::optional xla_compile_device_type_; + + const bool allow_soft_placement_; + + // CPU devices are null. Resource handles' devices are actual backing + // devices. + std::vector output_devices_; + // CPU devices are not null. Resource handles' devices are actual backing + // devices. + std::vector input_devices_; + // Maps from a CompositeDevice name to a list of physical device names. + absl::flat_hash_map*> composite_devices_; + std::unordered_map + input_resource_dtypes_and_shapes_; + + DataTypeVector input_dtypes_; + DataTypeVector output_dtypes_; + string name_; + + Rendezvous::Factory rendezvous_factory_; + std::function get_op_id_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_KERNEL_AND_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/placement_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/placement_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b182cf684027a44229c48afd43ab00abea1563ac --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/placement_utils.h @@ -0,0 +1,48 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_PLACEMENT_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_PLACEMENT_UTILS_H_ + +#include "tensorflow/c/eager/immediate_execution_operation.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/stringpiece.h" + +namespace tensorflow { +namespace eager { + +bool IsColocationExempt(StringPiece op_name); + +bool IsFunction(StringPiece op_name); + +// TODO(b/154234908): Unify placement logic. + +// Pin the op to cpu if all op inputs are on the CPU, small (<64 elements) and +// integers (int32/int64). This can be disabled by setting the environment +// variable "TF_EAGER_ENABLE_SMALL_TENSOR_CPU_PINNING" to "0" or "false". +Status MaybePinSmallOpsToCpu( + bool* result, StringPiece op_name, + absl::Span args, + StringPiece cpu_device_name); + +// If a resource touching input is specified, all resource-touching ops run in +// the device the resource is, regardless of anything else that has been +// specified. This is identical to the graph mode behavior. +Status MaybePinToResourceDevice(Device** device, const EagerOperation& op); +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_PLACEMENT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/rendezvous_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/rendezvous_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..e79171f8e8fd9d741fa510ff8d73c65df90af5b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/rendezvous_cache.h @@ -0,0 +1,146 @@ +/* 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_COMMON_RUNTIME_EAGER_RENDEZVOUS_CACHE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_RENDEZVOUS_CACHE_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/mutex.h" +#include "tsl/platform/refcount.h" +#include "tsl/platform/thread_annotations.h" + +namespace tensorflow { + +// The class for caching Rendezvous instances per step_id. +// If the Rendezvous object is destroyed for the step, a new one will be +// created on demand. +template +class RendezvousCache : public tsl::core::WeakRefCounted { + public: + RendezvousCache() = default; + ~RendezvousCache() override { + for (auto& p : table_) { + auto rendez = p.second.GetNewRef(); + if (rendez) { + rendez->StartAbort(tsl::errors::Aborted("Shutdown")); + } + } + } + + // Returns a new Reference. + template + tsl::core::RefCountPtr FindOrCreate(int64_t step_id, + RendezvousCreator create_fn) { + tsl::mutex_lock l(table_lock_); + tsl::core::RefCountPtr rendz = nullptr; + auto iter = table_.find(step_id); + if (iter != table_.end()) { + rendz = iter->second.GetNewRef(); + VLOG(5) << "step_id:" << step_id << " " + << "WeakPtr returned:" << rendz.get(); + if (!rendz) { + table_.erase(iter); + } + } + if (!rendz) { // Deleted or not found + rendz = create_fn(); + VLOG(5) << "step_id:" << step_id << " " + << "Rendezvous not found, inserting a new one." << rendz.get(); + auto cleanup_fn = [weak_cache = tsl::core::WeakPtr(this), + step_id]() { + tsl::core::RefCountPtr cache = weak_cache.GetNewRef(); + if (cache != nullptr) { + // If the rendezvous is released, Find() will clean it up from the + // map. + cache->Find(step_id); + } + }; + table_.insert({step_id, tsl::core::WeakPtr{rendz.get(), cleanup_fn}}); + } + return rendz; + } + + // Returns a new Reference. + tsl::core::RefCountPtr Find(int64_t step_id) { + tsl::mutex_lock l(table_lock_); + auto iter = table_.find(step_id); + if (iter == table_.end()) return nullptr; + tsl::core::RefCountPtr res = iter->second.GetNewRef(); + // Cleans the record if the rendezvous is already destroyed. + if (res == nullptr) { + table_.erase(iter); + } + return res; + } + + // Removes a Rendezvous weak reference from table. + void Remove(int64_t step_id) { + tsl::mutex_lock l(table_lock_); + table_.erase(step_id); + } + + // Removes a Rendezvous weak reference from table, and abort the rendezvous. + void RemoveAndAbort(int64_t step_id) { + tsl::core::RefCountPtr rendez = nullptr; + { + tsl::mutex_lock l(table_lock_); + auto iter = table_.find(step_id); + if (iter != table_.end()) { + rendez = iter->second.GetNewRef(); + table_.erase(iter); + } + } + if (rendez) { + rendez->StartAbort(tsl::errors::Aborted("Cleanup ", step_id)); + } + } + + void RemoveAll() { + tsl::mutex_lock l(table_lock_); + table_.clear(); + } + + // Returns a list of active step ids. This result is only informative + // at time of the call. The returned vector may contain step ids that have + // been invalidated after the call. + std::vector GetActiveStepIds() { + std::vector list; + tsl::mutex_lock l(table_lock_); + list.reserve(table_.size()); + for (const auto& iter : table_) { + list.push_back(iter.first); + } + return list; + } + + size_t Size() const { + tsl::mutex_lock l(table_lock_); + return table_.size(); + } + + private: + mutable tsl::mutex table_lock_; + absl::flat_hash_map> table_ + TF_GUARDED_BY(table_lock_); +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_RENDEZVOUS_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/shape_inference.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/shape_inference.h new file mode 100644 index 0000000000000000000000000000000000000000..456bfc3fcbd2388265be3d15a13943675296c9a2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/shape_inference.h @@ -0,0 +1,36 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SHAPE_INFERENCE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SHAPE_INFERENCE_H_ + +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" + +namespace tensorflow { +namespace eager { + +Status RunShapeInference(const NodeDef& ndef, + const FunctionLibraryDefinition& lib_def, + const gtl::InlinedVector& inputs, + const gtl::InlinedVector& retvals); + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SHAPE_INFERENCE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/small_constants_optimizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/small_constants_optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..cb70fb9993f93951ae0ffd02cfe0a27acfce2717 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/small_constants_optimizer.h @@ -0,0 +1,42 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SMALL_CONSTANTS_OPTIMIZER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SMALL_CONSTANTS_OPTIMIZER_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/function.pb.h" + +namespace tensorflow::small_constants_optimizer { + +// Checks whether small constant optimization is enabled for a tf.function. +bool IsSmallConstantOptimizationEnabled(const FunctionDef& fdef); + +// Generates new FunctionDefs with the boolean input tensors folded as +// constants into the FunctionDef. +std::vector FoldInputTensors( + const FunctionDef& fdef, const FunctionLibraryDefinition& flib); + +// Generates the FunctionDef name for the folded function. +std::string FoldedFunctionName(absl::string_view fname, + absl::string_view input_name, bool input_value); + +} // namespace tensorflow::small_constants_optimizer + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SMALL_CONSTANTS_OPTIMIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/summary_optimizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/summary_optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..0b337e04f3773257dade9cc81166d6f29e18761f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/summary_optimizer.h @@ -0,0 +1,51 @@ +/* Copyright 2023 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SUMMARY_OPTIMIZER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SUMMARY_OPTIMIZER_H_ + +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/function.pb.h" + +namespace tensorflow::summary_optimizer { +namespace internal { + +// Normalizes an edge's name to match the names stored in a NodeDef. +std::string NormalizeEdgeName(absl::string_view name); + +} // namespace internal + +// Returns the name of the input_arg and the bool value that determines whether +// or not to disable summaries. If no such arg exists returns an empty string. +std::pair GetDisableSummariesInputArg( + const FunctionDef& fdef); + +// Generates new FunctionDef(s) with the summaries stripped out. +// This function will traverse all the nested functions and generate a version +// of the nested functions with summaries stripped out. +std::vector StripSummaries(const FunctionDef& fdef, + const FunctionLibraryDefinition& flib); + +// Generates a new function name for the stripped function. +std::string StrippedFunctionName(absl::string_view fname); + +} // namespace tensorflow::summary_optimizer + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_SUMMARY_OPTIMIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle.h new file mode 100644 index 0000000000000000000000000000000000000000..53c733aaa5c8f3d655a1d109232571b14d063cea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle.h @@ -0,0 +1,416 @@ +/* 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_COMMON_RUNTIME_EAGER_TENSOR_HANDLE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_TENSOR_HANDLE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +// clang-format off +// Required for IS_MOBILE_PLATFORM +#include "tensorflow/core/framework/full_type.pb.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/platform.h" +// clang-format on + +#include "absl/types/variant.h" +#include "tensorflow/c/eager/immediate_execution_tensor_handle.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle_data.h" +#include "tensorflow/core/common_runtime/function.h" +#if !defined(IS_MOBILE_PLATFORM) +#include "tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h" +#endif // IS_MOBILE_PLATFORM +#include "tensorflow/core/framework/tensor.h" + +#include "tensorflow/core/lib/core/stringpiece.h" + +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" + +namespace tensorflow { + +class EagerContext; + +// Associates a Tensor and a Device, used in the eager runtime. Internal version +// of the TFE_TensorHandle struct and the python EagerTensor class +// (unrelated to python TensorHandle). +class TensorHandle : public ImmediateExecutionTensorHandle { + // TensorHandle for dtype != DT_RESOURCE + TensorHandle(tensorflow::Tensor&& t, Device* d, Device* op_device, + Device* resource_device, EagerContext* ctx); + // TensorHandle for dtype == DT_RESOURCE + TensorHandle(tensorflow::Tensor&& t, Device* d, Device* op_device, + EagerContext* ctx); + TensorHandle(Device* d, Device* op_device, Device* resource_device, + tensorflow::DataType dtype, EagerContext* ctx); + +#if !defined(IS_MOBILE_PLATFORM) + TensorHandle(int64_t op_id, int32_t output_num, const string& remote_task, + tensorflow::DataType dtype, Device* device, EagerContext* ctx, + bool unknown_device); + TensorHandle(int64_t op_id, int32_t output_num, tensorflow::DataType dtype, + Device* device, bool is_ready, EagerContext* ctx); +#endif // IS_MOBILE_PLATFORM + + public: + // TensorHandle with no assigned device + static TensorHandle* CreateLocalHandle(const tensorflow::Tensor& t); + static TensorHandle* CreateLocalHandle(tensorflow::Tensor&& t, Device* d, + Device* op_device, EagerContext* ctx); + static TensorHandle* CreateLocalHandle(tensorflow::Tensor&& t, Device* d, + Device* op_device, + Device* resource_device, + EagerContext* ctx); + static TensorHandle* CreateEmptyLocalHandle(Device* d, Device* op_device, + Device* resource_device, + tensorflow::DataType dtype, + EagerContext* ctx); + + // Create a handle which packs the given handles of the same dtype and shape. + // If handles are on different devices, assign the packed handle to a + // CompositeDevice. + // + // The new tensor handle shares ownership of the given handle: their reference + // count will be increased by one after a call to `CreatePackedHandle`. + // TODO(b/170414377): Use `TensorHandlePtr` instead. + static Status CreatePackedHandle(std::vector&& handles, + tensorflow::DataType dtype, + const tensorflow::TensorShape& shape, + const string& device_name, EagerContext* ctx, + TensorHandle** packed_handle); + static Status CreatePackedHandle(std::vector&& handles, + EagerContext* ctx, + TensorHandle** packed_handle); + +#if !defined(IS_MOBILE_PLATFORM) + // An unshaped remote handle refers to a tensor on a remote worker. It's not + // ready until the shape is set. It controls the lifetime of the remote + // tensor. + static TensorHandle* CreateUnshapedRemoteHandle(int64_t op_id, + int32_t output_num, + const string& remote_task, + tensorflow::DataType dtype, + Device* d, EagerContext* ctx, + bool unknown_device = false); + // A lazy remote handle refers to a tensor on a remote worker. The lifetime of + // the remote tensor is controlled by the remote worker, but not by the lazy + // remote handle. Lazy handles are normally created on a default function + // device. + static TensorHandle* CreateLazyRemoteHandle(int64_t op_id, int32_t output_num, + tensorflow::DataType dtype, + Device* d, bool is_ready, + EagerContext* ctx); +#endif // IS_MOBILE_PLATFORM + + // Templated struct `AutoReleaser` in + // core/runtime_fallback/runtime/kernel_utils.h needs a Release() method + // defined. + void Release(); + + tensorflow::DataType DataType() const override; + Status Shape(tensorflow::PartialTensorShape* shape) const override; + Status NumDims(int* num_dims) const override; + Status NumElements(int64_t* num_elements) const override; + Status Dim(int dim_index, int64_t* dim) const override; + + const char* DeviceName(Status* status) const override; + const char* BackingDeviceName(Status* status) const override; + const char* DeviceType(Status* status) const override; + int DeviceId(Status* status) const override; + AbstractTensorInterface* Resolve(Status* status) override; + + // Subclasses may return True to instruct the string formatter + // to use SummarizeValue instead of the NumPy formatter. + bool PreferCustomSummarizer() const override { + return dtype == DT_VARIANT || dtype == DT_RESOURCE; + } + + // Return the Tensor from the default device. + Status Tensor(const tensorflow::Tensor** t) const; + // Return the Tensor from the specified device which could be either the + // default device or a local mirror. The device pointer should be nullptr if + // requesting the HostCPU. + Status TensorFromDevice(const Device* d, const tensorflow::Tensor** t) const; + + // Return the TensorValue from the specified device which could be either the + // default device or a local mirror. The device pointer should be nullptr if + // requesting the HostCPU. + Status TensorValue(const Device* d, tensorflow::TensorValue* t); + + Device* device() const { return device_; } + Device* op_device() const { return op_device_; } + Device* resource_device() const { return resource_device_; } + int64_t resource_remote_device_incarnation() const { + return resource_remote_device_incarnation_; + } + + // If the devices are unknown at creation time, block until the actual devices + // are set (data is ready). + Status WaitUnknownDevice() const; + + Device* DeviceOrHostCPU(const EagerContext& ctx) const; + + Status Shape(tensorflow::TensorShape* shape); + + Status Unprotect(const Device* d); + + // Checks if a mirror tensor exists for the specified device. Mirrors are only + // maintained for local devices, like CPUs & GPUs. Note a mirror may be empty, + // as it is still to be set by an async operation. + bool HasLocalMirror(const Device* d) const; + // Add an empty mirror placeholder for the specified device. The expectation + // is this will be populated by a call to SetTensor. + Status AddEmptyLocalMirror(const Device* d); + // Add a local mirror. This will fail if an empty local mirror was previously + // added. For that case, SetTensor should be used instead. + Status AddLocalMirror(tensorflow::Tensor&& tensor, const Device* d); + +#if !defined(IS_MOBILE_PLATFORM) + bool HasRemoteMirror(const Device* d, uint64 context_view_id) const; + bool HasResourceShapeMirror(const Device* d, uint64 context_view_id) const; + + Status AddUnshapedRemoteMirror(const Device* d, int64_t op_id, int output_num, + const string& remote_task, EagerContext* ctx); + Status AddResourceShapeMirror(const Device* d, int64_t op_id, int output_num, + EagerContext* ctx); + + // Return the op_id and output num if the handle refers to a remote tensor. + // If wait_until_ready is true, block until the remote tensor is ready on the + // given remote worker. + Status RemoteAddress(const Device* d, bool wait_until_ready, int64_t* op_id, + int32* output_num) const; + + // Called on an async remote tensor once it's shape has been determined. This + // transitions the tensor handle from a non-ready to a ready state by + // replacing the backing data abstraction to allow for the shape to be + // queried. + // creating a TensorHandle (e.g. a remote output of a remote function). + // This method or Poison must be called exactly once for remote tensors that + // were created without a known shape. + Status SetRemoteShape(const TensorShape& shape, const Device* d, + uint64 context_view_id); + // If op_device is not empty, reset the devices of a remote tensor which is + // created without known devices (e.g. function outputs). + Status SetRemoteShapeAndDevice(const TensorShape& shape, const Device* d, + uint64 context_view_id, string op_device); + + // Poisons either this handle or a remote mirror with error `status`. + // Poisoning means that the handle will become ready and methods trying + // to access the remote shape will return this error `status`. + // Exactly one of SetRemoteShape or PoisonRemote methods must be called on a + // unshaped handle on a remote device. + void PoisonRemote(Status status, const Device* d, uint64 context_view_id); +#endif + + // Sets the `tensor` for this async non-ready handle making it ready. + // This method or Poison must be called exactly once for non-ready async + // handles to make them ready. + Status SetTensor(tensorflow::Tensor&& tensor, const Device* d); + + // Poisons either this handle or a local mirror with error `status`. + // Poisoning means that the handle will become ready and methods trying + // to access the actual tensor or shape will return this error `status`. + // Exactly one of SetTensor or Poison methods must be called on a non-ready + // tensor for a specific device. + void Poison(Status status, const Device* d); + + // TODO(b/154282629): Consider moving it to EagerContext. + // Copies to the tensor on the given device `d`, or to host iff `d` is null. + Status CopyToDevice(const EagerContext& ctx, tensorflow::Device* d, + tensorflow::Tensor* output) const; + + Status InferenceShape(shape_inference::InferenceContext* inference_context, + shape_inference::ShapeHandle* shape_handle); + void SetInferenceShape(shape_inference::InferenceContext* inference_context, + const shape_inference::ShapeHandle& shape_handle); + Status CopyInferenceShape(TensorHandle* other); + + // dtype for the handle. It must be the same as t.dtype() once the handle is + // ready. + const tensorflow::DataType dtype; + + enum HandleType { LOCAL = 0, PACKED = 1, REMOTE = 2 }; + + HandleType Type() const; + string TypeString() const; + + void SetResourceHandleDtypeAndShape( + std::vector dtypes_and_shapes); + + // If this TensorHandle is 1) a local tensor, and 2) a resource handle, + // return data types and shapes of the underlying resource. + Status GetResourceHandleDtypesAndShapes( + std::vector* result); + + // Returns the number of packed handles. 0 if the handle type is not PACKED. + int NumPackedHandles() const; + // It's called on a packed TensorHandle. Extract a handle with the given + // index. + Status ExtractPackedHandle(int index, TensorHandle** handle) const; + + // For LLVM style RTTI. + static bool classof(const AbstractTensorHandle* ptr) { + return ptr->getKind() == kEager; + } + + tensorflow::FullTypeDef FullType() const override { return full_type_; } + + void SetFullType(FullTypeDef& full_type) { full_type_ = full_type; } + + private: + friend class PackedTensorHandleTest; + + TensorHandle(std::vector&& handles, Device* device, + tensorflow::DataType dtype, const tensorflow::TensorShape& shape, + EagerContext* ctx); + + ~TensorHandle() override; + + // The TensorHandleData can either represent a local or remote tensor handle. + // Further, it can be in a non-ready state. It would become ready with a call + // to either SetTensor or SetRemoteShape which replaces the underlying data + // with a ready version of the tensor handle data. + bool IsReady() const; + Status WaitReady(const char* caller) const; + + tensorflow::Device* device_; + + // Device in which the op producing this tensor was executed. Equals to + // device_ for constant tensors. + // Can be nullptr if the op producing this tensor was a function executed + // with function library runtime. + tensorflow::Device* op_device_; + + // If the tensor dtype is DT_RESOURCE, resource_device_ holds the device + // backing the resource. Else resource_device_ is nullptr. + tensorflow::Device* resource_device_; + // Incarnation ID of the resource device if it locates on a remote device, or + // 0 if it locates on a local device. + int64_t resource_remote_device_incarnation_; + + // If true, the handle refers to a remote tensor which is created without + // known devices. The actual devices are set by SetRemoteShape. The devices + // should be accessed once the handle is ready. + const bool unknown_device_ = false; + + mutable mutex mu_; + + // Map of local mirrors. This can include both ready and non-ready mirrors. + std::unordered_map + local_mirrors_ TF_GUARDED_BY(mu_); +#if !defined(IS_MOBILE_PLATFORM) + // TODO(yujingzhang): Remove resource_shape_mirrors_ once scalable per-replica + // variable is ready, since we could get the shape locally without remote copy + // then. + std::unordered_map resource_shape_mirrors_ + TF_GUARDED_BY(mu_); + std::unordered_map remote_mirrors_ + TF_GUARDED_BY(mu_); +#endif + + // `ctx` is only guaranteed to be set if the handle is not "ready". This is + // typically true when the handle was produced during async execution. + // `ctx` object is not owned and should outlive this handle. + // + // TODO(b/150614042): Reference count EagerContext to ensure that 'device_' of + // a TensorHandle does not outlive the EagerContext from which it came? + EagerContext* const ctx_; + + // Does not need synchronization because it can be accessed only after + // WaitReady() has returned. At that point, is_poisoned_ is immutable. + Status is_poisoned_; + + // If this TensorHandle 1) is a local tensor, and 2) is a resource handle or + // refers to a remote resource handle, we store data types and shapes for + // the underlying resource. + std::vector handle_dtypes_and_shapes_; + + // A handle data which refers to multiple TensorHandles of the same dtype and + // shape. + class PackedTensorHandleData { + public: + // Initialize handle data from list of tensor handles. + // Ownership of the tensor handles is shared between the + // `PackedTensorHandleData` and the caller (the reference count for the + // given handles is incremented). + // TODO(b/170414377): Use `TensorHandlePtr` instead. + PackedTensorHandleData(std::vector&& handles, + const TensorShape& shape); + + ~PackedTensorHandleData(); + + Status Shape(TensorShape* shape) const; + Status NumDims(int* num_dims) const; + Status Dim(int dim_index, int64_t* dim) const; + Status NumElements(int64_t* num_elements) const; + Status Unprotect(); + bool IsReady() const; + Status WaitReady(const char* caller) const; + void Poison(Status status); + string DebugString() const; + + // Number of packed handles. + int NumPackedHandles() const; + // Extract a handle on the given index. + Status ExtractPackedHandle(int index, TensorHandle** handle) const; + + private: + // TODO(b/170414377): Use `TensorHandlePtr` instead. + const std::vector handles_; + const TensorShape shape_; + + mutable mutex mu_; + Status is_poisoned_ TF_GUARDED_BY(mu_); + }; + + // Does not need synchronization because it can be accessed only after + // WaitReady() has returned. At that point, data_ is immutable. +#if !defined(IS_MOBILE_PLATFORM) + std::variant + data_; +#else + absl::variant data_; +#endif + + PartialTensorShape inference_shape_; + + FullTypeDef full_type_; +}; + +// Returns the device backing the resource. Else, returns nullptr. +Device* GetResourceDevice(const ResourceHandle& handle, EagerContext* ctx); + +class TensorHandleInterface : public ImmediateExecutionTensorHandle { + public: +}; + +template +inline TensorHandle* TensorHandleFromInterface(T* handle) { + return down_cast(handle); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_TENSOR_HANDLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle_data.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle_data.h new file mode 100644 index 0000000000000000000000000000000000000000..8fb2083295a17639dd1e41bc90cd3dccaccd3efa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eager/tensor_handle_data.h @@ -0,0 +1,113 @@ +/* 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_COMMON_RUNTIME_EAGER_TENSOR_HANDLE_DATA_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_TENSOR_HANDLE_DATA_H_ + +#include +#include + +#include "absl/types/variant.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Local Tensor Handle: Handle to a Tensor present on the local host. +class LocalTensorHandleData { + public: + LocalTensorHandleData() : ctrl_(absl::in_place_type) {} + explicit LocalTensorHandleData(tensorflow::Tensor&& t) + : tensor_(std::move(t)), + forwarding_protection_tensor_(tensor_), + ctrl_(absl::in_place_type) {} + + // A local tensor handle should be able to satisfy all of these requests. + Status Tensor(const tensorflow::Tensor** t) const; + Status TensorValue(tensorflow::TensorValue* t); + Status Shape(TensorShape* shape) const; + Status NumDims(int* num_dims) const; + Status Dim(int dim_index, int64_t* dim) const; + Status NumElements(int64_t* num_elements) const; + Status Unprotect(); + + bool IsReady() const { + return std::visit([](auto& data) { return data.IsReady(); }, ctrl_); + } + + Status WaitReady(const char* caller) const { + return std::visit([caller](auto& data) { return data.WaitReady(caller); }, + ctrl_); + } + void Poison(Status status) { + return std::visit([status](auto& data) { data.Poison(status); }, ctrl_); + } + Status IsPoisoned() const { + return std::visit([](auto& data) { return data.IsPoisoned(); }, ctrl_); + } + + Status SetTensor(tensorflow::Tensor&& t); + + string DebugString() const; + + private: + tensorflow::Tensor tensor_; + // TensorHandle has its own reference counting which is distinct from the + // backing Tensor. As a result, if the Tensor reference count is 1 while + // executing an op, the TensorBuffer could be reused for the output. We avoid + // this behavior maintaining another reference count with the + // forwarding_protection_tensor_ Tensor. When Unprotect() is called, we + // release this Tensor to allow forwarding. + tensorflow::Tensor forwarding_protection_tensor_; + + // We distinguish between ready and empty tensors with the ctrl_ variant. + // which contains 2 implementations of the waiting logic. The + // NonBlockingControl is a simple no-op class whereas the BlockingControl + // actually uses a mutex. By using a variant we avoid the overhead of + // constructing and destructing the mutex for ready local tensors. + class NonBlockingControl { + public: + bool IsReady() const { return true; } + Status WaitReady(const char* caller) const { return OkStatus(); } + void Poison(Status status) {} + Status IsPoisoned() const { return OkStatus(); } + }; + + class BlockingControl { + public: + bool IsReady() const { + tf_shared_lock l(mu_); + return is_ready_; + } + void SetReady(); + Status WaitReady(const char* caller) const; + void Poison(Status status); + Status IsPoisoned() const { + tf_shared_lock l(mu_); + return is_poisoned_; + } + + private: + mutable mutex mu_; + bool is_ready_ TF_GUARDED_BY(mu_); + Status is_poisoned_ TF_GUARDED_BY(mu_); + }; + + std::variant ctrl_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EAGER_TENSOR_HANDLE_DATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eval_const_tensor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eval_const_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..e46c6ffc76aa51de1d72407a2f333af80bee7f3d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/eval_const_tensor.h @@ -0,0 +1,63 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EVAL_CONST_TENSOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EVAL_CONST_TENSOR_H_ + +#include +#include + +#include "absl/functional/function_ref.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +class GraphRunner; +class Node; +class OpRegistryInterface; +class ShapeRefiner; +class Tensor; + +// Configuration of the graph runner for constant folding. +struct EvaluateConstantTensorRunner { + // Op registry for temporary graphs. By default, the global registry will + // be used. + const OpRegistryInterface* op_registry = nullptr; + // Version of the graph API to use. + int32_t graph_def_version = 0; + // Graph runner for constant folding. By default, a temporary graph runner + // will be created. + GraphRunner* graph_runner = nullptr; +}; + +// Attempts to evaluate an output of the given node. This will only be possible +// if it doesn't depend on any graph inputs (this function is safe to call +// if this isn't the case though). +// +// When the evaluation is successful, the function returns a tensor, otherwise +// it returns std::nullopt. +StatusOr> EvaluateConstantTensor( + // The tensor to be evaluated. + const Node& node, int node_output, + // Used to fetch inference contexts for nodes in the graph. + const ShapeRefiner& refiner, + // Used to both lookup cached results and request function arguments. + absl::FunctionRef(const Node&, int)> lookup, + // Configuration of the graph runner. If not set, no attempt to fold a + // constant subgraph will be made. + std::optional runner); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EVAL_CONST_TENSOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/executor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/executor.h new file mode 100644 index 0000000000000000000000000000000000000000..607cf9b37a55a6b607a651fb2c616b4b54bcdadd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/executor.h @@ -0,0 +1,263 @@ +/* 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_COMMON_RUNTIME_EXECUTOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EXECUTOR_H_ + +#include + +#include "absl/time/time.h" +#include "absl/types/optional.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/local_executor_params.h" +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/framework/session_state.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/threadpool_interface.h" +#include "tensorflow/core/platform/error_logging.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/util/managed_stack_trace.h" + +namespace tensorflow { + +class StepStatsCollector; + +// Executor runs a graph computation. +// Example: +// Graph* graph = ...; +// ... construct graph ... +// Executor* executor; +// TF_CHECK_OK(NewSimpleExecutor(my_device, graph, &executor)); +// Rendezvous* rendezvous = NewNaiveRendezvous(); +// TF_CHECK_OK(rendezvous->Send("input", some_input_tensor)); +// TF_CHECK_OK(executor->Run({ExecutorOpts, rendezvous, nullptr})); +// TF_CHECK_OK(rendezvous->Recv("output", &output_tensor)); +// ... ... +// +// Multiple threads can call Executor::Run concurrently. +class Executor { + public: + virtual ~Executor() {} + + // RunAsync() executes the graph computation. "done" is run when the + // graph computation completes. If any error happens during the + // computation, "done" is run and the error is passed to "done". + // + // RunAsync() is given a few arguments in Args. The caller must + // ensure objects passed in Args (rendezvous, stats_collector, etc.) + // are alive at least until done is invoked. All pointers to the + // argument objects can be nullptr. + // + // "step_id" is a process-wide unique identifier for the step being + // run. Executors on different devices may receive the same step_id + // in the case that a step runs Ops on more than one device. The + // step_id is used for tracking resource usage of a given step. + // + // RunAsync() uses the given "rendezvous", if not null, as the + // mechanism to communicate inputs and outputs of the underlying + // graph computation. + // + // RunAsync() calls "stats_collector", if not null, to keep track of + // stats. This allows us to collect statistics and traces on demand. + // + // RunAsync() is provided a "call_frame", if the executor is used + // for executing a function, is used to pass arguments and return + // values between the caller and the callee. + // + // RunAsync() uses "cancellation_manager", if not nullptr, to + // register callbacks that should be called if the graph computation + // is canceled. Note that the callbacks merely unblock any + // long-running computation, and a canceled step will terminate by + // returning/calling the DoneCallback as usual. + // + // RunAsync() dispatches closures to "runner". Typically, "runner" + // is backed up by a bounded threadpool. + // + // "start_time_usecs" is a timestamp for the start of RunAsync() + // execution. Used for system-wide latency metrics. + struct Args { + int64_t step_id = 0; + // Used only by tracer/profiler, applicable only when running under + // FunctionRuntimeLibrary, unique per invocation. + std::optional function_trace_id; + RendezvousInterface* rendezvous = nullptr; + StepStatsCollectorInterface* stats_collector = nullptr; + CallFrameInterface* call_frame = nullptr; + CancellationManager* cancellation_manager = nullptr; + SessionState* session_state = nullptr; + // Unique session identifier. Can be empty. + string session_handle; + TensorStore* tensor_store = nullptr; + ScopedStepContainer* step_container = nullptr; + CollectiveExecutor* collective_executor = nullptr; + thread::ThreadPoolInterface* user_intra_op_threadpool = nullptr; + tsl::CoordinationServiceAgent* coordination_service_agent = nullptr; + int64_t start_time_usecs = 0; + // The deadline for the kernel to complete by. Empty if unspecified. + absl::optional deadline; + absl::optional stack_trace = absl::nullopt; + + // If true, calls Sync() on the device. + bool sync_on_finish = false; + + typedef std::function Closure; + typedef std::function Runner; + Runner runner = nullptr; + + // If true, all kernels will be treated as "inexpensive", and hence executed + // on the scheduling thread. + bool run_all_kernels_inline = false; + }; + typedef std::function DoneCallback; + + void RunAsync(const Args& args, DoneCallback done) { + RunAsyncInternal(args, [done = std::move(done)](const Status& s) { + if (!s.ok()) Log("TFExecutor", "Run", s.message()).IgnoreError(); + done(s); + }); + } + + // Synchronous wrapper for RunAsync(). + virtual Status Run(const Args& args) { + Status ret; + Notification n; + RunAsync(args, [&ret, &n](const Status& s) { + ret = s; + n.Notify(); + }); + n.WaitForNotification(); + return ret; + } + + private: + virtual void RunAsyncInternal(const Args& args, DoneCallback done) = 0; +}; + +// Creates an Executor that computes the given "graph". +// +// If successful, returns the constructed executor in "*executor". Otherwise, +// returns an error status. +// +// "params" provides a set of context for the executor. We expect that +// different context would provide different implementations. +::tensorflow::Status NewLocalExecutor(const LocalExecutorParams& params, + const Graph& graph, Executor** executor); + +// A class to help run multiple executors in parallel and wait until +// all of them are complete. +// +// ExecutorBarrier deletes itself after the function returned by Get() +// is called. +class ExecutorBarrier { + public: + typedef std::function StatusCallback; + + // Create an ExecutorBarrier for 'num' different executors. + // + // 'r' is the shared Rendezvous object that is used to communicate + // state. If any of the executors experiences an error, the + // rendezvous object will be aborted exactly once. + // + // 'done' is called after the last executor completes, and + // ExecutorBarrier is deleted. + ExecutorBarrier(size_t num, Rendezvous* r, StatusCallback done) + : rendez_(r), done_cb_(done), pending_(num) {} + + ~ExecutorBarrier() {} + + // Returns a closure that Executors must call when they are done + // computing, passing the status of their execution as an argument. + StatusCallback Get() { + return std::bind(&ExecutorBarrier::WhenDone, this, std::placeholders::_1); + } + + private: + Rendezvous* rendez_ = nullptr; + StatusCallback done_cb_ = nullptr; + + mutable mutex mu_; + int pending_ TF_GUARDED_BY(mu_) = 0; + StatusGroup status_group_ TF_GUARDED_BY(mu_); + + void WhenDone(const Status& s) { + Rendezvous* error_rendez = nullptr; + StatusCallback done = nullptr; + Status status; + + { + mutex_lock l(mu_); + + // If we are the first error encountered, trigger an abort of the + // Rendezvous object by this thread only. + if (status_group_.ok() && !s.ok()) { + error_rendez = rendez_; + error_rendez->Ref(); + } + + if (!s.ok() && !StatusGroup::IsDerived(s) && + !status_group_.HasLogMessages()) { + status_group_.AttachLogMessages(); + } + + status_group_.Update(s); + + // If this is the last call to WhenDone, call the final callback + // below. + if (--pending_ == 0) { + CHECK(done_cb_ != nullptr); + std::swap(done, done_cb_); + status = status_group_.as_summary_status(); + } + } + + if (error_rendez != nullptr) { + error_rendez->StartAbort( + errors::Aborted("Stopping remaining executors.")); + error_rendez->Unref(); + } + + if (done != nullptr) { + delete this; + if (!status.ok()) { + VLOG(1) << "ExecutorBarrier finished with bad status: " << status; + } + done(status); + } + } + + ExecutorBarrier(const ExecutorBarrier&) = delete; + void operator=(const ExecutorBarrier&) = delete; +}; + +// A few helpers to facilitate create/delete kernels. + +// Creates a kernel based on "props" on device "device". The kernel can +// access the functions in the "flib". The caller takes ownership of +// returned "*kernel". +Status CreateNonCachedKernel(Device* device, FunctionLibraryRuntime* flib, + const std::shared_ptr& props, + int graph_def_version, OpKernel** kernel); + +// Deletes "kernel" returned by CreateKernel. +void DeleteNonCachedKernel(OpKernel* kernel); + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EXECUTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/executor_factory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/executor_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..bda5d3c4b82fa2d3185abd6261235d3c79d3c40d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/executor_factory.h @@ -0,0 +1,50 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_EXECUTOR_FACTORY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_EXECUTOR_FACTORY_H_ + +#include + +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +class Executor; +class Graph; +struct LocalExecutorParams; + +class ExecutorFactory { + public: + virtual Status NewExecutor(const LocalExecutorParams& params, + const Graph& graph, + std::unique_ptr* out_executor) = 0; + virtual ~ExecutorFactory() {} + + static void Register(const string& executor_type, ExecutorFactory* factory); + static Status GetFactory(const string& executor_type, + ExecutorFactory** out_factory); +}; + +Status NewExecutor(const string& executor_type, + const LocalExecutorParams& params, const Graph& graph, + std::unique_ptr* out_executor); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_EXECUTOR_FACTORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function.h new file mode 100644 index 0000000000000000000000000000000000000000..f86732b2dd6e3f08d5a8da302ee3c5a049af8d0b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function.h @@ -0,0 +1,81 @@ +/* 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_COMMON_RUNTIME_FUNCTION_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_H_ + +#include +#include + +#include "absl/types/optional.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/common_runtime/function_def_utils.h" +#include "tensorflow/core/common_runtime/function_utils.h" +#include "tensorflow/core/common_runtime/graph_optimizer.h" +#include "tensorflow/core/common_runtime/inline_function_utils.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +// Get default customizable kernel creator if set +const CustomKernelCreator* GetDefaultCustomKernelCreator(); + +// Registers a default customizable kernel creator for a function call. +// +// If c->CanCreateKernel returns false, we still fall back to an executor-based +// interpreter op kernel to execute a function. Else c->CreateKernel() can be +// used to create a kernel that will compile the function with XLA and run the +// resulting program. +void RegisterDefaultCustomKernelCreator(CustomKernelCreator* c); + +// Creates a FunctionLibraryRuntime, which instantiates functions +// defined in "lib_def" and executes functions on the "device". +// "device_mgr" must contain the "device". +// +// The returned object does not take ownerships of "device" or +// "lib_def". The caller must ensure "device" and "lib_def" outlives +// the returned object. +// +// The "parent" is a pointer to the ProcessFunctionLibraryRuntime object that +// typically owns the created FunctionLibraryRuntime object. The parent pointer +// is not owned by the FunctionLibraryRuntime object. +core::RefCountPtr NewFunctionLibraryRuntime( + const DeviceMgr* device_mgr, Env* env, const ConfigProto* config, + Device* device, int graph_def_version, + const FunctionLibraryDefinition* lib_def, thread::ThreadPool* thread_pool, + const OptimizerOptions& optimizer_options, + const SessionMetadata* session_metadata, + ProcessFunctionLibraryRuntime* parent); + +// Given a numerical function "f", returns another numerical function +// "g", such that if "f" takes N inputs and produces M outputs, "g" +// takes N + M inputs and produces N outputs. I.e., if +// (y1, y2, ..., y_M) = f(x1, x2, ..., x_N), +// g is a function which is +// (dL/dx1, dL/dx2, ..., dL/dx_N) = g(x1, x2, ..., x_N, +// dL/dy1, dL/dy2, ..., dL/dy_M), +// where L is a scalar-value function of (...x_i...). +// +// TODO(zhifengc): Asks math expert to say the comment again. +std::unique_ptr SymbolicGradient(const FunctionBody& f); + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_body.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_body.h new file mode 100644 index 0000000000000000000000000000000000000000..cbd602612a2862508341eb9930370efbc578b7c5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_body.h @@ -0,0 +1,52 @@ +/* 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_COMMON_RUNTIME_FUNCTION_BODY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_BODY_H_ + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" + +namespace tensorflow { + +class Graph; +class Node; + +// FunctionLibraryRuntime::GetFunctionBody returns a description of an +// instantiated function that is represented as a Graph with arg/ret +// nodes annotated. +struct FunctionBody { + FunctionDef fdef; + Graph* graph = nullptr; // owned. + DataTypeVector arg_types; + DataTypeVector ret_types; + // arg_nodes[i] contains the i'th function input. In other words, + // GetNodeAttr(arg_nodes[i]->attrs(), "index") == i. + gtl::InlinedVector arg_nodes; + // ret_nodes[i] contains the i'th function output. In other words, + // GetNodeAttr(ret_nodes[i]->attrs(), "index") == i. + gtl::InlinedVector ret_nodes; + gtl::InlinedVector control_ret_nodes; + + FunctionBody() {} + FunctionBody(const FunctionDef& f, DataTypeSlice arg_types, + DataTypeSlice ret_types, Graph* g); + ~FunctionBody(); +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_BODY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_def_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_def_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f269cc6a608c8253409d7fcdf0e9703714960b7b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_def_utils.h @@ -0,0 +1,49 @@ +/* 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_COMMON_RUNTIME_FUNCTION_DEF_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_DEF_UTILS_H_ + +#include +#include + +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class AttrSlice; +struct FunctionBody; +class FunctionDef; +class FunctionLibraryDefinition; +class OpDef; + +// Instantiates FunctionDef into a graph. Set *fbody to point to the +// FunctionBody that holds the instantiated FunctionDef. +Status FunctionDefToBodyHelper(const FunctionDef& fdef, const AttrSlice& attrs, + const FunctionLibraryDefinition* lib_def, + std::unique_ptr* fbody); + +// Instantiates FunctionDef into a graph. Set *fbody to point to the +// FunctionBody that holds the instantiated FunctionDef. Use custom function +// signature lookup, in case instantiated function is not in the 'lib_def'. +Status FunctionDefToBodyHelper( + const FunctionDef& fdef, const AttrSlice& attrs, + const FunctionLibraryDefinition* lib_def, + const std::function& get_func_sig, + std::unique_ptr* fbody); + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_DEF_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_optimization_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_optimization_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..29fe381fe540f397accbf6f046519b61e4da52e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_optimization_registry.h @@ -0,0 +1,104 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_OPTIMIZATION_REGISTRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_OPTIMIZATION_REGISTRY_H_ + +#include +#include +#include + +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/protobuf/config.pb.h" + +// Classes to maintain a static registry of Graph based passes to be applied to +// a function graph. + +namespace tensorflow { + +// A pass to be registered with the FunctionOptimizationPassRegistry. This pass +// takes in a DeviceSet (available devices for executing the Graph), ConfigProto +// (session configuration parameters), an optional target device for XLA +// compilation, Graph (computation), +// FunctionLibraryDefinition (mapping between function names and function +// definitions of the Graph), control ret/target node names (names of nodes that +// must execute but their data outputs, if they have any, are irrelevant), and +// whether control ret nodes (via thier name) were updated. Mutations to the +// Graph and other associated arguments are performed inplace by the pass. +class FunctionOptimizationPass { + public: + // Grouped Options for the optimized function. + struct FunctionOptions { + // Specifies the compilation device type(CPU, GPU, etc) + // that should be used for entire function. + std::string xla_compile_device_type = ""; + // Whether soft placement and outside compilation + // are enabled for the function. + bool allow_soft_placement = false; + }; + + virtual ~FunctionOptimizationPass() {} + virtual Status Run(const std::string& function_name, + const DeviceSet& device_set, + const ConfigProto& config_proto, + const FunctionOptions& function_options, + std::unique_ptr* graph, + FunctionLibraryDefinition* flib_def, + std::vector* control_ret_node_names, + bool* control_rets_updated) = 0; +}; + +// A global function optimization pass registry that is used to hold one +// FunctionOptimizationPass. Passes registered to this registry will run before +// passes registered in OptimizationPassRegistry. +class FunctionOptimizationPassRegistry { + public: + // Initializes registry with a pass. Only one pass should be set. An assertion + // will be triggered if the registry already has a pass set and is being + // initialized with another pass. + void Init(std::unique_ptr pass); + + // Runs a pass if the registry contains one. + Status Run(const std::string& function_name, const DeviceSet& device_set, + const ConfigProto& config_proto, + const FunctionOptimizationPass::FunctionOptions& function_options, + std::unique_ptr* graph, FunctionLibraryDefinition* flib_def, + std::vector* control_ret_node_names, + bool* control_rets_updated); + + // Returns the global registry of function graph passes. + static FunctionOptimizationPassRegistry& Global(); + + private: + std::unique_ptr pass_; +}; + +namespace function_optimization_registration { + +class FunctionOptimizationPassRegistration { + public: + explicit FunctionOptimizationPassRegistration( + std::unique_ptr pass) { + FunctionOptimizationPassRegistry::Global().Init(std::move(pass)); + } +}; + +} // namespace function_optimization_registration + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_OPTIMIZATION_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..8a3de2a8402a61950fe24d0cde4e7414340e8aa4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/function_utils.h @@ -0,0 +1,105 @@ +/* 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_COMMON_RUNTIME_FUNCTION_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_UTILS_H_ + +#include +#include + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class AttrSlice; +class Graph; +class GraphDef; +class NameAttrList; +class Node; +class NodeDef; +class OpDef; + +// Debugging facility. Returns a debug string for a graph +// representing an instantiated function. +string DebugString(const Graph* g); + +// Dump the contents of the "graph" to log files if the logging level is +// sufficiently high. +void DumpGraph(StringPiece label, const Graph* g); + +// Convert the Graph of a function to a GraphDef. +// +// Handles renaming of nodes to avoid duplicate names which may +// be present after various rewriting operations. +void ToGraphDef(const Graph* g, GraphDef* gdef, bool pretty = false); + +// Extracts function name and attributes from `call_def` +// `call_def` can be a native function call (where the op type is the function +// name) or a call through PartitionedCall/StatefulPartitionedCall. +Status NameAndAttrsFromFunctionCall(const NodeDef& call_def, + NameAttrList* function); + +// A few hand-crafted optimization on the instantiated function body +// (a Graph*). + +// Removes nodes that are +// 1. not stateful; and +// 2. not _Arg; and +// 3. not reachable from _Retval. +// +// This function is triggered by function inlining, unlike 'PruneFunctionBody' +// it doesn't preserve nodes that are reachable from control returns. Function +// inlining is responsible for connecting control return nodes with the nodes +// that have input control edges from the inlined function call node. +// +// Assuming that automatic control dependency tracking is correct, absence of +// outgoing control edge from the function call node means that no one needs to +// observe side-effect that might have been generated by the function (see +// documentation in common_runtime/function.cc for details). +// +// Returns true iff any node is removed from "g". +bool RemoveDeadNodes(Graph* g); + +// Find a pattern: +// src -(in)-> node -(out)-> dst, where +// 1) node is an identity node; +// 2) in is the only incoming data edge; +// 3) out is the only outgoing data edge; +// +// Rewrites the above pattern with src->dst and relevant data +// dependencies updated. Repeat the process until no such pattern +// left. +bool RemoveIdentityNodes(Graph* g); + +// Rewrites _ListToArray and _ArrayToList to a set of Identity nodes. +bool RemoveListArrayConverter(Graph* g); + +// Extracts function name and attributes from `call_def` and invokes +// flr->Instantiate(name, attrs, handle). +// `call_def` can be a native function call (where the op type is the function +// name) or a call through PartitionedCall/StatefulPartitionedCall. +Status InstantiateFunctionCall(const NodeDef& call_def, + FunctionLibraryRuntime* flr, + FunctionLibraryRuntime::Handle* handle); + +// Returns true iff `n` represents a function call. `n` can be a native +// function call (n.type_string() is the function name), +// a PartitionedCall/StatefulPartitionedCall, or a SymbolicGradient (which +// has been deprecated for a while). +bool IsFunctionCall(const FunctionLibraryDefinition& lib_def, const Node& n); +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_FUNCTION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..4ecaa1210edc381bdcb8223edc0dc790963255c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h @@ -0,0 +1,63 @@ +/* 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_COMMON_RUNTIME_GPU_GPU_BFC_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_BFC_ALLOCATOR_H_ + +#include +#include +#include + +#include "tsl/framework/allocator.h" +#include "tsl/framework/bfc_allocator.h" +#include "tsl/platform/macros.h" + +namespace tensorflow { + +// A GPU memory allocator that implements a 'best-fit with coalescing' +// algorithm. +class GPUBFCAllocator : public tsl::BFCAllocator { + public: + // See BFCAllocator::Options. + struct Options { + // Overridden by TF_FORCE_GPU_ALLOW_GROWTH if that envvar is set. + bool allow_growth = false; + + // If nullopt, defaults to TF_ENABLE_GPU_GARBAGE_COLLECTION, or true if that + // envvar is not present. + // + // Note: + // + // - BFCAllocator defaults garbage_collection to false, not true. + // - this is not the same override behavior as TF_FORCE_GPU_ALLOW_GROWTH. + std::optional garbage_collection; + + double fragmentation_fraction = 0; + bool allow_retry_on_failure = true; + }; + + GPUBFCAllocator(std::unique_ptr sub_allocator, + size_t total_memory, const std::string& name, + const Options& opts); + + ~GPUBFCAllocator() override {} + + GPUBFCAllocator(const GPUBFCAllocator&) = delete; + void operator=(const GPUBFCAllocator&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_BFC_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_cudamalloc_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_cudamalloc_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..cf1360ef64f59026cc970dadc8a3e59f2c798874 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_cudamalloc_allocator.h @@ -0,0 +1,52 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_CUDAMALLOC_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_CUDAMALLOC_ALLOCATOR_H_ + +#include +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" +#include "tsl/platform/macros.h" + +namespace tensorflow { + +// An allocator which directly uses cuMemAlloc and cuMemFree to allocate and +// free memory. +class GPUcudaMallocAllocator : public tsl::Allocator { + public: + explicit GPUcudaMallocAllocator(tsl::PlatformDeviceId platform_device_id); + std::string Name() override { return "gpu_debug"; } + void* AllocateRaw(size_t alignment, size_t num_bytes) override; + void DeallocateRaw(void* ptr) override; + bool TracksAllocationSizes() const override; + + tsl::AllocatorMemoryType GetMemoryType() const override { + return tsl::AllocatorMemoryType::kDevice; + } + + private: + se::StreamExecutor* stream_exec_; // Not owned. + + GPUcudaMallocAllocator(const GPUcudaMallocAllocator&) = delete; + void operator=(const GPUcudaMallocAllocator&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_CUDAMALLOC_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_debug_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_debug_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..a753f0edc6cce27b2364465277bd00d60844ddb5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_debug_allocator.h @@ -0,0 +1,93 @@ +/* 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_COMMON_RUNTIME_GPU_GPU_DEBUG_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEBUG_ALLOCATOR_H_ + +#include +#include +#include +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" +#include "tsl/platform/macros.h" + +namespace tensorflow { + +// An allocator that wraps a GPU allocator and adds debugging +// functionality that verifies that users do not write outside their +// allocated memory. +class GPUDebugAllocator : public tsl::Allocator { + public: + explicit GPUDebugAllocator(tsl::Allocator* allocator, + tsl::PlatformDeviceId platform_device_id); + ~GPUDebugAllocator() override; + std::string Name() override { return "gpu_debug"; } + void* AllocateRaw(size_t alignment, size_t num_bytes) override; + void DeallocateRaw(void* ptr) override; + bool TracksAllocationSizes() const override; + size_t RequestedSize(const void* ptr) const override; + size_t AllocatedSize(const void* ptr) const override; + int64_t AllocationId(const void* ptr) const override; + std::optional GetStats() override; + bool ClearStats() override; + + // For testing. + bool CheckHeader(void* ptr); + bool CheckFooter(void* ptr); + + private: + tsl::Allocator* base_allocator_ = nullptr; // owned + + se::StreamExecutor* stream_exec_; // Not owned. + + GPUDebugAllocator(const GPUDebugAllocator&) = delete; + void operator=(const GPUDebugAllocator&) = delete; +}; + +// An allocator that wraps a GPU allocator and resets the memory on +// allocation and free to 'NaN', helping to identify cases where the +// user forgets to initialize the memory. +class GPUNanResetAllocator : public tsl::Allocator { + public: + explicit GPUNanResetAllocator(tsl::Allocator* allocator, + tsl::PlatformDeviceId platform_device_id); + ~GPUNanResetAllocator() override; + std::string Name() override { return "gpu_nan_reset"; } + void* AllocateRaw(size_t alignment, size_t num_bytes) override; + void DeallocateRaw(void* ptr) override; + size_t RequestedSize(const void* ptr) const override; + size_t AllocatedSize(const void* ptr) const override; + std::optional GetStats() override; + bool ClearStats() override; + + tsl::AllocatorMemoryType GetMemoryType() const override { + return base_allocator_->GetMemoryType(); + } + + private: + tsl::Allocator* base_allocator_ = nullptr; // owned + + se::StreamExecutor* stream_exec_; // Not owned. + + GPUNanResetAllocator(const GPUNanResetAllocator&) = delete; + void operator=(const GPUNanResetAllocator&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEBUG_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_device.h new file mode 100644 index 0000000000000000000000000000000000000000..23b55282ea5c433fe26f3862c4324280a78119ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_device.h @@ -0,0 +1,464 @@ +/* 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. +==============================================================================*/ + +#if !GOOGLE_CUDA && !TENSORFLOW_USE_ROCM +#error This file must only be included when building with Cuda or ROCm support +#endif + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEVICE_H_ + +// TODO(b/282059652): Merge google internal and open-source code path once TF +// dependency issue is resolved. +#if (defined(PLATFORM_GOOGLE) && defined(TF_PLATFORM_LINUX_X86_64)) +#define TF_GPU_USE_PJRT +#endif // PLATFORM_GOOGLE && TF_PLATFORM_LINUX_X86_64 + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#ifdef TF_GPU_USE_PJRT +#include "tensorflow/compiler/jit/pjrt_device_context.h" +#include "tensorflow/compiler/tf2xla/layout_util.h" +#include "xla/pjrt/local_device_state.h" +#include "xla/stream_executor/tf_allocator_adapter.h" +#endif // TF_GPU_USE_PJRT +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/common_runtime/gpu/gpu_event_mgr.h" +#include "tensorflow/core/common_runtime/gpu/gpu_id_manager.h" +#include "tensorflow/core/common_runtime/gpu_device_context.h" +#include "tensorflow/core/common_runtime/local_device.h" +#include "tensorflow/core/common_runtime/node_file_writer.h" +#include "tensorflow/core/common_runtime/scoped_allocator_mgr.h" +#include "tensorflow/core/common_runtime/shared_counter.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session_options.h" +#include "tsl/framework/device_id.h" + +namespace Eigen { +class StreamInterface; +} + +namespace tensorflow { +class GPUKernelTracker; + +class ConcretePerOpGpuDevice : public PerOpGpuDevice { + public: + ConcretePerOpGpuDevice(); + + void Reinitialize(OpKernelContext* context, void* gpu_stream, + tsl::TfDeviceId tf_device_id, Allocator* base_allocator, + char* scratch); + + void Reinitialize(OpKernelContext* context, void* gpu_stream, + tsl::PlatformDeviceId platform_device_id, + Allocator* base_allocator, char* scratch); + + const Eigen::GpuDevice& device() const override; + + private: + std::unique_ptr<::Eigen::StreamInterface> stream_device_; +}; + +class BaseGPUDevice : public LocalDevice { + public: + BaseGPUDevice(const SessionOptions& options, const std::string& name, + Bytes memory_limit, const DeviceLocality& locality, + tsl::TfDeviceId tf_device_id, + const std::string& physical_device_desc, + Allocator* gpu_allocator, Allocator* cpu_allocator, + bool sync_every_op); + + ~BaseGPUDevice() override; + + struct StreamGroup { + se::Stream* compute = nullptr; +#if TENSORFLOW_USE_ROCM + se::Stream* nccl = nullptr; +#endif + se::Stream* host_to_device = nullptr; + se::Stream* device_to_host = nullptr; + gtl::InlinedVector device_to_device; + int priority = 0; + }; + + // Initialize the device and return the status of initialization. +#ifdef TF_GPU_USE_PJRT + Status Init(const SessionOptions& options, + xla::LocalDeviceState* xla_local_device_state); +#else + Status Init(const SessionOptions& options); +#endif // TF_GPU_USE_PJRT + + void Compute(OpKernel* op_kernel, OpKernelContext* context) override; + + Status Sync() override; + + void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context, + AsyncOpKernel::DoneCallback done) override; + + Status MakeTensorFromProto(const TensorProto& tensor_proto, + AllocatorAttributes alloc_attrs, + Tensor* tensor) override; + + void CopyTensorInSameDevice(const Tensor* input_tensor, Tensor* output_tensor, + const DeviceContext* device_context, + StatusCallback done) override; + + // The caller owns the returned device. + PerOpGpuDevice* MakeGpuDevice() override; + + Status ReinitializeGpuDevice(OpKernelContext* context, PerOpGpuDevice* device, + DeviceContext* dc, + Allocator* allocator) override; + + // Returns the platform GPU id of this device within the native driver system; + // e.g., for CUDA and ROCm this is the ordinal of the GPU within the system. + int gpu_id() const { + tsl::PlatformDeviceId platform_device_id; + TF_CHECK_OK( + GpuIdManager::TfToPlatformDeviceId(tf_device_id_, &platform_device_id)); + return platform_device_id.value(); + } + + // The executor that provides control for the device; e.g., for CUDA this + // corresponds to the cuda context. + se::StreamExecutor* executor() const { return executor_; } + + Allocator* GetScopedAllocator(AllocatorAttributes attr, + int64_t step_id) override; + + ScopedAllocatorMgr* GetScopedAllocatorMgr() const override { + return scoped_allocator_mgr_.get(); + } + + // The following two functions always return 0 unless one of the + // related experimental config options has been specified. + + // If returned value is > 0 then GPU Memory chunks freed before this count + // are guaranteed not to be in use by any kernel pending on this device. + uint64 SafeAllocFrontier(uint64 old_value) override; + + // Returns the number of kernels that have been queued for execution on + // the compute stream and are not yet known to have completed. + int PendingKernels(); + + int priority() const { return stream_->priority; } + + // Helper method for unit tests to reset the streams. Never use in production. + static void TestOnlyReset(); + + se::Stream* compute_stream() { return stream_->compute; } + + // Given the compute stream for a GPU or virtual GPU, return the TfDeviceId + // for the GPU or vGPU. + static std::optional FindTfDeviceId(se::Stream* compute); + + protected: + Allocator* gpu_allocator_; // not owned + Allocator* cpu_allocator_; // not owned + + se::StreamExecutor* executor_; // not owned + std::unique_ptr scoped_allocator_mgr_; + + private: + friend class GPUDeviceTestHelper; + class StreamGroupFactory; + + core::RefCountPtr pjrt_device_context_; + StreamGroup* stream_; + mutex scratch_init_mutex_; + char* scratch_ = nullptr; + GPUDeviceContext* device_context_; + DeviceBase::AcceleratorDeviceInfo* accelerator_device_info_ = nullptr; + mutex trace_mu_; + tsl::TfDeviceId tf_device_id_; + const bool sync_every_op_ = false; + EventMgr* em_ = nullptr; + std::unique_ptr thread_pool_; + std::unique_ptr kernel_tracker_; + int32 pending_cap_ = 0; + bool timestamped_allocator_ = false; + NodeFileWriter* node_file_writer_ = nullptr; // not owned + + // Initialize scratch buffers used by Eigen. + Status InitScratchBuffers(); + + void ReinitializeDevice(OpKernelContext* context, PerOpGpuDevice* device, + int stream_id, Allocator* allocator); + + std::string ComputeOpKernelDebugString(const OpKernel& op_kernel, + const int& stream_id); + + // This method returns an initialization status, in addition to + // calling the "done" StatusCallback, if there is a failure to + // allocate memory or if the tensor "from" is not DMA-copyable. + // If there is no error prior to enqueueing the copy, an OK status + // is returned. + Status MaybeCopyTensorToGPU(const AllocatorAttributes& alloc_attrs, + const Tensor& from, Tensor* to, + StatusCallback done); + + Tensor CopyGpuTensorToHostDebugOnly(const Tensor& gpu_tensor); + void LogInputs(OpKernel* op_kernel, OpKernelContext* context); + void LogOutputs(OpKernel* op_kernel, OpKernelContext* context); +}; + +// A per-compute-stream utility that keeps track of kernels that have been +// queued for execution but may not yet have terminated and also the queued +// time of the most recently terminated kernel. +class GPUKernelTracker { + public: + // Controls the strategy for inserting tracking events after GPU kernels. + // If max_interval >= 0, then insert an event after this many kernels + // if an event has not been inserted for another reason. + // If max_bytes > 0, then insert an event after kernels allocating this + // many bytes have been queued since the last event. + // If max_pending > 0, then track up to this many events at once. If + // this limit is reached the GPU::Compute() method will delay starting + // additional ops until some event completes. If 0 and one of the other + // fields is non-zero, then a reasonable default will be selected. + struct Params { + int max_interval = 0; + int max_bytes = 0; + int max_pending = 0; + Params(int mi, int mb, int mp) + : max_interval(mi), max_bytes(mb), max_pending(mp) {} + }; + + // If we're going to share a SharedCounter with an allocator, it's owned + // by the allocator because allocators are initialized once per process. + // Devices are per-session. + explicit GPUKernelTracker(const Params& params, Env* env, + se::Stream* compute_stream, + SharedCounter* timing_counter, Allocator* allocator, + EventMgr* event_manager) + : params_(params), + env_(env), + stream_(compute_stream), + timing_counter_(timing_counter), + allocator_(allocator), + em_(event_manager), + pending_kernels_( + params.max_pending > 0 ? std::max(8, 2 * params.max_pending) : 64) { + mem_since_last_ = 0; + if (!timing_counter_) { + // There's not a preexisting counter owned by GPUProcessState, i.e. + // pending_cap > 0 but timestamped_allocator == false. + owned_counter_ = std::make_unique(); + timing_counter_ = owned_counter_.get(); + } + } + + // Determine whether a GPU kernel should have a recording event queued + // immediately afterwards. If so, advance the counter and return the new + // counter value after enqueuing. + uint64 MaybeQueue(OpKernelContext* ctx); + + // Record that a GPU kernel has just been enqueued on the compute stream. + // Inserts the supplied counter value in a new PendingKernel record appended + // to the end of the ring buffer then returns that same count. + // Caller is responsible for ensuring that RecordTerminate() is eventually + // called with the same counter value. + void RecordQueued(uint64 queued_count, int weight) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + // Takes a count value returned by RecordQueued and finds the corresponding + // PendingKernel record in the ring buffer. Marks the kernel as completed and + // advances the completion frontier accordingly. + void RecordTerminated(uint64 queued_count); + + // Returns the largest timing count such that all kernels queued no + // later than that count are known to have terminated. + inline uint64 LastTerminatedCount(uint64 old_value) { + uint64 new_value = last_terminated_count_.load(std::memory_order_relaxed); + if (new_value == old_value) { + MaybeQueueProgressEvent(); + } + return new_value; + } + + // Returns the number of kernels enqueued that are not yet known to + // have terminated. + int NumPending() { + mutex_lock l(mu_); + return num_pending_; + } + + // Yield current thread until number of pending kernels no longer + // exceeds the cap. + void PauseWhilePendingExceeds(int cap) TF_LOCKS_EXCLUDED(mu_) { + mutex_lock l(mu_); + while (num_pending_ > cap) { + VLOG(1) << "num_pending_=" << num_pending_ << " cap=" << cap; + pending_decreased_.wait(l); + } + } + + private: + friend class GPUKernelTrackerTest; + Params params_; + Env* env_; + se::Stream* stream_; + SharedCounter* timing_counter_; + std::unique_ptr owned_counter_; + Allocator* allocator_ = nullptr; + EventMgr* em_ = nullptr; + std::atomic last_terminated_count_ = {1}; + + void MaybeQueueProgressEvent(); + + // Records when a kernel was queued for execution. Kernel launches are + // identified by a unique count value from a per-GPU device timing counter. + struct PendingKernel { + uint64 queued_count; + int weight; + bool terminated; + PendingKernel(const PendingKernel& pk) = default; + PendingKernel() : queued_count(0), weight(0), terminated(false) {} + }; + mutex mu_; + int32 mem_since_last_ TF_GUARDED_BY(mu_); + int32 ops_since_last_ TF_GUARDED_BY(mu_); + // Ring buffer of PendingKernel records. + std::vector pending_kernels_ TF_GUARDED_BY(mu_); + // Next unused slot in pending_kernels_. + int first_available_ TF_GUARDED_BY(mu_) = 0; + // Last completed PendingKernel such that all prior PendingKernels are + // also completed. With out-of-order completion there may be a mixture + // of completed and uncompleted entries between last_completed_ and + // first_available_. + int last_completed_ TF_GUARDED_BY(mu_) = -1; + // Sum of weights of the outstanding events marking tracked kernels. + int num_pending_ TF_GUARDED_BY(mu_) = 0; + condition_variable pending_decreased_ TF_GUARDED_BY(mu_); +}; + +class BaseGPUDeviceFactory : public DeviceFactory { + public: + Status ListPhysicalDevices(std::vector* devices) override; + Status CreateDevices(const SessionOptions& options, + const std::string& name_prefix, + std::vector>* devices) override; + Status GetDeviceDetails(int device_index, + std::unordered_map* details) override; + + struct InterconnectMap { + // Name of interconnect technology, if known. + std::string name; + // If possible, strength should approximate Gb/sec bandwidth rate. + // Where architecture-specific subclassing is not done that won't + // always be possible. The minimum expectation is that + // faster links should have a higher value than slower links. + int32 strength; + static const int kSameDeviceStrength; + static const int kStreamExecutorStrength; + std::set> + directed_links; + }; + + protected: + // Populates *maps with interconnect maps for all local direct access + // pathways between GPUs. + virtual Status GetInterconnectMaps( + const std::vector& visible_gpu_order, + se::Platform* gpu_manager, std::vector* maps); + + struct TfDeviceIdHash { + std::size_t operator()(const tsl::TfDeviceId& id) const noexcept { + return std::hash{}(id.value()); + } + }; + typedef std::unordered_map + LocalityMap; + // Populates *localities with the DeviceLocality descriptor for + // every TfDeviceId. + virtual Status GetDeviceLocalities( + int num_tf_gpus, const std::vector& interconnects, + LocalityMap* localities); + + private: + // Creates a BaseGPUDevice associated with 'tf_device_id', and adds it to the + // 'devices' vector. The 'gpu_allocator' is created by the caller and usually + // preallocates a set amount of GPU memory. +#ifdef TF_GPU_USE_PJRT + Status CreateGPUDevice(const SessionOptions& options, + const std::string& name_prefix, + tsl::TfDeviceId tf_device_id, + const DeviceLocality& dev_locality, + xla::LocalDeviceState* xla_local_device_state, + Allocator* gpu_allocator, + std::vector>* devices); +#else + Status CreateGPUDevice(const SessionOptions& options, + const std::string& name_prefix, + tsl::TfDeviceId tf_device_id, + const DeviceLocality& dev_locality, + Allocator* gpu_allocator, + std::vector>* devices); +#endif // TF_GPU_USE_PJRT + + virtual std::unique_ptr CreateGPUDevice( + const SessionOptions& options, const string& name, Bytes memory_limit, + const DeviceLocality& dev_locality, tsl::TfDeviceId tf_device_id, + const string& physical_device_desc, Allocator* gpu_allocator, + Allocator* cpu_allocator) = 0; + + Status EnablePeerAccess( + const std::vector& visible_gpu_order); + + // Returns into 'ids' the list of valid platform GPU ids, in the order that + // they should map to TF GPU ids "/device:GPU:0", "/device:GPU:1", etc, + // based upon 'visible_gpu_order' which was generated by parsing + // GPUOptions::visible_device_list which is a comma-separated list of CUDA or + // ROCm GPU ids. + Status GetValidDeviceIds( + const std::vector& visible_gpu_order, + std::vector* ids); + + // Cache the valid device IDs if not already cached. Cached IDs are stored in + // field cached_device_ids_. Passes {0, 1, ..., num_devices-1} to + // GetValidDeviceIds, so this should only be used in functions where all + // devices should be treated as visible, like ListPhysicalDevices. + Status CacheDeviceIds(); + + // visible_gpu_initialized_[platform_device_id] is true if visible GPU + // platform_device_id has been initialized by the process. + std::unordered_map visible_gpu_initialized_; + + // Cached device IDs, as returned by GetValidDeviceIds when every physical + // device is visible. Cache should not be used if some devices are not + // visible. + std::vector cached_device_ids_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_event_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_event_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..601119fb832b419edccc8255f2715c0a656db7de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_event_mgr.h @@ -0,0 +1,23 @@ +/* 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. +==============================================================================*/ +// TODO(annarev): remove this file once all includes are updated to +// include device_event_mgr.h instead. + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_EVENT_MGR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_EVENT_MGR_H_ + +#include "tensorflow/core/common_runtime/device/device_event_mgr.h" + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_EVENT_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id.h new file mode 100644 index 0000000000000000000000000000000000000000..c2849d2db8f6a46bf60cfb85d5da3a7399993a5a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id.h @@ -0,0 +1,22 @@ +/* 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_COMMON_RUNTIME_GPU_GPU_ID_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_H_ + +#include "tensorflow/core/common_runtime/device/device_id.h" + +// TODO(sanjoy): Delete the header and forward the references. + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id_manager.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..b336db8451a93417528c92861a65e74304ffdda1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_id_manager.h @@ -0,0 +1,43 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_MANAGER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_MANAGER_H_ + +#include "tensorflow/core/lib/core/status.h" +#include "tsl/framework/device_id.h" + +namespace tensorflow { + +// Class that maintains a map from TfDeviceId to PlatformDeviceId, and manages +// the translation between them. +class GpuIdManager { + public: + // Adds a mapping from tf_device_id to platform_device_id. + static Status InsertTfPlatformDeviceIdPair( + tsl::TfDeviceId tf_device_id, tsl::PlatformDeviceId platform_device_id); + + // Gets the platform_device_id associated with tf_device_id. Returns OK if + // found. + static Status TfToPlatformDeviceId(tsl::TfDeviceId tf_device_id, + tsl::PlatformDeviceId* platform_device_id); + + // Clears the map. Used in unit tests only. + static void TestOnlyReset(); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_ID_MANAGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_managed_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_managed_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..4bdf6cf2b6cb972bfed217e25f1362736d9ad1a4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_managed_allocator.h @@ -0,0 +1,38 @@ +/* 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_COMMON_RUNTIME_GPU_GPU_MANAGED_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_MANAGED_ALLOCATOR_H_ + +#include + +#include "tsl/framework/allocator.h" + +namespace tensorflow { + +// An allocator for CUDA unified memory. Memory allocated with this allocator +// can be accessed from both host and device. CUDA transparently migrates dirty +// pages, which can be slow. Therefore, this allocator is intended for +// convenience in functional tests only. +class GpuManagedAllocator : public tsl::Allocator { + public: + std::string Name() override { return "GpuManagedAllocator"; } + void* AllocateRaw(size_t alignment, size_t num_bytes) override; + void DeallocateRaw(void* ptr) override; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_MANAGED_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_process_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_process_state.h new file mode 100644 index 0000000000000000000000000000000000000000..db91de11f80f85d2a3a72be17dfced6001b13e9b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_process_state.h @@ -0,0 +1,187 @@ +/* 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_COMMON_RUNTIME_GPU_GPU_PROCESS_STATE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_PROCESS_STATE_H_ + +// TODO(b/282059652): Merge google internal and open-source code path once TF +// dependency issue is resolved. +#if (defined(PLATFORM_GOOGLE) && defined(TF_PLATFORM_LINUX_X86_64)) +#define TF_GPU_USE_PJRT +#endif // PLATFORM_GOOGLE && TF_PLATFORM_LINUX_X86_64 + +#include +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/process_state.h" +#include "tensorflow/core/common_runtime/shared_counter.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tsl/framework/device_id.h" + +namespace tensorflow { + +class GPUBFCAllocator; +class PoolAllocator; + +// Singleton that manages per-process state when GPUs are present. +class GPUProcessState { + public: + // If ps == nullptr, returns pointer to the single instance of this class to + // be used within this process. + // + // If ps != nullptrs, accepts a value to be returned by all subsequent calls. + // A non-null ps may ONLY be provided during program static storage + // initialization. Must not be called more than once with a non-null ps. + // + // If a derived class of GPUProcessState is ever used in a process, it must + // always be used in place of this class. In order to ensure that existing + // calls to GPUProcessState::singleton() all resolve to the derived instance + // instead, this function must be called once during startup, supplying the + // derived instance value, prior to any accessor call to this function. + static GPUProcessState* singleton(GPUProcessState* ps = nullptr); + + // Query whether any GPU device has been created so far. + // Disable thread safety analysis since a race is benign here. + bool HasGPUDevice() const TF_NO_THREAD_SAFETY_ANALYSIS { + return gpu_device_enabled_; + } + + // Set the flag to indicate a GPU device has been created. + // Disable thread safety analysis since a race is benign here. + void EnableGPUDevice() TF_NO_THREAD_SAFETY_ANALYSIS { + gpu_device_enabled_ = true; + } + + // Returns the one GPU allocator used for the indexed GPU. + // Note that this is a system GPU index, not (necessarily) a brain + // device index. + // + // 'total_bytes' is the total number of bytes that should be made + // available to the allocator. The first call to this function for + // a given tf_device_id creates the allocator, so only the total_bytes + // used on that first call is used. + // + // "Allocator type" describes the type of algorithm to use for the + // underlying allocator. REQUIRES: Must be a valid type (see + // config.proto for the list of supported strings.). + // + // `options` is read on the very first call to this function in the process. + // After that if you pass in a set of options, they will be ignored. + // + // REQUIRES: tf_device_id must be a valid id for a BaseGPUDevice available in + // the current system environment. Otherwise returns nullptr. + virtual Allocator* GetGPUAllocator( + const GPUOptions& options, tsl::TfDeviceId tf_device_id, + size_t total_bytes, const std::vector& peer_gpu_ids); + + Allocator* GetGPUAllocator(tsl::TfDeviceId tf_device_id) { + return GetGPUAllocator(/*options=*/{}, tf_device_id, /*total_bytes=*/0, + /*peer_gpu_ids=*/{}); + } + + int NumGPUAllocators() { + mutex_lock l(mu_); + return gpu_allocators_.size(); + } + + // `options` is read on the very first call to this function in the process, + // e.g. to set the memory limit on this allocator. After that if you pass in + // a different set of options, they will be ignored. + virtual Allocator* GetGpuHostAllocator(const GPUOptions& options, + int numa_node); + + // Registers a Visitor to be invoked on new chunks of memory allocated by the + // SubAllocator of every GPU proximate to the specified bus. The AllocVisitor + // is provided with a memory pointer, a GPU id, and the size of the area it + // identifies. The pointer is not guaranteed to be valid after the call + // terminates. The intention is for this interface to be used for network + // device memory registration. "bus_id" is platform-specific. On many + // platforms it should be 0. On machines with multiple PCIe buses, it should + // be the index of one of the PCIe buses (maybe the NUMA node at which the + // PCIe is rooted). If the bus_id is invalid, results are undefined. + virtual void AddGPUAllocVisitor(int bus_id, + const SubAllocator::Visitor& visitor); + + // Registers a Visitor to be invoked on new chunks of memory allocated by + // the SubAllocator of the GpuHostAllocator for the given numa_node. + virtual void AddGpuHostAllocVisitor(int numa_node, + const SubAllocator::Visitor& visitor); + + // Registers a Visitor to be invoked on each chunk handed back for freeing to + // the SubAllocator of the GpuHostAllocator for the given numa_node. + virtual void AddGpuHostFreeVisitor(int numa_node, + const SubAllocator::Visitor& visitor); + + // Returns bus_id for the given GPU id. + virtual int BusIdForGPU(tsl::TfDeviceId tf_device_id); + + SharedCounter* GPUAllocatorCounter(tsl::TfDeviceId tf_device_id); + + protected: + // GPUProcessState is a singleton that should not normally be deleted except + // at process shutdown. + GPUProcessState(); + virtual ~GPUProcessState() {} + friend class GPUDeviceTest; + + // Helper method for unit tests to reset the ProcessState singleton by + // cleaning up everything. Never use in production. + virtual void TestOnlyReset(); + + ProcessState::MDMap* mem_desc_map() { + if (process_state_) return &process_state_->mem_desc_map_; + return nullptr; + } + + static GPUProcessState* instance_; + ProcessState* process_state_; // Not owned. + bool gpu_device_enabled_; + + mutex mu_; + + struct AllocatorParts { + std::unique_ptr allocator; + std::unique_ptr counter; + GPUBFCAllocator* bfc_allocator; + SubAllocator* sub_allocator; // owned by allocator + std::unique_ptr recording_allocator; + +#ifdef TF_GPU_USE_PJRT + // Not owning GPU allocator. The allocator is owned by PJRT. If + // `allocator_not_owned` is set, `allocator` owned by AllocatorParts won't + // be set. + Allocator* allocator_not_owned; +#endif // TF_GPU_USE_PJRT + }; + std::vector gpu_allocators_ TF_GUARDED_BY(mu_); + std::vector> gpu_visitors_ + TF_GUARDED_BY(mu_); + + std::vector gpu_host_allocators_ TF_GUARDED_BY(mu_); + std::vector> gpu_host_alloc_visitors_ + TF_GUARDED_BY(mu_); + std::vector> gpu_host_free_visitors_ + TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_PROCESS_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_util.h new file mode 100644 index 0000000000000000000000000000000000000000..b3614e1bf189685e53bdc9e7dbc81727460d3662 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_util.h @@ -0,0 +1,111 @@ +/* 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_COMMON_RUNTIME_GPU_GPU_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_UTIL_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/dma_helper.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/stream_executor.h" + +namespace tensorflow { + +class RecvTensorResponse; +class TensorProto; + +class GPUUtil { + public: + // "tensor" is GPU-local. "dev" is the hosting GPU. + // "device_context" should be the context of the GPU "_Send" op + // which provides the Tensor. + // Sets all necessary fields of "proto" by transferring value + // bytes from GPU to CPU RAM. "is_dead" indicates that the + // tensor is dead with an uninit value. + static void SetProtoFromGPU(const Tensor& tensor, Device* dev, + const DeviceContext* device_context, + TensorProto* proto, bool is_dead, + StatusCallback done); + + // Copies the data in 'gpu_tensor' into 'cpu_tensor'. + // 'gpu_tensor''s backing memory must be on 'gpu_device' and + // 'cpu_tensor' must be allocated to be of the same size as + // 'gpu_tensor'. Synchronous: may block. + static void CopyGPUTensorToCPU(Device* gpu_device, + const DeviceContext* device_context, + const Tensor* gpu_tensor, Tensor* cpu_tensor, + StatusCallback done); + + // Blocks until all operations queued on the stream associated with + // "gpu_device" at the time of the call have completed. Returns any + // error pending on the stream at completion. + static Status Sync(Device* gpu_device); + + // Blocks until all operations queued on all streams associated with the + // corresponding GPU device at the time of call have completed. + // Returns any error pending on the stream at completion. + static Status SyncAll(Device* gpu_device); + + // For debugging purpose, given a "device" and a "tensor" allocated + // on the device, return a string printing each byte in the tensor + // (up to a limit). "device" can be either a CPU or a GPU device. + static string MemoryDebugString(const Device* device, Tensor* tensor); + + // Map a Tensor as a DeviceMemory object wrapping the given typed + // buffer. + // + // NOTE: will be removed soon, see StreamExecutorUtil::AsDeviceMemory + // instead. + template + static se::DeviceMemory AsDeviceMemory(const Tensor& t) { + T* ptr = reinterpret_cast(const_cast(DMAHelper::base(&t))); + return se::DeviceMemory(se::DeviceMemoryBase(ptr, t.TotalBytes())); + } + + // Computes a checksum over the contents of "tensor", which is allocated + // on "gpu_device". + static uint64 Checksum(Device* gpu_device, + const DeviceContext* device_context, + const Tensor& tensor); + + // Computes a checksum over the contents of "tensor", which is allocated + // in local CPU RAM. + static uint64 Checksum(const Tensor& tensor); + + static void CopyCPUTensorToGPU(const Tensor* cpu_tensor, + const DeviceContext* device_context, + Device* gpu_device, Tensor* gpu_tensor, + StatusCallback done, bool sync_dst_compute); + + static void DeviceToDeviceCopy( + DeviceContext* send_dev_context, DeviceContext* recv_dev_context, + Device* src, Device* dst, AllocatorAttributes src_alloc_attr, + AllocatorAttributes dst_alloc_attr, const Tensor* input, Tensor* output, + int dev_to_dev_stream_index, StatusCallback done); + + // Deep-copying of GPU tensor on the same device. + // 'src_gpu_tensor''s and 'dst_gpu_tensor''s backing memory must be on + // 'gpu_device' and 'dst_cpu_tensor' must be allocated to be of the same + // size as 'src_gpu_tensor'. + static void CopyGPUTensorToSameGPU(Device* gpu_device, + const DeviceContext* device_context, + const Tensor* src_gpu_tensor, + Tensor* dst_gpu_tensor, + StatusCallback done); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_virtual_mem_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_virtual_mem_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..abe9b4bf050d49dcf6c9be98bc932fc3b4de823e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu/gpu_virtual_mem_allocator.h @@ -0,0 +1,117 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// CUDA virtual memory API is only available in CUDA versions greater than 10.2. + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_VIRTUAL_MEM_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_VIRTUAL_MEM_ALLOCATOR_H_ + +#include +#include + +#include "xla/stream_executor/stream_executor.h" +#include "tsl/framework/allocator.h" +#include "tsl/framework/device_id.h" + +#if GOOGLE_CUDA +#include "xla/stream_executor/gpu/gpu_driver.h" +#include "xla/stream_executor/gpu/gpu_types.h" +#endif + +#if CUDA_VERSION >= 10020 + +namespace tensorflow { + +// GpuVirtualMemAllocator is a SubAllocator for use with BFCAllocator which +// provides contiguous allocations with each call to Alloc. This is done by +// reserving a large chunk of virtual addresses at construction and then mapping +// physical memory pages to this virtual address range as requested. +// +// This class is not thread-safe. +class GpuVirtualMemAllocator : public tsl::SubAllocator { + public: + static tsl::StatusOr> Create( + const std::vector& alloc_visitors, + const std::vector& free_visitors, + stream_executor::gpu::GpuContext& gpu_context, + tsl::PlatformDeviceId gpu_id, size_t virtual_address_space_size, + const std::vector& peer_gpu_ids); + ~GpuVirtualMemAllocator() override; + + // Allocates memory at least as large as requested by num_bytes. Will be + // aligned to the min allocation granularity (typically 2MiB). + // alignment is ignored by this allocator. + void* Alloc(size_t alignment, size_t num_bytes, + size_t* bytes_received) override; + + // Frees should only happen at the end of the contiguous memory allocations or + // else we introduce pointless fragmentation...But, this is supported. If the + // allocation happens at the end, then the next_alloc_offset_ is moved back, + // otherwise a hole is created. + // + // Holes are not re-used, all allocations continue to come at the end of the + // next_alloc_offset_. To accommodate this, the virtual_address_space_size + // should be much larger than the max physical size of the allocator. + // + // In practice, since the BFC allocator coalesces adjacent AllocationRegions, + // this free function should never be invoked. + void Free(void* ptr, size_t num_bytes) override; + + bool SupportsCoalescing() const override { return true; } + + private: + GpuVirtualMemAllocator( + const std::vector& alloc_visitors, + const std::vector& free_visitors, + stream_executor::gpu::GpuContext& gpu_context, + tsl::PlatformDeviceId gpu_id, + std::vector access_device_handles, + stream_executor::gpu::GpuDriver::VmemSpan vmem, size_t granularity); + + stream_executor::gpu::GpuContext& gpu_context_; + tsl::PlatformDeviceId gpu_id_; + + // Peer access is configured at mmap time so the allocator must be aware of + // all gpus that may want to read the memory. This list also includes the + // above gpu_id_ to facilitate the invocation of the GpuDriver::MapMemory + // function. + const std::vector access_gpu_handles_; + + // The virtual memory span held by this allocator. + stream_executor::gpu::GpuDriver::VmemSpan vmem_; + // The next offset from the vmem base address that will be allocated. This + // corresponds to the size of physically pinned memory if holes haven't been + // created with "free". + size_t next_alloc_offset_ = 0; + + // Smallest allocation as determined by CUDA. + const size_t granularity_; + + struct Mapping { + stream_executor::gpu::GpuDevicePtr va; + stream_executor::gpu::GpuDriver::GenericMemoryHandle physical; + }; + // List of mappings, sorted by va. + std::vector mappings_; + + GpuVirtualMemAllocator(const GpuVirtualMemAllocator&) = delete; + void operator=(const GpuVirtualMemAllocator&) = delete; +}; + +} // namespace tensorflow + +#endif // CUDA_VERSION >= 10200 + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_VIRTUAL_MEM_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu_device_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu_device_context.h new file mode 100644 index 0000000000000000000000000000000000000000..dcc3bfb4335d950d23248737a4d3f523dc093195 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gpu_device_context.h @@ -0,0 +1,107 @@ +/* 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_COMMON_RUNTIME_GPU_DEVICE_CONTEXT_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_DEVICE_CONTEXT_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" + +namespace stream_executor { +class Stream; +} // namespace stream_executor + +namespace tensorflow { + +class GPUDeviceContext : public DeviceContext { + public: + // Does not take ownership of streams. + GPUDeviceContext(int stream_id, se::Stream* stream, +#if TENSORFLOW_USE_ROCM + se::Stream* nccl_stream, +#endif + se::Stream* host_to_device_stream, + se::Stream* device_to_host_stream, + gtl::InlinedVector device_to_device_stream, + Allocator* host_memory_allocator) + : stream_id_(stream_id), + stream_(stream), +#if TENSORFLOW_USE_ROCM + nccl_stream_(nccl_stream), +#endif + host_to_device_stream_(host_to_device_stream), + device_to_host_stream_(device_to_host_stream), + device_to_device_stream_(device_to_device_stream), + host_memory_allocator_(host_memory_allocator) { + } + + ~GPUDeviceContext() override {} + + se::Stream* stream() const override { return stream_; } +#if TENSORFLOW_USE_ROCM + se::Stream* nccl_stream() const { return nccl_stream_; } +#endif + se::Stream* host_to_device_stream() const { return host_to_device_stream_; } + se::Stream* device_to_host_stream() const { return device_to_host_stream_; } + se::Stream* device_to_device_stream(int index) const { + return device_to_device_stream_[index % device_to_device_stream_.size()]; + } + int stream_id() const { return stream_id_; } + Allocator* host_memory_allocator() const override { + return host_memory_allocator_; + } + + void CopyCPUTensorToDevice(const Tensor* cpu_tensor, Device* device, + Tensor* device_tensor, StatusCallback done, + bool sync_dst_compute) const override; + + void CopyDeviceTensorToCPU(const Tensor* device_tensor, StringPiece edge_name, + Device* device, Tensor* cpu_tensor, + StatusCallback done) override; + + void CopyTensorInSameDevice(const Tensor* input_tensor, Device* device, + Tensor* output_tensor, + StatusCallback done) const override; + + void MaintainLifetimeOnStream(const Tensor* t, + se::Stream* stream) const override {} + + Status ThenExecute(Device* device, se::Stream* stream, + std::function func) override; + + private: + int stream_id_; + // The default primary stream to use for this context. + // All the memory belongs to this stream. + se::Stream* stream_; +#if TENSORFLOW_USE_ROCM + // The stream to use for nccl operations. + se::Stream* nccl_stream_; +#endif + // The stream to use for copying data from host into GPU. + se::Stream* host_to_device_stream_; + // The stream to use for copying data from GPU to host. + se::Stream* device_to_host_stream_; + // Streams to use for copying data between GPUs. + gtl::InlinedVector device_to_device_stream_; + // The allocator to use for allocating pinned host memory. + // Not owned. + Allocator* host_memory_allocator_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_DEVICE_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gradients.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gradients.h new file mode 100644 index 0000000000000000000000000000000000000000..1f86af5298de3806edaa22c7ce419b80e93d14c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/gradients.h @@ -0,0 +1,58 @@ +/* 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_COMMON_RUNTIME_GRADIENTS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GRADIENTS_H_ + +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/array_slice.h" + +namespace tensorflow { + +// Represents the output of 'node' at 'index'. +struct NodeOut { + Node* node; + int index; + + // Returns the string name that represents the output of this node. + string name() const; + // Returns the data type of the output of this node. + DataType dtype() const; +}; + +// NOTE: This API is a work in progress and will likely be changing frequently. +// +// Given initial gradient-node outputs 'y_grad_node_outputs' (which compute the +// symbolic partial derivatives of some loss function 'L' w.r.t the node outputs +// 'y_node_outputs'), adds gradient nodes to 'graph' that compute the symbolic +// partial derivatives of 'L' w.r.t the node outputs 'x_node_outputs'. +// +// REQUIRES: Each node in 'x_node_outputs' to be unique, and so to have a single +// output (this restriction will be removed in a subsequent change). + +// TODO(andydavis) Add symbolic gradient support for general graphs (the current +// implementation only supports gradients for functions). In particular, +// the nodes in 'x_nodes' are currently restricted to have one output. + +Status AddSymbolicGradients(gtl::ArraySlice y_node_outputs, + gtl::ArraySlice x_node_outputs, + gtl::ArraySlice y_grad_node_outputs, + std::vector* x_grad_node_outputs, + Graph* graph); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GRADIENTS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_constructor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_constructor.h new file mode 100644 index 0000000000000000000000000000000000000000..cb164732da150eae9f02f789513711e7056e3ae6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_constructor.h @@ -0,0 +1,210 @@ +/* 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_COMMON_RUNTIME_GRAPH_CONSTRUCTOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_CONSTRUCTOR_H_ + +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/graph/tensor_id.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +class ShapeRefiner; + +// Construct a Graph *g out of a GraphDef gdef. Returns non-OK on +// error, in which case *g is left in an incomplete state. +// +// *g is expected to be an empty graph (with no more than a source and sink +// nodes) when provided to ConvertGraphDefToGraph. To enhance an existing Graph, +// see ImportGraphDef. +struct GraphConstructorOptions { + GraphConstructorOptions() = default; + + // If true, allows internal ops in the GraphDef. + bool allow_internal_ops = false; + + // If true, the graph def is expected to have fully specified + // devices for all nodes. A node in the resulting graph "g" has the + // device name set accordingly. + // + // TODO(zhifengc): if possible, consider removing this option. + bool expect_device_spec = false; + + // If true, validates that nodes being converted have all expected attrs + // set and no unknown attrs set by calling ValidateNodeDef(). + // Setting validate_nodes without add_default_attributes, will fail if + // the GraphDef does not have all required attributes set. + bool validate_nodes = false; + + // If true, GraphConstructor will add attributes with their default + // value to the Node when they are missing from the NodeDef. + bool add_default_attributes = true; +}; +extern Status ConvertGraphDefToGraph(const GraphConstructorOptions& opts, + const GraphDef& gdef, Graph* g); +extern Status ConvertGraphDefToGraph(const GraphConstructorOptions& opts, + GraphDef&& gdef, Graph* g); + +// Same as ConvertGraphDefToGraph, but takes just nodes. Used by function +// instantiation. +// TODO(irving): This will turn into std::vector soon. +extern Status ConvertNodeDefsToGraph( + const GraphConstructorOptions& opts, gtl::ArraySlice nodes, + Graph* g, const GraphDebugInfo* debug_info = nullptr); + +// Options for calling ImportGraphDef(). +struct ImportGraphDefOptions { + ImportGraphDefOptions() + : uniquify_names(false), + uniquify_prefix(false), + skip_mapped_nodes(false), + validate_shape(true), + propagate_device_spec(false) {} + + // Name prefix to use for nodes imported from the GraphDef. For example, if + // prefix="animals" and GraphDef contains a node "bunny" then the node will be + // named "animals/bunny" in *g. Must not be already used as a node name or + // prefix in the graph. + string prefix; + + // If true, imported node names will be modified if their name already exists + // in the graph. If false, conflicting names will be treated as an error. Note + // that this option has no effect if `prefix` is specified, since `prefix` + // will guarantee all node names are unique. + bool uniquify_names; + + // If true, `prefix` will be modified if it already exists as a node name or + // prefix in the graph. If false, a conflicting prefix will be treated as an + // error. This option has no effect if `prefix` isn't specified. + bool uniquify_prefix; + + // Maps tensors in `gdef` to existing tensors in `g`. Inputs in `gdef` + // corresponding to `input_map` keys will be remapped to the nodes in `g` + // corresponding to the values. + // + // Keys should not include `prefix`, i.e., a key ID's name should be the name + // as it originally appears in `gdef`. + // + // If this is non-empty, ImportGraphDef must be called with the shape refiner + // used to create the existing nodes referenced in `input_map`. + // TODO(skyewm): can we remove this requirement? How do we access the original + // shape refiner? + std::map input_map; + + // If true, nodes that will have all output edges removed because of + // overrides in `input_map` will not be imported. + bool skip_mapped_nodes; + + // The names of existing nodes in `g` that the imported graph should have + // control dependencies on. + // + // Note that to avoid creating many redundant control edges, ImportGraphDef() + // won't add control edges to nodes that will inherit the dependencies from + // other nodes in `gdef`. + std::vector control_dependencies; + + // Tensors in `gdef` that will be returned via the ImportGraphDefResults + // output parameter of `ImportGraphDef()`. If this list is non-empty, the + // caller must pass a results object to `ImportGraphDef()`. The + // `return_tensors` field will be populated with the imported nodes in `g`. + // + // Entries should not include `prefix`, i.e., each ID's name should be the + // name as it originally appears in `gdef`. + // + // If this contains a tensor that's also being remapped via `input_map`, the + // corresponding existing tensor in `g` will be returned. + std::vector return_tensors; + + // The names of nodes in `gdef` that will be returned via the + // ImportGraphDefResults output parameter of `ImportGraphDef()`. If this list + // is non-empty, the caller must pass a results object to + // `ImportGraphDef()`. The `return_nodes` field will be populated with the + // imported nodes in `g`. + // + // Entries should not include `prefix`, i.e., each node's name should be the + // name as it originally appears in `gdef`. + // + // Unlike `return_tensors`, `input_map` has no effect on the nodes + // returned. `return_nodes` must be empty if `skip_mapped_nodes` is true. + // TODO(skyewm): make this work with `skip_mapped_nodes` if there's a need. + std::vector return_nodes; + + // If true, checks that all colocation constraints are nodes in the GraphDef. + bool validate_colocation_constraints = true; + + // If false skips shape validation. + bool validate_shape; + + // TODO(ashankar): Enable handling of GraphDefs produced by newer binaries + // with ops that are not defined in the binary calling ImportGraphDef. + // Similar to the producer_op_list argument to import_graph_def in the + // python API. + + // Try to set default execution device for this grapth. + string default_device; + + // If true, propagates a node's assigned device. By default the runtime + // will recompute the assigned device every time. + bool propagate_device_spec; +}; + +// Optional results that may be returned by ImportGraphDef. +struct ImportGraphDefResults { + // The requested tensors associated with + // ImportGraphDefOptions::return_tensors. Note that the index may be different + // than the requested index if the returned tensor has been remapped according + // to `input_map`. + typedef int Index; + std::vector> return_tensors; + + // The requested nodes associated with ImportGraphDefOptions::return_nodes. + std::vector return_nodes; + + // Keys in ImportGraphDefOptions::input_map that don't appear in `gdef` and + // weren't used as an input to any node in `gdef`. These keys are likely due + // to typos, and callers may wish to treat their existence as an error. + std::vector missing_unused_input_map_keys; +}; + +// Adds the graph in GraphDef `gdef` into an existing Graph `*g`. +// +// On error, returns non-OK and leaves `*g` unmodified. +// +// `refiner` can be null. It should be non-null if the caller +// intends to add additional nodes to the graph after the import. This +// allows the caller to validate shapes of those nodes (since +// ShapeRefiner::AddNode must be called in topological order). +// +// `results` must be non-null if `opts.return_tensors` or `opts.result_nodes` is +// non-empty. It can also be set to fetch the unused input map keys. If it's +// non-null, all the vector fields must be empty. +// +// TODO(ashankar): Push this mechanism and get rid of Session::Extend() +// as a means of enhancing an existing Graph. +extern Status ImportGraphDef(const ImportGraphDefOptions& opts, + const GraphDef& gdef, Graph* g, + ShapeRefiner* refiner, + ImportGraphDefResults* results = nullptr); + +// Make a copy of "src" into "*dest". +// +// REQUIRES: "*dest" is a freshly allocated graph without any nodes or edges +// other than the implicit Source/Sink nodes. +extern void CopyGraph(const Graph& src, Graph* dest); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_CONSTRUCTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_def_builder_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_def_builder_util.h new file mode 100644 index 0000000000000000000000000000000000000000..01f3d710460d6d1c9667ebbe67f019bb930638d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_def_builder_util.h @@ -0,0 +1,35 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_DEF_BUILDER_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_DEF_BUILDER_UTIL_H_ + +#include "tensorflow/core/graph/graph_def_builder.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class Graph; + +// Converts the `GraphDef` being built by `builder` to a `Graph` and +// stores it in `*graph`. +// TODO(josh11b): Make this faster; right now it converts +// Graph->GraphDef->Graph. This cleans up the graph (e.g. adds +// edges from the source and to the sink node, resolves back edges +// by name), and makes sure the resulting graph is valid. +Status GraphDefBuilderToGraph(const GraphDefBuilder& builder, Graph* graph); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_DEF_BUILDER_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_execution_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_execution_state.h new file mode 100644 index 0000000000000000000000000000000000000000..87b3a12891d45a5832c8e7300961ef65aaa69e7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_execution_state.h @@ -0,0 +1,237 @@ +/* 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_COMMON_RUNTIME_GRAPH_EXECUTION_STATE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_EXECUTION_STATE_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/build_graph_options.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/graph/costmodel.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +struct SessionOptions; + +namespace subgraph { +struct RewriteGraphMetadata; +} + +struct GraphExecutionStateOptions { + const DeviceSet* device_set = nullptr; + const SessionOptions* session_options = nullptr; + // Unique session identifier. Can be empty. + string session_handle; + // A map from node name to device name, representing the unchangeable + // placement of stateful nodes. + std::unordered_map stateful_placements; + // Whether to run Placer on the graph. + bool run_placer = true; +}; + +// A ClientGraph is simply a sub-graph of the full graph as induced by +// BuildGraphOptions. +struct ClientGraph { + explicit ClientGraph(std::unique_ptr flib, + DataTypeVector feed_types, DataTypeVector fetch_types, + int64_t collective_graph_key) + : flib_def(std::move(flib)), + graph(flib_def.get()), + feed_types(std::move(feed_types)), + fetch_types(std::move(fetch_types)), + collective_graph_key(collective_graph_key) {} + // Each client-graph gets its own function library since optimization passes + // post rewrite for execution might want to introduce new functions. + std::unique_ptr flib_def; + Graph graph; + DataTypeVector feed_types; + DataTypeVector fetch_types; + int64_t collective_graph_key; +}; + +// GraphExecutionState is responsible for generating an +// executable ClientGraph from the original GraphDef that specifies +// the complete graph and from BuildGraphOptions which specifies +// input/output nodes. +// +// An executable Graph differs from a GraphDef by being Placed, +// meaning that each Node is assigned to a single Device in the +// available set. +// +// When GraphExecutionState is first constructed it instantiates +// a full Graph from the provided GraphDef, and places it, using only +// the static device assignments from the GraphDef. Nodes without are +// currently placed in a very naive way. Since stateful Nodes cannot +// be moved after initial placement, it is important that stateful +// Nodes get sensible initial device assignments in the graph +// definition. +// +// Subsequently, GraphExecutionState generates a SimpleClientGraph on +// demand, which is a sub-graph of the latest placement of the full +// Graph. MasterSession uses such a ClientGraph to execute one or +// more similar client requests. +// +// GraphExecutionState is thread-safe. + +class GraphExecutionState { + public: + virtual ~GraphExecutionState(); + + // Creates a new `GraphExecutionState` for the given + // `graph_def`, which represents the entire graph for a session. + static Status MakeForBaseGraph( + GraphDef&& graph_def, const GraphExecutionStateOptions& options, + std::unique_ptr* out_state); + + // Creates a new `GraphExecutionState` and `SimpleClientGraph` + // for the subgraph of `original_graph_def` defined by + // `subgraph_options`. + static Status MakeForPrunedGraph( + const GraphExecutionState& base_execution_state, + const GraphExecutionStateOptions& options, + const BuildGraphOptions& subgraph_options, + std::unique_ptr* out_state, + std::unique_ptr* out_client_graph); + + // Creates a new GraphExecutionState representing the + // concatenation of this graph, and the graph defined by + // "extension_def". The same name may not be used to define a node + // in both this graph and "extension_def". + // + // If successful, returns OK and the caller takes ownership of "*out". + // Otherwise returns an error and does not modify "*out". + // + // After calling `old_state->Extend()`, `old_state` may no longer be + // used. + // + // NOTE(mrry): This method respects the placement of stateful nodes in + // in *this, but currently does not transfer any other placement + // or cost model information to the new graph. + // + // Note that using this interface requires setting the value of + // config.experimental().disable_optimize_for_static_graph() in the state + // options to `true`, otherwise it will return an error. + Status Extend(const GraphDef& extension_def, + std::unique_ptr* out) const; + + // Builds a ClientGraph (a sub-graph of the full graph as induced by + // the Node set specified in "options"). If successful, returns OK + // and the caller takes the ownership of "*out". Otherwise, returns + // an error. + Status BuildGraph(const BuildGraphOptions& options, + std::unique_ptr* out); + + // Optimize the graph with the node set specified in `options`. + Status OptimizeGraph( + const BuildGraphOptions& options, const Graph& graph, + const FunctionLibraryDefinition* flib_def, + std::unique_ptr* optimized_graph, + std::unique_ptr* optimized_flib); + + // The graph returned by BuildGraph may contain only the pruned + // graph, whereas some clients may want access to the full graph. + const Graph* full_graph() { return graph_; } + + // The original graph. + GraphDef* original_graph_def() { return original_graph_def_.get(); } + + // The original function library of this graph. + const FunctionLibraryDefinition& flib_def() const { return *flib_def_; } + + // Returns the node with the given name, or null if it does not exist. + const Node* get_node_by_name(const string& name) const { + NodeNameToCostIdMap::const_iterator iter = + node_name_to_cost_id_map_.find(name); + if (iter != node_name_to_cost_id_map_.end()) { + return graph_->FindNodeId(iter->second); + } else { + return nullptr; + } + } + + // Returns the map of stateful placements as a map of + // node name to placement string. + std::unordered_map GetStatefulPlacements() const { + return stateful_placements_; + } + + private: + GraphExecutionState(std::unique_ptr&& graph_def, + std::unique_ptr&& flib_def, + const GraphExecutionStateOptions& options); + + Status InitBaseGraph(std::unique_ptr&& graph); + + // Map of placed stateful nodes, i.e. nodes for which is_stateful() + // is true, such as "params" and "queue" nodes. Once placed these + // nodes can not be moved to a different device. Maps node names to + // device names. + std::unordered_map stateful_placements_; // Immutable after + // ctor. + void SaveStatefulNodes(Graph* graph); + void RestoreStatefulNodes(Graph* graph); + + // Extract the subset of the graph that needs to be run, adding feed/fetch + // ops as needed. + Status PruneGraph(const BuildGraphOptions& options, Graph* graph, + subgraph::RewriteGraphMetadata* out_rewrite_metadata); + + // The GraphExecutionState must store a copy of the original GraphDef if + // either of the following conditions holds: + // + // * `session_options_.config.graph_options().place_pruned_graph()` is true. + // * `session_options_.config.experimental().optimize_for_static_graph()` is + // false. + const std::unique_ptr original_graph_def_; + + const DeviceSet* device_set_; // Not owned + const SessionOptions* session_options_; // Not owned + // Unique session identifier. Can be empty. + string session_handle_; + + // Map from name to Node for the full graph in placed_. + NodeNameToCostIdMap node_name_to_cost_id_map_; + + // 'flib_def_' is initialized from the initial graph def's library, + // and may be updated by a graph optimization pass. + std::unique_ptr flib_def_; + + // `rewrite_metadata_` is only set for GraphExecutionState + // objects created by `MakeForPrunedGraph()`. + std::unique_ptr rewrite_metadata_; + + // The dataflow graph owned by this object. + Graph* graph_; + + // Whether to run Placer. + bool run_placer_; + + GraphExecutionState(const GraphExecutionState&) = delete; + void operator=(const GraphExecutionState&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_EXECUTION_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_optimizer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_optimizer.h new file mode 100644 index 0000000000000000000000000000000000000000..f8322cfe7213a2cbf271e686043f17fe2805d6d1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_optimizer.h @@ -0,0 +1,100 @@ +/* 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_COMMON_RUNTIME_GRAPH_OPTIMIZER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_OPTIMIZER_H_ + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +class GraphOptimizer { + public: + using NodePredicate = std::function; + + struct Options { + // If not null it maps from nodes in graph to partially-known + // shapes of their outputs, and may be used, e.g., in the constant folding + // pass. The use of shape_map implies that the mapping from node name to the + // vector of partial shapes of its outputs is stable, i.e., no optimization + // pass may replace a node with a different node of the same name that has a + // different number of outputs, or outputs with different known shapes. + // TODO(b/65453533) introduce a unique way to name nodes in a graph. + std::unordered_map>* shape_map = + nullptr; + + // If not null then only nodes for which cse_consider_fn returns true will + // be considered for CSE. + NodePredicate cse_consider_fn = nullptr; + + // If not null then only nodes for which cf_consider_fn returns true will be + // considered for CF. + NodePredicate cf_consider_fn = nullptr; + + // If true, multi-device functions will be inlined if + // opts_.do_function_inlining() is true. + bool inline_multi_device_functions = false; + + // If true, functions in implementation selection group will be inlined if + // opts_.do_function_inlining() is true. + bool inline_impl_selection_group_functions = false; + + // If true all functions will be inlined with a single device function + // body placer strategy. + bool inline_with_single_device_body_placer = false; + + // If true, the _noinline attribute on functions and callers is ignored. + bool ignore_noinline = false; + }; + + explicit GraphOptimizer(const OptimizerOptions& opts); + ~GraphOptimizer(); + + // Applies optimization passes specified in 'opts' to 'graph'. + // Maybe replace *graph with a new graph object. 'device' is device + // on which the 'graph' will execute. It's passed to the optimizers + // so that they can respect constraints if any, that should be + // respected. + void Optimize(FunctionLibraryRuntime* runtime, Env* env, const Device* device, + std::unique_ptr* graph, + const Options& graph_optimizer_options); + + const OptimizerOptions& options() { return opts_; } + + private: + OptimizerOptions opts_; + + GraphOptimizer(const GraphOptimizer&) = delete; + void operator=(const GraphOptimizer&) = delete; +}; + +// Applies graph rewrite optimization such as inlining, dead code +// removal, etc. +// +// **g is a graph constructed based on the runtime library 'lib'. +// OptimizeGraph mutates **g extensively and replaces '*g' with a +// complete copy. Therefore, the caller should not keep any references +// to nodes *g. +void OptimizeGraph(FunctionLibraryRuntime* lib, std::unique_ptr* g, + const GraphOptimizer::Options& graph_optimizer_options); +void OptimizeGraph(FunctionLibraryRuntime* lib, std::unique_ptr* g); + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_OPTIMIZER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_runner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_runner.h new file mode 100644 index 0000000000000000000000000000000000000000..95bb95371d587301a17c5ba5272d577952add8b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/graph_runner.h @@ -0,0 +1,74 @@ +/* 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_COMMON_RUNTIME_GRAPH_RUNNER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_RUNNER_H_ + +#include +#include +#include + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tsl { +class Env; +} // namespace tsl +namespace tensorflow { +using Env = tsl::Env; + +class Device; +class Graph; + +// GraphRunner takes a Graph, some inputs to feed, and some outputs +// to fetch and executes the graph required to feed and fetch the +// inputs and outputs. +// +// This class is only meant for internal use where one needs to +// partially evaluate inexpensive nodes in a graph, such as for shape +// inference or for constant folding. Because of its limited, simple +// use-cases, it executes all computation on the given device (CPU by default) +// and is not meant to be particularly lightweight, fast, or efficient. +class GraphRunner { + public: + // REQUIRES: `env` is not nullptr. + GraphRunner(Env* env); + // REQUIRES: 'device' is not nullptr. Not owned. + GraphRunner(Device* device); + ~GraphRunner(); + + // Function semantics for `inputs`, `output_names` and `outputs` + // matches those from Session::Run(). + // + // NOTE: The output tensors share lifetime with the GraphRunner, and could + // be destroyed once the GraphRunner is destroyed. + // + // REQUIRES: `graph`, `env`, and `outputs` are not nullptr. + // `function_library` may be nullptr. + typedef std::vector> NamedTensorList; + Status Run(Graph* graph, FunctionLibraryRuntime* function_library, + const NamedTensorList& inputs, + const std::vector& output_names, + std::vector* outputs); + + private: + std::unique_ptr device_deleter_; + Device* const device_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_GRAPH_RUNNER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/hierarchical_tree_broadcaster.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/hierarchical_tree_broadcaster.h new file mode 100644 index 0000000000000000000000000000000000000000..f058a10c5a0f788ea449c065748c4707e3e8d992 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/hierarchical_tree_broadcaster.h @@ -0,0 +1,86 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_HIERARCHICAL_TREE_BROADCASTER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_HIERARCHICAL_TREE_BROADCASTER_H_ + +#include + +#include "tensorflow/core/common_runtime/base_collective_executor.h" +#include "tensorflow/core/framework/collective.h" + +namespace tensorflow { + +// Hierarchical tree-algorithm implementation of collective broadcast. +class HierarchicalTreeBroadcaster : public CollectiveImplementationInterface { + public: + HierarchicalTreeBroadcaster(); + ~HierarchicalTreeBroadcaster() override = default; + + // Establishes the subdiv permutations needed for a hierarchical broadcast. + // If all devices are local, establishes a single subdiv comprising all + // devices. If any devices are on a different task, establishes n+1 subdivs + // for n tasks. + // The first subdiv comprises one device per task which gets the tensor on + // each task. Subdiv i+1 corresponds to a task-local tree-broadcast for task + // i. + Status InitializeCollectiveParams(CollectiveParams* col_params) override; + + // Initializes members of CollectiveContext not yet initialized, i.e. device + // and device_locality. Also saves the CollectiveContext in this object. + Status InitializeCollectiveContext( + std::shared_ptr col_ctx) override; + + // Begins async execution of the hierarchical tree broadcast. + // Must be called in a blockable thread. + // TODO(b/80529858): remove the previous warning when we have a dedicated + // collective threadpool. + void Run(StatusCallback done) override; + + // Returns the rank of the device from which this device should receive + // its value, -1 if no value should be received. + static int TreeRecvFrom(const CollectiveParams& cp, int subdiv); + + // Populates targets with the ranks of the devices to which this device + // should forward the value. + static void TreeSendTo(const CollectiveParams& cp, int subdiv, + std::vector* targets); + + private: + // Get the task to which the device at `device_rank` belongs. + int GetDeviceTask(int device_rank, const std::vector& dev_per_task); + + // Sends `src_tensor` asynchronously from this device to device at `dst_rank` + // in `subdiv`. Calls `done` upon completion. + void DispatchSend(int subdiv, int dst_rank, int src_rank, + const Tensor* src_tensor, const StatusCallback& done); + + // Receives a tensor into the memory buffer owned by `dst_tensor` at this + // device from device at `src_rank` in `subdiv`. Calls `done` upon + // completion. + void DispatchRecv(int subdiv, int src_rank, int dst_rank, Tensor* dst_tensor, + const StatusCallback& done); + + // Executes the hierarchical broadcast defined by this op. + void RunTree(); + + std::shared_ptr col_ctx_; + const CollectiveParams* col_params_; // Not owned + StatusCallback done_; + Status status_; + bool is_source_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_HIERARCHICAL_TREE_BROADCASTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/inline_function_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/inline_function_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a11f2e8b770b2a7918a1912ec35077e081bf1166 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/inline_function_utils.h @@ -0,0 +1,240 @@ +/* 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_COMMON_RUNTIME_INLINE_FUNCTION_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_INLINE_FUNCTION_UTILS_H_ + +#include +#include + +#include "absl/types/optional.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/common_runtime/lower_function_call_inline_policy.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +static constexpr const char* const kNoInlineAttr = "_noinline"; + +// Optionally override device assignment for nodes added to the graph for +// inlined functions: +// (1) Identity nodes added in place of function input arguments. +// (2) Identity nodes added in place of function return values. +// (3) Special NoOp nodes that enforce side-effects execution order. +// (4) All nodes inside function body specified in FunctionDef. +class InlinedFunctionBodyPlacer { + public: + virtual ~InlinedFunctionBodyPlacer() = default; + + virtual absl::optional InputNodeDevice(int input_index) const = 0; + virtual absl::optional OutputNodeDevice(int output_index) const = 0; + // Returns true if the added input/output identity nodes should be colocated + // with the corresponding input/output from the function body. + virtual bool ColocateInputOutputIdentities() const = 0; + virtual absl::optional ControlNodeDevice() const = 0; + virtual absl::optional BodyNodeDevice(const NodeDef& ndef) const = 0; + + // LINT.IfChange + // Place input nodes on the same device as the corresponding caller input + // node. Do not specify any placement for all other nodes. + static std::unique_ptr DefaultPlacer( + const Graph& graph, const Node& caller); + + // Place all nodes on the same device as caller node. + static std::unique_ptr SingleDevicePlacer( + const Graph& graph, const Node& caller); + + // Place input nodes on the same device as the corresponding caller input + // node. Do not place output node. Place control nodes on the same device as + // caller node. For all function body nodes set job, replica and task + // parts of the device assignment to match function caller node where those + // are unspecified. + static std::unique_ptr MultiDevicePlacer( + const Graph& graph, const Node& caller); + // LINT.ThenChange(lower_function_call_inline_policy.h) + + using Factory = std::function( + const Graph&, const Node&)>; + + struct Config { + string name; + Factory get; + }; + + static Config Default() { return {"default", DefaultPlacer}; } + static Config SingleDevice() { return {"single_device", SingleDevicePlacer}; } + static Config MultiDevice() { return {"multi_device", MultiDevicePlacer}; } +}; + +struct InlineFunctionBodyOptions { + // All nodes that have incoming control edge *from* the function call node, + // will be forwarded to the "output control node". There are two options for + // choosing which nodes will have a control edge *to* the "output control + // node": + // a) control returns (`control_ret` field in FunctionDef) + // b) data returns (`ret` field in FunctionDef) + enum class OutputControlSource { kDataOutputs, kControlOutputs }; + + // Keep a node in a graph with the same name as the function call node: + // + // a) DoNotKeep: Function call node is fully inlined, and there is no node in + // a graph with the same name. + // + // b) Fetchable: Add an IdentityN node to the graph in place of the inlined + // function call node. It will have a control edge from inlined + // 'output_control_node' and data edges from function output nodes. + // The IdentityN node will be placed on the same device as the caller node. + // + // This is mostly for compatibility with Tensorflow v1 and sessions. + // When we prepare a graph for execution in + // GraphExecutionState::MakeForBaseGraph we don't know what nodes will be + // fetched, so we can't safely remove any of them. When graph executed as a + // function it has 'Retval' nodes for all fetched tensors, and we can + // safely inline function calls. + // + // c) Targetable: Add a NoOp node to the graph in place of the inlined + // function call node. It will have a control edge from inline + // 'output_control_node' and no data edges. NoOp node will be placed on the + // same device as the caller node. This will keep the inlined function call + // node a valid 'session.run' target, and also will keep it a valid control + // output node. + enum class KeepCallerNode { kDoNotKeep, kFetchable, kTargetable }; + + // If 'true' function inlining is completely disabled. This allows to control + // function inlining for different types of function calls (see + // 'ExpandInlineFunctionsOptions' below). + bool disable_inlining = false; + // Ignore '_noinline' function attribute. + bool ignore_noinline = false; + // If 'true' function inlining will inline functions in implementation + // selection group. Normally those functions should not be inlined; they will + // be handled by Grappler. + bool inline_impl_selection_group_functions = false; + // Controls if we want to keep a node with the name as the function call node + // in a graph after function inlining. + KeepCallerNode keep_caller_node = KeepCallerNode::kDoNotKeep; + // For compatibility with Tensorflow v1 by default we will use data outputs. + // Control returns were added to Tensorflow v2 with automatic control + // dependencies tracking in Eager mode. + OutputControlSource output_control_src = OutputControlSource::kDataOutputs; + // Inlined function body placer decides what requested device assignments + // should be added to the nodes added to the graph. See documentation above + // for available strategies. + InlinedFunctionBodyPlacer::Config inlined_function_body_placer = + InlinedFunctionBodyPlacer::Default(); + // If true, frame names in the function body will be + // made unique in the resulting graph (e.g. by prepending a unique prefix). + // NOTE(mrry): Only set this option to false when there is a single function + // call in the graph (e.g. when making a remote function call via + // ClusterFunctionLibraryRuntime). This option is provided because the graph + // partitioner generates frame names that must remain unmodified across all + // partitions of a multi-device function. + bool uniquify_frame_names = true; + + // A human-readable debug string for this options. + string DebugString() const; +}; + +// Returns 'OkStatus()' iff the function '*fbody' can be inlined at 'node' +// based on the type signature of 'node' and 'fbody': +// +// (1) Caller node has the same number of inputs and outputs as the function. +// (2) Caller node inputs and outputs have the same data types as function +// inputs and returns. +// (3) Validation rules defined in InlineFunctionBodyOptions. +// +// If function can't be safely inlined, returns error message with details why +// inlining is not possible or safe. +Status ValidateInlining(const Node* node, const FunctionBody* fbody, + const InlineFunctionBodyOptions& options); + +// Given a "caller" in graph "g", which is a function call of a function +// to "fbody". Replaces the "caller" with fbody->graph and connects +// edges properly. "override_device" specifies whether inlining should replace +// explicitly specified devices inside fbody with the callee's device. +// +// Returns 'OkStatus()' if function was successfully inlined into the graph. +// If function inlining is not possible returns an error with a reason, and +// leaves the graph in unmodified state. +Status InlineFunctionBody(const FunctionLibraryDefinition& flib_def, Graph* g, + Node* caller, const FunctionBody* fbody, + const InlineFunctionBodyOptions& options); + +// There are three types of function calls that could be invoked during +// *Tensorflow graph execution*: +// +// 1) Native function call (node.type_string() is the function name). These +// functions are always executed on a single-device, which is the device of +// the function call node. +// +// 2) Multi-device function calls (PartitionedCall or StatefulPartitionedCall +// ops) can execute on multiple devices and accept DT_RESOURCE inputs that +// belong to different devices. This type of functions was added in +// Tensorflow 2.0 Eager mode, and it has control outputs to represent +// side-effects that must always execute (see `control_ret` in FunctionDef). +// +// 3) SymbolicGradient has been deprecated for a while, but we still keep it and +// use `native` options for inlining for compatibility. +// +// We need to have distinct inlining rules for compatibility with Tensorflow v1. +// +// There are few other places in Tensorflow that could execute functions: +// +// 1) common_runtime/eager/kernel_and_device.{h,cc} - executes "top level" +// functions directly via function library runtime, without going through +// the graph. +// 2) tf.data pipelines - also execute functions directly via function library +// runtime with custom executors. +struct ExpandInlineFunctionsOptions { + ExpandInlineFunctionsOptions() : native_options(), multi_device_options() { + using OutputControlSrc = InlineFunctionBodyOptions::OutputControlSource; + multi_device_options.output_control_src = OutputControlSrc::kControlOutputs; + } + + InlineFunctionBodyOptions native_options; + InlineFunctionBodyOptions multi_device_options; +}; + +// WARNING(ezhulenev): PLEASE DO NOT USE THIS FUNCTION. This is a temporary +// workaround that will be enabled only during the function inlining unification +// (b/126811947). Contact ezhulenev@ if you think you need it. +// TODO(ezhulenev): Delete this function. +bool ExpandInlineFunctions(FunctionLibraryRuntime* lib, Graph* graph, + const ExpandInlineFunctionsOptions& options); + +// For each node in "graph", if "lib" indicates that the node is a +// function call, inline the function body. Returns true if at least +// one node is inlined. +// +// This routine goes through "graph" nodes once and applies the +// inlining. The caller may decide to apply the inlining on "graph" +// multiple times by calling ExpandInlineFunctions a few times. +// +// Function calls that can't be safely inlined into the graph (ValidateInlining +// returns error), are ignored. +// +// TODO(ezhulenev): We do not FunctionLibraryRuntime for this. We need just the +// FunctionLibraryDefinition and FunctionDefToBodyHelper to implement this (see +// lower_function_call.cc). +inline bool ExpandInlineFunctions(FunctionLibraryRuntime* lib, Graph* graph) { + return ExpandInlineFunctions(lib, graph, ExpandInlineFunctionsOptions()); +} + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_INLINE_FUNCTION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/input_colocation_exemption_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/input_colocation_exemption_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..c393fe7498b6966d6ca0ed6249ea0b43195c4ede --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/input_colocation_exemption_registry.h @@ -0,0 +1,76 @@ +/* Copyright 2019 The TensorFlow Authors. Al Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES 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_COMMON_RUNTIME_INPUT_COLOCATION_EXEMPTION_REGISTRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_INPUT_COLOCATION_EXEMPTION_REGISTRY_H_ + +#include + +#include "tensorflow/core/lib/gtl/flatset.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// TensorFlow runtime (both eager and graph) will aim to colocate ops with +// their resource inputs so that the ops can access the resource state. In some +// cases, such as tf.data ops, this is not desirable as the ops themselves might +// not have a kernel registered for the device on which the resource is placed +// and instead use a mechanism, such as a multi-device function, to access the +// resource state. +// +// This registry can be used to register and list ops that should be exempt from +// the input colocation described above. +// +// Example usage: +// REGISTER_INPUT_COLOCATION_EXEMPTION("MapDataset"); +class InputColocationExemptionRegistry { + public: + // Returns a pointer to a global InputColocationExemptionRegistry object. + static InputColocationExemptionRegistry* Global(); + + // Returns the set of ops exempt from the input colocation constraints. + const gtl::FlatSet& Get() { return ops_; } + + // Registers an op to be excluded from the input colocation constraints. + void Register(const string& op); + + private: + gtl::FlatSet ops_; +}; + +namespace input_colocation_exemption_registration { + +class InputColocationExemptionRegistration { + public: + explicit InputColocationExemptionRegistration(const string& op) { + InputColocationExemptionRegistry::Global()->Register(op); + } +}; + +} // namespace input_colocation_exemption_registration + +#define REGISTER_INPUT_COLOCATION_EXEMPTION(op) \ + REGISTER_INPUT_COLOCATION_EXEMPTION_UNIQ_HELPER(__COUNTER__, op) + +#define REGISTER_INPUT_COLOCATION_EXEMPTION_UNIQ_HELPER(ctr, op) \ + REGISTER_INPUT_COLOCATION_EXEMPTION_UNIQ(ctr, op) + +#define REGISTER_INPUT_COLOCATION_EXEMPTION_UNIQ(ctr, op) \ + static input_colocation_exemption_registration:: \ + InputColocationExemptionRegistration \ + input_colocation_exemption_registration_fn_##ctr(op) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_INPUT_COLOCATION_EXEMPTION_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/inspecting_placer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/inspecting_placer.h new file mode 100644 index 0000000000000000000000000000000000000000..b9d19a48917d94b6436b4d049b12b2e3cbc0ab6c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/inspecting_placer.h @@ -0,0 +1,96 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_INSPECTING_PLACER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_INSPECTING_PLACER_H_ + +#include + +#include "absl/strings/str_join.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/placer_inspection_required_ops_utils.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/util/device_name_utils.h" +#include "tensorflow/core/util/port.h" + +namespace tensorflow { + +// TODO(iga): Convert this struct into a class to ensure invariants between +// device names, i.e. +// DeviceNameUtils::IsSpecification(resource_device_name, +// requested_device_name) +// PossibleDevices does not contain assigned_device_name because we don't +// assign devices to nested functions. +struct PossibleDevices { + // The same as Member::requested_device_name_ in colocation_graph.cc. + DeviceNameUtils::ParsedName requested_device_name; + + // The same as Member::resource_device_name_ in colocation_graph.cc. + DeviceNameUtils::ParsedName resource_device_name; + + // A device type outside of this set will not be supported by some + // internal op. + PrioritizedDeviceTypeVector device_types; +}; + +// A struct for communicating constraints on devices that can +// be chosen for inputs and outputs of an op requiring deep placer inspection. +struct IOColocationGroups { + // input_groups[i] contains the group id that i'th input belongs to. + // List inputs are not supported. + std::vector input_groups; + // output_groups[i] contains the group id that i'th output belongs to. + // List inputs are not supported. + std::vector output_groups; + // group_devices[i] contains possible devices for group with id i. + std::vector group_devices; + + string DebugString() const; +}; + +class InspectingPlacer { + public: + // graph and device_set must not be null and must outlive this + // InspectingPlacer. default_device can be null. If not, must outlive this. + // TODO(iga): Add a "stack trace" to detect recursion and improve log + // messages. Currently, we will enter an infinite loop for recursive + // functions. + InspectingPlacer(const FunctionStack& stack, + const FunctionLibraryDefinition* flib_def, + const DeviceSet* device_set, const Device* default_device, + bool allow_soft_placement, bool log_device_placement); + + // `node` must be + // PlacerInspectionRequiredOpsChecker::IsPlacerInspectionRequired. + Status ComputeIOColocationGroups(const Node& node, + IOColocationGroups* groups); + + private: + const FunctionStack stack_; + const FunctionLibraryDefinition& flib_def_; + const DeviceSet& device_set_; + const Device* default_device_; + const bool allow_soft_placement_; + const bool log_device_placement_; + + InspectingPlacer(const InspectingPlacer&) = delete; + void operator=(const InspectingPlacer&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_INSPECTING_PLACER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/int32_fulltype.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/int32_fulltype.h new file mode 100644 index 0000000000000000000000000000000000000000..f2be1c87e3f090df40c65ec3f6e8e9e13dd6683f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/int32_fulltype.h @@ -0,0 +1,65 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_INT32_FULLTYPE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_INT32_FULLTYPE_H_ + +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +// An optimization (graph rewrite) pass to automatically set TFT_SHAPE_TENSOR +// full type information annotations for all int32 tensors, creating or +// modifying existing full type information as needed. This allows placement +// mechanisms using full type information to always place int32 on host. +class Int32FulltypePass { + public: + Int32FulltypePass() = default; + explicit Int32FulltypePass(string debug_location) + : debug_location_(debug_location) {} + + // For each node in this graph that outputs int32 tensors, set full + // type information such that the int32 tensors use TFT_SHAPE_TENSOR + // (or TFT_TENSOR if ints_on_device is true, which is only for single + // device functions including the functions with just one op used for + // eager execution). + // + // This method is not thread-safe. + Status ProcessGraph(Graph* graph, bool ints_on_device); + + // Update full type information for int32 tensors that are in HOST_MEMORY + // to use TFT_SHAPE_TENSOR. The type_id of TENSOR_T is expected to be + // TFT_UNSET, TFT_TENSOR or TFT_SHAPE_TENSOR on input and will be updated + // to TFT_SHAPE_TENSOR on output for int32 tensors if it is not + // TFT_SHAPE_TENSOR already. For tensors that are not int32, if the input full + // type information is TFT_UNSET, it will only be updated if SET_ONLY_INT32 is + // false. Note that TENSOR_T is not the full type information for the outputs + // of a node, so it does have an outer TFT_PRODUCT. NODE and OUTPUT_IDX are + // optional and only used in an error message to say that the tensor is output + // OUTPUT_IDX of node NODE. + Status Int32FullTypeForTensor(DataType dtype, FullTypeDef* tensor_t, + bool set_only_int32, Node* node = nullptr, + int output_idx = 0); + + private: + // Location of where annotations were added for debug messages. + string debug_location_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_INT32_FULLTYPE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/isolate_placer_inspection_required_ops_pass.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/isolate_placer_inspection_required_ops_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..3d86c4538f0d171bb51d4e093b96e635c7f286a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/isolate_placer_inspection_required_ops_pass.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_COMMON_RUNTIME_ISOLATE_PLACER_INSPECTION_REQUIRED_OPS_PASS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_ISOLATE_PLACER_INSPECTION_REQUIRED_OPS_PASS_H_ + +#include "tensorflow/core/common_runtime/optimization_registry.h" + +namespace tensorflow { +// Adds Identities for each input/output of function-calling ops. +// +// For example, the following graph calling a function on inputs `a` and `b` +// and producing output `y` will be rewritted to include identities on all +// edges: +// +// a b +// | | +// v v +// f (PartitionedCallOp) +// | +// v +// y +// +// is transformed to +// +// a b +// | | +// a_f (Identity) a_f (Identity) +// | | +// v v +// f (PartitionedCallOp) +// | +// f_y (Identity) +// | +// v +// y +// +// This pass is currently needed to simplify correctly placing the nodes +// producing inputs for as well as consuming output from function-calling ops. +// +// This pass should also help to implement replacing PartitionedCallOp with +// component function calls (to avoid copying input/output tensors), if we get +// to it. +class IsolatePlacerInspectionRequiredOpsPass : public GraphOptimizationPass { + public: + Status Run(const GraphOptimizationPassOptions& options) override; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_ISOLATE_PLACER_INSPECTION_REQUIRED_OPS_PASS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_device.h new file mode 100644 index 0000000000000000000000000000000000000000..595d3b88e8f09241381dff01ed3b77373df85691 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_device.h @@ -0,0 +1,58 @@ +/* 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_COMMON_RUNTIME_LOCAL_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOCAL_DEVICE_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +namespace test { +class Benchmark; +} +struct SessionOptions; + +// This class is shared by ThreadPoolDevice and GPUDevice and +// initializes a shared Eigen compute device used by both. This +// should eventually be removed once we refactor ThreadPoolDevice and +// GPUDevice into more 'process-wide' abstractions. +class LocalDevice : public Device { + public: + LocalDevice(const SessionOptions& options, + const DeviceAttributes& attributes); + ~LocalDevice() override; + + private: + static bool use_global_threadpool_; + + static void set_use_global_threadpool(bool use_global_threadpool) { + use_global_threadpool_ = use_global_threadpool; + } + + struct EigenThreadPoolInfo; + std::unique_ptr owned_tp_info_; + + friend class test::Benchmark; + + LocalDevice(const LocalDevice&) = delete; + void operator=(const LocalDevice&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOCAL_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_executor_params.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_executor_params.h new file mode 100644 index 0000000000000000000000000000000000000000..6c201d79dafa8ea658641f4aed30275ac51b1011 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_executor_params.h @@ -0,0 +1,57 @@ +/* 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_COMMON_RUNTIME_LOCAL_EXECUTOR_PARAMS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOCAL_EXECUTOR_PARAMS_H_ + +#include +#include + +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +class Device; +class StepStatsCollector; +class SessionMetadata; +class FunctionLibraryRuntime; +class NodeProperties; +class OpKernel; + +// LocalExecutorParams provides arguments that will be shared by all invocations +// of an executor. We expect that different contexts would provide different +// implementations (e.g. local versus distributed). +struct LocalExecutorParams { + Device* device; + + const SessionMetadata* session_metadata = nullptr; + + // The library runtime support. + FunctionLibraryRuntime* function_library = nullptr; + + // create_kernel returns an instance of op kernel based on NodeDef. + // delete_kernel is called for every kernel used by the executor + // when the executor is deleted. + std::function&, + OpKernel**)> + create_kernel; + std::function delete_kernel; + + // Whether control flow nodes are allowed to be executed synchronously. + bool allow_control_flow_sync_execution = false; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOCAL_EXECUTOR_PARAMS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_session_selection.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_session_selection.h new file mode 100644 index 0000000000000000000000000000000000000000..9e21c8d7ff65b81e2ed3c471e7b4046d61f515be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/local_session_selection.h @@ -0,0 +1,33 @@ +/* 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_COMMON_RUNTIME_LOCAL_SESSION_SELECTION_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOCAL_SESSION_SELECTION_H_ + +namespace tensorflow { + +// The TF Session implementations that can be used to run local sessions, i.e. +// when session_target in SessionOptions is empty. +enum class LocalSessionImpl { + kDirectSession, + kTfrtSession, +}; + +void SetDefaultLocalSessionImpl(LocalSessionImpl impl); +LocalSessionImpl GetDefaultLocalSessionImpl(); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOCAL_SESSION_SELECTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_case_op.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_case_op.h new file mode 100644 index 0000000000000000000000000000000000000000..110ac20a929d89af6cd63616bd42a76965e96f72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_case_op.h @@ -0,0 +1,31 @@ +/* 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_COMMON_RUNTIME_LOWER_CASE_OP_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_CASE_OP_H_ + +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class Graph; +class Node; + +// Replaces Case node `n` with a lowered form that uses _SwitchN/Merge nodes. +Status RewriteCaseNode(Node* n, Graph* g, bool keep_node_fetchable); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_CASE_OP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_function_call_inline_policy.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_function_call_inline_policy.h new file mode 100644 index 0000000000000000000000000000000000000000..6dc48f8e3732068b38ac69aa961a1488bcad71fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_function_call_inline_policy.h @@ -0,0 +1,60 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_INLINE_POLICY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_INLINE_POLICY_H_ + +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { + +// LINT.IfChange +enum class FunctionCallInlinePolicy { + // Place input nodes on the same device as the corresponding caller input + // node. Do not specify any placement for all other nodes. + kDefaultPlacer, + + // Place all nodes on the same device as caller node. + kSingleDevicePlacer, + + // Place input nodes on the same device as the corresponding caller input + // node. Do not place output node. Place control nodes on the same device as + // caller node. For all function body nodes overrides job, replica and task + // parts of the device assignment to match function caller node. + kMultiDevicePlacer +}; +// LINT.ThenChange(inline_function_utils.h,\ +// ../../compiler/mlir/tensorflow/ir/tf_ops.cc) + +struct LowerFunctionalOpsConstants { + static constexpr const char* const kLowerUsingSwitchMergeAttr = + "_lower_using_switch_merge"; + static constexpr const char* const kLowerAsMultiDeviceFunctionAttr = + "_lower_as_multi_device_function"; +}; + +// Inliner policy used in common runtime's lower function call op. + +// Returns the function call inline policy to use for a given call. +FunctionCallInlinePolicy GetFunctionCallInlinePolicy(const Node* n); + +// Overload of GetFunctionCallInlinePolicy that doesn't require an op but only +// the features required. +FunctionCallInlinePolicy GetFunctionCallInlinePolicy( + bool is_partioned_call, bool has_lower_as_multi_device_function_attr); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_INLINE_POLICY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_function_call_op.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_function_call_op.h new file mode 100644 index 0000000000000000000000000000000000000000..84f6f68dd71b65da6606f922181feafc82b399e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_function_call_op.h @@ -0,0 +1,37 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_OP_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_OP_H_ + +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class FunctionLibraryDefinition; +class Graph; +class Node; + +// Replaces function call node `n` with its function body. Uses +// InlineFunctionBody from `common_runtime/function.{h,cc}`. If function +// inlining is not possible or safe (see ValidateInlining), leaves the graph in +// unmodified state and returns OkStatus(); +Status RewriteFunctionCallNode(Node* n, Graph* g, + const FunctionLibraryDefinition& flib_def, + bool keep_caller_fetchable); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTION_CALL_OP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_functional_ops.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_functional_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c372dfbad40ed6c0491966e548cd051fcae29f20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_functional_ops.h @@ -0,0 +1,47 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTIONAL_OPS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTIONAL_OPS_H_ + +#include "absl/types/optional.h" +#include "tensorflow/core/common_runtime/inline_function_utils.h" +#include "tensorflow/core/common_runtime/optimization_registry.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Rewrite functional ops into low level primitives: +// - If/While ops lowered into low level control flow primitives: Switch, Merge, +// Enter, Exit, NextIteration +// - Function calls inlined into the main graph +// +// IMPORTANT: Although SymbolicGradient is a function call, we currently do not +// lower it, because it has been deprecated for a while. +class LowerFunctionalOpsPass : public GraphOptimizationPass { + public: + LowerFunctionalOpsPass() = default; + + Status Run(const GraphOptimizationPassOptions& options) override; + + static constexpr const char* const kLowerUsingSwitchMergeAttr = + LowerFunctionalOpsConstants::kLowerUsingSwitchMergeAttr; + static constexpr const char* const kLowerAsMultiDeviceFunctionAttr = + LowerFunctionalOpsConstants::kLowerAsMultiDeviceFunctionAttr; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_FUNCTIONAL_OPS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_if_op.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_if_op.h new file mode 100644 index 0000000000000000000000000000000000000000..55b7b91b56f460ca8b7503434860ab0e5322146e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_if_op.h @@ -0,0 +1,31 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_IF_OP_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_IF_OP_H_ + +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class Graph; +class Node; + +// Replaces If node `n` with its lowered form that uses Switch and Merge nodes. +Status RewriteIfNode(Node* n, Graph* g, bool keep_node_fetchable); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_IF_OP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_while_op.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_while_op.h new file mode 100644 index 0000000000000000000000000000000000000000..479cdc23a1d84559ef1b2d2d3cc0276067bca056 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/lower_while_op.h @@ -0,0 +1,35 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_WHILE_OP_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_WHILE_OP_H_ + +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +class Graph; +class Node; +class FunctionLibraryDefinition; + +// Replaces While node `n` with its lowered form that uses Enter, Exit, Switch, +// Merge, NextIteration and LoopCond nodes. +Status RewriteWhileNode(Node* n, Graph* g, + const FunctionLibraryDefinition* flib_def, + bool keep_node_fetchable); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_LOWER_WHILE_OP_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/memory_types.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/memory_types.h new file mode 100644 index 0000000000000000000000000000000000000000..f854acfdc55d66c1ffa93acc0954edae393b2359 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/memory_types.h @@ -0,0 +1,48 @@ +/* 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_COMMON_RUNTIME_MEMORY_TYPES_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_MEMORY_TYPES_H_ + +#include "tensorflow/core/framework/memory_types.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Returns an error iff *g running on a single device of 'device_type' +// has memory type mismatch for any edge's source and destination. +Status ValidateMemoryTypes(const DeviceType& device_type, const Graph* g); + +// Updates '*g' so that every edge's source and destination has +// compatible memory types by inserting proper HostSend/Recv and +// Send/HostRecv nodes. 'device_type' specifies the type of device on +// which '*g' is going to run on and that device has the name +// 'device_name'. +// +// Returns OK if '*g' is updated properly (ValidateMemoryTypes(g) must +// be OK). Otherwise, returns an error and '*g' may be in an +// invalidate state and the caller should discard it. +Status EnsureMemoryTypes(const DeviceType& device_type, + const string& device_name, Graph* g); + +// Get the memory type for 'index'th output of node 'n' in graph 'g', when +// running on 'device_type'. +Status MemoryTypeForOutput(const DeviceType& device_type, const Graph* g, + const Node* n, int index, MemoryType* memory_type); + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_MEMORY_TYPES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/mkl_cpu_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/mkl_cpu_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..54d60fdc93ad66f5e2e8c1abb0b5279a8a14bf76 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/mkl_cpu_allocator.h @@ -0,0 +1,331 @@ +/* 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. +==============================================================================*/ + +// A simple CPU allocator that intercepts malloc/free calls from MKL library +// and redirects them to Tensorflow allocator + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_MKL_CPU_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_MKL_CPU_ALLOCATOR_H_ + +#ifdef INTEL_MKL + +#include + +#include "tensorflow/core/common_runtime/bfc_allocator.h" +#include "tensorflow/core/common_runtime/pool_allocator.h" +#include "tensorflow/core/lib/strings/numbers.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/platform/mem.h" +#include "tensorflow/core/platform/numa.h" +#include "tensorflow/core/util/env_var.h" +#include "tensorflow/core/util/onednn_env_vars.h" +#ifdef _WIN32 +typedef unsigned int uint; +#endif + +namespace tensorflow { + +static bool mkl_small_allocator_collect_stats = false; + +class MklSubAllocator : public BasicCPUAllocator { + public: + MklSubAllocator() : BasicCPUAllocator(port::kNUMANoAffinity, {}, {}) {} + ~MklSubAllocator() override {} +}; + +// CPU allocator that handles small-size allocations by calling +// suballocator directly. Mostly, it is just a wrapper around a suballocator +// (that calls malloc and free directly) with support for bookkeeping. +class MklSmallSizeAllocator : public Allocator { + public: + MklSmallSizeAllocator(SubAllocator* sub_allocator, size_t total_memory, + const string& name) + : sub_allocator_(sub_allocator), name_(name) { + stats_.bytes_limit = total_memory; + } + ~MklSmallSizeAllocator() override {} + + MklSmallSizeAllocator(const MklSmallSizeAllocator&) = delete; + void operator=(const MklSmallSizeAllocator&) = delete; + + inline string Name() override { return name_; } + + void* AllocateRaw(size_t alignment, size_t num_bytes) override { + void* ptr = port::AlignedMalloc(num_bytes, alignment); + if (mkl_small_allocator_collect_stats) IncrementStats(num_bytes); + return ptr; + } + + void DeallocateRaw(void* ptr) override { + if (ptr == nullptr) { + LOG(ERROR) << "tried to deallocate nullptr"; + return; + } + + if (mkl_small_allocator_collect_stats) { + const size_t alloc_size = port::MallocExtension_GetAllocatedSize(ptr); + DecrementStats(alloc_size); + } + port::AlignedFree(ptr); + } + + absl::optional GetStats() override { + mutex_lock l(mutex_); + return stats_; + } + + bool ClearStats() override { + mutex_lock l(mutex_); + stats_.num_allocs = 0; + stats_.peak_bytes_in_use = 0; + stats_.largest_alloc_size = 0; + stats_.bytes_in_use = 0; + stats_.bytes_limit = 0; + return true; + } + + private: + // Increment statistics for the allocator handling small allocations. + inline void IncrementStats(size_t alloc_size) TF_LOCKS_EXCLUDED(mutex_) { + mutex_lock l(mutex_); + ++stats_.num_allocs; + stats_.bytes_in_use += alloc_size; + stats_.peak_bytes_in_use = + std::max(stats_.peak_bytes_in_use, stats_.bytes_in_use); + stats_.largest_alloc_size = + std::max(alloc_size, static_cast(stats_.largest_alloc_size)); + } + + // Decrement statistics for the allocator handling small allocations. + inline void DecrementStats(size_t dealloc_size) TF_LOCKS_EXCLUDED(mutex_) { + mutex_lock l(mutex_); + stats_.bytes_in_use -= dealloc_size; + } + + SubAllocator* sub_allocator_; // Not owned by this class. + + // Mutex for protecting updates to map of allocations. + mutable mutex mutex_; + + // Allocator name + string name_; + + // Allocator stats for small allocs + AllocatorStats stats_ TF_GUARDED_BY(mutex_); +}; + +/// CPU allocator for MKL that wraps BFC allocator and intercepts +/// and redirects memory allocation calls from MKL. +class MklCPUAllocator : public Allocator { + public: + // Constructor and other standard functions + + /// Environment variable that user can set to upper bound on memory allocation + static constexpr const char* kMaxLimitStr = "TF_MKL_ALLOC_MAX_BYTES"; + + /// Default upper limit on allocator size - 64GB + static constexpr size_t kDefaultMaxLimit = 64LL << 30; + + MklCPUAllocator() { TF_CHECK_OK(Initialize()); } + + ~MklCPUAllocator() override { + delete small_size_allocator_; + delete large_size_allocator_; + } + + Status Initialize() { + VLOG(2) << "MklCPUAllocator: In MklCPUAllocator"; + + // Set upper bound on memory allocation to physical RAM available on the + // CPU unless explicitly specified by user + uint64 max_mem_bytes = kDefaultMaxLimit; +#if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) + max_mem_bytes = + (uint64)sysconf(_SC_PHYS_PAGES) * (uint64)sysconf(_SC_PAGESIZE); +#endif + char* user_mem_bytes = getenv(kMaxLimitStr); + + if (user_mem_bytes != NULL) { + uint64 user_val = 0; + if (!strings::safe_strtou64(user_mem_bytes, &user_val)) { + return errors::InvalidArgument("Invalid memory limit (", user_mem_bytes, + ") specified for MKL allocator through ", + kMaxLimitStr); + } +#if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) + if (user_val > max_mem_bytes) { + LOG(WARNING) << "The user specified a memory limit " << kMaxLimitStr + << "=" << user_val + << " greater than available physical memory: " + << max_mem_bytes + << ". This could significantly reduce performance!"; + } +#endif + max_mem_bytes = user_val; + } + + VLOG(1) << "MklCPUAllocator: Setting max_mem_bytes: " << max_mem_bytes; + + sub_allocator_ = new MklSubAllocator(); + + // SubAllocator is owned by BFCAllocator, so we do not need to deallocate + // it in MklSmallSizeAllocator. + small_size_allocator_ = + new MklSmallSizeAllocator(sub_allocator_, max_mem_bytes, kName); + + BFCAllocator::Options large_allocator_opts; + large_allocator_opts.allow_growth = kAllowGrowth; + large_size_allocator_ = + new BFCAllocator(absl::WrapUnique(sub_allocator_), max_mem_bytes, kName, + large_allocator_opts); + return OkStatus(); + } + + inline string Name() override { return kName; } + inline bool IsSmallSizeAllocation(const void* ptr) const + TF_LOCKS_EXCLUDED(mutex_) { + mutex_lock l(mutex_); + return large_allocations_map_.find(ptr) == large_allocations_map_.end(); + } + // AddLargeAllocMap and RemoveLargeAllocMap are always called with a lock held + inline void AddLargeAllocMap(void* ptr, size_t num_bytes) + TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_) { + if (ptr != nullptr) { + std::pair map_val(ptr, num_bytes); + large_allocations_map_.insert(map_val); + } + } + inline void RemoveLargeAllocMap(void* ptr) + TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_) { + auto map_iter = large_allocations_map_.find(ptr); + if (map_iter != large_allocations_map_.end()) { + large_allocations_map_.erase(map_iter); + } else { + LOG(ERROR) << "tried to deallocate invalid pointer"; + } + return; + } + + inline void* AllocateRaw(size_t alignment, size_t num_bytes) override { + // If the allocation size is less than threshold, call small allocator, + // otherwise call large-size allocator (BFC). We found that BFC allocator + // does not deliver good performance for small allocations when + // inter_op_parallelism_threads is high. + if (UseSystemAlloc() || num_bytes < kSmallAllocationsThreshold) { + return small_size_allocator_->AllocateRaw(alignment, num_bytes); + } else { + mutex_lock l(mutex_); + void* ptr = large_size_allocator_->AllocateRaw(alignment, num_bytes); + AddLargeAllocMap(ptr, num_bytes); + return ptr; + } + } + inline void DeallocateRaw(void* ptr) override { + // Check if ptr is for "small" allocation. If it is, then call Free + // directly. Otherwise, call BFC to handle free. + if (UseSystemAlloc() || IsSmallSizeAllocation(ptr)) { + small_size_allocator_->DeallocateRaw(ptr); + } else { + mutex_lock l(mutex_); + RemoveLargeAllocMap(ptr); + large_size_allocator_->DeallocateRaw(ptr); + } + } + absl::optional GetStats() override { + auto s_stats = small_size_allocator_->GetStats(); + auto l_stats = large_size_allocator_->GetStats(); + + // Combine statistics from small-size and large-size allocator. + mutex_lock l(mutex_); + stats_.num_allocs = l_stats->num_allocs + s_stats->num_allocs; + stats_.bytes_in_use = l_stats->bytes_in_use + s_stats->bytes_in_use; + stats_.peak_bytes_in_use = + l_stats->peak_bytes_in_use + s_stats->peak_bytes_in_use; + + // Since small-size allocations go to MklSmallSizeAllocator, + // max_alloc_size from large_size_allocator would be the maximum + // size allocated by MklCPUAllocator. + stats_.largest_alloc_size = l_stats->largest_alloc_size; + stats_.bytes_limit = std::max(s_stats->bytes_limit, l_stats->bytes_limit); + return stats_; + } + + bool ClearStats() override { + bool stats_cleared = small_size_allocator_->ClearStats(); + stats_cleared &= large_size_allocator_->ClearStats(); + return stats_cleared; + } + + private: + // Hooks provided by this allocator for memory allocation routines from MKL + static inline void* MallocHook(size_t size) { + VLOG(3) << "MklCPUAllocator: In MallocHook"; + return cpu_allocator()->AllocateRaw(kAlignment, size); + } + + static inline void FreeHook(void* ptr) { + VLOG(3) << "MklCPUAllocator: In FreeHook"; + cpu_allocator()->DeallocateRaw(ptr); + } + + static inline void* CallocHook(size_t num, size_t size) { + Status s = Status(absl::StatusCode::kUnimplemented, + "Unimplemented case for hooking MKL function."); + TF_CHECK_OK(s); // way to assert with an error message + return nullptr; // return a value and make static code analyzers happy + } + + static inline void* ReallocHook(void* ptr, size_t size) { + Status s = Status(absl::StatusCode::kUnimplemented, + "Unimplemented case for hooking MKL function."); + TF_CHECK_OK(s); // way to assert with an error message + return nullptr; // return a value and make static code analyzers happy + } + + // Do we allow growth in BFC Allocator + static const bool kAllowGrowth = true; + + // Name + static constexpr const char* kName = "mklcpu"; + + // The alignment that we need for the allocations + static constexpr const size_t kAlignment = 64; + + Allocator* large_size_allocator_; // owned by this class + MklSmallSizeAllocator* small_size_allocator_; // owned by this class. + + SubAllocator* sub_allocator_; // not owned by this class + mutable mutex mutex_; + AllocatorStats stats_ TF_GUARDED_BY(mutex_); + + // Hash map to keep track of "BFC" allocations + // We do not use BFC allocator for small allocations. + std::unordered_map large_allocations_map_ + TF_GUARDED_BY(mutex_); + + // Size in bytes that defines the upper-bound for "small" allocations. + // Any allocation below this threshold is "small" allocation. + static constexpr const size_t kSmallAllocationsThreshold = 262144; + + // Prevent copying and assignment + MklCPUAllocator(const MklCPUAllocator&) = delete; + void operator=(const MklCPUAllocator&) = delete; +}; + +} // namespace tensorflow + +#endif // INTEL_MKL + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_MKL_CPU_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/mkl_layout_pass.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/mkl_layout_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..6b5c586ceabb3ed01c188deba266cdb22f6f98be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/mkl_layout_pass.h @@ -0,0 +1,36 @@ +/* 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. +==============================================================================*/ + +// A graph pass that rewrites graph for propagating MKL layout as a tensor + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_MKL_LAYOUT_PASS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_MKL_LAYOUT_PASS_H_ + +#ifdef INTEL_MKL + +#include +#include +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { +// Interface to invoke the pass for unit test +// +// Returns true if and only if 'g' is mutated. +extern bool RunMklLayoutRewritePass(std::unique_ptr* g); +} // namespace tensorflow + +#endif + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_MKL_LAYOUT_PASS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/c/plugin_c_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/c/plugin_c_api.h new file mode 100644 index 0000000000000000000000000000000000000000..e44e5f3ff26aaeecae68970ea2d4410809f99081 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/c/plugin_c_api.h @@ -0,0 +1,176 @@ +/* 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_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_C_PLUGIN_C_API_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_C_PLUGIN_C_API_H_ + +#include + +#include "tensorflow/c/c_api.h" +#include "tensorflow/c/c_api_macros.h" +#include "tensorflow/c/tf_status.h" +#include "tensorflow/c/tf_tensor.h" +#include "xla/c/c_api_decl.h" +#include "xla/pjrt/c/pjrt_c_api.h" +#include "xla/stream_executor/tpu/c_api_decl.h" + +#define TFNPD_MAJOR 0 +#define TFNPD_MINOR 0 +#define TFNPD_PATCH 1 + +// Experimental C API for TensorFlow Next Pluggable device (TFNPD). + +#ifdef __cplusplus +extern "C" { +#endif + +// ---------------------------- Event ---------------------------------------- +typedef struct TFNPD_DeviceEvent TFNPD_DeviceEvent; + +typedef TFNPD_DeviceEvent* TFNPD_NewDeviceEvent(); + +typedef void TFNPD_DeviceEventAwait(TFNPD_DeviceEvent* event, + TF_Status* status); + +typedef bool TFNPD_DeviceEventIsReady(TFNPD_DeviceEvent* event); + +// Invokes the callback after event becomes ready. +typedef void TFNPD_DeviceEventAndThen(TFNPD_DeviceEvent* event, + void (*callback)(void*), + void* callback_arg); + +typedef void TFNPD_DeviceEventDelete(TFNPD_DeviceEvent* event); + +// -------------------------- Allocator -------------------------------------- +typedef struct TFNPD_DeviceAllocator TFNPD_DeviceAllocator; + +typedef TFNPD_DeviceAllocator* TFNPD_DeviceAllocatorCreate(int device_ordinal); + +typedef void* TFNPD_DeviceAllocateRaw(TFNPD_DeviceAllocator* allocator, + size_t alignment, size_t num_bytes); + +typedef void TFNPD_DeviceDeallocateRaw(TFNPD_DeviceAllocator* allocator, + void* ptr); + +typedef TF_StringView TFNPD_DeviceAllocatorName( + TFNPD_DeviceAllocator* allocator); + +typedef bool TFNPD_DeviceAllocatorAllocatesOpaqueHandle( + TFNPD_DeviceAllocator* allocator); + +typedef void TFNPD_DeviceAllocatorDelete(TFNPD_DeviceAllocator* allocator); + +// ------------------------ Tensor Transfers --------------------------------- +typedef struct TFNPD_DeviceContext TFNPD_DeviceContext; + +// TODO(chuanhao): use an option struct to create context. Plugin can define the +// option so that we support more features in the DeviceContext, e.g. +// shape_determination_fns. +typedef TFNPD_DeviceContext* TFNPD_DeviceContextCreate(int device_ordinal); + +typedef TFNPD_DeviceEvent* TFNPD_DeviceTensorToHostTensor( + TFNPD_DeviceContext* device_context, const TF_Tensor* device_tensor, + TF_Tensor* cpu_tensor, TF_Status* status); + +typedef TFNPD_DeviceEvent* TFNPD_HostTensorToDeviceTensor( + TFNPD_DeviceContext* device_context, const TF_Tensor* cpu_tensor, + TF_Tensor* device_tensor, TF_Status* status); + +typedef TFNPD_DeviceEvent* TFNPD_SameDeviceTensorCopy( + TFNPD_DeviceContext* context); + +typedef PJRT_Buffer* TFNPD_SameDevicePjRtBufferCopy(PJRT_Buffer* src_buffer, + PJRT_Client* c_client, + TF_Status* status); + +typedef void TFNPD_DeviceContextDelete(TFNPD_DeviceContext* context); + +// ------------------------------ TF2XLA ------------------------------------- +// TODO(b/254484247): either separate XLA_Shape to its own file, or use PJRT +// solution when it is ready. +typedef void TFNPD_XlaShapeToDeviceShapeRepresentation( + XLA_Shape* serialized_xla_shape, int data_type, bool use_fast_memory, + XLA_LayoutPreference layout_preference, XLA_Shape* serialized_device_shape, + TF_Status* tf_status); + +// ----------------------- Plugin System related ----------------------------- +typedef int32_t TFNPD_GetDeviceCount(TF_Status* status); + +// Initialize any per-device states or resources that are internal to plugin. +typedef void TFNPD_InitPluginInternalDeviceStates(TF_Status* status); + +// --------------------------- C API access ------------------------------------ +#define TFNPD_API_STRUCT_FN(fn_type) fn_type* fn_type + +typedef struct { + size_t struct_size; + void* priv; + + TFNPD_API_STRUCT_FN(TFNPD_NewDeviceEvent); + TFNPD_API_STRUCT_FN(TFNPD_DeviceEventAwait); + TFNPD_API_STRUCT_FN(TFNPD_DeviceEventIsReady); + TFNPD_API_STRUCT_FN(TFNPD_DeviceEventAndThen); + TFNPD_API_STRUCT_FN(TFNPD_DeviceEventDelete); + + TFNPD_API_STRUCT_FN(TFNPD_DeviceAllocatorCreate); + TFNPD_API_STRUCT_FN(TFNPD_DeviceAllocateRaw); + TFNPD_API_STRUCT_FN(TFNPD_DeviceDeallocateRaw); + TFNPD_API_STRUCT_FN(TFNPD_DeviceAllocatorName); + TFNPD_API_STRUCT_FN(TFNPD_DeviceAllocatorAllocatesOpaqueHandle); + TFNPD_API_STRUCT_FN(TFNPD_DeviceAllocatorDelete); + + TFNPD_API_STRUCT_FN(TFNPD_DeviceContextCreate); + TFNPD_API_STRUCT_FN(TFNPD_DeviceContextDelete); + + // TODO(chuanhao): Deprecate the tensor transfer C APIs when PJRT API + // development is ready since we plan to adopt PJRT as Device API. + TFNPD_API_STRUCT_FN(TFNPD_DeviceTensorToHostTensor); + TFNPD_API_STRUCT_FN(TFNPD_HostTensorToDeviceTensor); + TFNPD_API_STRUCT_FN(TFNPD_SameDeviceTensorCopy); + TFNPD_API_STRUCT_FN(TFNPD_SameDevicePjRtBufferCopy); + + TFNPD_API_STRUCT_FN(TFNPD_XlaShapeToDeviceShapeRepresentation); + + TFNPD_API_STRUCT_FN(TFNPD_GetDeviceCount); + TFNPD_API_STRUCT_FN(TFNPD_InitPluginInternalDeviceStates); +} TFNPD_Api; + +const size_t TFNPD_Api_STRUCT_SIZE = + TF_OFFSET_OF_END(TFNPD_Api, TFNPD_InitPluginInternalDeviceStates); + +#undef TFNPD_API_STRUCT_FN + +typedef struct TFNPD_PluginParams { + size_t struct_size; + void* ext; // reserved for future use + + const char* device_type; // output, set by plugin + const char* compilation_device_name; // output, set by plugin + int32_t priority; // output, set by plugin + // Certain devices may set this one to false to avoid using device copy logic + // implemented for legacy PluggableDevice. + bool is_pluggable_device; // output, set by plugin + bool use_pjrt_on_demand_compile; // output, set by plugin +} TFNPD_PluginParams; +const size_t TFNPD_PLUGIN_PARAMS_STRUCT_SIZE = + TF_OFFSET_OF_END(TFNPD_PluginParams, is_pluggable_device); +const TFNPD_Api* TFNPD_InitPlugin(TFNPD_PluginParams* params, + TF_Status* tf_status); + +#if defined(__cplusplus) +} // extern "C" +#endif // defined(__cplusplus) + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_C_PLUGIN_C_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_api.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_api.h new file mode 100644 index 0000000000000000000000000000000000000000..8576b75e4212898890a9178a3c6e514525464157 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_api.h @@ -0,0 +1,36 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_NEXT_PLUGGABLE_DEVICE_API_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_NEXT_PLUGGABLE_DEVICE_API_H_ + +#include + +#include "tensorflow/core/common_runtime/next_pluggable_device/c/plugin_c_api.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { + +// Global TFNPD_Api* singleton. +const TFNPD_Api* TfnpdApi(); +void SetTfnpdApi(const TFNPD_Api* api); + +typedef const TFNPD_Api* (*TFNPDInitPluginFn)(TFNPD_PluginParams*, TF_Status*); +tsl::StatusOr InitNextPluggableDevicePlugin( + TFNPDInitPluginFn init_fn); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_NEXT_PLUGGABLE_DEVICE_API_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_factory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..6d9d4d4d1ab16a0d52b433bab8dff9658c091138 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_factory.h @@ -0,0 +1,56 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_NEXT_PLUGGABLE_DEVICE_FACTORY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_NEXT_PLUGGABLE_DEVICE_FACTORY_H_ + +#include +#include +#include + +#include "tensorflow/core/common_runtime/next_pluggable_device/c/plugin_c_api.h" +#include "tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_api.h" +#include "tensorflow/core/framework/device_factory.h" + +namespace tensorflow { + +class NextPluggableDeviceFactory : public DeviceFactory { + public: + explicit NextPluggableDeviceFactory( + const std::string& device_type, + const std::string& compilation_device_name) + : api_(TfnpdApi()), + device_type_(device_type), + compilation_device_name_(compilation_device_name) {} + + Status ListPhysicalDevices(std::vector* devices) override; + + Status CreateDevices(const SessionOptions& session_options, + const std::string& name_prefix, + std::vector>* devices) override; + + const std::string& compilation_device_name() const { + return compilation_device_name_; + } + + private: + const TFNPD_Api* api_; + const std::string device_type_; + const std::string compilation_device_name_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_NEXT_PLUGGABLE_DEVICE_NEXT_PLUGGABLE_DEVICE_FACTORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/node_file_writer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/node_file_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..f0e0ae830c6e4846e65de2abc7c8f7ad35a3036e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/node_file_writer.h @@ -0,0 +1,71 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_NODE_FILE_WRITER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_NODE_FILE_WRITER_H_ + +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/util/env_var.h" + +namespace tensorflow { + +// Writes out the NodeDef and the input shapes/dtypes for an executed node to a +// file. This allows the set of executed nodes for a model or test to be +// examined and processed. Currently this is used by an internal tool which +// checks that ops executed by tests are deterministic. +class NodeFileWriter { + public: + // Creates or reuses a NodeFileWriter if environmental variable + // TF_NODE_FILE_WRITER_DIRECTORY is set, which specifies the directory where + // the node file will be created in. Otherwise, returns nullptr. When called + // with the same device_name, the same NodeFileWriter will be returned. + static StatusOr GetNodeFileWriterIfEnabled( + const std::string& device_name, Env* env); + + // Records the execution of a node, if eligible, by writing the node to the + // file. Only writes the node if the exact node with the given input + // shapes/dtypes hasn't already been written. Should be called once every time + // a node is run. + Status RecordNodeExecution(OpKernel* op_kernel, OpKernelContext* context); + + const std::string& filename() { return filename_; } + + private: + explicit NodeFileWriter(std::string filename) + : filename_{std::move(filename)} {} + + Status Init(Env* env) { + return env->NewWritableFile(filename_, &node_def_file_); + } + + // Writes the NodeDef to a file, if it hasn't already been written yet. + Status MaybeWriteNodeDefToFile(const NodeDef& def); + + const std::string filename_; + mutex mu_; + // Hashes of the NodeDefs already written to the file + absl::flat_hash_set written_hashes_ TF_GUARDED_BY(mu_); + + std::unique_ptr node_def_file_ TF_PT_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_NODE_FILE_WRITER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/optimization_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/optimization_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..290887711f0b5a15439397f8828284b77698670a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/optimization_registry.h @@ -0,0 +1,188 @@ +/* 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. +==============================================================================*/ + +// Classes to maintain a static registry of whole-graph optimization +// passes to be applied by the Session when it initializes a graph. +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_OPTIMIZATION_REGISTRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_OPTIMIZATION_REGISTRY_H_ + +#include +#include +#include + +#include "tensorflow/core/common_runtime/composite_device.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/costmodel.h" +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { +struct SessionOptions; + +// All the parameters used by an optimization pass are packaged in +// this struct. They should be enough for the optimization pass to use +// as a key into a state dictionary if it wants to keep state across +// calls. +struct GraphOptimizationPassOptions { + // Filled in by DirectSession for PRE_PLACEMENT optimizations. Can be empty. + string session_handle; + const SessionOptions* session_options = nullptr; + const CostModel* cost_model = nullptr; + + FunctionLibraryDefinition* flib_def = nullptr; // Not owned. + // The DeviceSet contains all the devices known to the system and is + // filled in for optimizations run by the session master, i.e., + // PRE_PLACEMENT, POST_PLACEMENT, and POST_REWRITE_FOR_EXEC. It is + // nullptr for POST_PARTITIONING optimizations which are run at the + // workers. + const DeviceSet* device_set = nullptr; // Not owned. + + // Maps from a CompositeDevice name to a list of underlying physical + // devices. + const std::vector* composite_devices = + nullptr; // Not owned. + + // The graph to optimize, for optimization passes that run before + // partitioning. Null for post-partitioning passes. + // An optimization pass may replace *graph with a new graph object. + std::unique_ptr* graph = nullptr; + + // Graphs for each partition, if running post-partitioning. Optimization + // passes may alter the graphs, but must not add or remove partitions. + // Null for pre-partitioning passes. + std::unordered_map>* partition_graphs = + nullptr; + + // Indicator of whether or not the graph was derived from a function. + bool is_function_graph = false; + // Set when is_function_graph is true. The default device where the function + // runs. If nullptr, it runs on the local host. + const Device* default_function_device = nullptr; + // Set when is_function_graph is true. The function where the graph was + // derived. `graph` doesn't contain all the information in the function_def, + // e.g. function attributes. + const FunctionDef* function_def = nullptr; + + // TODO(b/176491312): Remove this if shape inference on import flag is + // removed. If True, allows mlir roundtrip to run shape inference on import. + bool shape_inference_on_tfe_dialect_import = true; + + // A unique filename prefix (using hostname, process ID, thread ID and + // timestamp) for graph dumps. + string debug_filename_prefix; +}; + +// Optimization passes are implemented by inheriting from +// GraphOptimizationPass. +class GraphOptimizationPass { + public: + virtual ~GraphOptimizationPass() {} + virtual Status Run(const GraphOptimizationPassOptions& options) = 0; + void set_name(const string& name) { name_ = name; } + string name() const { return name_; } + + private: + // The name of the optimization pass, which is the same as the inherited + // class name. + string name_; +}; + +// The key is a 'phase' number. Phases are executed in increasing +// order. Within each phase the order of passes is undefined. +typedef std::map>> + GraphOptimizationPasses; + +// A global OptimizationPassRegistry is used to hold all passes. +class OptimizationPassRegistry { + public: + // Groups of passes are run at different points in initialization. + enum Grouping { + PRE_PLACEMENT, // after cost model assignment, before placement. + POST_PLACEMENT, // after placement. + POST_REWRITE_FOR_EXEC, // after re-write using feed/fetch endpoints. + POST_PARTITIONING, // after partitioning + }; + + // Add an optimization pass to the registry. + void Register(Grouping grouping, int phase, + std::unique_ptr pass); + + const std::map& groups() { + return groups_; + } + + // Run all passes in grouping, ordered by phase, with the same + // options. + Status RunGrouping(Grouping grouping, + const GraphOptimizationPassOptions& options); + + // Returns the global registry of optimization passes. + static OptimizationPassRegistry* Global(); + + // Prints registered optimization passes for debugging. + void LogGrouping(Grouping grouping, int vlog_level); + void LogAllGroupings(int vlog_level); + + private: + std::map groups_; + + const char* GetGroupingName(Grouping grouping) const { + switch (grouping) { + case PRE_PLACEMENT: + return "pre_placement"; + case POST_PLACEMENT: + return "post_placement"; + case POST_REWRITE_FOR_EXEC: + return "post_rewrite_for_exec"; + case POST_PARTITIONING: + return "post_partitioning"; + } + return "unknown"; + } +}; + +namespace optimization_registration { + +class OptimizationPassRegistration { + public: + OptimizationPassRegistration(OptimizationPassRegistry::Grouping grouping, + int phase, + std::unique_ptr pass, + string optimization_pass_name) { + pass->set_name(optimization_pass_name); + OptimizationPassRegistry::Global()->Register(grouping, phase, + std::move(pass)); + } +}; + +} // namespace optimization_registration + +#define REGISTER_OPTIMIZATION(grouping, phase, optimization) \ + REGISTER_OPTIMIZATION_UNIQ_HELPER(__COUNTER__, grouping, phase, optimization) + +#define REGISTER_OPTIMIZATION_UNIQ_HELPER(ctr, grouping, phase, optimization) \ + REGISTER_OPTIMIZATION_UNIQ(ctr, grouping, phase, optimization) + +#define REGISTER_OPTIMIZATION_UNIQ(ctr, grouping, phase, optimization) \ + static ::tensorflow::optimization_registration::OptimizationPassRegistration \ + register_optimization_##ctr( \ + grouping, phase, \ + ::std::unique_ptr<::tensorflow::GraphOptimizationPass>( \ + new optimization()), \ + #optimization) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_OPTIMIZATION_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/optimized_function_graph_info.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/optimized_function_graph_info.h new file mode 100644 index 0000000000000000000000000000000000000000..2b92e145b6b63787e1abc1eee84b3e8e8e57c573 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/optimized_function_graph_info.h @@ -0,0 +1,89 @@ +/* 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_COMMON_RUNTIME_OPTIMIZED_FUNCTION_GRAPH_INFO_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_OPTIMIZED_FUNCTION_GRAPH_INFO_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/optimized_function_graph.pb.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Function graph related information after optimizations. This struct can be +// converted to and from +// third_party/tensorflow/core/framework/optimized_function_graph.proto. +struct OptimizedFunctionGraphInfo { + // Function name. + string name; + // Optimized function graph. + std::unique_ptr function_graph; + // Optimized function library. + FunctionLibraryDefinition lib_def; + // Map from original node names to control return names. + std::unordered_map node_name_to_control_ret; + // Return node types of the function. + DataTypeVector ret_types; + // Number of return nodes. + size_t num_return_nodes; + // Time (in microseconds) spent on running the graph optimization passes for + // this function. + uint64_t optimization_duration_usecs; + // Indicates the source environment where the optimization is created. + OptimizedFunctionGraph::OptimizationSource optimization_source; + + ~OptimizedFunctionGraphInfo() = default; + OptimizedFunctionGraphInfo() : lib_def(OpRegistry::Global()) {} + OptimizedFunctionGraphInfo( + const std::string& name, std::unique_ptr&& graph, + FunctionLibraryDefinition&& lib_def, + const std::unordered_map& node_name_to_control_ret, + const DataTypeVector& ret_types, size_t num_return_nodes, + uint64_t optimization_duration_usecs, + OptimizedFunctionGraph::OptimizationSource optimization_source) + : name(name), + function_graph(std::move(graph)), + lib_def(std::move(lib_def)), + node_name_to_control_ret(node_name_to_control_ret), + ret_types(ret_types), + num_return_nodes(num_return_nodes), + optimization_duration_usecs(optimization_duration_usecs), + optimization_source(optimization_source) {} + + OptimizedFunctionGraphInfo(OptimizedFunctionGraphInfo& info) = delete; + OptimizedFunctionGraphInfo& operator=(OptimizedFunctionGraphInfo& info) = + delete; + OptimizedFunctionGraphInfo(OptimizedFunctionGraphInfo&& info) = default; + OptimizedFunctionGraphInfo& operator=(OptimizedFunctionGraphInfo&& info) = + default; + + // Converts from the struct to OptimizedFunctionGraph proto. + static OptimizedFunctionGraph ToProto(const OptimizedFunctionGraphInfo& info); + + // Converts from the proto to struct OptimizedFunctionGraphInfo. Returns error + // if the conversion fails. + static StatusOr FromProto( + const OptimizedFunctionGraph& proto); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_OPTIMIZED_FUNCTION_GRAPH_INFO_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/partitioning_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/partitioning_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f62633996ecf995bb5e09553e0cc13ff802e7c82 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/partitioning_utils.h @@ -0,0 +1,108 @@ +/* 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_COMMON_RUNTIME_PARTITIONING_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PARTITIONING_UTILS_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Given a `device_set` and a `graph`, partitions the `graph` into +// `subgraphs`. `subgraphs` maps device names to the graph assigned to that +// device. `graph` must have been placed (e.g. by running Placer), +// i.e. all nodes must have an assigned_device set. +// `graph` is non-const because the underlying Partition() function transforms +// the graph to correctly partition distributed control flow. +// `get_tensor_name_attr` computes the "tensor_name" attr value of Send/Recv ops +// inserted during partitioning. Use the default one if not set. It needs to be +// thread safe if it's shared in multple threads. +Status PartitionFunctionGraph( + const DeviceSet& device_set, std::unique_ptr graph, + std::unordered_map>* subgraphs, + std::function get_tensor_name_attr = nullptr); + +// Inserts send/recv ops to `graph` if nodes are assigned to multiple devices. +// Returns the new graph with the added nodes. Moreover, the dependency between +// a send/recv pair is made explicit by adding a control dependency between +// them. +// Note that, the returned graph is intended to be used by TF MLIR importer. +// The dependencies between send/recv pairs ensure the importer will generate TF +// MLIR ops in a valid order. +StatusOr> InsertTransferOps( + const DeviceSet& device_set, std::unique_ptr graph); + +// This function performs bookkeeping to track which `Arg` and `Retval` nodes +// were placed on a particular device / graph. +// +// More specifically, this function +// +// (1) rewrites the indices of the `Arg` and `Retval` nodes in `graph` to be +// consecutive. +// +// These indices might not be consecutive after grappler's pruning +// optimization (e.g. removing redundant Args), or graph partitioning. In +// the latter case, the nodes in `graph` are placed on `device_type`, and +// each such graph partition gets a subset of the arguments and return +// values. The `index` attributes of these _Arg and _Retval nodes reflect +// the indices of these parameters in the original function. To convert +// `subgraph` to a function, we need to replace there original indices with +// 0, 1, 2, ... . +// +// The argument and return value order in `graph` is determined by the +// argument and return value order in the original function. This stability +// is important because it enables us to treat a single-partition function +// as having the same signature as the subgraph. +// +// (2) records the subsets of `Arg` and `Retval` nodes assigned to the +// device in `*_indices`, and +// (3) records which `Arg` and `Retval` nodes live in host memory in +// `*_alloc_attrs`. If these vectors are NULL, do nothing here. If +// `ints_on_device` is false, int32 `Arg` and `Retval` nodes are placed on +// host else not. This is needed because in certain special cases e.g. +// when graph is placed on TPU/XLA device or when the `Retval` is an output +// of an iterator, int32 tensors live on device. +Status UpdateArgAndRetvalMetadata( + Graph* graph, std::vector* arg_indices, + std::vector* ret_indices, + std::vector* arg_alloc_attrs, + std::vector* ret_alloc_attrs, bool ints_on_device); + +// Utility for generating function names not present in `flib_def`, using +// given `name` as the base for the name. +class FunctionNameGenerator { + public: + // `flib_def` must outlive this. + FunctionNameGenerator(const FunctionLibraryDefinition* flib_def, + const string& name) + : flib_def_(flib_def), name_(name), counter_(0) {} + + // Returns a function name not present in `flib_def` using `name` as + // the base and appending a numeric suffix. + string GetName(); + + private: + const FunctionLibraryDefinition* flib_def_; + const string name_; + uint32 counter_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PARTITIONING_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/permuter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/permuter.h new file mode 100644 index 0000000000000000000000000000000000000000..654ab0b27291d82b21d3ed812fe60b877e80d5f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/permuter.h @@ -0,0 +1,82 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_PERMUTER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PERMUTER_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/base_collective_executor.h" +#include "tensorflow/core/framework/collective.h" + +namespace tensorflow { +class Device; + +// Implementation of collective permute. +// +// Permute takes +// - a list of devices participating in the collective +// - a permutation as a list of integers. +// - a tensor +// +// The list of devices replaces the need for group_key and group_size. The +// number of inputs only scales with the number of devices within one group. +// +// The integers in the permutation are based on indices of the list of devices. +// E.g. devices = {"GPU:0", "GPU:1"} and permutation = {1,0} means +// - devices[0] sends to devices[permutation[0]] and +// - devices[1] sends to devices[permutation[1]]. +// +// Each device sends exactly one tensor and receives exactly one tensor. +class Permuter : public CollectiveImplementationInterface { + public: + Permuter(); + ~Permuter() override = default; + + void Run(StatusCallback done) override; + + Status InitializeCollectiveParams(CollectiveParams* col_params) override { + return OkStatus(); + } + + // Initializes members of CollectiveContext not yet initialized, i.e. device + // and device_locality. Also saves the CollectiveContext in this object. + Status InitializeCollectiveContext( + std::shared_ptr col_ctx) override; + + private: + std::shared_ptr col_ctx_; + const CollectiveParams* col_params_; // Not owned + StatusCallback done_; + mutex mu_; + Status status_ TF_GUARDED_BY(mu_); + int counter_ TF_GUARDED_BY(mu_); + + void DispatchSend(int src_rank, int target_rank, const Tensor* tensor, + const StatusCallback& done); + + void DispatchRecv(int src_rank, int target_rank, Tensor* tensor, + const StatusCallback& done); + + // Atomically increments counter_ by one for sending, one for receiving. + // Invokes done when counter_ reaches 2. + // The purpose of checking counter_ is to ensure that done_ is called once. + StatusCallback CheckCounterAndCallDone(); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PERMUTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/placer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/placer.h new file mode 100644 index 0000000000000000000000000000000000000000..53d9ec9d170f9ed22d5ae16c23a4972be86e130c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/placer.h @@ -0,0 +1,112 @@ +/* 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_COMMON_RUNTIME_PLACER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLACER_H_ + +#include + +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/optimization_registry.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { + +// A placement algorithm that assigns the nodes of the given Graph to +// devices the given DeviceSet, respecting the following constraints: +// +// 1. Existing device assignments remain unchanged. +// 2. Requested (partial or complete) device specifications given by device name +// for each node are granted. +// 3. Nodes connected by edges of a reference type are colocated on +// the same device. +// 4. Given nodes "A" and "B", if node "B" has a colocation group +// "@loc:A", nodes "A" and "B" will be colocated on the same device. +// +// The implementation builds a constraint graph with the same set of +// nodes, and edges that represent colocation constraints between +// nodes. Each connected component in the resulting constraint graph +// is then assigned to a set of valid devices. +// +// Run() will finally assign the device to each node given the list of +// possible devices. +// +// TODO(mrry): "Soft" constraints, such as "place node 'x' as close as +// possible to node 'y' while respecting the other constraints"? +// TODO(mrry): Create a common interface for this and the other +// placement algorithms so that they may be injected into the graph +// builder. +class Placer { + public: + // Creates an instance of the Placer algorithm for the given + // Graph "graph" (nodes in which may or may not be assigned) on the + // given DeviceSet "devices". + // "function_name" should be set to the name of the function whose body is + // represented by "graph". If "graph" is not representing a function body, + // "function_name" should be empty. + // + // If non-null, default_local_device is used where possible as a placement for + // nodes which do not have a device specified, ahead of other devices which + // would otherwise be higher priority. default_local_device should be on the + // local host so that its FLR is directly accessible by the current process. + // + // The "graph", "devices", and "default_local_device" pointer arguments are + // borrowed by this Placer, and must outlive it. + Placer(Graph* graph, const string& function_name, + const FunctionLibraryDefinition* flib_def, const DeviceSet* devices, + const Device* default_local_device, bool allow_soft_placement, + bool log_device_placement); + Placer(Graph* graph, const string& function_name, + const FunctionLibraryDefinition* flib_def, const DeviceSet* devices); + Placer(Graph* graph, const string& function_name, + const FunctionLibraryDefinition* flib_def, const DeviceSet* devices, + const Device* default_local_device); + + ~Placer(); + + // Assigns each node in this Placer's graph to a device in its + // set of devices. + // + // This method is not thread-safe. + // Run() may be invoked at most once. + Status Run(); + Status Run(const GraphOptimizationPassOptions& options); + + private: + // Returns true if the device type of 'candidate_device_name' is + // found in 'devices'. + bool CanAssignToDevice(const string& candidate_device_name, + const std::vector& devices) const; + + Graph* const graph_; // Not owned. + const string function_name_; + const FunctionLibraryDefinition* const flib_def_; // Not owned. + const DeviceSet* const devices_; // Not owned. + const Device* default_local_device_; // Not owned. + const bool allow_soft_placement_; + const bool log_device_placement_; + + Placer(const Placer&) = delete; + void operator=(const Placer&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLACER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/placer_inspection_required_ops_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/placer_inspection_required_ops_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f882d02b9160e15e344d312d3c0e012383009964 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/placer_inspection_required_ops_utils.h @@ -0,0 +1,156 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_PLACER_INSPECTION_REQUIRED_OPS_UTILS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLACER_INSPECTION_REQUIRED_OPS_UTILS_H_ + +// Operations calling functions are becoming ubiquitous in TF 2.0. +// Examples include PartitionedCallOp, functional If/While, and Dataset ops. +// Such operations might require deep inspection - looking at the body of the +// called function - to place them and surrounding ops correctly. + +// This file contains some utilities for placer to correctly place such ops +// including: +// - PlacerInspectionRequiredOpChecker: A simple class with a single +// IsPlacerInspectionRequired method. +// - IsolatePlacerInspectionRequiredOps: This function adds Identity ops for +// each input/output of ops requiring placer inspection. It greatly simplifies +// the implementation of placing such ops. + +#include + +#include "absl/types/optional.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// PlacerInspectionRequiredOpChecker allows one to check if Placer needs to +// look deeply into the op to place ops consuming the outputs correctly. +// +// It is a class instead of a standalone method because checking whether +// a function returns a resource takes non-trivial time and we cache the +// results. +class PlacerInspectionRequiredOpChecker { + public: + // Constructs a PlacerInspectionRequiredOpChecker for nodes of `graph`. + // The functions referenced by nodes in `graph` will be looked up in + // `flib_def` + PlacerInspectionRequiredOpChecker(const Graph* graph, + const FunctionLibraryDefinition* flib_def); + + // If `node` is considered a deep op, sets `*is_deep` to true and returns + // OkStatus(). If an error occurs, returns that error, and the value of + // `*is_deep` is undefined. + // Currently, an op is considered deep, if it is a calling a function + // returning a resource. This definition is driven by Placer's need to + // look inside the op. + // REQUIRES: `node` is part of `graph` passed into constructor. + Status IsPlacerInspectionRequired(const Node& node, bool* is_deep); + + private: + const Graph& graph_; + const FunctionLibraryDefinition& flib_def_; + // Indexed by the node id. + // If cache_[node_id] is empty, the deepness of the node with id `node_id` has + // not been computed yet. Else, it contains the value already computed. + std::vector> cache_; +}; + +// Extracts `fdef` and `func` from `flib_def` for the function identified +// in "f" attribute of `node`. +Status GetFunctionDefAndAttrs(const FunctionLibraryDefinition& flib_def, + const Node& node, const FunctionDef** fdef, + NameAttrList* func); + +// The "call" stack of functions. +// Useful for better error messages as well as for detecting recursion. +// Stores references to graph nodes. These references must outlive this. +class FunctionStack { + public: + explicit FunctionStack(const string& function_name); + + // `node_in_current_function` must outlive this. + FunctionStack Push(const Node* node_in_current_function, + const string& new_current_function) const; + + // Returns true iff this stack already includes `function_name`. + bool HasFunction(const string& function_name) const; + + const string& current_function_name() const { return current_function_name_; } + + // Format's this suitable for error interpolation that retrieves + // Python files and line numbers. + string FormatForError() const; + + private: + struct Frame { + Frame(const string& function, const Node* node) + : function_name(function), node(node) {} + + string function_name; + const Node* node; + }; + + // The function at the top of the stack. In other words, the function + // that is currently being inspected for placement. + string current_function_name_; + + // The stack of frames that got the placement to the current_function_name_. + // frames_[0].function_name is the top function that Placer was constructed + // with. frames_[0].function_name can be empty if placer was constructed with + // a nameless graph, not a function. frames_[0].node_name is a name of a node + // in frames_[0].function_name that required deep inspection (e.g. a + // PartitionedCallOp). The function that this node invoked is + // frames_[1].function_name, if frames_.size() > 1. Else, the function that + // this node invoked is current_function_name_. + std::vector frames_; +}; + +// Adds Identities for each input and output of function-calling ops in `graph` +// +// For example, the following graph calling a function on inputs `a` and `b` +// and producing output `y` will be rewritten to include identities on all +// edges: +// +// a b +// | | +// v v +// f (PartitionedCallOp) +// | +// v +// y +// +// is transformed to +// +// a b +// | | +// a_f (Identity) b_f (Identity) +// | | +// v v +// f (PartitionedCallOp) +// | +// f_y (Identity) +// | +// v +// y +// +Status IsolatePlacerInspectionRequiredOps( + const FunctionLibraryDefinition& flib_def, Graph* graph); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLACER_INSPECTION_REQUIRED_OPS_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device.h new file mode 100644 index 0000000000000000000000000000000000000000..74ad5893921ecc844f009f71449117bb18dc0829 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device.h @@ -0,0 +1,117 @@ +/* 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_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/device/device_event_mgr.h" +#include "tensorflow/core/common_runtime/device/device_id.h" +#include "tensorflow/core/common_runtime/device/device_id_manager.h" +#include "tensorflow/core/common_runtime/local_device.h" +#include "tensorflow/core/common_runtime/pluggable_device/pluggable_device_context.h" +#include "tensorflow/core/common_runtime/shared_counter.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { + +class PluggableDevice : public LocalDevice { + public: + PluggableDevice(const SessionOptions& options, const std::string& name, + const string& device_type, const string& platform_name, + Bytes memory_limit, const DeviceLocality& locality, + TfDeviceId tf_device_id, + const std::string& physical_device_desc, + Allocator* device_allocator, Allocator* cpu_allocator, + bool sync_every_op); + + ~PluggableDevice() override; + + // Initialize the device and return the status of initialization. + Status Init(const SessionOptions& options); + + void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context, + AsyncOpKernel::DoneCallback done) override; + + void Compute(OpKernel* op_kernel, OpKernelContext* context) override; + + Status Sync() override; + + Allocator* GetAllocator(AllocatorAttributes attr) override; + + Status MakeTensorFromProto(const TensorProto& tensor_proto, + AllocatorAttributes alloc_attrs, + Tensor* tensor) override; + + void CopyTensorInSameDevice(const Tensor* input_tensor, Tensor* output_tensor, + const DeviceContext* device_context, + StatusCallback done) override; + + // The executor that provides control for the pluggable device; + se::StreamExecutor* executor() const { return executor_; } + + private: + Allocator* device_allocator_; + Allocator* cpu_allocator_; + + se::StreamExecutor* executor_ = nullptr; + struct StreamGroup { + se::Stream* compute = nullptr; + se::Stream* host_to_device = nullptr; + se::Stream* device_to_host = nullptr; + gtl::InlinedVector device_to_device; + }; + + class StreamGroupFactory; + + StreamGroup* stream_; + PluggableDeviceContext* device_context_; + // TODO(penpornk): Investigate renaming `GpuDeviceInfo` to `DeviceInfo`. + DeviceBase::AcceleratorDeviceInfo* pluggable_device_info_ = nullptr; + TfDeviceId tf_device_id_; + const string platform_name_; + const bool sync_every_op_ = false; + EventMgr* em_ = nullptr; + std::unique_ptr thread_pool_; + bool force_gpu_compatible_ = false; + std::string ComputeOpKernelDebugString(const OpKernel& op_kernel, + int stream_id); + + // This method returns an initialization status, in addition to + // calling the "done" StatusCallback, if there is a failure to + // allocate memory or if the tensor "from" is not DMA-copyable. + // If there is no error prior to enqueueing the copy, an OK status + // is returned. + Status MaybeCopyTensorToPluggableDevice( + const AllocatorAttributes& alloc_attrs, const Tensor& from, Tensor* to, + StatusCallback done); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_bfc_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_bfc_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..b668bf0f2fd749d3dd16a83e7e75d55da21ddbf2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_bfc_allocator.h @@ -0,0 +1,56 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_BFC_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_BFC_ALLOCATOR_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/bfc_allocator.h" +#include "tensorflow/core/common_runtime/device/device_mem_allocator.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +// A PluggableDevice memory allocator that implements a 'best-fit with +// coalescing' algorithm +class PluggableDeviceBFCAllocator : public BFCAllocator { + public: + PluggableDeviceBFCAllocator(DeviceMemAllocator* sub_allocator, + size_t total_memory, const string& name, + bool force_memory_growth_requested); + PluggableDeviceBFCAllocator(DeviceMemAllocator* sub_allocator, + size_t total_memory, + const GPUOptions& gpu_options, const string& name, + bool force_memory_growth_requested); + ~PluggableDeviceBFCAllocator() override = default; + + PluggableDeviceBFCAllocator(const PluggableDeviceBFCAllocator&) = delete; + void operator=(const PluggableDeviceBFCAllocator&) = delete; + + private: + static bool GetAllowGrowthValue(const GPUOptions& gpu_options, + bool force_memory_growth_requested); + static bool GetGarbageCollectionValue(); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_BFC_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_context.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_context.h new file mode 100644 index 0000000000000000000000000000000000000000..5798be1c13bc747e0439353c1bd1bb4fb6951761 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_context.h @@ -0,0 +1,89 @@ +/* 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_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_CONTEXT_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_CONTEXT_H_ + +#include + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" + +namespace stream_executor { +class Stream; +} // namespace stream_executor + +namespace tensorflow { + +class PluggableDeviceContext : public DeviceContext { + public: + // Does not take ownership of streams. + PluggableDeviceContext( + int stream_id, se::Stream* stream, se::Stream* host_to_device_stream, + se::Stream* device_to_host_stream, + gtl::InlinedVector device_to_device_stream) + : stream_id_(stream_id), + stream_(stream), + host_to_device_stream_(host_to_device_stream), + device_to_host_stream_(device_to_host_stream), + device_to_device_stream_(device_to_device_stream) {} + + ~PluggableDeviceContext() override = default; + + se::Stream* stream() const override { return stream_; } + se::Stream* host_to_device_stream() const { return host_to_device_stream_; } + se::Stream* device_to_host_stream() const { return device_to_host_stream_; } + se::Stream* device_to_device_stream(int index) const { + return device_to_device_stream_[index % device_to_device_stream_.size()]; + } + int stream_id() const { return stream_id_; } + + void CopyCPUTensorToDevice(const Tensor* cpu_tensor, Device* device, + Tensor* device_tensor, StatusCallback done, + bool sync_dst_compute) const override; + + void CopyDeviceTensorToCPU(const Tensor* device_tensor, + StringPiece tensor_name, Device* device, + Tensor* cpu_tensor, StatusCallback done) override; + + void CopyTensorInSameDevice(const Tensor* input_tensor, Device* device, + Tensor* output_tensor, + StatusCallback done) const override; + + void MaintainLifetimeOnStream(const Tensor* t, + se::Stream* stream) const override {} + + Status ThenExecute(Device* device, se::Stream* stream, + std::function func) override; + + bool IsPluggableDevice() override; + + private: + int stream_id_; + // The default primary stream to use for this context. + // All the memory belongs to this stream. + se::Stream* stream_; + // The stream to use for copying data from host into PluggableDevice. + se::Stream* host_to_device_stream_; + // The stream to use for copying data from PluggableDevice to host. + se::Stream* device_to_host_stream_; + // Streams to use for copying data between PluggableDevices. + gtl::InlinedVector device_to_device_stream_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_CONTEXT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..c423dd2a1fc13a5b58a5b1e76be0eb83d93b2e38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.h @@ -0,0 +1,61 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_FACTORY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_FACTORY_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/device/device_id.h" +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { +class PluggableDeviceFactory : public DeviceFactory { + public: + PluggableDeviceFactory(const string& device_type, + const string& platform_name); + Status ListPhysicalDevices(std::vector* devices) override; + Status CreateDevices(const SessionOptions& options, + const std::string& name_prefix, + std::vector>* devices) override; + Status GetDeviceDetails(int device_index, + std::unordered_map* details) override; + + private: + // Populates *device_localities with the DeviceLocality descriptor for + // every TfDeviceId. + Status GetDeviceLocalities(int num_tf_devices, + std::vector* device_localities); + // Create a PluggableDevice associated with 'tf_device_id', allocates + // (strictly) 'memory_limit' bytes of PluggableDevice memory to it, and adds + // it to the 'devices' vector. + Status CreatePluggableDevice(const SessionOptions& options, + const std::string& name_prefix, + TfDeviceId tf_device_id, int64_t memory_limit, + const DeviceLocality& dev_locality, + std::vector>* devices); + + const string device_type_; + const string platform_name_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_FACTORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_init.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_init.h new file mode 100644 index 0000000000000000000000000000000000000000..6362de9856ae38b6d511cc43e4dc8d959e4c286a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_init.h @@ -0,0 +1,43 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_INIT_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_INIT_H_ + +#include + +#include "tensorflow/core/lib/core/status.h" + +namespace stream_executor { +class Platform; +} // namespace stream_executor + +namespace tensorflow { + +// Initializes the PluggableDevice platform and returns OK if the +// PluggableDevice platform could be initialized. +Status ValidatePluggableDeviceMachineManager(const string& platform_name); + +// Returns the PluggableDevice machine manager singleton, creating it and +// initializing the PluggableDevices on the machine if needed the first time it +// is called. Must only be called when there is a valid PluggableDevice +// environment in the process (e.g., ValidatePluggableDeviceMachineManager() +// returns OK). +stream_executor::Platform* PluggableDeviceMachineManager( + const string& platform_name); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_INIT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_process_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_process_state.h new file mode 100644 index 0000000000000000000000000000000000000000..b968c15fa84d61cf11f37bed813de564fa6fa297 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_process_state.h @@ -0,0 +1,127 @@ +/* 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_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_PROCESS_STATE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_PROCESS_STATE_H_ + +#include +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/device/device_id.h" +#include "tensorflow/core/common_runtime/process_state.h" +#include "tensorflow/core/common_runtime/shared_counter.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +class PluggableDeviceBFCAllocator; +class PluggableDeviceSimpleAllocator; +class PoolAllocator; + +// Singleton that manages per-process state when PluggableDevices are present. +class PluggableDeviceProcessState { + public: + // Singleton that manages each platform's per-process state. e.g. allocation + // of shared resource. + static PluggableDeviceProcessState* singleton(const string& device_type, + const string& platform_name); + + // Query whether any PluggableDevice has been created so far. + // Disable thread safety analysis since a race is benign here. + bool HasPluggableDevice() const TF_NO_THREAD_SAFETY_ANALYSIS { + return pluggable_device_enabled_; + } + + // Set the flag to indicate a PluggableDevice has been created. + // Disable thread safety analysis since a race is benign here. + void EnablePluggableDevice() TF_NO_THREAD_SAFETY_ANALYSIS { + pluggable_device_enabled_ = true; + } + + // Returns the one PluggableDevice allocator used for the indexed + // PluggableDevice. Note that this is a system PluggableDevice index. + // + // 'total_bytes' is the total number of bytes that should be made + // available to the allocator. The first call to this function for + // a given tf_device_id creates the allocator, so only the + // total_bytes used on that first call is used. + // + // 'allocator_type' describes the type of algorithm to use for the + // underlying allocator. REQUIRES: Must be a valid type (see + // config.proto for the list of supported strings.). + // + // REQUIRES: tf_device_id must be a valid id for a PluggableDevice + // available in the current system environment. Otherwise returns nullptr. + virtual Allocator* GetPluggableDeviceAllocator(const GPUOptions& options, + TfDeviceId tf_device_id, + size_t total_bytes); + + int NumPluggableDeviceAllocators() { + mutex_lock l(mu_); + return pluggable_device_allocators_.size(); + } + + virtual Allocator* GetPluggableDeviceHostAllocator(int numa_node); + + // Returns bus_id for the given PluggableDevice id. + virtual int BusIdForPluggableDevice(TfDeviceId tf_device_id); + + protected: + // PluggableDeviceProcessState is a singleton that should not normally be + // deleted except at process shutdown. + PluggableDeviceProcessState(const string& device_type, + const string& platform_name); + virtual ~PluggableDeviceProcessState() = default; + + ProcessState::MDMap* mem_desc_map() { + if (process_state_) return &process_state_->mem_desc_map_; + return nullptr; + } + + static PluggableDeviceProcessState* instance_; + ProcessState* process_state_; // Not owned. + bool pluggable_device_enabled_; + const string device_type_; + const string platform_name_; + mutex mu_; + + struct AllocatorParts { + std::unique_ptr allocator; + Allocator* device_allocator; + SubAllocator* sub_allocator; // owned by allocator + }; + + std::vector pluggable_device_allocators_ TF_GUARDED_BY(mu_); + std::vector> pluggable_device_visitors_ + TF_GUARDED_BY(mu_); + + std::vector pluggable_device_host_allocators_ + TF_GUARDED_BY(mu_); + std::vector> + pluggable_device_host_alloc_visitors_ TF_GUARDED_BY(mu_); + std::vector> + pluggable_device_host_free_visitors_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_PROCESS_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_simple_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_simple_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..3a46f76680944949fac292c1cdb07caa6ee624b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_simple_allocator.h @@ -0,0 +1,56 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_SIMPLE_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_SIMPLE_ALLOCATOR_H_ + +#include +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/device/device_mem_allocator.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +class PluggableDeviceSimpleAllocator : public Allocator { + public: + explicit PluggableDeviceSimpleAllocator(DeviceMemAllocator* sub_allocator); + ~PluggableDeviceSimpleAllocator() override = default; + + void* AllocateRaw(size_t alignment, size_t num_bytes) override; + void DeallocateRaw(void* ptr) override; + + bool TracksAllocationSizes() const override { return false; } + string Name() override { return "Simple allocator"; } + std::optional GetStats() override; + + AllocatorMemoryType GetMemoryType() const override { + return sub_allocator_->GetMemoryType(); + } + + private: + PluggableDeviceSimpleAllocator(const PluggableDeviceSimpleAllocator&) = + delete; + void operator=(const PluggableDeviceSimpleAllocator&) = delete; + std::unique_ptr sub_allocator_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_SIMPLE_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_util.h new file mode 100644 index 0000000000000000000000000000000000000000..8cff5449c853f5bdd38e7c5e4bb7ef928b70792d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pluggable_device/pluggable_device_util.h @@ -0,0 +1,72 @@ +/* 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_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_UTIL_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/dma_helper.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/stream_executor.h" + +namespace tensorflow { + +class RecvTensorResponse; +class TensorProto; + +class PluggableDeviceUtil { + public: + // Copies the data in 'device_tensor' into 'cpu_tensor'. + // 'device_tensor''s backing memory must be on 'device' and + // 'cpu_tensor' must be allocated to be of the same size as + // 'device_tensor'. Synchronous: may block. + static void CopyPluggableDeviceTensorToCPU( + Device* device, const DeviceContext* device_context, + const Tensor* device_tensor, Tensor* cpu_tensor, StatusCallback done); + // Blocks until all operations queued on the stream associated with + // 'device' at the time of the call have completed. Returns any + // error pending on the stream at completion. + static Status Sync(Device* device); + + // Blocks until all operations queued on all streams associated with the + // corresponding 'device' at the time of call have completed. + // Returns any error pending on the stream at completion. + static Status SyncAll(Device* device); + + static void CopyCPUTensorToPluggableDevice( + const Tensor* cpu_tensor, const DeviceContext* device_context, + Device* device, Tensor* device_tensor, StatusCallback done, + bool sync_dst_compute); + + static void DeviceToDeviceCopy( + DeviceContext* send_dev_context, DeviceContext* recv_dev_context, + Device* src, Device* dst, AllocatorAttributes src_alloc_attr, + AllocatorAttributes dst_alloc_attr, const Tensor* input, Tensor* output, + int dev_to_dev_stream_index, StatusCallback done); + + // Deep-copying of PluggableDevice tensor on the same device. + // 'src_device_tensor''s and 'dst_device_tensor''s backing memory must be on + // 'device' and 'dst_cpu_tensor' must be allocated to be of the same + // size as 'src_device_tensor'. + static void CopyPluggableDeviceTensorToSameDevice( + Device* device, const DeviceContext* device_context, + const Tensor* src_device_tensor, Tensor* dst_device_tensor, + StatusCallback done); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PLUGGABLE_DEVICE_PLUGGABLE_DEVICE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pool_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pool_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..6ce3b7886cfa6b8fae7370802e50c05c78ae549c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/pool_allocator.h @@ -0,0 +1,181 @@ +/* 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_COMMON_RUNTIME_POOL_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_POOL_ALLOCATOR_H_ + +// Simple LRU pool allocators for various flavors of CPU RAM. + +#include +#include +#include +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/lib/core/bits.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// Interface of an object that rounds up integers. +class RoundUpInterface { + public: + virtual ~RoundUpInterface() {} + virtual size_t RoundUp(size_t num_bytes) = 0; +}; + +// Size-limited pool of memory buffers obtained from a SubAllocator +// instance. Pool eviction policy is LRU. +class PoolAllocator : public Allocator { + public: + // "pool_size_limit" is the maximum number of returned, re-usable + // memory buffers to keep in the pool. If pool_size_limit == 0, the + // pool is effectively a thin wrapper around the allocator. + // If "auto_resize" is true, then the pool_size_limit will gradually + // be raised so that deallocations happen very rarely, if at all. + // Transitory start-up objects may deallocate, but the long-term + // working-set should not. Auto-resizing can raise pool_size_limit + // but will never lower it. + // "allocator" is the object that performs the underlying memory + // malloc/free operations. This object takes ownership of allocator. + PoolAllocator(size_t pool_size_limit, bool auto_resize, + SubAllocator* allocator, RoundUpInterface* size_rounder, + string name); + ~PoolAllocator() override; + + string Name() override { return name_; } + + void* AllocateRaw(size_t alignment, size_t num_bytes) override; + + void DeallocateRaw(void* ptr) override; + + // Allocate an unused memory region of size "num_bytes". Fetch from + // the pool if available, otherwise call allocator_. + void* Get(size_t num_bytes); + + // Return a no-longer needed memory region to the pool. It is an error + // to deference "ptr" after this call. If the pool is full, the least + // recently used region will be deallocated. + void Put(void* ptr, size_t num_bytes); + + // Reset the pool to empty. + void Clear(); + + // The following accessors permit monitoring the effectiveness of + // the pool at avoiding repeated malloc/frees on the underlying + // allocator. Read locks are not taken on the theory that value + // consistency with other threads is not important. + + // Number of Get() requests satisfied from pool. + int64_t get_from_pool_count() const TF_NO_THREAD_SAFETY_ANALYSIS { + return get_from_pool_count_; + } + // Number of Put() requests. + int64_t put_count() const TF_NO_THREAD_SAFETY_ANALYSIS { return put_count_; } + // Number of Get() requests requiring a fresh allocation. + int64_t allocated_count() const TF_NO_THREAD_SAFETY_ANALYSIS { + return allocated_count_; + } + // Number of pool evictions. + int64_t evicted_count() const TF_NO_THREAD_SAFETY_ANALYSIS { + return evicted_count_; + } + // Current size limit. + size_t size_limit() const TF_NO_THREAD_SAFETY_ANALYSIS { + return pool_size_limit_; + } + + AllocatorMemoryType GetMemoryType() const override { + return allocator_->GetMemoryType(); + } + + private: + struct PtrRecord { + void* ptr; + size_t num_bytes; + PtrRecord* prev; + PtrRecord* next; + }; + + // Remove "pr" from the double-linked LRU list. + void RemoveFromList(PtrRecord* pr) TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // Add "pr" to the head of the double-linked LRU list. + void AddToList(PtrRecord* pr) TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + // Delete the least recently used record. + void EvictOne() TF_EXCLUSIVE_LOCKS_REQUIRED(mutex_); + + const string name_; + const bool has_size_limit_; + const bool auto_resize_; + size_t pool_size_limit_; + std::unique_ptr allocator_; + std::unique_ptr size_rounder_; + mutex mutex_; + std::multimap pool_ TF_GUARDED_BY(mutex_); + PtrRecord* lru_head_ TF_GUARDED_BY(mutex_) = nullptr; + PtrRecord* lru_tail_ TF_GUARDED_BY(mutex_) = nullptr; + int64_t get_from_pool_count_ TF_GUARDED_BY(mutex_) = 0; + int64_t put_count_ TF_GUARDED_BY(mutex_) = 0; + int64_t allocated_count_ TF_GUARDED_BY(mutex_) = 0; + int64_t evicted_count_ TF_GUARDED_BY(mutex_) = 0; +}; + +// Do-nothing rounder. Passes through sizes unchanged. +class NoopRounder : public RoundUpInterface { + public: + size_t RoundUp(size_t num_bytes) override { return num_bytes; } +}; + +// Power of 2 rounder: rounds up to nearest power of 2 size. +class Pow2Rounder : public RoundUpInterface { + public: + size_t RoundUp(size_t num_bytes) override { + return 1uLL << Log2Ceiling64(num_bytes); + } +}; + +class BasicCPUAllocator : public SubAllocator { + public: + BasicCPUAllocator(int numa_node, const std::vector& alloc_visitors, + const std::vector& free_visitors) + : SubAllocator(alloc_visitors, free_visitors), numa_node_(numa_node) {} + + ~BasicCPUAllocator() override {} + + void* Alloc(size_t alignment, size_t num_bytes, + size_t* bytes_received) override; + + void Free(void* ptr, size_t num_bytes) override; + + bool SupportsCoalescing() const override { return false; } + + AllocatorMemoryType GetMemoryType() const override { + return AllocatorMemoryType::kHostPageable; + } + + private: + int numa_node_; + + BasicCPUAllocator(const BasicCPUAllocator&) = delete; + void operator=(const BasicCPUAllocator&) = delete; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_POOL_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_function_library_runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_function_library_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..8721fb448ed2eba7d5a1f42aee7912fef175b4db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_function_library_runtime.h @@ -0,0 +1,554 @@ +/* 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_COMMON_RUNTIME_PROCESS_FUNCTION_LIBRARY_RUNTIME_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PROCESS_FUNCTION_LIBRARY_RUNTIME_H_ + +#include +#include +#include +#include + +#include "absl/types/variant.h" +#include "tensorflow/core/common_runtime/composite_device.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/optimized_function_graph_info.h" +#include "tensorflow/core/common_runtime/stats_publisher_interface.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/platform.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tsl/platform/notification.h" +#include "tsl/platform/thread_annotations.h" + +#if !defined(IS_MOBILE_PLATFORM) +#include "tensorflow/core/protobuf/remote_tensor_handle.pb.h" +#endif // !IS_MOBILE_PLATFORM + +namespace tensorflow { + +class FunctionArgsInterface { + public: + virtual ~FunctionArgsInterface() {} + + virtual bool HasRemoteOrPackedInputs() const = 0; + + virtual Status GetLocalArg(const FunctionArgIndex& index, + Tensor* val) const = 0; + + virtual std::vector GetLocalTensors() const = 0; + +#if !defined(IS_MOBILE_PLATFORM) + virtual Status GetRemoteArg(const FunctionArgIndex& index, + eager::RemoteTensorHandle* val) const { + return errors::Unimplemented( + "Serializing a remote argument is not implemented."); + } +#endif // IS_MOBILE_PLATFORM +}; + +// A class that stores all the FunctionLibraryRuntime objects, one per device. +class ProcessFunctionLibraryRuntime { + public: + // Creates FunctionLibraryRuntime objects for each device in the provided + // DeviceMgr. Caller needs to make sure that device_mgr, lib_def and parent + // (if provided) outlive this object. + ProcessFunctionLibraryRuntime( + const DeviceMgr* device_mgr, Env* env, const ConfigProto* config, + int graph_def_version, const FunctionLibraryDefinition* lib_def, + const OptimizerOptions& optimizer_options, + thread::ThreadPool* thread_pool = nullptr, + DistributedFunctionLibraryRuntime* parent = nullptr, + const SessionMetadata* session_metadata = nullptr, + Rendezvous::Factory rendezvous_factory = Rendezvous::Factory(), + StatsPublisherFactory stats_publisher_factory = CreateNoOpStatsPublisher); + + ~ProcessFunctionLibraryRuntime() { + // Deleting the FunctionLibraryRuntime map will delete the function handles + // registered in it, which may call ReleaseHandle in this class again to + // release their sub-function. These circular calls may cause segfault + // since the flr_map_ may have already been deleted. Explicitly releasing + // flr_map_ here and checking flr_map_ in ReleaseHandle to avoid this. + flr_map_.reset(); + // Graph and stats publishers might have pending work in async threads that + // requires access to PFLR instance. Wait for completion before destructing. + for (const auto& n : stats_publisher_completed_) { + n->WaitForNotification(); + } + } + + // Sends `tensors_to_send` from `source_device` to `target_device` using + // `rendezvous`. `key_prefix` is used as a prefix for the keys sent to the + // Rendezvous. `device_context` should be the DeviceContext of the device + // doing the sending. `alloc_attrs` should either be empty or be the size of + // `tensors_to_send` and indicates how the input tensors are allocated. Method + // takes references on each of the `tensors_to_send`. Method doesn't block. + static Status SendTensors(const string& source_device, + const string& target_device, + const string& key_prefix, int64_t src_incarnation, + gtl::ArraySlice tensors_to_send, + DeviceContext* device_context, + const std::vector& alloc_attrs, + RendezvousInterface* rendezvous); + + // Receives `received_tensors` from `target_device` (originally sent from + // `source_device`) using `rendezvous`. Uses `key_prefix` to construct the + // keys to be retrieved. `device_context` should be for the device receiving + // the tensors. `alloc_attrs` indicates how to allocate the received + // tensors and should either be empty or `num_tensors` in size. Method doesn't + // block and calls `done` when `num_tensors` are fetched. + static void ReceiveTensorsAsync( + const string& source_device, const string& target_device, + const string& key_prefix, int64_t src_incarnation, int64_t num_tensors, + DeviceContext* device_context, + const std::vector& alloc_attrs, + RendezvousInterface* rendezvous, std::vector* received_tensors, + StatusCallback done); + + static const char kDefaultFLRDevice[]; + // Returns the FunctionLibraryRuntime for the corresponding device_name. + FunctionLibraryRuntime* GetFLR(const string& device_name) const; + + // Returns the return types for the function identified by handle `h`. + Status GetRetTypes(FunctionLibraryRuntime::Handle h, + DataTypeVector* ret_types); + + // Returns the device incarnation for the given device_name. + Status GetDeviceIncarnation(const string& device_name, + int64_t* incarnation) const; + + // For a given canonicalized key signature of the function instantiated + // on device `device_name` and a `local_handle`, creates a handle and returns + // that value. Uses core/common_runtime/framework/function.h::Canonicalize + // to canonicalize the function signature. + FunctionLibraryRuntime::Handle AddHandle( + const string& function_key, const string& device_name, + FunctionLibraryRuntime::LocalHandle local_handle); + + // Returns a handle if found for the given key, else returns kInvalidHandle. + FunctionLibraryRuntime::Handle GetHandle(const string& function_key) const; + + // For the given handle instantiated on device `device_name` returns the local + // index of instantiation of that function. If the function was not + // instantiated on `device_name` or the function is multi-device, + // returns kInvalidLocalHandle. + // + // If `include_multi_device` is true and `handle` is a multi-device function + // with a single component that is placed on `device_name`, then this method + // will return the local handle for that component. + FunctionLibraryRuntime::LocalHandle GetHandleOnDevice( + const string& device_name, FunctionLibraryRuntime::Handle handle, + bool include_multi_device = false) const; + + // Fills `output_devices` with the devices on which the results will + // be produced. If some output is produced on CPU, the corresponding Device* + // is set to nullptr. If some output is DT_RESOURCE, the corresponding Device* + // is set to the device backing the resource. + // REQUIRES: `handle` identifies a multi-device function. + Status GetOutputDevices(FunctionLibraryRuntime::Handle handle, + std::vector* output_devices) const; + + // Instantiates the function. See framework/function.h for more details. + // Allows for function_name to be instantiated on different devices + // as specified in attrs. + Status Instantiate(const string& function_name, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + FunctionLibraryRuntime::Handle* handle); + + // Returns whether the function represented by the given handle needs to + // execute cross process. + Status IsCrossProcess(FunctionLibraryRuntime::Handle handle, + bool* is_cross_process) const; + + // Delegates to the local FLR that owns state corresponding to `handle` and + // tells it to release it. If the `handle` isn't needed at all, the local FLR + // might call RemoveHandle on this to get rid of the state owned by the Proc + // FLR. + // For multi-device functions, calls ReleaseHandle on local FLRs for each + // component function that is part of this multi-device function. + // Each local FLR might call RemoveHandle on this. + Status ReleaseHandle(FunctionLibraryRuntime::Handle handle); + + // Runs the function with given `handle`. Function could have been + // instantiated on any device. More details in framework/function.h + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, gtl::ArraySlice args, + std::vector* rets, + FunctionLibraryRuntime::DoneCallback done) const; + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, CallFrameInterface* frame, + FunctionLibraryRuntime::DoneCallback done) const; + + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, + const FunctionArgsInterface& args, std::vector* rets, + FunctionLibraryRuntime::DoneCallback done) const; + + Status RunSync(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, + gtl::ArraySlice args, std::vector* rets) const; + Status RunSync(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, + CallFrameInterface* frame) const; + + const DeviceMgr* device_mgr() { return device_mgr_; } + + const std::shared_ptr device_set() const { + tf_shared_lock l(mu_); + return device_set_; + } + + // Initialize the set of local and remote devices and corresponding flr for op + // device selection. + void InitializeDeviceAndFlr(); + + const ConfigProto* config() const { return config_ ? &(*config_) : nullptr; } + + const FunctionLibraryDefinition* GetFunctionLibraryDefinition() const { + return lib_def_; + } + + // Add a CompositeDevice to `device_set_` + void AddCompositeDevice(CompositeDevice* d) TF_LOCKS_EXCLUDED(mu_) { + mutex_lock l(mu_); + device_set_->AddDevice(d); + composite_devices_.push_back(d); + } + + protected: + friend class FunctionLibraryRuntimeImpl; + + struct InternalArgs { + std::vector args; +#if !defined(IS_MOBILE_PLATFORM) + // Holds the RemoteTensorHandles referred by args. + std::vector> remote_args; +#endif // IS_MOBILE_PLATFORM + }; + + // Structure detailing the asynchronous assumptions of a component function, + // such as whether it can support synchronous execution and any information + // needed to execute in proper order to resolve inter-subgraph dependencies. + class AsyncAttributes { + public: + enum Summary { kSafeForSync = 0, kSendOnly, kRecvOnly, kAsyncRequired }; + + AsyncAttributes() + : allow_control_flow_sync_execution_(false), summary_(kSafeForSync) {} + explicit AsyncAttributes(const Graph* graph, + bool allow_control_flow_sync_execution) + : allow_control_flow_sync_execution_(allow_control_flow_sync_execution), + summary_(Summarize(graph)) {} + Summary summary() const { return summary_; } + bool allow_control_flow_sync_execution() const { + return allow_control_flow_sync_execution_; + } + + private: + // This data member should be initialized before the summary_. + bool allow_control_flow_sync_execution_; + Summary summary_; + Summary Summarize(const Graph* graph); + }; + + // Structure to keep track of how a component function (a single-device + // piece of a multi-device function) fits into the multi-device function. + struct ComponentFunctionData { + // The handle for the instantiated component function. + FunctionLibraryRuntime::Handle handle; + // arg_indices.size() is the number of arguments to the component function. + // The i-th argument of the component function comes from the + // `arg_indices[i]`-th argument of the multi-device function. + std::vector arg_indices; + // ret_indices.size() is the number of return values of the component + // function. The i-th return value of the component function goes to the + // `ret_indices[i]`-th return value of the multi-device function. + std::vector ret_indices; + // arg_alloc_attrs[i] are the allocator attributes of the i-th argument to + // the component function. + std::vector arg_alloc_attrs; + // ret_alloc_attrs[i] are the allocator attributes of the i-th return value + // of the component function. + std::vector ret_alloc_attrs; + + AsyncAttributes async_attributes; + }; + + // Data structure holding information for a single instantiated multi-device + // function. + // The fields are filled in during instantiation. Once the object is + // added to mdevice_data_, all fields are constant. + struct MultiDeviceFunctionData { + MultiDeviceFunctionData(const string& function_name, + const string& function_key, int num_outputs, + FunctionLibraryDefinition&& lib_def, + DataTypeVector ret_types) + : function_name_(function_name), + function_key_(function_key), + instantiation_counter_(1), + lib_def_(std::move(lib_def)), + num_outputs_(num_outputs), + ret_types_(std::move(ret_types)), + is_cross_process_(false), + has_remote_outputs(false) {} + + const string function_name_; + const string function_key_; + uint64 instantiation_counter_; + // A library that contains definitions of component functions and their + // transitive dependencies. + FunctionLibraryDefinition lib_def_; + // Stored here to resize the output tensor vector when function is run. + const int num_outputs_; + DataTypeVector ret_types_; + + // Indicates whether this function needs to execute cross process. + bool is_cross_process_; + // Indicates whether this function has remote outputs. + bool has_remote_outputs; + + // Indicates if running this function synchronously is both allowed + safe. + bool enable_sync_execution; + + // Maps the device name to the information about the component function + // be run on this device. + std::unordered_map glue_; + }; + + struct CleanUpItem { + string device; + uint64 step_id; + FunctionLibraryRuntime::Handle local_handle; + }; + + // If `handle` represents a multi-device function, returns the multi-device + // data associated with `handle`. Else, nullptr. + MultiDeviceFunctionData* IsMultiDevice( + FunctionLibraryRuntime::Handle handle) const; + + DistributedFunctionLibraryRuntime* const parent_; + + private: + FunctionLibraryRuntime::Handle AddHandleLocked( + const string& function_key, const string& device_name, + FunctionLibraryRuntime::LocalHandle local_handle) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + // For a given device_name, returns a DeviceContext for copying + // tensors to/from the device. + Status GetDeviceContext(const string& device_name, + DeviceContext** device_context) const; + + // Looks up the information for the given `handle` and returns the name + // of the device where the function is registered. + string GetDeviceName(FunctionLibraryRuntime::Handle handle) const; + + // Removes handle from the state owned by this object. + Status RemoveHandle(FunctionLibraryRuntime::Handle handle); + + // Clones ProcessFunctionLibraryRuntime and FunctionLibraryDefinition + // (transferring ownership of both to the caller). Note that the + // ProcessFunctionLibraryRuntime borrows a pointer to the + // FunctionLibraryDefinition and so the FunctionLibraryDefinition should + // outlive the ProcessFunctionLibraryRuntime. + // + // The `skip_flib_def` argument controls whether the method should clone the + // FunctionLibraryDefinition (default behavior) or return an empty function + // library. The latter is used by tf.data, which manages + // FunctionLibraryDefinitions for its functions independently (and passes + // these into the FunctionLibraryRuntime through an overlay), to avoid linear + // runtime w.r.t. to number of functions in the current function library. + Status Clone(Env* env, int graph_def_version, + const OptimizerOptions& optimizer_options, + std::unique_ptr* out_lib_def, + std::unique_ptr* out_pflr, + bool skip_flib_def = false) const; + + Status ReleaseMultiDeviceHandle(FunctionLibraryRuntime::Handle handle); + + Status InstantiateMultiDevice( + const string& function_name, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + FunctionLibraryRuntime::Handle* handle); + + void InstantiateRemote( + const string& function_name, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + FunctionLibraryRuntime::Handle* handle, + FunctionLibraryRuntime::DoneCallback done); + + FunctionLibraryRuntime::Handle AddMultiDeviceHandle( + const std::unique_ptr data, + const string& function_key); + + bool HasMultiDeviceHandle(FunctionLibraryRuntime::Handle handle) const; + + void RunInternal(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, + gtl::ArraySlice args, + std::vector* rets, + std::vector>* cleanup_items, + FunctionLibraryRuntime::DoneCallback done) const; + + Status CreateRendezvous( + FunctionLibraryRuntime::Options& opts, + tsl::core::RefCountPtr* created_rendezvous) const; + + FunctionLibraryRuntime::DoneCallback ApplyCleanUpToDoneCallback( + std::vector>* items, + FunctionLibraryRuntime::DoneCallback done, + const FunctionLibraryRuntime::Options& opts, + tsl::core::RefCountPtr rendezvous) const; + + void CleanUp(std::vector>* items, + FunctionLibraryRuntime::DoneCallback done) const; + + static Status GetComponentArgs(gtl::ArraySlice args, + const ComponentFunctionData& comp_data, + InternalArgs* comp_args); + +#if !defined(IS_MOBILE_PLATFORM) + static Status GetComponentArgs(const FunctionArgsInterface& args, + const ComponentFunctionData& comp_data, + InternalArgs* comp_args); +#endif // IS_MOBILE_PLATFORM + + std::vector GetOrderedSubgraphs( + const MultiDeviceFunctionData* data) const; + + Status PrepareRunMultiDevice(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, + const MultiDeviceFunctionData** data) const; + + Status RunMultiDeviceSync( + const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, std::vector* rets, + std::function + get_component_args) const; + + void RunMultiDeviceAsync( + const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::Handle handle, std::vector* rets, + std::vector>* cleanup_items, + FunctionLibraryRuntime::DoneCallback done, + std::function + get_component_args) const; + + void PublishSubgraphs( + const std::string& function_name, + std::unique_ptr>> + subgraphs); + + // Data structure holding information for a single instantiated remote + // (to be executed on `target_device`) function. + class FunctionData { + public: + FunctionData(const string& target_device, + FunctionLibraryRuntime::LocalHandle local_handle, + const string& function_key) + : target_device_(target_device), + local_handle_(local_handle), + function_key_(function_key) {} + + const string& target_device() { return target_device_; } + const string& function_key() { return function_key_; } + + FunctionLibraryRuntime::LocalHandle local_handle() { + mutex_lock l(mu_); + return local_handle_; + } + + // Initializes the FunctionData object by potentially making an Initialize + // call to the DistributedFunctionLibraryRuntime. + void DistributedInit( + DistributedFunctionLibraryRuntime* parent, const string& function_name, + const FunctionLibraryDefinition& lib_def, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + FunctionLibraryRuntime::DoneCallback done); + + bool is_cross_process() { + mutex_lock l(mu_); + return is_cross_process_; + } + + private: + mutex mu_; + + const string target_device_; + FunctionLibraryRuntime::LocalHandle local_handle_ TF_GUARDED_BY(mu_); + const string function_key_; + bool is_cross_process_ TF_GUARDED_BY(mu_) = false; + bool init_started_ TF_GUARDED_BY(mu_) = false; + Status init_result_ TF_GUARDED_BY(mu_); + Notification init_done_; + }; + + mutable mutex mu_; + + Env* const env_; + const std::optional config_; + const DeviceMgr* const device_mgr_; + const FunctionLibraryDefinition* lib_def_; + thread::ThreadPool* default_thread_pool_; + + // Cluster update can reinitialize the device_set_ due to remote device + // changes. At the same time, InstantiateMultiDevice can use the cached + // devices to instantiate multi-worker functions. Function instantiation would + // fail if it spans the changed remote devices. + std::shared_ptr device_set_ TF_GUARDED_BY(mu_); + + // Composite devices owned by a EagerContext. + std::vector composite_devices_ TF_GUARDED_BY(mu_); + + // Holds all the function instantiations. Maps function_keys to handles. + std::unordered_map table_ + TF_GUARDED_BY(mu_); + + // Function data for instantiated remote functions. + std::unordered_map> + function_data_ TF_GUARDED_BY(mu_); + + // Function data for instantiated multi-device functions. + std::unordered_map> + mdevice_data_ TF_GUARDED_BY(mu_); + + std::unique_ptr< + std::unordered_map>> + flr_map_; + int next_handle_ TF_GUARDED_BY(mu_); + const SessionMetadata* const session_metadata_; + const Rendezvous::Factory rendezvous_factory_; + + const OptimizerOptions optimizer_options_; + const int graph_def_version_; + + StatsPublisherFactory stats_publisher_factory_; + // Holds all stats publishers, one for publishing subgraphs of each + // instantiated function. + std::vector> stats_publishers_ + TF_GUARDED_BY(mu_); + std::vector> stats_publisher_completed_ + TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PROCESS_FUNCTION_LIBRARY_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_state.h new file mode 100644 index 0000000000000000000000000000000000000000..dd667cc236a8e9b0e82a0c435b2027de352606df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_state.h @@ -0,0 +1,161 @@ +/* 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_COMMON_RUNTIME_PROCESS_STATE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PROCESS_STATE_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/allocator_registry.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +class PoolAllocator; + +// Singleton that manages per-process state, e.g. allocation of +// shared resources. +class ProcessState : public ProcessStateInterface { + public: + static ProcessState* singleton(); + + // Descriptor for memory allocation attributes, used by optional + // runtime correctness analysis logic. + struct MemDesc { + enum MemLoc { CPU, GPU }; + MemLoc loc; + int dev_index; + bool gpu_registered; + bool nic_registered; + MemDesc() + : loc(CPU), + dev_index(0), + gpu_registered(false), + nic_registered(false) {} + string DebugString(); + }; + + // If NUMA Allocators are desired, call this before calling any + // Allocator accessor. + void EnableNUMA() { numa_enabled_ = true; } + + // Returns what we know about the memory at ptr. + // If we know nothing, it's called CPU 0 with no other attributes. + MemDesc PtrType(const void* ptr); + + // Returns the one CPUAllocator used for the given numa_node. + // Treats numa_node == kNUMANoAffinity as numa_node == 0. + Allocator* GetCPUAllocator(int numa_node) override; + + // Registers alloc visitor for the CPU allocator(s). + // REQUIRES: must be called before GetCPUAllocator. + void AddCPUAllocVisitor(SubAllocator::Visitor v); + + // Registers free visitor for the CPU allocator(s). + // REQUIRES: must be called before GetCPUAllocator. + void AddCPUFreeVisitor(SubAllocator::Visitor v); + + typedef std::unordered_map MDMap; + + protected: + ProcessState(); + virtual ~ProcessState() {} + friend class GPUProcessState; + friend class PluggableDeviceProcessState; + + // If these flags need to be runtime configurable consider adding + // them to ConfigProto. + static constexpr bool FLAGS_brain_mem_reg_gpu_dma = true; + static constexpr bool FLAGS_brain_gpu_record_mem_types = false; + + // Helper method for unit tests to reset the ProcessState singleton by + // cleaning up everything. Never use in production. + void TestOnlyReset(); + + static ProcessState* instance_; + bool numa_enabled_; + + mutex mu_; + + // Indexed by numa_node. If we want numa-specific allocators AND a + // non-specific allocator, maybe should index by numa_node+1. + std::vector cpu_allocators_ TF_GUARDED_BY(mu_); + std::vector cpu_alloc_visitors_ TF_GUARDED_BY(mu_); + std::vector cpu_free_visitors_ TF_GUARDED_BY(mu_); + + // A cache of cpu allocators indexed by a numa node. Used as a fast path to + // get CPU allocator by numa node id without locking the mutex. We can't use + // `cpu_allocators_` storage in the lock-free path because concurrent + // operation can deallocate the vector storage. + std::atomic cpu_allocators_cached_; + std::array cpu_allocators_cache_; + + // Optional RecordingAllocators that wrap the corresponding + // Allocators for runtime attribute use analysis. + MDMap mem_desc_map_; + std::vector cpu_al_ TF_GUARDED_BY(mu_); +}; + +namespace internal { +class RecordingAllocator : public Allocator { + public: + RecordingAllocator(ProcessState::MDMap* mm, Allocator* a, + ProcessState::MemDesc md, mutex* mu) + : mm_(mm), a_(a), md_(md), mu_(mu) {} + + string Name() override { return a_->Name(); } + void* AllocateRaw(size_t alignment, size_t num_bytes) override { + void* p = a_->AllocateRaw(alignment, num_bytes); + mutex_lock l(*mu_); + (*mm_)[p] = md_; + return p; + } + void DeallocateRaw(void* p) override { + mutex_lock l(*mu_); + auto iter = mm_->find(p); + mm_->erase(iter); + a_->DeallocateRaw(p); + } + bool TracksAllocationSizes() const override { + return a_->TracksAllocationSizes(); + } + size_t RequestedSize(const void* p) const override { + return a_->RequestedSize(p); + } + size_t AllocatedSize(const void* p) const override { + return a_->AllocatedSize(p); + } + absl::optional GetStats() override { return a_->GetStats(); } + bool ClearStats() override { return a_->ClearStats(); } + + AllocatorMemoryType GetMemoryType() const override { + return a_->GetMemoryType(); + } + + ProcessState::MDMap* mm_; // not owned + Allocator* a_; // not owned + ProcessState::MemDesc md_; + mutex* mu_; +}; +} // namespace internal +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PROCESS_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_util.h new file mode 100644 index 0000000000000000000000000000000000000000..cc2bc4390793c0658f372c60bc66b523437261fd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/process_util.h @@ -0,0 +1,64 @@ +/* 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_COMMON_RUNTIME_PROCESS_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PROCESS_UTIL_H_ + +#include + +#include "absl/functional/any_invocable.h" +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/public/session_options.h" + +// TODO(vrv, mrry): Remove this library: its interface circumvents the +// callers' Env and calls Env::Default() directly. + +namespace tensorflow { + +// Returns a process-wide ThreadPool for scheduling compute operations +// using 'options'. Caller does not take ownership over threadpool. +thread::ThreadPool* ComputePool(const SessionOptions& options); + +// Returns the TF_NUM_INTEROP_THREADS environment value, or 0 if not specified. +int32 NumInterOpThreadsFromEnvironment(); + +// Returns the TF_NUM_INTRAOP_THREADS environment value, or 0 if not specified. +int32 NumIntraOpThreadsFromEnvironment(); + +// Returns the number of inter op threads specified in `options` or a default. +// If no value or a negative value is specified in the provided options, then +// the function returns the value defined in the TF_NUM_INTEROP_THREADS +// environment variable. If neither a value is specified in the options or in +// the environment, this function will return a reasonable default value based +// on the number of schedulable CPUs, and any MKL and OpenMP configurations. +int32 NumInterOpThreadsFromSessionOptions(const SessionOptions& options); + +// Creates a thread pool with number of inter op threads. +// The number is set if `num_threads` > 0, otherwise it will be configured by +// SessionOptions. +thread::ThreadPool* NewThreadPoolFromSessionOptions( + const SessionOptions& options, int32_t num_threads = 0); + +// Schedule "closure" in the default thread queue. +void SchedClosure(absl::AnyInvocable closure); + +// Schedule "closure" after the given number of microseconds in the +// fixed-size ThreadPool used for non-blocking compute tasks. +void SchedNonBlockingClosureAfter(int64_t micros, + absl::AnyInvocable closure); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PROCESS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/profile_handler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/profile_handler.h new file mode 100644 index 0000000000000000000000000000000000000000..391dc8c19878b7fddf22f1c0950460005033c129 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/profile_handler.h @@ -0,0 +1,67 @@ +/* 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_COMMON_RUNTIME_PROFILE_HANDLER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_PROFILE_HANDLER_H_ + +#include "tensorflow/core/framework/step_stats.pb.h" +#include "tensorflow/core/graph/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" + +namespace tensorflow { + +// A profile handler collects event stats from a running step. +class ProfileHandler { + public: + ProfileHandler() {} + virtual ~ProfileHandler() {} + + // Records that a single Op was executed in the current step. + // + // Implementations of this method must be thread-safe. + // + // Args: + // - device: Device on which the Op was executed. + // - stats: Statistics of node execution timing. + // - is_copy: True if the op was a copy, send or recv. + // - label: Extra content for timeline click text. + // - op_type: String name of the Op. + // - details: Main content for timeline click text. + virtual void RecordOneOp(const string& device, const NodeExecStats& stats, + bool is_copy, StringPiece label, StringPiece op_type, + StringPiece details) = 0; + + // Records that the current step finished. + // + // Implementations of this method need not be thread-safe. + // + // Args: + // - start_time: The time at which the step started. + // - finish_time: The time at which the step finished. + // - cleanup_time: The time at which cleanup for the step finished. + // - total_runops: The number of ops that ran during this step. + // - final_status: The status that this step finished with. + virtual void StepDone(Microseconds start_time, Microseconds finish_time, + Microseconds cleanup_time, int total_runops, + Status final_status) = 0; + + // Returns true if the caller should collect rpc activity. + virtual bool should_collect_rpcs() = 0; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_PROFILE_HANDLER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/quantize_training.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/quantize_training.h new file mode 100644 index 0000000000000000000000000000000000000000..4013caef4126385b50c1663f297aead4f1eb6555 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/quantize_training.h @@ -0,0 +1,57 @@ +/* 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_COMMON_RUNTIME_QUANTIZE_TRAINING_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_QUANTIZE_TRAINING_H_ + +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { +// Rewrites graph for quantized training. +// Rewrites the forward pass to include the precision loss with quantization so +// the model can learn to deal with such loss and achieve better accuracy when +// it is quantized later for inference. +// Note that the num_bits should be in [1, 63] and 'g' must be not null. +// quant_op_type specifies which quantization op should be used. +// Current ops supported: +// - QuantizeAndDequantizeV2. +// - FakeQuantWithMinMaxVars. +// +// On success, returns OK. +// +// On failure, returns the error status. Possible errors include: +// - num_bits out of range. +// - g is null. +// - More than 1 unknown ops encountered. +Status DoQuantizeTraining(int32_t num_bits, const string& quant_op_type, + Graph* g); + +// Converts the input serialized GraphDef and returns a rewritten serialized +// GraphDef for quantized training. +Status DoQuantizeTrainingOnSerializedGraphDef(const string& input_graph, + int32_t num_bits, + const string& quant_op_type, + string* result_graph); + +// Converts the input GraphDef and returns a rewritten GraphDef for quantized +// training. +Status DoQuantizeTrainingOnGraphDef(const GraphDef& input_graphdef, + int32_t num_bits, + const string& quant_op_type, + GraphDef* result_graphdef); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_QUANTIZE_TRAINING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/renamed_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/renamed_device.h new file mode 100644 index 0000000000000000000000000000000000000000..d67bdf228108f45d6c3aecff646cce86367ead19 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/renamed_device.h @@ -0,0 +1,173 @@ +/* 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_COMMON_RUNTIME_RENAMED_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_RENAMED_DEVICE_H_ + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/lib/core/threadpool_interface.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace tensorflow { + +// Wraps a device with a new name, delegating work to the wrapped device. +// +// This class is used to wrap local devices when using clusterspec propagation +// where the name of a particular device may change in the context of a given +// session. +class RenamedDevice : public Device { + public: + static std::unique_ptr NewRenamedDevice( + const string& new_base, Device* underlying, bool owns_underlying, + bool isolate_session_state, + thread::ThreadPoolInterface* underlying_threadpool = nullptr); + + ~RenamedDevice() override; + + const DeviceBase* UnderlyingDevice() const override { + return underlying_device_->UnderlyingDevice(); + } + DeviceBase* UnderlyingDevice() override { + return underlying_device_->UnderlyingDevice(); + } + + const CpuWorkerThreads* tensorflow_cpu_worker_threads() const override { + if (underlying_threadpool_) { + return Device::tensorflow_cpu_worker_threads(); + } + return underlying_device_->tensorflow_cpu_worker_threads(); + } + + const DeviceBase::AcceleratorDeviceInfo* tensorflow_accelerator_device_info() + const override { + return underlying_device_->tensorflow_accelerator_device_info(); + } + + Allocator* GetAllocator(AllocatorAttributes attr) override { + return underlying_device_->GetAllocator(attr); + } + + Allocator* GetScopedAllocator(AllocatorAttributes attr, + int64_t step_id) override { + return underlying_device_->GetScopedAllocator(attr, step_id); + } + + ScopedAllocatorMgr* GetScopedAllocatorMgr() const override { + return underlying_device_->GetScopedAllocatorMgr(); + } + + const Eigen::ThreadPoolDevice* eigen_cpu_device() override { + // Use the underlying threadpool only if the underlying device supports + // eigen_cpu_device. + if (underlying_threadpool_ && underlying_device_->has_eigen_cpu_device()) { + return Device::eigen_cpu_device(); + } + return underlying_device_->eigen_cpu_device(); + } + + thread::ThreadPool* tensorflow_device_thread_pool() override { + // Use the underlying threadpool instead of tensorflow_device_thread_pool + // of the underlying device only if tensorflow_device_thread_pool is defined + // for the underlying device. + if (underlying_threadpool_ && + underlying_device_->tensorflow_device_thread_pool() != nullptr) { + return Device::tensorflow_device_thread_pool(); + } + return underlying_device_->tensorflow_device_thread_pool(); + } + + bool has_eigen_cpu_device() const override { + return underlying_device_->has_eigen_cpu_device(); + } + + + PerOpGpuDevice* MakeGpuDevice() override { + return underlying_device_->MakeGpuDevice(); + } + + Status ReinitializeGpuDevice(OpKernelContext* context, PerOpGpuDevice* device, + DeviceContext* dc, + Allocator* allocator) override { + return underlying_device_->ReinitializeGpuDevice(context, device, dc, + allocator); + } + + Status MakeTensorFromProto(const TensorProto& tensor_proto, + const AllocatorAttributes alloc_attrs, + Tensor* tensor) override { + return underlying_device_->MakeTensorFromProto(tensor_proto, alloc_attrs, + tensor); + } + + void CopyTensorInSameDevice(const Tensor* input_tensor, Tensor* output_tensor, + const DeviceContext* device_context, + StatusCallback done) override { + underlying_device_->CopyTensorInSameDevice(input_tensor, output_tensor, + device_context, std::move(done)); + } + + // Below are virtual methods defined on Device + + void Compute(OpKernel* op_kernel, OpKernelContext* context) override { + underlying_device_->Compute(op_kernel, context); + } + + void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context, + AsyncOpKernel::DoneCallback done) override { + underlying_device_->ComputeAsync(op_kernel, context, std::move(done)); + } + + Status Sync() override { return underlying_device_->Sync(); } + + Status MaybeRewriteGraph(std::unique_ptr* graph) override { + return underlying_device_->MaybeRewriteGraph(graph); + } + + Status TryGetDeviceContext(DeviceContext** out_context) override { + return underlying_device_->TryGetDeviceContext(out_context); + } + + // Returns the resource manager associated w/ this device. + ResourceMgr* resource_manager() override { + if (isolate_session_state_) { + return Device::resource_manager(); + } else { + return underlying_device_->resource_manager(); + } + } + + bool IsLocal() const override { return underlying_device_->IsLocal(); } + + bool IsRemoteCallAllowed() const override { + return underlying_device_->IsRemoteCallAllowed(); + } + + private: + RenamedDevice(Device* underlying, const DeviceAttributes& attributes, + bool owns_underlying, bool isolate_session_state, + thread::ThreadPoolInterface* underlying_threadpool); + Device* const underlying_device_; + const bool owns_underlying_device_; + const bool isolate_session_state_; + + std::unique_ptr underlying_threadpool_; + // eigen_worker_threads_ is stored here so that we can pass the pointer + // of eigen_worker_threads_.workers to the parent class. + DeviceBase::CpuWorkerThreads eigen_worker_threads_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_RENAMED_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/rendezvous_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/rendezvous_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..a6e70fcab911010a872ffa775c82af2d2d22c1f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/rendezvous_mgr.h @@ -0,0 +1,106 @@ +/* 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_COMMON_RUNTIME_RENDEZVOUS_MGR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_MGR_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/framework/local_rendezvous.h" +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// The IntraProcessRendezvous classes are implementations of a Rendezvous that +// expects all producers and consumers to be devices immediately accessible +// within the process. That is, it will never be necessary to perform an RPC to +// communicate with either. +// +// Buffering of Tensor values is delegated to a `LocalRendezvous`. An +// IntraProcessRendezvous. just adds functionality to coordinate multiple +// process-local devices. + +// Reference-counted implementation that may be shared between multiple threads. +class RefCountedIntraProcessRendezvous : public Rendezvous { + public: + explicit RefCountedIntraProcessRendezvous(const DeviceMgr* device_mgr); + + // Implementation of RendezvousInterface methods. + // NOTE: The methods may clear the Item list and destroy 'this' if there are + // no other references to the RefCountedIntraProcessRendezvous object. + // If the caller intend to keep a longer life time then it shall keep its own + // reference to the RefCountedIntraProcessRendezvous. + Status Send(const ParsedKey& key, const Rendezvous::Args& args, + const Tensor& val, const bool is_dead) override; + void RecvAsync(const ParsedKey& key, const Rendezvous::Args& args, + DoneCallback done) override; + void StartAbort(const Status& status) override; + + // Returns the member LocalRendezvous' status. + Status GetLocalRendezvousStatus(); + + inline void UpdateDeviceManager(DeviceMgr* device_mgr) { + device_mgr_ = device_mgr; + } + + private: + const DeviceMgr* device_mgr_; // Not owned. + LocalRendezvous local_; + + ~RefCountedIntraProcessRendezvous() override; + + RefCountedIntraProcessRendezvous(const RefCountedIntraProcessRendezvous&) = + delete; + void operator=(const RefCountedIntraProcessRendezvous&) = delete; +}; + +// RefCountedIntraProcessRendezvous is aliased to IntraProcessRendezvous for +// backwards compatibility with existing users. +using IntraProcessRendezvous = RefCountedIntraProcessRendezvous; + +// Non-reference-counted implementation that may be stack-allocated for +// performance. +// +// Prefer to use PrivateIntraProcessRendezvous in new code. +class PrivateIntraProcessRendezvous : public RendezvousInterface { + public: + explicit PrivateIntraProcessRendezvous(const DeviceMgr* device_mgr); + ~PrivateIntraProcessRendezvous() override; + + // Implementation of RendezvousInterface methods. + Status Send(const ParsedKey& key, const Rendezvous::Args& args, + const Tensor& val, const bool is_dead) override; + void RecvAsync(const ParsedKey& key, const Rendezvous::Args& args, + DoneCallback done) override; + void StartAbort(const Status& status) override; + + private: + const DeviceMgr* device_mgr_; + LocalRendezvous local_; + + PrivateIntraProcessRendezvous(const PrivateIntraProcessRendezvous&) = delete; + void operator=(const PrivateIntraProcessRendezvous&) = delete; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/rendezvous_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/rendezvous_util.h new file mode 100644 index 0000000000000000000000000000000000000000..fe95dc0ef57c85972949c85fd2072e0f72d9ee6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/rendezvous_util.h @@ -0,0 +1,54 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_UTIL_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_UTIL_H_ + +#include + +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +typedef std::map NamedTensors; +typedef std::function StatusCallback; + +// Uses `rendezvous` to send tensors in `tensors_to_send`. `device_context` +// should be the DeviceContext associated with the source of the tensors. +// `alloc_attrs` contains information about how the `tensors_to_send` are +// allocated. `alloc_attrs` should either be {} or should match the length of +// `keys`. +Status SendTensorsToRendezvous( + RendezvousInterface* rendezvous, DeviceContext* device_context, + const std::vector& alloc_attrs, + const std::vector& keys, gtl::ArraySlice tensors_to_send); + +// Uses `rendezvous` to obtain tensors. `device_context` should be the +// DeviceContext associated with the receiving device. `alloc_attrs` contains +// information as how to store the received tensors. Should be {} or match the +// length of `keys`. +void RecvOutputsFromRendezvousAsync( + RendezvousInterface* rendezvous, DeviceContext* device_context, + const std::vector& alloc_attrs, + const std::vector& keys, std::vector* received_tensors, + StatusCallback done); + +Status RecvOutputsFromRendezvous(RendezvousInterface* rendezvous, + NamedTensors* out, + const Rendezvous::Args& args); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/replicate_constants_pass.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/replicate_constants_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..b7b2f0fe98c0d205c0c8bbf90cb652bdf0c40fa0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/replicate_constants_pass.h @@ -0,0 +1,50 @@ +/* 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_COMMON_RUNTIME_REPLICATE_CONSTANTS_PASS_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_REPLICATE_CONSTANTS_PASS_H_ + +#include "tensorflow/core/common_runtime/optimization_registry.h" + +// Small constants are replicated to the hosts of their successors. This pass +// only applies when there are multiple successors. +// +// For example, the graph: +// C -> {Op0, Op1, Op2, Op3} +// C's assigned_device is /job:tpu_host_worker/replica:0/task:0/device:CPU:0 +// Op0's assigned_device is /job:tpu_host_worker/replica:0/task:0/device:TPU:0 +// Op1's assigned_device is /job:tpu_host_worker/replica:0/task:0/device:TPU:1 +// Op2's assigned_device is /job:tpu_host_worker/replica:0/task:1/device:TPU:0 +// Op3's assigned_device is /job:tpu_host_worker/replica:0/task:1/device:TPU:1 +// is rewritten to: +// C0 -> {Op0, Op1} +// C1 -> {Op2, Op3} +// C0's assigned_device is /job:tpu_host_worker/replica:0/task:0/device:CPU:0 +// C1's assigned_device is /job:tpu_host_worker/replica:0/task:1/device:CPU:0 +// Op0's assigned_device is /job:tpu_host_worker/replica:0/task:0/device:TPU:0 +// Op1's assigned_device is /job:tpu_host_worker/replica:0/task:0/device:TPU:1 +// Op2's assigned_device is /job:tpu_host_worker/replica:0/task:1/device:TPU:0 +// Op3's assigned_device is /job:tpu_host_worker/replica:0/task:1/device:TPU:1 + +namespace tensorflow { + +class ReplicateConstantsPass : public GraphOptimizationPass { + public: + Status Run(const GraphOptimizationPassOptions& options) override; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_REPLICATE_CONSTANTS_PASS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/replicate_per_replica_nodes.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/replicate_per_replica_nodes.h new file mode 100644 index 0000000000000000000000000000000000000000..fd696db4905e9af6bdc682cf5b77ab25bf0792c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/replicate_per_replica_nodes.h @@ -0,0 +1,44 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_REPLICATE_PER_REPLICA_NODES_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_REPLICATE_PER_REPLICA_NODES_H_ + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// `composite_device` maps from a virtual device to a set of devices. +// In a function graph, for each node assigned to a composite device +// (representing N devices), replace it with N replicated nodes (one per +// device). +// REQUIREMENTS: +// 1) Each node has been assigned to a device (including composite device). +// 2) Each cluster of nodes assigned to a composite device should include at +// least one "_Arg" node. +// composite device. +// 3) Clusters assigned to different composite devices should have no data +// dependency. +// TODO(b/145922293): Register it as a POST_REWRITE_FOR_EXEC pass. +Status ReplicatePerReplicaNodesInFunctionGraph( + const absl::flat_hash_map*>& + composite_devices, + Graph* graph); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_REPLICATE_PER_REPLICA_NODES_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost.h new file mode 100644 index 0000000000000000000000000000000000000000..c67827014663eb3a66376cfa21efe22515b49bb4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost.h @@ -0,0 +1,78 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_H_ + +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" +#include "absl/time/time.h" + +namespace tensorflow { + +// RequestCost collects the costs and metrics for processing an rpc request. +class RequestCost { + public: + // Records costs. The inputs should be pairs of cost type and cost. + // It's thread-safe, and can be called from different threads. + void RecordCost( + const std::vector>& costs); + + // Gets all types of costs for processing an rpc request. + // It's thread-safe. It's expected to be called at the end of processing an + // rpc request, when all the costs have been collected. + absl::flat_hash_map GetCosts() const; + + // Metrics of each batch that processes this rpc request. + struct BatchMetrics { + // Size of the batch. + int64_t processed_size = 0; + // In this batch, input size from this rpc request. + int64_t input_size = 0; + // In this batch, the padding amount. + int64_t padding_size = 0; + }; + + // Records the metrics of a batch. + // It's thread-safe, and can be called from different threads. It may be + // called multiple times if a request is processed by more than one batches. + void RecordBatchMetrics(const BatchMetrics& batch_metrics); + + // Get metrics of all the batches that process this rpc request. + // It's thread-safe. It's expected to be called at the end of processing an + // rpc request, when all batch processing has completed. + std::vector GetBatchMetrics() const; + + private: + mutable absl::Mutex mutex_; + + // Query costs. Map from cost type to cost. + absl::flat_hash_map cost_map_ + ABSL_GUARDED_BY(mutex_); + + // Metrics of batches that process this rpc request. + std::vector batch_metrics_ ABSL_GUARDED_BY(mutex_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor.h new file mode 100644 index 0000000000000000000000000000000000000000..ba64da4b296a7b94fd6239da6ed435baf3a49734 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor.h @@ -0,0 +1,37 @@ +/* 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_COMMON_RUNTIME_REQUEST_COST_ACCESSOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_ACCESSOR_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/time/time.h" +#include "tensorflow/core/common_runtime/request_cost.h" + +namespace tensorflow { + +// An interface for accessing the RequestCost associated with the current rpc +// request. +class RequestCostAccessor { + public: + virtual ~RequestCostAccessor() {} + virtual RequestCost* GetRequestCost() const = 0; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_ACCESSOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..6e91678f8ae136a309ad88a41cfa79ea09eda32e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/request_cost_accessor_registry.h @@ -0,0 +1,71 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_ACCESSOR_REGISTRY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_ACCESSOR_REGISTRY_H_ + +#include +#include +#include + +#include "absl/memory/memory.h" +#include "absl/strings/string_view.h" +#include "tensorflow/core/common_runtime/request_cost_accessor.h" + +namespace tensorflow { + +// TODO(b/185852990): Create a template Registry that allows registering +// different types (e.g RequestCostAccessor, CostMeasurement). +// +// RequestCostAccessorRegistry allows to +// - register a RequestCostAccessor type to the global map +// - create an instance of registered RequestCostAccessor. +class RequestCostAccessorRegistry { + public: + // Creates an instance of registered RequestCostAccessor by name. If the named + // RequestCostAccessor is not registered yet, returns nullptr. + static std::unique_ptr CreateByNameOrNull( + absl::string_view name); + + using Creator = std::function()>; + + // Registers a RequestCostAccessor type to the global map. Registering + // different types of RequestCostAccessor with the same name is prohibited. + static void RegisterRequestCostAccessor(absl::string_view name, + Creator creator); +}; + +// Registers a RequestCostAccessor type to the global map. Registering different +// types of RequestCostAccessor with the same name is prohibited. +class RequestCostAccessorRegistrar { + public: + explicit RequestCostAccessorRegistrar( + absl::string_view name, RequestCostAccessorRegistry::Creator creator) { + RequestCostAccessorRegistry::RegisterRequestCostAccessor( + name, std::move(creator)); + } +}; + +#define REGISTER_REQUEST_COST_ACCESSOR(name, MyRequestCostAccessorClass) \ + namespace { \ + static ::tensorflow::RequestCostAccessorRegistrar \ + MyRequestCostAccessorClass##_registrar((name), [] { \ + return std::make_unique(); \ + }); \ + } // namespace + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_REQUEST_COST_ACCESSOR_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_alg.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_alg.h new file mode 100644 index 0000000000000000000000000000000000000000..a5d5f2931d81f3ac1377d096a8d4eeeceef782f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_alg.h @@ -0,0 +1,120 @@ +/* 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_COMMON_RUNTIME_RING_ALG_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_RING_ALG_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/base_collective_executor.h" +#include "tensorflow/core/framework/collective.h" + +namespace tensorflow { +class Device; + +// Basic ring-algorithm implementation to be further specialized +// for specific collective functions. +class RingAlg : public CollectiveImplementationInterface { + public: + explicit RingAlg(CollectiveType type, const string& name); + ~RingAlg() override {} + + // Establishes the requested number of subdivision permutations based on the + // ring order implicit in the device order. + Status InitializeCollectiveParams(CollectiveParams* col_params) override; + + // Initializes members of CollectiveContext not yet initialized, i.e. device + // and device_locality. Also saves the CollectiveContext in this object. + Status InitializeCollectiveContext( + std::shared_ptr col_ctx) override; + + protected: + // Called when a bad status is received that implies we should terminate + // execution and return a bad status. + void StartAbort(const Status& s); + void Finish(bool ok); + + // Current status of a RingField + enum RingFieldAction { + RF_INIT = 0, // Just initialized for a pass + RF_RECV, // Recv pending + RF_REDUCE, // Reduce pending + RF_FINALIZE, // FinalOp pending + RF_SEND_READY, // Ready to send + RF_SEND, // Send pending + RF_DONE, // No more work + }; + + // Tracks progress of actions on a single subfield of the entire tensor. + struct RingField { + int16 chunk_idx; // major division index + int16 subdiv_idx; // minor division index + int16 sc_idx; // subchunk index + int16 rank; // rank within subdiv permutation + int16 recv_dev_idx; // dev from which value should be recv'd + RingFieldAction action; + bool second_pass; + bool recv_is_remote = false; + bool send_is_remote = false; + bool do_send = false; // is the value sent in this pass? + bool do_recv = false; // is the value recv'd in this pass? + bool is_final = false; // is the last field in the pass for this rank + Tensor chunk; // alias to field values + Tensor tmp_chunk; + Status status; + string DebugString() const; + }; + virtual void InitRingField(RingField* rf, int chunk_idx, int subdiv_idx, + int field_idx); + void AdvanceToSecondPass(RingField* rf); + void DispatchSend(RingField* rf, const StatusCallback& done); + void DispatchRecv(RingField* rf, const StatusCallback& done); + + // For constructing log messages for debugging. + string FieldState(); + string TensorDebugString(const Tensor& tensor); + + // Producer/Consumer Queue of RingField structs. + class PCQueue { + public: + void Enqueue(RingField* rf); + RingField* Dequeue(); + + private: + mutex pcq_mu_; + condition_variable cv_; + int waiter_count_ TF_GUARDED_BY(pcq_mu_) = 0; + std::deque deque_ TF_GUARDED_BY(pcq_mu_); + }; + + const CollectiveType type_; + const string name_; + std::shared_ptr col_ctx_; + const CollectiveParams* col_params_; // Not owned + StatusCallback done_; + int group_size_; + int num_subdivs_; + Tensor group_size_tensor_; + Notification group_size_tensor_ready_; + std::unique_ptr ca_; + mutex status_mu_; + Status status_ TF_GUARDED_BY(status_mu_); + std::vector rfv_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_RING_ALG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_gatherer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_gatherer.h new file mode 100644 index 0000000000000000000000000000000000000000..ee9634834d2b6c9d986cfb1841ae03c51e22564b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_gatherer.h @@ -0,0 +1,51 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_RING_GATHERER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_RING_GATHERER_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/base_collective_executor.h" +#include "tensorflow/core/common_runtime/ring_alg.h" +#include "tensorflow/core/framework/collective.h" + +namespace tensorflow { +class Device; + +// Ring-algorithm implementation of collective all-gather. +class RingGatherer : public RingAlg { + public: + RingGatherer() : RingAlg(GATHER_COLLECTIVE, "Gather") {} + ~RingGatherer() override {} + + Status InitializeCollectiveParams(CollectiveParams* col_params) override; + + // Begins async execution of the ring gather algorithm. + // Must be called in a blockable thread. + // TODO(b/80529858): remove the previous warning when we have a dedicated + // collective threadpool. + void Run(StatusCallback done) override; + + private: + bool RunAsyncParts(); + + friend class RingGathererTest; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_RING_GATHERER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_reducer.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_reducer.h new file mode 100644 index 0000000000000000000000000000000000000000..e7b869398bf7faaa6d418fe158ccef3c5218556e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/ring_reducer.h @@ -0,0 +1,60 @@ +/* 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_COMMON_RUNTIME_RING_REDUCER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_RING_REDUCER_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/base_collective_executor.h" +#include "tensorflow/core/common_runtime/ring_alg.h" +#include "tensorflow/core/framework/collective.h" + +namespace tensorflow { +class Device; + +// Ring-algorithm implementation of collective all-reduce. +class RingReducer : public RingAlg { + public: + RingReducer() : RingAlg(REDUCTION_COLLECTIVE, "Reduce") {} + ~RingReducer() override; + + // Begins async execution of the ring reduce algorithm. + // Must be called in a blockable thread. + // TODO(b/80529858): remove the previous warning when we have a dedicated + // collective threadpool. + void Run(StatusCallback done) override; + + Status InitializeCollectiveParams(CollectiveParams* col_params) override; + + protected: + void InitRingField(RingField* rf, int chunk_idx, int subdiv_idx, + int field_idx) override; + + private: + void ContinueAfterInputCopy(); + bool RunAsyncParts(); + + Tensor group_size_tensor_; + Notification group_size_tensor_ready_; + + friend class RingReducerTest; + friend class RingReducerInitParamsTest; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_RING_REDUCER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/scoped_allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/scoped_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..15e581024c9cd85c806ae5570fb82e0cfded11e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/scoped_allocator.h @@ -0,0 +1,127 @@ +/* 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_COMMON_RUNTIME_SCOPED_ALLOCATOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_SCOPED_ALLOCATOR_H_ + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { +class ScopedAllocatorContainer; +class ScopedAllocatorInstance; + +// Manages a single backing tensor and a collection of aliases. +class ScopedAllocator { + public: + static constexpr int32_t kInvalidId = 0; + static constexpr size_t kMaxAlignment = 64; + + // A subrange of the TensorBuffer associated with this object that + // will be the backing memory for one aliased tensor. + struct Field { + int32 scope_id; + size_t offset; + size_t bytes_requested; + size_t bytes_allocated; + }; + // Field index that refers to backing tensor, not any aliased field. + static constexpr int32_t kBackingIndex = -1; + + // backing_tensor is expected to be newly allocated by a ScopedAllocatorOp + // instance. It must be large enough to back all of the specified + // (offset, byte) ranges of the fields. + ScopedAllocator(const Tensor& backing_tensor, int32_t scope_id, + const std::string& name, const gtl::ArraySlice fields, + int32_t expected_call_count, + ScopedAllocatorContainer* container); + + // Automatically deletes when last use expires, or when + // ScopedAllocatorContainer decides to delete. + ~ScopedAllocator() TF_LOCKS_EXCLUDED(mu_); + + // For debugging: returns true iff p is a pointer that could have + // been returned by AllocateRaw. + bool VerifyPointer(const void* p); + bool VerifyTensor(const Tensor* t); + + const Tensor& tensor() const { return backing_tensor_; } + + const std::string& name() const { return name_; } + + private: + friend class ScopedAllocatorInstance; + // Only ScopedAllocatorInstances can call AllocateRaw and DeallocateRaw on a + // ScopedAllocator + void* AllocateRaw(int32_t field_index, size_t num_bytes) + TF_LOCKS_EXCLUDED(mu_); + void DeallocateRaw(void* p) TF_LOCKS_EXCLUDED(mu_); + Tensor backing_tensor_; + TensorBuffer* tbuf_; + int32 id_; + std::string name_; + ScopedAllocatorContainer* container_; + std::vector fields_; + mutex mu_; + int32 expected_call_count_ TF_GUARDED_BY(mu_); + int32 live_alloc_count_ TF_GUARDED_BY(mu_); +}; + +// An Allocator that will return a pointer into the backing buffer of +// a previously allocated tensor, allowing creation of an alias +// tensor. There is a one-to-one mapping between the fields of a +// ScopedAllocator and ScopedAllocatorInstances. There is also a one-to-one +// mapping between scope_ids and ScopedAllocatorInstances. It should be +// discarded immediately after a single use. +class ScopedAllocatorInstance : public Allocator { + public: + explicit ScopedAllocatorInstance(ScopedAllocator* sa, int32_t field_index); + + private: + ~ScopedAllocatorInstance() override { + VLOG(1) << "~ScopedAllocatorInstance " << this; + } + + public: + // When a ScopedAllocatorContainer "Drops" a scope_id, it calls DropFromTable + // on the underlying ScopedAllocatorInstance. If this instance has already + // deallocated the tensor slice, we can safely delete this. + void DropFromTable() TF_LOCKS_EXCLUDED(mu_); + void* AllocateRaw(size_t alignment, size_t num_bytes) + TF_LOCKS_EXCLUDED(mu_) override; + void* AllocateRaw(size_t alignment, size_t num_bytes, + const AllocationAttributes& allocator_attr) override { + return AllocateRaw(alignment, num_bytes); + } + void DeallocateRaw(void* p) TF_LOCKS_EXCLUDED(mu_) override; + bool TracksAllocationSizes() const override { return false; } + size_t RequestedSize(const void* ptr) const override { return 0; } + size_t AllocatedSize(const void* ptr) const override { return 0; } + int64_t AllocationId(const void* ptr) const override { return 0; } + size_t AllocatedSizeSlow(const void* ptr) const override { return 0; } + std::string Name() override; + + private: + mutex mu_; + ScopedAllocator* scoped_allocator_; + int32 field_index_; + bool allocated_ TF_GUARDED_BY(mu_); + bool deallocated_ TF_GUARDED_BY(mu_); + bool in_table_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SCOPED_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/scoped_allocator_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/scoped_allocator_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..b8e5dcb15649fc77a94e43e1122557b9ff71d433 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/scoped_allocator_mgr.h @@ -0,0 +1,111 @@ +/* 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_COMMON_RUNTIME_SCOPED_ALLOCATOR_MGR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_SCOPED_ALLOCATOR_MGR_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/scoped_allocator.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { +class ScopedAllocatorMgr; + +// At most one of these exists per pair. +// A Ref is held by every ScopedAllocator and also by the ScopedAllocatorMgr. +class ScopedAllocatorContainer : public core::RefCounted { + public: + // Establishes a reachable ScopedAllocator. + Status AddScopedAllocator( + const Tensor& backing_tensor, int32_t scope_id, + const std::string& scope_name, + const gtl::ArraySlice& fields, + int32_t expected_call_count); + + ScopedAllocatorInstance* GetInstance(int32_t scope_id); + ScopedAllocator* GetAllocator(int32_t scope_id); + + // Retire the scope_id. + void Drop(int32_t scope_id, ScopedAllocator* sa); + + protected: + friend class ScopedAllocatorMgr; + ScopedAllocatorContainer(const ScopedAllocatorMgr* mgr, int64_t step_id) + : mgr_(mgr), step_id_(step_id) {} + ~ScopedAllocatorContainer(); + + private: + const ScopedAllocatorMgr* mgr_; + int64_t step_id_; + mutex mu_; + struct SAField { + int32 field_index; + union { + ScopedAllocator* scoped_allocator; + ScopedAllocatorInstance* instance; + }; + SAField(int32_t fi, ScopedAllocatorInstance* sai) + : field_index(fi), instance(sai) {} + SAField(int32_t fi, ScopedAllocator* sa) + : field_index(fi), scoped_allocator(sa) {} + SAField() + : field_index(ScopedAllocator::kBackingIndex), + scoped_allocator(nullptr) {} + }; + std::unordered_map allocators_ TF_GUARDED_BY(mu_); +}; + +// At most one of these exists per device. +class ScopedAllocatorMgr { + public: + explicit ScopedAllocatorMgr(const std::string& device_name) + : device_name_(device_name) {} + ~ScopedAllocatorMgr(); + + ScopedAllocatorContainer* GetContainer(int64_t step_id); + + // Establishes a reachable ScopedAllocator. + Status AddScopedAllocator( + const Tensor& backing_tensor, int64_t step_id, int32_t scope_id, + const std::string& scope_name, + const gtl::ArraySlice& fields, + int32_t expected_call_count); + + void Cleanup(int64_t step_id); + + // Populate the bytes and offset members of Field. Instance allocaters get + // consecutive scope_id values following that of the base ScopedAllocator. + // Returns the total number of bytes required to be allocated in the + // backing tensor, for convenience. (The same value can be obtained + // by summing offset and bytes in the last field.) + static size_t PopulateFields(int32_t scope_id, + const gtl::ArraySlice& shapes, + const DataType dtype, + std::vector* fields); + + const std::string& device_name() const { return device_name_; } + + private: + std::string device_name_; + mutex mu_; + std::unordered_map per_step_map_ + TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SCOPED_ALLOCATOR_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/session_factory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/session_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..8976abd1a818d94892689dbf78b580ea1e6536ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/session_factory.h @@ -0,0 +1,76 @@ +/* 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_COMMON_RUNTIME_SESSION_FACTORY_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_SESSION_FACTORY_H_ + +#include + +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +class Session; +struct SessionOptions; + +class SessionFactory { + public: + // Creates a new session and stores it in *out_session, or fails with an error + // status if the Session could not be created. Caller takes ownership of + // *out_session if this returns OkStatus(). + virtual Status NewSession(const SessionOptions& options, + Session** out_session) = 0; + + virtual bool AcceptsOptions(const SessionOptions& options) = 0; + + // Abort and close all existing sessions, disconnecting their resources from + // future sessions. + // + // Reset() allows misbehaving or slow sessions to be aborted and closed, and + // causes their resources eventually to be released. Reset() does not wait + // for the computations in old sessions to cease; it merely starts the + // process of tearing them down. However, if a new session is started after + // a Reset(), the new session is isolated from changes that old sessions + // (started prior to the Reset()) may continue to make to resources, provided + // all those resources are in containers listed in "containers". + // + // Old sessions may continue to have side-effects on resources not in + // containers listed in "containers", and thus may affect future + // sessions' results in ways that are hard to predict. Thus, if well-defined + // behavior is desired, is it recommended that all containers be listed in + // "containers". + // + // If the "containers" vector is empty, the default container is assumed. + // If the "containers" vector is non-empty, the default container should be + // listed explicitly. + // + // Sessions that support resource containers should override this function. + virtual Status Reset(const SessionOptions& options, + const std::vector& containers) { + return errors::Unimplemented("Reset()"); + } + + virtual ~SessionFactory() {} + static void Register(const string& runtime_type, SessionFactory* factory); + static Status GetFactory(const SessionOptions& options, + SessionFactory** out_factory); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SESSION_FACTORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/shape_refiner.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/shape_refiner.h new file mode 100644 index 0000000000000000000000000000000000000000..29ade55ea9b417d0f3c793bff539bf52445382af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/shape_refiner.h @@ -0,0 +1,336 @@ +/* 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_COMMON_RUNTIME_SHAPE_REFINER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_SHAPE_REFINER_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/common_runtime/graph_runner.h" +#include "tensorflow/core/framework/function.pb.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { +namespace grappler { +class GraphProperties; +} + +// This class stores extra inference information in addition to +// InferenceContext, such as node input and output types. +class ExtendedInferenceContext { + public: + ExtendedInferenceContext( + std::unique_ptr ic, const Node* node) + : inference_context_(std::move(ic)), op_(node->name()) { + input_types_.reserve(node->num_inputs()); + for (int i = 0; i < node->num_inputs(); i++) { + input_types_.push_back(node->input_type(i)); + } + output_types_.reserve(node->num_outputs()); + for (int i = 0; i < node->num_outputs(); i++) { + output_types_.push_back(node->output_type(i)); + } + } + + DataType input_type(int64_t idx) const { return input_types_[idx]; } + DataType output_type(int64_t idx) const { return output_types_[idx]; } + + shape_inference::InferenceContext* get_context() { + return inference_context_.get(); + } + + std::string op() const { return op_; } + + private: + std::unique_ptr inference_context_; + std::string op_; + std::vector input_types_; + std::vector output_types_; + + ExtendedInferenceContext(const ExtendedInferenceContext&) = delete; + void operator=(const ExtendedInferenceContext&) = delete; +}; + +// ShapeRefiner performs shape inference for TensorFlow Graphs. It is +// responsible for instantiating InferenceContext objects for each +// Node in the Graph, and providing/storing the 'input_tensor' Tensors +// used by Shape Inference functions, when available at graph +// construction time. +class ShapeRefiner { + public: + ShapeRefiner(int graph_def_version, const OpRegistryInterface* ops); + + // Same as ShapeRefiner(versions.producer(), ops) + ShapeRefiner(const VersionDef& versions, const OpRegistryInterface* ops); + + ~ShapeRefiner(); + + // Performs validation of 'node' and runs 'node's shape function, + // storing its shape outputs. + // + // All inputs of 'node' must be added to ShapeRefiner prior to + // adding 'node'. + // + // Returns an error if: + // - the shape function for 'node' was not registered. + // - 'node' was added before its inputs. + // - The shape inference function returns an error. + Status AddNode(const Node* node); + + // Sets 'node's 'output_port' output to have shape 'shape'. + // + // Returns an error if 'node' was not previously added to this + // object, if 'output_port' is invalid, or if 'shape' is + // not compatible with the existing shape of the output. + Status SetShape(const Node* node, int output_port, + shape_inference::ShapeHandle shape); + + // Update the input shapes of node in case the shapes of the fan-ins of 'node' + // have themselves been modified (For example, in case of incremental shape + // refinement). If 'relax' is true, a new shape with the broadest set of + // information will be set as the new input (see InferenceContext::RelaxInput + // for full details and examples). Sets refined to true if any shapes have + // changed (in their string representations). Note that shapes may have been + // updated to newer versions (but with identical string representations) even + // if <*refined> is set to false. + Status UpdateNode(const Node* node, bool relax, bool* refined); + + // Returns the InferenceContext for 'node', if present. + shape_inference::InferenceContext* GetContext(const Node* node) const { + auto it = node_to_context_.find(node); + if (it == node_to_context_.end()) { + return nullptr; + } + return it->second->get_context(); + } + + // Returns the ExtendedInferenceContext for 'node', if present. + ExtendedInferenceContext* GetExtendedContext(const Node* node) const { + auto it = node_to_context_.find(node); + if (it == node_to_context_.end()) { + return nullptr; + } + return it->second.get(); + } + + // Getters and setters for graph_def_version_. + int32 graph_def_version() const { return graph_def_version_; } + void set_graph_def_version(int32_t version) { graph_def_version_ = version; } + + void set_require_shape_inference_fns(bool require_shape_inference_fns) { + require_shape_inference_fns_ = require_shape_inference_fns; + } + void set_disable_constant_propagation(bool disable) { + disable_constant_propagation_ = disable; + } + + // Set function library to enable function shape inference. + // Without function library, function inference always yields unknown shapes. + // With this enabled, shape inference can take more time since it descends + // into all function calls. It doesn't do inference once for each function + // definition, but once for each function call. + // The function library must outlive the shape refiner. + void set_function_library_for_shape_inference( + const tensorflow::FunctionLibraryDefinition* lib) { + function_library_ = lib; + } + + bool function_shape_inference_supported() const { + return function_library_ != nullptr; + } + + private: + friend class ShapeRefinerTest; + friend class ::tensorflow::grappler::GraphProperties; + + // Returns true if the ranks and all dimensions of and are either + // equal in value or both unknown. + static bool SameDefinedShape(shape_inference::InferenceContext* c, + shape_inference::ShapeHandle s0, + shape_inference::ShapeHandle s1); + + // Returns true if the shapes and types stored in <*existing> are identical in + // value to the shapes and types in <*updated>. + static bool IsUpdatedShapesOrTypes( + shape_inference::InferenceContext* c, + const std::vector& existing, + const std::vector& updated); + + // Performs shape inference for the given function_def within the + // given outer_context. Internally it instantiates the function as a graph + // and runs shape inference recursively on it with the input shapes provided + // by the outer_context. + // + // Returns an error if: + // - number of inputs/outputs on outer_context doesn't match the function_def + // + // On success: + // - outer_context will contain output shapes inferred from input shapes + Status InferShapesForFunction( + const FunctionDef* function_def, AttrSlice attributes, + shape_inference::InferenceContext* outer_context); + + // Performs shape inference for a node inside a function. + // + // 'outer_context' is the 'InferenceContext' for the function's call op. + Status InferShapesForFunctionSubNode( + const Node* node, shape_inference::InferenceContext* outer_context); + + // Performs validation of 'node' and runs 'node's shape function, + // storing its shape outputs. + // + // All inputs of 'node' must be added to ShapeRefiner prior to + // adding 'node'. + // + // Optionally, if 'node' is in a nested function, the 'InferenceContext' for + // the call op of the function can be passed as 'outer_context' (pass nullptr + // otherwise). This gets used to perform constant propagation across Arg nodes + // by requesting the constant of value of the incoming tensor from the + // 'outer_context'. + // + // Returns an error if: + // - the shape function for 'node' was not registered. + // - 'node' was added before its inputs. + // - The shape inference function returns an error. + Status AddNodeInternal(const Node* node, + shape_inference::InferenceContext* outer_context); + + // Attempts to evaluate the 'dst_idx'-th input to 'node'. If the input edge + // value can be evaluated, 'evaluated' is set to true and the value returned + // in 'result'. Otherwise 'evaluated' is set to false. + // + // Optionally, if 'node' is in a nested function, the 'InferenceContext' for + // the call op of the function can be passed as 'outer_context' (pass nullptr + // otherwise). This gets used to perform constant propagation across Arg nodes + // by requesting the constant of value of the incoming tensor from the + // 'outer_context'. + Status EvaluateConstantTensorForEdge( + const Node* node, int dst_idx, bool* evaluated, Tensor* result, + shape_inference::InferenceContext* outer_context); + + // Wrapper around EvaluateConstantTensorForEdge for scalar int32/int64 input + // tensors. The caller is responsible for checking that the specified edge is + // scalar and int32 or int64. + // + // Optionally, if 'node' is in a nested function, the 'InferenceContext' for + // the call op of the function can be passed as 'outer_context' (pass nullptr + // otherwise). This gets used to perform constant propagation across Arg nodes + // by requesting the constant of value of the incoming tensor from the + // 'outer_context'. + Status EvaluateConstantIntScalarEdge( + const Node* node, int dst_idx, bool* evaluated, int64_t* result, + shape_inference::InferenceContext* outer_context); + + // This function tries to materialize as much information about the 'node''s + // dst_idx input as a statically computable shape, and the result may be + // partially known, depending on what is statically inferable. + // + // This is called when node.input[dst_idx] is a tensor that is used to define + // the shape of some other tensor (e.g., the second argument to Reshape is a + // tensor, where each element of the shape tensor is a dimension of + // the target tensor). It returns in a shape for that input. + // + // Unlike simply resolving node.input[dst_idx] to a constant and then + // converting that to a shape, this function can return a partial shape. This + // is useful for cases where the shape tensor is only partially defined, such + // as with calls for: reshape(x, shape(y)) where shape(y) is partially + // defined. + // + // The implementation has op implementations for ops commonly called on shape + // tensors, and the implementations are specialized to shape tensors (namely, + // the output is a vector). + // + // is used when creating new DimensionHandle and ShapeHandle + // objects. + // + // Optionally, if 'node' is in a nested function, the 'InferenceContext' for + // the call op of the function can be passed as 'outer_context' (pass nullptr + // otherwise). This gets used to perform constant propagation across Arg nodes + // by requesting the constant of value of the incoming tensor from the + // 'outer_context'. + Status ConstantPartialShape(shape_inference::InferenceContext* target_context, + const Node* node, int dst_idx, + shape_inference::ShapeHandle* result, + shape_inference::InferenceContext* outer_context); + + // Implementation of ConstantPartialShape for StridedSlice nodes. + // + // Optionally, if 'node' is in a nested function, the 'InferenceContext' for + // the call op of the function can be passed as 'outer_context' (pass nullptr + // otherwise). This gets used to perform constant propagation across Arg nodes + // by requesting the constant of value of the incoming tensor from the + // 'outer_context'. + Status PartialStridedSliceShape( + Node* slice_node, shape_inference::InferenceContext* ctx, + shape_inference::ShapeHandle* result, + shape_inference::InferenceContext* outer_context); + + // Runs the shape function registered for the node's op type. + // + // Optionally, if 'node' is in a nested function, the 'InferenceContext' for + // the call op of the function can be passed as 'outer_context' (pass nullptr + // otherwise). This gets used to perform constant propagation across Arg nodes + // by requesting the constant of value of the incoming tensor from the + // 'outer_context'. + Status RunShapeFn(const Node* node, const OpRegistrationData* op_reg_data, + ExtendedInferenceContext* ec, + shape_inference::InferenceContext* outer_context = nullptr); + + int32 graph_def_version_; + const OpRegistryInterface* const ops_registry_; + + // The lifetime of the tensors are bound to the runner, so it should be the + // deleted after the tensors. + GraphRunner graph_runner_; + + // Stores a map from a node to its ExtendedInferenceContext. + absl::flat_hash_map, + hash> + node_to_context_; + + // Holds a cache from tensor id (node id:node output) to the tensor that + // is evaluable as a constant expression. This reduces repeated execution + // of the entire constant subgraph as a graph is being built up. This could + // be changed to some kind of size-based LRU cache to avoid consuming too much + // memory, if that eventually becomes a concern. + // + // Only tensors less than 1KiB are currently stored in the cache. + static constexpr int64_t kMaxTensorSize = 1024; + absl::flat_hash_map, Tensor> const_tensor_map_; + + bool require_shape_inference_fns_ = true; + bool disable_constant_propagation_ = false; + + // Function library is optional, but has to be set to enable function + // shape inference. + const tensorflow::FunctionLibraryDefinition* function_library_ = nullptr; + + // Cache the graph corresponding to each function definition for which shapes + // are refined. + absl::flat_hash_map> functions_; + + ShapeRefiner(const ShapeRefiner&) = delete; + void operator=(const ShapeRefiner&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SHAPE_REFINER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/shared_counter.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/shared_counter.h new file mode 100644 index 0000000000000000000000000000000000000000..7931dba4661cb96ae6895083cdf7c2ffc9203041 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/shared_counter.h @@ -0,0 +1,26 @@ +/* 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_COMMON_RUNTIME_SHARED_COUNTER_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_SHARED_COUNTER_H_ + +#include + +#include "tensorflow/core/platform/types.h" +#include "tsl/framework/shared_counter.h" + +namespace tensorflow { +using tsl::SharedCounter; // NOLINT +} // namespace tensorflow +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SHARED_COUNTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/single_threaded_cpu_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/single_threaded_cpu_device.h new file mode 100644 index 0000000000000000000000000000000000000000..3498e4aa6ea2e684c21003de634414c9339aac06 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/single_threaded_cpu_device.h @@ -0,0 +1,36 @@ +/* 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_COMMON_RUNTIME_SINGLE_THREADED_CPU_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_SINGLE_THREADED_CPU_DEVICE_H_ + +namespace tsl { +class Env; +} // namespace tsl +namespace tensorflow { +using Env = tsl::Env; + +class Device; + +// Returns a simple single-threaded CPU device. This can be used to run +// inexpensive computations. In particular, using this avoids initializing the +// global thread pools in LocalDevice. +// +// The returned pointer is owned by the caller. +Device* NewSingleThreadedCpuDevice(Env* env); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_SINGLE_THREADED_CPU_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/stats_publisher_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/stats_publisher_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..6f771068101ec7d3a971dca4822a240e46939148 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/stats_publisher_interface.h @@ -0,0 +1,82 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_STATS_PUBLISHER_INTERFACE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_STATS_PUBLISHER_INTERFACE_H_ + +#include +#include +#include + +#include "tensorflow/core/common_runtime/build_graph_options.h" +#include "tensorflow/core/common_runtime/profile_handler.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { + +class StatsPublisherInterface; + +typedef std::function( + const std::string&, const BuildGraphOptions&, const SessionOptions&)> + StatsPublisherFactory; + +// StatsPublisherInterface describes objects that publish information exported +// by Sessions. +// NOTE: This interface is experimental and subject to change. +// Implementations must be thread-safe. +class StatsPublisherInterface { + public: + // PublishStatsProto publishes step_stats. + // When PublishStatsProto is called multiple times, only the step_stats + // corresponding to the latest call will be published. + virtual void PublishStatsProto(const StepStats& step_stats) = 0; + + // PublishGraphProto publishes the graph_defs corresponding to each partition + // in the session. + // When PublishGraphProto is called multiple times, only the graph_defs + // corresponding to the latest call will be published. + virtual void PublishGraphProto( + const std::vector& graph_defs) = 0; + virtual void PublishGraphProto(std::vector graph_defs) = 0; + + // Returns a profile handler for the given step based on the execution_count + // and RunOptions. + // + // This method may return a null pointer, if no handler was created. + virtual std::unique_ptr GetProfileHandler( + uint64 step, int64_t execution_count, const RunOptions& ropts) = 0; + + virtual ~StatsPublisherInterface() {} + + static void RegisterStatsPublisher(StatsPublisherFactory factory_fn); + + static StatsPublisherFactory GetStatsPublisherFactory(); + + private: + static StatsPublisherFactory** GetStatsPublisherFactoryPtr() { + static StatsPublisherFactory* stats_publisher_factory = nullptr; + return &stats_publisher_factory; + } +}; + +std::unique_ptr CreateNoOpStatsPublisher( + const string& session, const BuildGraphOptions& bopts, + const SessionOptions& sopts); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_STATS_PUBLISHER_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/step_stats_collector.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/step_stats_collector.h new file mode 100644 index 0000000000000000000000000000000000000000..df1e579f6d89327dc259962d1c8c47c78d06671d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/step_stats_collector.h @@ -0,0 +1,208 @@ +/* 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_COMMON_RUNTIME_STEP_STATS_COLLECTOR_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_STEP_STATS_COLLECTOR_H_ + +#include +#include +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/step_stats.pb.h" +#include "tensorflow/core/framework/tracking_allocator.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +class AllocatorMemoryUsed; +class CostModelManager; +class Graph; +class NodeDef; +class NodeExecStats; +class OpKernelContext; +class StepStats; +class StepStatsCollector; +class Tensor; + +// Statistics collection interface for individual node execution. +// +// See `NodeExecStatsWrapper` for a concrete implementation of this interface +// that interfaces with the `Session` layer. +class NodeExecStatsInterface { + public: + virtual ~NodeExecStatsInterface() {} + + // Called when the statistics collection for the node has finished. Once this + // method is called, the caller should not make assumptions about the validity + // of this object. + virtual void Done(const string& device) = 0; + + // Called immediately after this node starts being processed by the executor. + virtual void RecordExecutorStarted() = 0; + + // Called immediately before this node's `Compute()` or `ComputeAsync()` + // method is called. + virtual void RecordComputeStarted() = 0; + + // Called immediately after this node's `Compute()` method returned (or, for + // asynchronous operations, the callback passed to its `ComputeAsync()` method + // was called). + virtual void RecordComputeEnded() = 0; + + // Called immediately after this executor finishes processing this node. + virtual void RecordExecutorEnded() = 0; + + // Returns `true` if this object should track memory allocations. + virtual bool TrackAllocations() const = 0; + + // Records information about the memory allocated during the execution of this + // node. + // + // Takes ownership of any `TrackingAllocator` objects stored in `ctx`. + virtual void SetMemory(OpKernelContext* ctx) = 0; + + // Records information about the tensor produced by this node at the given + // output slot. + virtual void SetOutput(int slot, const Tensor* tensor) = 0; + + // Records the absolute time in nanoseconds at which this node became + // runnable (i.e. was scheduled for execution). + virtual void SetScheduled(int64_t nanos) = 0; +}; + +// Wraps NodeExecStats and adds allocation to it. +class NodeExecStatsWrapper : public NodeExecStatsInterface { + public: + // Does not take ownership of `node` or `step_stats_collector`. + NodeExecStatsWrapper(const NodeDef* node, + StepStatsCollector* step_stats_collector); + + // Takes ownership of 'stats' but not `node` or `step_stats_collector`. + NodeExecStatsWrapper(std::unique_ptr stats, + const NodeDef* node, + StepStatsCollector* step_stats_collector); + + // Destructor calls Finalize() to release the TrackingAllocators. + ~NodeExecStatsWrapper() override { Finalize(); } + + void Done(const string& device) override; + void RecordExecutorStarted() override; + void RecordComputeStarted() override; + void RecordComputeEnded() override; + void RecordExecutorEnded() override; + bool TrackAllocations() const override { return true; } + void SetMemory(OpKernelContext* ctx) override; + void SetOutput(int slot, const Tensor* tensor) override; + void SetScheduled(int64_t nanos) override; + + private: + friend class StepStatsCollector; + + NodeExecStats* stats() { return stats_.get(); } + + // Populates stats_ and releases TrackingAllocator. + void Finalize(); + + // Does not take ownership of the `allocator`. + // Takes ownership of `tracking_allocator`. + void AddAllocation(Allocator* allocator, + TrackingAllocator* tracking_allocator); + + gtl::InlinedVector, 2> + allocations_; + std::unique_ptr stats_; + const NodeDef* const node_; // Not owned. + StepStatsCollector* const step_stats_collector_; // Not owned. +}; + +// Statistics collection interface for step execution. +// +// See `StepStatsCollector` for a concrete implementation of this interface +// that interfaces with the `Session` layer. +class StepStatsCollectorInterface { + public: + virtual ~StepStatsCollectorInterface() {} + + // Creates an instance of `NodeExecStatsInterface` that should be used for + // collecting statistics about individual node execution. + virtual NodeExecStatsInterface* CreateNodeExecStats(const NodeDef* node) = 0; + + // Generates a string reporting the currently used memory based + // on ResourceExhausted OOM `err` message. + // `err` message needs to contain device name and allocator name, e.g.: + // "ResourceExhaustedError: OOM when allocating tensor ... + // on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc" + virtual string ReportAllocsOnResourceExhausted(absl::string_view err) = 0; +}; + +// StepStatsCollector manages the collection of a StepStats object. +// The StepStats object holds multiple DeviceStats. +// Each DeviceStats object holds multiple NodeExecStats. +class StepStatsCollector : public StepStatsCollectorInterface { + public: + // Does not take ownership of `step_stats`. + explicit StepStatsCollector(StepStats* step_stats); + + // BuildCostModel builds or updates a CostModel managed by cost_model_manager, + // using the currently collected DeviceStats associated with the devices in + // device_map. + void BuildCostModel( + CostModelManager* cost_model_manager, + const std::unordered_map& device_map); + + // Saves node statistics to the DeviceStats object associated with device. + // Should be called before Finalize. + void Save(const string& device, NodeExecStats* node_stats_pb); + void Save(const string& device, NodeExecStatsWrapper* node_stats); + + // Saves thread name. + void SaveThreadName(const string& device, const uint32 thread_id, + const string& thread_name); + + NodeExecStatsInterface* CreateNodeExecStats(const NodeDef* node) override; + string ReportAllocsOnResourceExhausted(absl::string_view err) override; + + // The following 2 Finalize methods populate the StepStats passed + // from the constructor. Calling it more than once won't have any effect. + // User shouldn't call Save() methods after Finalize. + void Finalize(); + // swaps the content of StepStats* from constructor with 'ss'. + void FinalizeAndSwap(StepStats* step_stats); + + private: + // TODO(suharshs): Make this configurable if its not possible to find a value + // that works for all cases. + static constexpr uint64 kMaxCollectedNodes = 1 << 20; + + typedef std::vector> NodeStatsVector; + typedef std::unordered_map ThreadNamesMap; + + void FinalizeInternal() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + mutex mu_; + bool finalized_ TF_GUARDED_BY(mu_); + std::unordered_map dev_stats_ TF_GUARDED_BY(mu_); + std::unordered_map thread_names_ TF_GUARDED_BY(mu_); + StepStats* step_stats_ TF_GUARDED_BY(mu_); + uint64 collected_nodes_ TF_GUARDED_BY(mu_) = 0; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_STEP_STATS_COLLECTOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/threadpool_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/threadpool_device.h new file mode 100644 index 0000000000000000000000000000000000000000..5ca3deb7247602bfdecc83ac77f23cd4f5f98b8b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/common_runtime/threadpool_device.h @@ -0,0 +1,63 @@ +/* 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_COMMON_RUNTIME_THREADPOOL_DEVICE_H_ +#define TENSORFLOW_CORE_COMMON_RUNTIME_THREADPOOL_DEVICE_H_ + +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/common_runtime/local_device.h" +#include "tensorflow/core/common_runtime/node_file_writer.h" + +namespace tensorflow { + +// CPU device implementation. +class ThreadPoolDevice : public LocalDevice { + public: + ThreadPoolDevice(const SessionOptions& options, const string& name, + Bytes memory_limit, const DeviceLocality& locality, + Allocator* allocator); + ~ThreadPoolDevice() override; + + Allocator* GetAllocator(AllocatorAttributes attr) override; + Allocator* GetScopedAllocator(AllocatorAttributes attr, + int64_t step_id) override; + ScopedAllocatorMgr* GetScopedAllocatorMgr() const override { + return scoped_allocator_mgr_.get(); + } + Status MakeTensorFromProto(const TensorProto& tensor_proto, + const AllocatorAttributes alloc_attrs, + Tensor* tensor) override; + void CopyTensorInSameDevice(const Tensor* input_tensor, Tensor* output_tensor, + const DeviceContext* device_context, + StatusCallback done) override; + + Status Sync() override { return OkStatus(); } + + void Compute(OpKernel* op_kernel, OpKernelContext* context) override; + void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context, + AsyncOpKernel::DoneCallback done) override; + + private: + void LogInputs(OpKernel* op_kernel, OpKernelContext* context); + void LogOutputs(OpKernel* op_kernel, OpKernelContext* context); + + Allocator* allocator_; // Not owned + std::unique_ptr scoped_allocator_mgr_; + NodeFileWriter* node_file_writer_ = nullptr; // not owned +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_COMMON_RUNTIME_THREADPOOL_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/config/flag_defs.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/config/flag_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..14ae3cbf24e7328ec1f03385207b37690f69b77d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/config/flag_defs.h @@ -0,0 +1,64 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_CONFIG_FLAG_DEFS_H_ +#define TENSORFLOW_CORE_CONFIG_FLAG_DEFS_H_ + +#include "tensorflow/core/config/flags.h" + +namespace tensorflow { +namespace flags { + +class Flags { + public: + // Test only flags. See flags_test.cc for example usage. + TF_DECLARE_FLAG(test_only_experiment_1, true, "Test only experiment 1."); + TF_DECLARE_FLAG(test_only_experiment_2, false, "Test only experiment 2."); + + // Declare flags below here. + // LINT.IfChange + TF_DECLARE_FLAG(enable_nested_function_shape_inference, false, + "Allow ops such as tf.cond to invoke the ShapeRefiner on " + "their nested functions."); + TF_DECLARE_FLAG(enable_quantized_dtypes_training, false, + "Set quantized dtypes, like tf.qint8, to be trainable."); + TF_DECLARE_FLAG(graph_building_optimization, false, + "Optimize graph building for faster tf.function tracing."); + TF_DECLARE_FLAG( + op_building_optimization, true, + "Optimize tf.Operation building for faster tf.function tracing."); + TF_DECLARE_FLAG(saved_model_fingerprinting, true, + "Add fingerprint to SavedModels."); + TF_DECLARE_FLAG( + tf_shape_default_int64, false, + "The default output of tf.shape (i.e. when out_type is not specified) is " + "int64 when this flag is true and int32 otherwise. Setting this to true " + "is an unsupported, experimental setting that causes known breakages."); + TF_DECLARE_FLAG(more_stack_traces, false, + "Enable experimental code that preserves and propagates " + "graph node stack traces in C++."); + TF_DECLARE_FLAG(replicate_small_constants, true, + "Enable a graph optimization pass that replicate each small " + "constant to its successors' devices. This can decrease " + "message passing."); + // LINT.ThenChange(//tensorflow/core/config/flags_api_wrapper.cc) +}; + +Flags& Global(); + +} // namespace flags +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_CONFIG_FLAG_DEFS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/config/flags.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/config/flags.h new file mode 100644 index 0000000000000000000000000000000000000000..3a01e65f12b294953684d756d097008cb61ca354 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/config/flags.h @@ -0,0 +1,47 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_CONFIG_FLAGS_H_ +#define TENSORFLOW_CORE_CONFIG_FLAGS_H_ + +#include "tensorflow/core/platform/stringpiece.h" + +namespace tensorflow { +namespace config { + +// Container class for a single feature flag. +// Note: this class is not thread safe. +class Flag { + public: + explicit Flag(StringPiece flag_name, bool default_value); + bool value() { return value_; } + void reset(bool value) { value_ = value; } + + private: + bool value_; +}; + +// Macro to declare new flags. Declare all flags in core/config/flag_defs.h +// These flags can be overridden by setting the associated environment variable +// TF_FLAG_* flag to true or false. E.g. setting TF_FLAG_MY_FLAG=false will +// override the default value for a flag named `my_flag` to false. +#define TF_DECLARE_FLAG(flag_name, default_value, doc) \ + ::tensorflow::config::Flag flag_name = \ + ::tensorflow::config::Flag("TF_FLAG_" #flag_name, default_value); + +} // namespace config +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_CONFIG_FLAGS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/captured_function.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/captured_function.h new file mode 100644 index 0000000000000000000000000000000000000000..c3d489dd8552639986acc4eec638057096e12c6c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/captured_function.h @@ -0,0 +1,322 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_CAPTURED_FUNCTION_H_ +#define TENSORFLOW_CORE_DATA_CAPTURED_FUNCTION_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/model.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/lib/random/random.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +class Device; +class OpKernelContext; +class ResourceMgr; + +namespace data { + +class CapturedFunction; +class InstantiatedCapturedFunction; + +// Creates an iterator for a dataset which is created by applying the given +// function to the given input element. +Status MakeIteratorFromInputElement( + IteratorContext* ctx, const IteratorBase* parent, + const std::vector& input_element, int64_t thread_index, + const InstantiatedCapturedFunction& inst_captured_func, StringPiece prefix, + std::unique_ptr* out_iterator); + +// Creates an iterator for a dataset which is created by applying the given +// function to the given input element. Pass non-null `node` to record +// processing time for modeling Iterator's GetNext() resource usage. +Status MakeIteratorFromInputElement( + IteratorContext* ctx, const IteratorBase* parent, + const std::vector& input_element, int64_t thread_index, + const InstantiatedCapturedFunction& inst_captured_func, StringPiece prefix, + std::unique_ptr* out_iterator, + const std::shared_ptr& node); + +struct ShortCircuitInfo { + std::vector indices; + std::vector can_move; +}; + +// Metadata shared across all captures of the same function. +class FunctionMetadata { + public: + struct Params { + bool use_inter_op_parallelism = true; + bool use_default_device = true; + }; + + // Creates a new instance of the `FunctionMetadata` class, fetching function + // from a context argument. + static Status Create(tensorflow::OpKernelConstruction* ctx, + const string& func_name, Params params, + std::shared_ptr* out_metadata); + + // Creates a new instance of the `FunctionMetadata` class, using the provided + // function. + static Status Create(tensorflow::OpKernelConstruction* ctx, + NameAttrList&& func, Params params, + std::shared_ptr* out_metadata); + + // Returns the named list of function arguments. + const NameAttrList& func() const { return func_; } + + // Returns a borrowed pointer to the function library that contains the + // transitive closure of definitions used by the function. + const FunctionLibraryDefinition* lib_def() const { return lib_def_.get(); } + + // Returns short-circuit information. + const ShortCircuitInfo& short_circuit_info() const { + return short_circuit_info_; + } + + // Indicates whether a default device should be used for executing function + // ops. + bool use_default_device() const { return use_default_device_; } + + // Indicates whether to use inter-op parallelism for execution of the + // function. + bool use_inter_op_parallelism() const { return use_inter_op_parallelism_; } + + // Indicates whether the function should a multi-device function backend. + bool use_multi_device_function() const { return use_multi_device_function_; } + + private: + FunctionMetadata(NameAttrList&& func, Params params) + : func_(std::move(func)), + use_default_device_(params.use_default_device), + use_inter_op_parallelism_(params.use_inter_op_parallelism) {} + + NameAttrList func_; + std::unique_ptr lib_def_ = nullptr; + ShortCircuitInfo short_circuit_info_; + bool use_default_device_ = true; + bool use_inter_op_parallelism_ = true; + bool use_multi_device_function_ = true; +}; + +// Constructs and stores the parameters for the CapturedFunction Instantiate +// function. +struct InstantiateCapturedFunctionParams { + explicit InstantiateCapturedFunctionParams(IteratorContext* ctx) { + flr = ctx->flr(); + function_handle_cache = ctx->function_handle_cache(); + runner = ctx->runner(); + } + + explicit InstantiateCapturedFunctionParams(OpKernelContext* ctx) { + flr = ctx->function_library(); + function_handle_cache = nullptr; + runner = ctx->runner(); + } + + FunctionLibraryRuntime* flr; + FunctionHandleCache* function_handle_cache; + std::function)>* runner; +}; + +// A `CapturedFunction` encapsulates a TensorFlow function, plus any "captured" +// arguments that it closed over in the user program. +class CapturedFunction { + public: + // Creates a new instance using a list of named attributes, fetching captured + // inputs from a context argument. + static Status Create(OpKernelContext* ctx, + std::shared_ptr metadata, + const string& argument_name, + std::unique_ptr* out_function); + + // Creates a new instance using a list of named attributes, using provided + // captured inputs. + static Status Create(OpKernelContext* ctx, + std::shared_ptr metadata, + std::vector&& captured_inputs, + std::unique_ptr* out_function); + + // Adds the definition of this captured function into the given graph, + // returning its captured inputs and types through the respective output + // arguments. + Status AddToGraph(SerializationContext* ctx, + DatasetBase::DatasetGraphDefBuilder* b, + std::vector* other_arguments, + DataTypeVector* other_arguments_types) const; + + // Instantiates this function for use in the given context, providing an + // InstantiatedCapturedFunction that can be used to execute functions. + Status Instantiate(IteratorContext* ctx, + std::unique_ptr* + instantiated_captured_function); + + Status Instantiate(InstantiateCapturedFunctionParams params, + std::unique_ptr* + instantiated_captured_function); + + // Determines whether the captured function is stateful. + Status CheckExternalState() const; + + // Returns the additional captured inputs that will be passed to the function. + const std::vector& captured_inputs() const { + return captured_inputs_; + } + + // Returns the named list of function arguments. + const NameAttrList& func() const { return metadata_->func(); } + + // Returns the transitive set of function definition required to instantiate + // this function. + const FunctionLibraryDefinition* lib_def() const { + return metadata_->lib_def(); + } + + // If every function output corresponds to one of its inputs, the method + // returns the mapping from output indices to input indices. Otherwise, it + // returns an empty list. + const ShortCircuitInfo& short_circuit_info() const { + return metadata_->short_circuit_info(); + } + + // Indicates whether the function should use inter op parallelism. + bool use_inter_op_parallelism() const { + return metadata_->use_inter_op_parallelism(); + } + + private: + CapturedFunction(std::shared_ptr metadata, + std::vector captured_inputs); + + Status IsMultiDevice(FunctionLibraryRuntime* flr, + bool* is_multi_device) const; + + const std::shared_ptr metadata_; + const std::vector captured_inputs_; + + CapturedFunction(const CapturedFunction&) = delete; + void operator=(const CapturedFunction&) = delete; +}; + +// `InstantiatedCapturedFunction` encapsulates all the runtime support needed +// to execute a tensorflow function. +// +// While `CapturedFunction` encapsulates constant attributes of the function, +// such as its name and captured arguments, `InstantiatedCapturedFunction` +// encapsulates runtime aspects, such as `FunctionLibraryRuntime` and function +// handle. +// +// The `Iterator` related classes use `InstantiatedCapturedFunction` to execute +// functions outside of the normal `OpKernel::Compute()` context. +class InstantiatedCapturedFunction { + public: + // Runs the instantiated captured function. This method takes ownership of + // the tensors in `args`, in order to be able to deallocate them as early as + // possible. Use `RunWithBorrowedArgs()` if the caller needs to retain + // ownership of the `args`. + Status Run(IteratorContext* ctx, std::vector&& args, + std::vector* rets) const; + + // Runs the instantiated captured function. This method takes ownership of + // the tensors in `args`, in order to be able to deallocate them as early as + // possible. Use `RunWithBorrowedArgs()` if the caller needs to retain + // ownership of the `args`. Pass non-null `node` to record processing time + // for modeling Iterator's GetNext() resource usage. When non-null node is + // provided, the pre-requisite is that the calling thread has previously + // called `DatasetBaseIterator::RecordStart(). + Status Run(IteratorContext* ctx, std::vector&& args, + std::vector* rets, + const std::shared_ptr& node) const; + + // Synchronously runs the captured function on the given `args`, and stores + // the results in `*rets`. Prefer to use `Run()` or `RunAsync()` when + // possible. + Status RunWithBorrowedArgs(IteratorContext* ctx, + const std::vector& args, + std::vector* rets) const; + + // Synchronously runs the captured function on the given `args`, and stores + // the results in `*rets`. Prefer to use `Run()` or `RunAsync()` when + // possible. Pass non-null `node` to record processing time for modeling + // Iterator's GetNext() resource usage. When non-null node is provided, the + // pre-requisite is that the calling thread has previously called + // `DatasetBaseIterator::RecordStart(). + Status RunWithBorrowedArgs(IteratorContext* ctx, + const std::vector& args, + std::vector* rets, + const std::shared_ptr& node) const; + + // Synchronously runs the captured function on the given `args`, and stores + // the results in `*rets`. Prefer to use `Run()` or `RunAsync()` when + // possible. This can be useful for calling a captured function in cases where + // an `IteratorContext*` is not available (such as a destructor). + // + // TODO(b/144278100): Avoid running functions without IteratorContext. + Status RunInstantiated(const std::vector& args, + std::vector* rets); + + // Asynchronously runs the captured function on the given `args`, stores the + // results in `*rets`, and calls the given `done` callback when the function + // returns. This method takes ownership of the tensors in `args`, in order to + // be able to deallocate them as early as possible. Pass non-null `node` to + // record processing time for modeling Iterator's GetNext() resource usage. + // When non-null node is provided, the pre-requisite is that the calling + // thread has previously called `DatasetBaseIterator::RecordStart(). + void RunAsync(IteratorContext* ctx, std::vector&& args, + std::vector* rets, + FunctionLibraryRuntime::DoneCallback done, + const std::shared_ptr& node) const; + + private: + friend class CapturedFunction; + + InstantiatedCapturedFunction( + FunctionLibraryRuntime* lib, FunctionLibraryRuntime::Handle f_handle, + DataTypeVector ret_types, + std::function)> runner, + CapturedFunction* captured_func, bool is_multi_device); + + // Determines whether a rendezvous object should be created when running the + // instantiated function. + bool ShouldCreateRendezvous() const; + + FunctionLibraryRuntime* const lib_; // Not owned. + const FunctionLibraryRuntime::Handle f_handle_; + const DataTypeVector ret_types_; + // Note: We capture the runner at function instantiation time to be able to + // run the function without `IteratorContext` via `RunInstantiated`. + std::function)> captured_runner_; + CapturedFunction* const captured_func_; // Not owned. + const bool is_multi_device_; + + InstantiatedCapturedFunction(const InstantiatedCapturedFunction&) = delete; + void operator=(const InstantiatedCapturedFunction&) = delete; +}; + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_CAPTURED_FUNCTION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/compression_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/compression_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0d309fc5c05d0a49455b5d973797cd3f861d7c2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/compression_utils.h @@ -0,0 +1,43 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_COMPRESSION_UTILS_H_ +#define TENSORFLOW_CORE_DATA_COMPRESSION_UTILS_H_ + +#include + +#include "tensorflow/core/framework/dataset.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace data { + +// Compresses the components of `element` into the `CompressedElement` proto. +// +// In addition to writing the actual compressed bytes, `Compress` fills +// out the per-component metadata for the `CompressedElement`. +// +// Returns an error if the uncompressed size of the element exceeds 4GB. +Status CompressElement(const std::vector& element, + CompressedElement* out); + +// Uncompresses a `CompressedElement` into a vector of tensor components. +Status UncompressElement(const CompressedElement& compressed, + std::vector* out); + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_COMPRESSION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/dataset_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/dataset_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b975fc0aad567ee037401f2ec060dc365b80c56d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/dataset_utils.h @@ -0,0 +1,441 @@ +/* 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_DATA_DATASET_UTILS_H_ +#define TENSORFLOW_CORE_DATA_DATASET_UTILS_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/resource_handle.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { +namespace data { + +// Constant used for indicating that the argument of tf.data.Dataset.shard +// should be supplied by the auto-sharding rewrite. +constexpr int kShardHint = -1; + +// The initial parallelism value before Autotune has a chance to optimize. +constexpr int kAutotuneDefaultParallelism = 16; + +// Creates a resource handle with a unique name for the given resource where +// the resource is managed by the Resource Manager. +template +Status CreateWeakHandle(OpKernelContext* ctx, T* resource, + const string& container_name, ResourceHandle* handle) { + static std::atomic resource_id_counter(0); + string unique_name = + strings::StrCat(container_name, resource_id_counter.fetch_add(1)); + ResourceMgr* mgr = ctx->resource_manager(); + TF_RETURN_IF_ERROR(mgr->Create(container_name, unique_name, resource)); + + *handle = MakeResourceHandle(container_name, unique_name, *ctx->device(), + TypeIndex::Make()); + return OkStatus(); +} + +// Creates a ref-counting resource handle for the given resource, where the +// resource is owned by the handle. +template +Status CreateHandle(OpKernelContext* ctx, T* resource, ResourceHandle* handle) { + ResourceMgr* mgr = ctx->resource_manager(); + *handle = + ResourceHandle::MakeRefCountingHandle(resource, ctx->device()->name()); + TF_RETURN_IF_ERROR( + mgr->CreateUnowned(handle->container(), handle->name(), resource)); + return OkStatus(); +} + +// TODO(b/198162355): Merge this class with ResourceOpKernel. +template +class AnonymousResourceOp : public OpKernel { + public: + // Creates an AnonymousResourceOp. + // ref_counting: Determines if the Op returns a ref-counting ResourceHandle. + // ResourceHandle. See go/tf-resource-handle-ref-count. + // return_deleter: Determines if the Op outputs a deleter tensor in addition + // to the resource handle tensor. + // If the resource handle is ref-counting, a no-op deleter is returned. + explicit AnonymousResourceOp(OpKernelConstruction* context, bool ref_counting, + bool return_deleter) + : OpKernel(context), + ref_counting_(ref_counting), + return_deleter_(return_deleter) {} + + void Compute(OpKernelContext* ctx) override { + FunctionLibraryRuntime* lib; + std::unique_ptr flib_def(nullptr); + std::unique_ptr pflr(nullptr); + OP_REQUIRES_OK( + ctx, ctx->function_library()->Clone(&flib_def, &pflr, &lib, true)); + T* resource; + OP_REQUIRES_OK(ctx, CreateResource(ctx, std::move(flib_def), + std::move(pflr), lib, &resource)); + + ResourceHandle handle; + if (ref_counting_) { + OP_REQUIRES_OK(ctx, CreateHandle(ctx, resource, &handle)); + } else { + OP_REQUIRES_OK(ctx, CreateWeakHandle(ctx, resource, name(), &handle)); + } + Tensor* handle_t; + OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &handle_t)); + handle_t->scalar()() = handle; + + if (return_deleter_) { + Tensor* deleter_t; + AllocatorAttributes attr; + attr.set_on_host(true); + OP_REQUIRES_OK( + ctx, ctx->allocate_output(1, TensorShape({}), &deleter_t, attr)); + // TODO(feyu): Consider returning an OptionalVariant. + if (!ref_counting_) { + // A deleter output that deletes the resource when destroyed. + deleter_t->scalar()() = + ResourceDeleter(handle, ctx->resource_manager()); + } + } + } + + protected: + virtual string name() = 0; + + virtual Status CreateResource( + OpKernelContext* ctx, std::unique_ptr flib_def, + std::unique_ptr pflr, + FunctionLibraryRuntime* lib, T** resource) = 0; + + private: + const bool ref_counting_; + const bool return_deleter_; +}; + +// Returns OkStatus() if `expected` and `received` types match, +// errors::InvalidArgument otherwise. +Status VerifyTypesMatch(const DataTypeVector& expected, + const DataTypeVector& received); + +Status VerifyTypesMatch(const DataTypeVector& expected, + const std::vector& received); + +// Returns OkStatus() if `expected` and `received` shapes are compatible, +// errors::InvalidArgument otherwise. +Status VerifyShapesCompatible(const std::vector& expected, + const std::vector& received); + +Status VerifyShapesCompatible(const std::vector& expected, + const std::vector& received); + +// Dataset op level determinism policy. +class DeterminismPolicy { + public: + enum class Type : int { + // The op must produce elements deterministically. + kDeterministic, + // The op may relax determinism to improve performance. + kNondeterministic, + // The determinism policy is not specified at the op level. In this case we + // use the experimental_deterministic dataset option to determine the + // determinism policy. + kDefault, + }; + static constexpr const char* const kDeterministic = "true"; + static constexpr const char* const kNondeterministic = "false"; + static constexpr const char* const kDefault = "default"; + + DeterminismPolicy() : determinism_(Type::kDefault) {} + explicit DeterminismPolicy(Type determinism) : determinism_(determinism) {} + // Creates a DeterminismPolicy with Type kDeterministic or + // kNondeterministic, depending on the values of `is_deterministic`. + explicit DeterminismPolicy(bool is_deterministic); + + static Status FromString(const std::string& s, DeterminismPolicy* out); + + // Returns the string representing the determinism policy. This will be one of + // the string constants defined above. + std::string String() const; + + /// Convenience methods for checking the DeterminismPolicy::Type. + bool IsDeterministic() const { return determinism_ == Type::kDeterministic; } + bool IsNondeterministic() const { + return determinism_ == Type::kNondeterministic; + } + bool IsDefault() const { return determinism_ == Type::kDefault; } + + private: + Type determinism_; +}; + +// Resolves non-deterministic seeds if necessary, returning either the original +// seeds or the resolved seeds. +// +// By TensorFlow convention, if both seeds are 0, they should be replaced with +// non-deterministically chosen seeds. +std::pair MaybeOverrideSeeds( + std::pair seeds); + +// Adds the functions in `to_add` to `base`. If a function with a matching +// signature already exists in `base`, replaces it with the function from +// `to_add`. +Status AddToFunctionLibrary(FunctionLibraryDefinition* base, + const FunctionLibraryDefinition& to_add); +Status AddToFunctionLibrary(FunctionLibraryDefinition* base, + const FunctionDefLibrary& to_add); + +// Determines whether the given function is stateful. +Status IsFunctionStateful(const FunctionLibraryDefinition& library, + const FunctionDef& function_def); + +// Determines whether the given node is stateful. +Status IsNodeStateful(const FunctionLibraryDefinition& library, + const NodeDef& node); + +// Creates a runner that runs functions with limited parallelism. +std::function)> RunnerWithMaxParallelism( + std::function)> runner, int max_parallelism); + +// Op for creating a typed dummy resource. +// +// This op is used to provide a resource "placeholder" for ops such as +// `CacheDatasetV2` or `ShuffleDatasetV2` that expects a resource input. +// Originally, the lifetime of the resources passed into these ops was managed +// externally. After the implementation changed to manage the lifetime of the +// resources (including creation) by the ops themselves, the resource input is +// only needed to pass a resource handle through graph rewrites. When they are +// invoked from user code, the implementation passes in a dummy resource. +template +class DummyResourceOp : public OpKernel { + public: + explicit DummyResourceOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} + + void Compute(OpKernelContext* ctx) override { + Tensor* tensor; + OP_REQUIRES_OK(ctx, ctx->allocate_output(0, TensorShape({}), &tensor)); + tensor->scalar()() = MakeResourceHandle( + ctx, /*container=*/"", /*name=*/"dummy_resource"); + } +}; + +// Given an op prefix and an op to match, returns whether the op to match +// is a match for any version of the op prefix. For example, +// MatchesAnyVersion("BatchDataset", "BatchDataset") == true +// MatchesAnyVersion("BatchDataset", "BatchDatasetV2") == true +// MatchesAnyVersion("BatchDataset", "BatchDatasetV3") == true +// MatchesAnyVersion("PaddedBatchDataset", "BatchDataset") == false +bool MatchesAnyVersion(StringPiece op_prefix, StringPiece op_to_match); + +// Returns the index-th slice of a given tensor. If the index-th slice of +// the tensor is not aligned, returns a deep copy of the tensor. +Tensor MaybeCopySubSlice(const Tensor& tensor, int64 index); + +// Removes device placements from the ops of all functions in `library`. +void StripDevicePlacement(FunctionDefLibrary* library); + +// Copies partial of the batch output. +Status CopyPartialBatch(int64_t num_elements, const Tensor& value, + Tensor* output); + +// Reads a batch when restoring the iterator. +Status ReadBatch(IteratorContext* ctx, IteratorStateReader* reader, + int64_t batch_size, const string& iterator_prefix, + const string& batch_prefix, std::vector* batch); + +// Writes a batch when saving the iterator. +Status WriteBatch(int64_t batch_size, int64_t num_elements, + const string& iterator_prefix, const string& batch_prefix, + IteratorStateWriter* writer, std::vector* batch); + +// Reads a status when restoring the iterator. +Status ReadStatus(const string& iterator_prefix, const string& prefix, + IteratorStateReader* reader, Status* status); + +// Writes a status when saving the iterator. +Status WriteStatus(const string& iterator_prefix, const string& prefix, + const Status& status, IteratorStateWriter* writer); + +// Processes a batch to output. In the case a partial batch is encountered, copy +// only partial of the batch. +Status ProcessBatch(int64_t batch_size, int64_t num_elements, + bool drop_remainder, const Status& status, + IteratorContext* ctx, std::vector* output, + bool* end_of_sequence, std::vector* batch); + +// Constructs and stores the parameters for the CopyBatch function. +struct CopyBatchParams { + Allocator* allocator; + std::function)>* runner; + int64 runner_threadpool_size; + + explicit CopyBatchParams(IteratorContext* ctx) { + allocator = ctx->allocator({}); + runner = ctx->runner(); + runner_threadpool_size = ctx->runner_threadpool_size(); + } + + explicit CopyBatchParams(OpKernelContext* ctx) { + allocator = ctx->get_allocator({}); + runner = ctx->runner(); + runner_threadpool_size = GetRunnerThreadpoolSizeFromOpKernelContext(ctx); + } +}; + +// Copies the input elements to a batch. +// +// The `batch_elements` argument contains the individual elements to copy into a +// batch. The `parallel_copy` argument indicates whether to parallelize the +// copy. The `allocation_callback` argument can be used to pass a callback to +// invoke upon successful allocation of the memory for the batch. The +// `out_tensors` argument will be used to store the resulting batch (one for +// each component of the input). +Status CopyBatch(CopyBatchParams params, + const std::vector>& batch_elements, + bool parallel_copy, + std::function allocation_callback, + std::vector* out_tensors); + +// Computes the set of experiments to apply based on the job name, task id, +// rollout percentage of registered experiments, and the +// TF_DATA_EXPERIMENT_OPT_IN and TF_DATA_EXPERIMENT_OPT_OUT environment +// variables. +absl::flat_hash_set GetExperiments(); +absl::flat_hash_set GetExperiments( + const std::string& job_name, int64_t task_id, + std::function hash_func); + +// Logs and records the experiments that will be applied. +void LogAndRecordExperiments(const absl::flat_hash_set& experiments); + +// Computes the set of enabled, disabled, and default optimizations based on the +// given options. An optimization must be a graph optimizer name that has been +// registered with Grappler. +void GetOptimizations(const Options& options, + absl::flat_hash_set* optimizations_enabled, + absl::flat_hash_set* optimizations_disabled, + absl::flat_hash_set* optimizations_default); + +// Creates graph rewrite configs based on the given options. The configs will +// only be used if their corresponding optimizers registered with Grappler are +// enabled. +// A config is a string with the following format: +// :: +absl::flat_hash_set CreateGraphRewriteConfigs(const Options& options); + +// Determines whether max intra-op parallelism should be configured. +bool ShouldConfigureMaxIntraOpParallelism(const Options& options); + +// Determines whether private threadpool should be used. +bool ShouldUsePrivateThreadPool(const Options& options); + +// Determines whether autotuning should be used. +bool ShouldUseAutotuning(const Options& options); + +// Determines whether optimizations should be applied. +bool ShouldApplyOptimizations( + const Options& options, + const absl::flat_hash_set& optimizations_enabled, + const absl::flat_hash_set& optimizations_default); + +// Returns the default CPU budget. +inline int GetCpuBudget() { + static bool in_experiment = GetExperiments().contains("tune_cpu_budget"); + return (in_experiment ? 1.2 : 1.0) * port::NumSchedulableCPUs(); +} + +// Returns the initial value for parallelism parameter before the first Autotune +// optimization. +int64 GetAutotuneDefaultParallelism(IteratorContext* ctx); + +// Creates an iterator context appropriate for a nested dataset's iterator. A +// nested dataset is a dataset created within another dataset, e.g. by the +// function passed to `interleave` or `flat_map`. +IteratorContext MakeNestedIteratorContext(IteratorContext* ctx); + +// A `DatasetExperimentRegistry::JobSelector` that randomly selects +// `rollout_pct` percent of all jobs. `name_hash` is a hash of the experiment +// and job names. +template +bool RandomJobSamplePercentage(uint64_t name_hash) { + return name_hash % 100 < rollout_pct; +} + +// A `DatasetExperimentRegistry::TaskSelector` that selects all tasks. +bool AllTasks(int64_t unused_task_id, bool unused_evens); + +// A `DatasetExperimentRegistry::TaskSelector` that selects the tasks for half +// of all hosts. Typically, one or two consecutive tasks run on a single host. +// If `evens` is `true`, selects tasks 0,1,4,5,8,9,..., otherwise selects tasks +// 2,3,6,7,10,11,... +bool IndependentHostTasks(int64_t task_id, bool evens); + +// Registry of tf.data experiments. +class DatasetExperimentRegistry { + public: + using JobSelector = std::function; + using TaskSelector = std::function; + + struct ExperimentSelector { + JobSelector job_selector; + TaskSelector task_selector; + }; + + // Registers the experiment. + static void Register(const string& experiment, JobSelector job_selector, + TaskSelector task_selector); + + // Returns all registered experiments. + static absl::flat_hash_map Experiments(); +}; + +// Helper class to register a dataset experiment. +class DatasetExperimentRegistrar { + public: + explicit DatasetExperimentRegistrar( + const string& experiment, + DatasetExperimentRegistry::JobSelector job_selector, + DatasetExperimentRegistry::TaskSelector task_selector) { + DatasetExperimentRegistry::Register(experiment, job_selector, + task_selector); + } +}; + +// Macro that can be used to register a dataset experiment. +#define REGISTER_DATASET_EXPERIMENT(experiment, job_selector, task_selector) \ + REGISTER_DATASET_OP_NAME_UNIQ_HELPER(__COUNTER__, experiment, job_selector, \ + task_selector) + +#define REGISTER_DATASET_OP_NAME_UNIQ_HELPER(ctr, experiment, job_selector, \ + task_selector) \ + REGISTER_DATASET_OP_NAME_UNIQ(ctr, experiment, job_selector, task_selector) + +#define REGISTER_DATASET_OP_NAME_UNIQ(ctr, experiment, job_selector, \ + task_selector) \ + static ::tensorflow::data::DatasetExperimentRegistrar \ + registrar__body__##ctr##__object(experiment, job_selector, \ + task_selector) + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_DATASET_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/finalization_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/finalization_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..c0ed2afb1b053e79d5a3796536a0ea33c9029d22 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/finalization_utils.h @@ -0,0 +1,35 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DATA_FINALIZATION_UTILS_H_ +#define TENSORFLOW_CORE_DATA_FINALIZATION_UTILS_H_ + +#include + +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { +namespace data { + +// Returns the finalized version of the dataset. The returned DatasetBase is +// unowned and lives for as long as this dataset. +StatusOr GetFinalizedDataset(OpKernelContext* ctx, + const DatasetBase* dataset); + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_FINALIZATION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/hash_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/hash_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..401f047e47003f7715fd7d92afeedf91113362c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/hash_utils.h @@ -0,0 +1,62 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_HASH_UTILS_H_ +#define TENSORFLOW_CORE_DATA_HASH_UTILS_H_ + +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { +namespace data { + +// Returns a stable hash of the subgraph rooted at the given node. +// +// NOTE: There is currently no guarantee that the hash of a subgraph will stay +// the same between TensorFlow builds. +Status HashNode(const GraphDef& graph, const NodeDef& node, uint64* hash); +Status HashNode(const GraphDef& graph, const NodeDef& node, + const FunctionLibraryDefinition& flib_def, uint64* hash); + +// Returns a stable hash of the given tensor. +// +// NOTE: There is currently no guarantee that the hash of a subgraph will stay +// the same between TensorFlow builds. +Status HashTensor(const Tensor& tensor, uint64* hash); + +// Returns a stable hash of the given graph. +// +// NOTE: There is currently no guarantee that the hash of a subgraph will stay +// the same between TensorFlow builds. +Status HashGraph(const GraphDef& graph, uint64* hash); + +// Determines whether the given graphs are equal, following the same logic used +// for HashGraph. Returns OK if the graphs can be determined to be equal, +// otherwise returns an error message explaining why the graphs couldn't be +// determined to be equal. +Status CheckGraphsEqual(const GraphDef& a, const GraphDef& b); + +// Determines whether the subgraphs rooted at the given nodes are equal +// following the same logic used for HashGraph. Returns OK if the graphs can be +// determined to be equal, otherwise returns an error message explaining why the +// graphs couldn't be determined to be equal. +Status CheckSubgraphsEqual(const GraphDef& a, const NodeDef* node_a, + const GraphDef& b, const NodeDef* node_b); +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_HASH_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/metric_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/metric_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..7d67cb92115fdec730b1a0fef8f1948dfbc1d69f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/metric_utils.h @@ -0,0 +1,87 @@ +/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_METRIC_UTILS_H_ +#define TENSORFLOW_CORE_DATA_METRIC_UTILS_H_ + +#include +#include +#include + +#include "absl/time/time.h" +#include "tensorflow/core/data/tfdataz_metrics.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" + +namespace tensorflow { +namespace data { + +// Exports the metrics for `GetNext` calls by tf.data iterators. When the user +// calls `RecordStart` and `RecordStop`, it will export a latency sample. It +// also exports throughput, tf.data iterator life time, etc. This class is +// thread-safe. Example usage: +// +// ``` +// IteratorMetricsCollector metrics_collector(DEVICE_CPU, env); +// absl::Time start_time = metrics_collector.RecordStart(); +// auto status = iterator_->GetNext(IteratorContext(std::move(params)), +// out_tensors, end_of_sequence); +// metrics_collector.RecordStop(start_time, *out_tensors); +// ``` +class IteratorMetricsCollector { + public: + // Constructs a `IteratorMetricsCollector`. `device_type` is one of the + // devices defined in `types.h` (DEVICE_CPU, DEVICE_GPU, DEVICE_TPU, etc). + // We only collect metrics for CPU devices. This is a heuristic to avoid + // collecting metrics for device-side iterators created by the multi-device + // iterator mechanism. + IteratorMetricsCollector(const std::string& device_type, const Env& env); + + // Starts the timer for the next `GetNext` call. Returns the start time. + absl::Time RecordStart(); + + // Records metrics for the most recent `GetNext` call, including the latency, + // bytes fetched, iterator life time, etc. `start_time` is the start time + // returned by `RecordStart`. `output` is the output of the `GetNext` call. + void RecordStop(absl::Time start_time, const std::vector& output); + + private: + // We only collect metrics for CPU devices. + bool ShouldCollectMetrics() const; + + // One of the devices defined in `types.h` + // (DEVICE_CPU, DEVICE_GPU, DEVICE_TPU, etc). + const std::string device_type_; + const Env& env_; + + mutex mu_; + + // Records the number of currently active `GetNext` calls. + uint64_t num_active_calls_ TF_GUARDED_BY(mu_) = 0; + + // Records the start time (in microseconds) of the first `RecordStart()` call + // that followed the last period of inactivity. + uint64_t first_start_time_us_ TF_GUARDED_BY(mu_) = 0; + + // Records the end time (in microseconds) of the most recent `RecordStop()` + // call. + uint64_t end_time_us_ TF_GUARDED_BY(mu_) = 0; +}; + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_METRIC_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/name_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/name_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..72e870a1caccfe11024ad0efda8225639bcdc2e9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/name_utils.h @@ -0,0 +1,109 @@ +/* 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_DATA_NAME_UTILS_H_ +#define TENSORFLOW_CORE_DATA_NAME_UTILS_H_ + +#include + +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace data { +namespace name_utils { + +extern const char kDelimiter[]; +extern const char kDefaultDatasetDebugStringPrefix[]; + +struct OpNameParams { + int op_version = 1; +}; + +struct DatasetDebugStringParams { + template + void set_args(T... input_args) { + args = {static_cast(input_args).data()...}; + } + + int op_version = 1; + string dataset_prefix = ""; + std::vector args; +}; + +struct IteratorPrefixParams { + int op_version = 1; + string dataset_prefix = ""; +}; + +// Merge the given args in the format of "(arg1, arg2, ..., argn)". +// +// e.g. ArgsToString({"1", "2", "3"}) -> "(1, 2, 3)"; ArgsToString({}) -> "". +string ArgsToString(const std::vector& args); + +// Returns the dataset op name. +// +// e.g. OpName("Map") -> "MapDataset". +string OpName(const string& dataset_type); + +// Returns the dataset op names. +// +// e.g. OpName(ConcatenateDatasetOp::kDatasetType, OpNameParams()) +// -> "ConcatenateDataset" +// +// OpNameParams params; +// params.op_version = 2; +// OpName(ParallelInterleaveDatasetOp::kDatasetType, params) +// -> "ParallelInterleaveDatasetV2" +string OpName(const string& dataset_type, const OpNameParams& params); + +// Returns a human-readable debug string for this dataset in the format of +// "FooDatasetOp(arg1, arg2, ...)::Dataset". +// +// e.g. DatasetDebugString("Map") -> "MapDatasetOp::Dataset"; +string DatasetDebugString(const string& dataset_type); + +// Returns a human-readable debug string for this dataset in the format of +// "FooDatasetOp(arg1, arg2, ...)::Dataset". +// +// e.g. +// DatasetDebugStringParams range_params; +// range_params.set_args(0, 10, 3); +// DatasetDebugString(RangeDatasetOp::kDatasetType, range_params) +// -> "RangeDatasetOp(0, 10, 3)::Dataset"); +string DatasetDebugString(const string& dataset_type, + const DatasetDebugStringParams& params); + +// Returns a string that identifies the sequence of iterators leading up to +// the iterator of this dataset. +// +// e.g. IteratorPrefix("Map", "Iterator::Range") -> "Iterator::Range::Map". +string IteratorPrefix(const string& dataset_type, const string& prefix); + +// Returns a string that identifies the sequence of iterators leading up to +// the iterator of this dataset. +// +// e.g. +// IteratorPrefixParams params; +// params.op_version = 2; +// IteratorPrefix(BatchDatasetOp::KDatasetType, "Iterator::Range", params) -> +// "Iterator::Range::BatchV2". +string IteratorPrefix(const string& dataset_type, const string& prefix, + const IteratorPrefixParams& params); + +} // namespace name_utils +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_NAME_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/rewrite_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/rewrite_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..23ea965d67e1057b8c49173c40369b4862ee2749 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/rewrite_utils.h @@ -0,0 +1,88 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_REWRITE_UTILS_H_ +#define TENSORFLOW_CORE_DATA_REWRITE_UTILS_H_ + +#include "tensorflow/core/platform/platform.h" + +// On mobile we do not provide this functionality because not all of its +// dependencies are available there. +#if !defined(IS_MOBILE_PLATFORM) + +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/statusor.h" +#include "tensorflow/core/platform/tstring.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/rewriter_config.pb.h" + +namespace tensorflow { +namespace data { + +RewriterConfig CreateRewriterConfig( + const absl::flat_hash_set& optimizations, + const absl::flat_hash_set& optimizations_configs); + +// Rewrites the input dataset using the given config. The rewritten_input +// stored in the core::RefCountPtr* output parameter is owned. +Status RewriteDataset(OpKernelContext* ctx, const DatasetBase* input, + std::function config_factory, + bool record_fingerprint, + core::RefCountPtr* rewritten_input); + +// Creates a grappler item for `graph_def`, which is required for graph +// optimization. +// `dataset_node` is the name of the node corresponding to the dataset. +// If `add_fake_sinks` is true, it adds fake sink node to graph and functions to +// allow rewriting the actual sink nodes. +// TODO(b/118820916): When MetaOptimizer adds provisions for function retvals to +// be optimizable, we will no longer need to add fake nodes. +std::unique_ptr GetGrapplerItem( + GraphDef* graph_def, std::string* dataset_node, bool add_fake_sinks); + +// Returns the name of the node corresponding to the dataset. It is indicated by +// the symbolic `_Retval` node. +StatusOr GetDatasetNode(const GraphDef& graph_def); + +// Like `GetDatasetNode` above, but returns the entire node object. +StatusOr GetDatasetNodeDef(const GraphDef& graph_def); + +// Determines which optimizations should be applied. +// +// The result will contain any optimizations that are explicitly enabled, any +// default optimization that are not explicitly disabled, and any experiment +// that corresponds to an optimization as long as the optimization is not +// explicitly disabled. +absl::flat_hash_set SelectOptimizations( + const absl::flat_hash_set& experiments, + const absl::flat_hash_set& optimizations_enabled, + const absl::flat_hash_set& optimizations_disabled, + const absl::flat_hash_set& optimizations_default); + +} // namespace data +} // namespace tensorflow +#endif // !IS_MOBILE_PLATFORM + +#endif // TENSORFLOW_CORE_DATA_REWRITE_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/root_dataset.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/root_dataset.h new file mode 100644 index 0000000000000000000000000000000000000000..3d73f6e8cbdfac9e2b84a64959400657fc66a494 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/root_dataset.h @@ -0,0 +1,99 @@ +/* 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_DATA_ROOT_DATASET_H_ +#define TENSORFLOW_CORE_DATA_ROOT_DATASET_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/model.pb.h" +#include "tensorflow/core/platform/refcount.h" + +namespace tensorflow { +namespace data { + +// Dataset transformation responsible for internal tf.data logic such as +// autotuning, applying threading configuration. +class RootDataset : public DatasetBase { + public: + struct Params { + bool autotune = true; + model::AutotuneAlgorithm autotune_algorithm; + std::function autotune_cpu_budget_func; + std::function autotune_free_memory_func; + int64_t autotune_ram_budget_from_options; + int64_t max_intra_op_parallelism = 1; + int64_t private_threadpool_size = 0; + + int64_t ComputeInitialAutotuneRamBudget() const { + if (autotune_ram_budget_from_options > 0) { + return autotune_ram_budget_from_options; + } else { + return autotune_free_memory_func(); + } + } + }; + + static Status FromOptions(const DatasetBase* input, DatasetBase** output); + static Status FromOptions(core::RefCountPtr input, + DatasetBase** output); + + ~RootDataset() override; + + const DataTypeVector& output_dtypes() const override; + const std::vector& output_shapes() const override; + + int64_t CardinalityInternal(CardinalityOptions options) const override; + Status Get(OpKernelContext* ctx, int64 index, + std::vector* out_tensors) const override; + Status CheckExternalState() const override; + string DebugString() const override; + Status InputDatasets(std::vector* inputs) const override; + std::unique_ptr MakeIteratorInternal( + const string& prefix) const override; + + protected: + Status AsGraphDefInternal(SerializationContext* ctx, + DatasetGraphDefBuilder* b, + Node** output) const override; + + private: + class Iterator; + + RootDataset(const DatasetBase* input, const Params& params); + + RootDataset(core::RefCountPtr input, const Params& params); + + const DatasetBase* input_; + core::RefCountPtr owned_input_; + const Params params_; + TraceMeMetadata traceme_metadata_; +}; + +// Finalizes the `input` dataset, which is expected to be called before the +// dataset is about to be iterated. This can for instance apply static graph +// optimizations or inject internal tf.data transformations responsible for +// autotuning or threading configuration. The caller must ensure that the +// input dataset to be finalized outlives the output. +Status FinalizeDataset(OpKernelContext* ctx, const DatasetBase* input, + DatasetBase** output); + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_ROOT_DATASET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/serialization_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/serialization_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..d5e83c32eb488f245292be11b28a36f340df2384 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/serialization_utils.h @@ -0,0 +1,220 @@ +/* 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_DATA_SERIALIZATION_UTILS_H_ +#define TENSORFLOW_CORE_DATA_SERIALIZATION_UTILS_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/dataset.pb.h" +#include "tensorflow/core/framework/variant_tensor_data.h" +#include "tensorflow/core/lib/core/status.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { +namespace data { + +// Reads dataset elements from the checkpoint reader using the given key prefix. +Status ReadElementsFromCheckpoint(IteratorContext* ctx, + IteratorStateReader* reader, + StringPiece key_prefix, + std::vector>* elements); + +// Writes dataset elements to the checkpoint writer using the given key prefix. +// The elements can be read back by passing the same key prefix to +// ReadElementsFromCheckpoint. Only one list of elements can be written under +// the same key_prefix. +Status WriteElementsToCheckpoint( + IteratorStateWriter* writer, StringPiece key_prefix, + const std::vector>& elements); + +// Helper class for reading data from a vector of VariantTensorData objects. +class VariantTensorDataReader : public IteratorStateReader { + public: + explicit VariantTensorDataReader( + const std::vector& data); + + bool Contains(StringPiece key) const override; + bool Contains(StringPiece name, StringPiece key) const override; + + Status ReadScalar(StringPiece key, int64_t* val) const override; + Status ReadScalar(StringPiece name, StringPiece key, + int64_t* val) const override; + Status ReadScalar(StringPiece key, tstring* val) const override; + Status ReadScalar(StringPiece name, StringPiece key, + tstring* val) const override; + Status ReadTensor(StringPiece key, Tensor* val) const override; + Status ReadTensor(FunctionLibraryRuntime* flr, StringPiece key, + Tensor* val) const override; + Status ReadTensor(StringPiece name, StringPiece key, + Tensor* val) const override; + Status ReadTensor(FunctionLibraryRuntime* flr, StringPiece name, + StringPiece key, Tensor* val) const override; + + private: + template + Status ReadScalarInternal(StringPiece name, StringPiece key, T* val) const; + Status ReadTensorInternal(FunctionLibraryRuntime* flr, StringPiece name, + StringPiece key, Tensor* val) const; + Status ReadDatasetInternal(FunctionLibraryRuntime* flr, StringPiece name, + StringPiece key, Tensor* val) const; + // Produces all key/value pairs stored in this reader. Useful for debugging. + std::map ReadAllTensors(); + + // For access to ReadAllTensors() + friend tsl::StatusOr> + CheckpointStats(const std::string& checkpoint_bytes); + + std::map> map_; + std::map data_; // Not owned. +}; + +// Helper class used to build a list of VariantTensorData objects, one for each +// iterator which is determined from the key supplied from the Write* calls. +// Sample usage: +// VariantTensorDataWriter writer; +// writer.WriteScalar(full_name("buffer_size"), buffer_.size()); +// writer.WriteScalar(full_name("num_threads"), threadpool_.size()); +// .... +// std::vector> variants; +// writer.ReleaseData(&variants); +// Now the VariantTensorData objects can be used to serialize. +class VariantTensorDataWriter : public IteratorStateWriter { + public: + Status WriteScalar(StringPiece key, int64_t val) override; + Status WriteScalar(StringPiece name, StringPiece key, int64_t val) override; + + Status WriteScalar(StringPiece key, const tstring& val) override; + Status WriteScalar(StringPiece name, StringPiece key, + const tstring& val) override; + + Status WriteTensor(StringPiece key, const Tensor& val) override; + Status WriteTensor(StringPiece name, StringPiece key, + const Tensor& val) override; + + // Releases the built VariantTensorData's to `variants`. Clears out all + // class state. + void ReleaseData(std::vector>* variants); + + // Obtains a read-only version of the VariantTensorData's built. + void GetData(std::vector* variants); + + private: + void MaybeFlush(); + void Reset(); + + template + Status WriteScalarInternal(StringPiece name, StringPiece key, const T& val); + Status WriteTensorInternal(StringPiece name, StringPiece key, + const Tensor& val); + Status WriteDatasetInternal(StringPiece name, StringPiece key, + const DatasetBase* dataset); + + bool is_flushed_ = false; + std::map> data_; + std::map> keys_; +}; + +// Wrapper for encoding/decoding the iterator state stored in a Variant tensor. +// The `GetData()` method returns an VariantTensorData object which contains all +// the state needed to restore a single iterator. +// +// Usage example: +// +// Encoding: +// +// Tensor t(DT_VARIANT, TensorShape({})); +// t->scalar()() = IteratorStateVariant(); +// +// Encode() sets the type_name of the VariantTensorData object to +// IteratorStateVariant::TypeName(). +// +// Decoding: +// +// Variant v = ; +// DecodeUnaryVariant(&v); +// IteratorStateVariant* wrapper = v.get(); +// IteratorStateReader reader({wrapper->GetData()}); +// iterator_resource->Restore(ctx, &reader); +// +// The type_name of the VariantTensorData object to be decoded must match +// IteratorStateVariant::TypeName(). +class IteratorStateVariant { + public: + IteratorStateVariant() = default; + IteratorStateVariant(const IteratorStateVariant& other); + IteratorStateVariant& operator=(IteratorStateVariant&& other) = default; + IteratorStateVariant& operator=(const IteratorStateVariant& other) = delete; + + static std::string TypeName(); + + // Initializes `this` from a VariantTensorData object. + Status InitializeFromVariantData(std::unique_ptr data); + + // Returns a borrowed pointer to the underlying VariantTensorData. + const VariantTensorData* GetData() const { return data_.get(); } + + // Encodes this `IteratorStateVariant` into `*data`. Data will be compressed + // and stored as a scalar `CompressedElement` tensor, or left uncompressed if + // compression fails. + void Encode(VariantTensorData* data) const; + + // Decodes from `data`. If `data` contains a single scalar `CompressedElement` + // tensor, it is assumed to be compressed by `Encode`, and will be + // uncompressed as part of `Decode`. + bool Decode(VariantTensorData data); + + std::string DebugString() const; + + private: + // Returns the compressed element in `data`. If `data` does not contain a + // compressed element, returns nullptr. + static const CompressedElement* GetCompressedElement( + const VariantTensorData& data); + + std::unique_ptr data_; +}; + +// Returns a GraphDef representation of the given dataset. +Status AsGraphDef(const DatasetBase* dataset, + SerializationContext&& serialization_ctx, + GraphDef* graph_def); + +// Returns a GraphDef representation of the given dataset suitable for +// optimization rewrites. It sets serialization parameters to export a minimum +// graph with additional information for optimization (i.e. ignoring external +// state, not serializing data tensors, not failing if there are datasets which +// do not have AsGraphDef implemented). Sets the `dataset_node` parameter to the +// dataset's node name in the resulting GraphDef. +Status AsGraphDefForRewrite(OpKernelContext* ctx, const DatasetBase* input, + std::vector>* input_list, + GraphDef* result, string* dataset_node); + +// Analyzes the bytes of a tf.data iterator checkpoint to identify all of the +// keys in the checkpoint along with their sizes in bytes. +tsl::StatusOr> CheckpointStats( + const std::string& checkpoint_bytes); + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_KERNELS_SERIALIZATION_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/snapshot_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/snapshot_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..4e8c3a79b85eb2cfe80992add67be06051269786 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/snapshot_utils.h @@ -0,0 +1,448 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DATA_SNAPSHOT_UTILS_H_ +#define TENSORFLOW_CORE_DATA_SNAPSHOT_UTILS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/io/compression.h" +#include "tensorflow/core/lib/io/inputstream_interface.h" +#include "tensorflow/core/lib/io/record_reader.h" +#include "tensorflow/core/lib/io/record_writer.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/file_system.h" +#include "tensorflow/core/platform/path.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/protobuf/snapshot.pb.h" + +namespace tensorflow { + +class GraphDef; + +namespace data { + +namespace experimental { + +class SnapshotMetadataRecord; +class SnapshotTensorMetadata; + +} // namespace experimental + +namespace snapshot_util { + +constexpr char kMetadataFilename[] = "snapshot.metadata"; + +constexpr char kModeAuto[] = "auto"; +constexpr char kModeWrite[] = "write"; +constexpr char kModeRead[] = "read"; +constexpr char kModePassthrough[] = "passthrough"; +constexpr char kShardDirectorySuffix[] = ".shard"; + +enum Mode { READER = 0, WRITER = 1, PASSTHROUGH = 2 }; + +// Returns the name of the "hash" directory for the given base path and hash ID. +std::string HashDirectory(const std::string& path, uint64 hash); + +// Returns the name of the "run" directory for the given base path and run ID. +std::string RunDirectory(const std::string& hash_directory, uint64 run_id); +std::string RunDirectory(const std::string& hash_directory, + const std::string& run_id); + +// Returns the name of the "shard" directory for the given base path and shard +// ID. +std::string ShardDirectory(const std::string& run_directory, int64_t shard_id); + +// Returns the checkpoint file name for the given directory and checkpoint ID. +std::string GetCheckpointFileName(const std::string& shard_directory, + uint64 checkpoint_id); + +// This is a interface class that exposes snapshot writing functionality. +class Writer { + public: + // Creates a new writer object. + static Status Create(Env* env, const std::string& filename, + const std::string& compression_type, int version, + const DataTypeVector& dtypes, + std::unique_ptr* out_writer); + + // Writes a vector of tensors to the snapshot writer file. + virtual Status WriteTensors(const std::vector& tensors) = 0; + + // Flushes any in-memory buffers to disk. + virtual Status Sync() = 0; + + // Closes and finalizes the snapshot file. All calls to any other method will + // be invalid after this call. + virtual Status Close() = 0; + + virtual ~Writer() = default; + + protected: + virtual Status Initialize(tensorflow::Env* env) = 0; +}; + +// Writes snapshots with the standard TFRecord file format. +class TFRecordWriter : public Writer { + public: + TFRecordWriter(const std::string& filename, + const std::string& compression_type); + + Status Initialize(tensorflow::Env* env) override; + + Status WriteTensors(const std::vector& tensors) override; + + Status Sync() override; + + Status Close() override; + + ~TFRecordWriter() override; + + private: + const std::string filename_; + const std::string compression_type_; + + std::unique_ptr dest_; + std::unique_ptr record_writer_; +}; + +// Writes snapshot with a custom (legacy) file format. +class CustomWriter : public Writer { + public: + static constexpr const size_t kHeaderSize = sizeof(uint64); + + static constexpr const char* const kClassName = "SnapshotWriter"; + static constexpr const char* const kWriteStringPiece = "WriteStringPiece"; + static constexpr const char* const kWriteCord = "WriteCord"; + static constexpr const char* const kSeparator = "::"; + + CustomWriter(const std::string& filename, const std::string& compression_type, + const DataTypeVector& dtypes); + + Status WriteTensors(const std::vector& tensors) override; + + Status Sync() override; + + Status Close() override; + + ~CustomWriter() override; + + protected: + Status Initialize(tensorflow::Env* env) override; + + private: + Status WriteRecord(const StringPiece& data); + +#if defined(TF_CORD_SUPPORT) + Status WriteRecord(const absl::Cord& data); +#endif // TF_CORD_SUPPORT + + std::unique_ptr dest_; + const std::string filename_; + const std::string compression_type_; + const DataTypeVector dtypes_; + // We hold zlib_dest_ because we may create a ZlibOutputBuffer and put that + // in dest_ if we want compression. ZlibOutputBuffer doesn't own the original + // dest_ and so we need somewhere to store the original one. + std::unique_ptr zlib_underlying_dest_; + std::vector simple_tensor_mask_; // true for simple, false for complex. + int num_simple_ = 0; + int num_complex_ = 0; +}; + +// Interface class for reading snapshot files previous written with Writer. +class Reader { + public: + // Op kernel that creates an instance of `Reader::Dataset` needed to support + // serialization and deserialization of `Reader::Dataset`. + class DatasetOp : public DatasetOpKernel { + public: + explicit DatasetOp(OpKernelConstruction* ctx); + + protected: + void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override; + + private: + DataTypeVector output_types_; + std::vector output_shapes_; + std::string compression_; + int64_t version_; + }; + + // Op kernel that creates an instance of `Reader::NestedDataset` needed to + // support serialization and deserialization of `Reader::NestedDataset`. + class NestedDatasetOp : public DatasetOpKernel { + public: + explicit NestedDatasetOp(OpKernelConstruction* ctx); + + protected: + void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override; + + private: + DataTypeVector output_types_; + std::vector output_shapes_; + }; + + // Creates a new Reader object that reads data from `filename`. Note that + // the `version`, `compression_type`, and `dtypes` arguments passed into + // `Writer` and `Reader` must be the same for the reading to succeed. + static Status Create(Env* env, const std::string& filename, + const string& compression_type, int version, + const DataTypeVector& dtypes, + std::unique_ptr* out_reader); + + // Returns a nested dataset for a set of given snapshot file names. + // + // This function takes a vector of snapshot files, and returns a nested + // dataset. Each element within the nested dataset is itself a dataset, and + // contains all the elements written out to each individual snapshot file. + static Status MakeNestedDataset(Env* env, + const std::vector& shard_dirs, + const string& compression_type, int version, + const DataTypeVector& dtypes, + const std::vector& shapes, + int64_t start_index, DatasetBase** output); + + // Returns a nested dataset for the given datasets. + static void MakeNestedDataset(const std::vector& datasets, + DatasetBase** output); + + // Reads a vector of Tensors from the snapshot file. + virtual Status ReadTensors(std::vector* read_tensors) = 0; + + // Skips `num_records`. Equivalent to calling `ReadTensors` `num_records` + // times then discarding the results. + virtual Status SkipRecords(int64_t num_records); + + virtual ~Reader() = default; + + protected: + virtual Status Initialize(Env* env) = 0; + + class Dataset; + class NestedDataset; +}; + +class TFRecordReaderImpl { + public: + // Constructs a `TFRecordReaderImpl`. + // `filename` is the file to read from. + // `compression_type` is the compression method, as defined in + // tensorflow/tsl/lib/io/compression.h. + // `output_buffer_size` specifies the buffer size required by Snappy/Zlib + // compression algorithms. Ignored if compression is not enabled. + TFRecordReaderImpl(const std::string& filename, const string& compression, + std::optional output_buffer_size = std::nullopt); + + // Initializes the reader. Callers must initialize the reader before calling + // `GetNext` or `GetTensors`. + Status Initialize(Env* env); + + // Reads the next Tensor in the input file. + StatusOr GetNext(); + + // Reads all Tensors in the input file. + StatusOr> GetTensors(); + + private: + // Parses `record` into a Tensor. + StatusOr Parse(const tstring& record); + + std::string filename_; + std::unique_ptr file_; + std::unique_ptr record_reader_; + uint64_t offset_; + + const string compression_; + const std::optional output_buffer_size_; +}; + +// Reads snapshots previously written with `TFRecordWriter`. +class TFRecordReader : public Reader { + public: + TFRecordReader(const std::string& filename, const string& compression, + const DataTypeVector& dtypes, + std::optional output_buffer_size = std::nullopt) + : reader_impl_(filename, compression, output_buffer_size), + dtypes_(dtypes) {} + + // Initializes the reader. Callers must initialize the reader before calling + // `ReadTensors`. + Status Initialize(Env* env) override { return reader_impl_.Initialize(env); } + + // Reads Tensors into `read_tensors`. Returns OK on success, OutOfRange for + // end of file, or an error status if there is an error. + Status ReadTensors(std::vector* read_tensors) override; + + private: + TFRecordReaderImpl reader_impl_; + const DataTypeVector dtypes_; +}; + +// Reads snapshots previously written with `CustomWriter`. +class CustomReader : public Reader { + public: + // The reader input buffer size is deliberately large because the input reader + // will throw an error if the compressed block length cannot fit in the input + // buffer. + static constexpr const int64_t kSnappyReaderInputBufferSizeBytes = + 1 << 30; // 1 GiB + // TODO(b/148804377): Set this in a smarter fashion. + static constexpr const int64_t kSnappyReaderOutputBufferSizeBytes = + 32 << 20; // 32 MiB + static constexpr const size_t kHeaderSize = sizeof(uint64); + + static constexpr const char* const kClassName = "SnapshotReader"; + static constexpr const char* const kReadString = "ReadString"; + static constexpr const char* const kReadCord = "ReadCord"; + static constexpr const char* const kSeparator = "::"; + + CustomReader(const std::string& filename, const string& compression_type, + int version, const DataTypeVector& dtypes); + + Status ReadTensors(std::vector* read_tensors) override; + + ~CustomReader() override = default; + + protected: + Status Initialize(Env* env) override; + + private: + Status ReadTensorsV0(std::vector* read_tensors); + + Status SnappyUncompress( + const experimental::SnapshotTensorMetadata* metadata, + std::vector* simple_tensors, + std::vector, size_t>>* + tensor_proto_strs); + + Status ReadRecord(tstring* record); + +#if defined(TF_CORD_SUPPORT) + Status ReadRecord(absl::Cord* record); +#endif + + std::string filename_; + std::unique_ptr file_; + std::unique_ptr input_stream_; + const string compression_type_; + const int version_; + const DataTypeVector dtypes_; + int num_simple_ = 0; + int num_complex_ = 0; + std::vector simple_tensor_mask_; // true for simple, false for complex. +}; + +// Writes snapshot metadata to the given directory. +Status WriteMetadataFile(Env* env, const string& dir, + const experimental::SnapshotMetadataRecord* metadata); + +// Writes distributed snapshot metadata to the given directory. An error is +// returned if `dir` is unable to be created or if `metadata` is unable to be +// written. +Status WriteMetadataFile( + Env* env, const string& dir, + const experimental::DistributedSnapshotMetadata* metadata); + +// Reads snapshot metadata from the given directory. +Status ReadMetadataFile(Env* env, const string& dir, + experimental::SnapshotMetadataRecord* metadata, + bool* file_exists); + +// Reads distributed snapshot metadata from the given directory. If the file +// doesn't exist in `dir`, `file_exists` is set to true and an ok status is +// returned. If the file exists in `dir` but is unable to be opened, an error +// is returned. +Status ReadMetadataFile(Env* env, const string& dir, + experimental::DistributedSnapshotMetadata* metadata, + bool* file_exists); + +// Writes a dataset graph to the given directory. +Status DumpDatasetGraph(Env* env, const std::string& path, uint64 hash, + const GraphDef* graph); + +Status DetermineOpState(const std::string& mode_string, bool file_exists, + const experimental::SnapshotMetadataRecord* metadata, + uint64 pending_snapshot_expiry_seconds, Mode* mode); + +// Represents a dataset element or EOF. +struct ElementOrEOF { + std::vector value; + bool end_of_sequence = false; +}; + +// AsyncWriter provides API for asynchronously writing dataset elements +// (each represented as a vector of tensors) to a file. +// +// The expected use of this API is: +// +// std::unique_ptr writer = absl_make_unique(...); +// +// while (data_available()) { +// std::vector data = read_data() +// writer->Write(data); +// } +// writer->SignalEOF(); +// writer = nullptr; // This will block until writes are flushed. +class AsyncWriter { + public: + explicit AsyncWriter(Env* env, int64_t file_index, + const std::string& shard_directory, uint64 checkpoint_id, + const std::string& compression, int64_t version, + const DataTypeVector& output_types, + std::function done); + + // Writes the given tensors. The method is non-blocking and returns without + // waiting for the element to be written. + void Write(const std::vector& tensors) TF_LOCKS_EXCLUDED(mu_); + + // Signals the end of input. The method is non-blocking and returns without + // waiting for the writer to be closed. + void SignalEOF() TF_LOCKS_EXCLUDED(mu_); + + private: + void Consume(ElementOrEOF* be) TF_LOCKS_EXCLUDED(mu_); + bool ElementAvailable() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + Status WriterThread(Env* env, const std::string& shard_directory, + uint64 checkpoint_id, const std::string& compression, + int64_t version, DataTypeVector output_types); + + mutex mu_; + std::deque deque_ TF_GUARDED_BY(mu_); + + // This has to be last. During destruction, we need to make sure that the + // Thread object is destroyed first as its destructor blocks on thread + // completion. If there are other member variables after this, they may get + // destroyed first before the thread finishes, potentially causing the + // thread to access invalid memory. + std::unique_ptr thread_; +}; + +} // namespace snapshot_util +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_SNAPSHOT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/split_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/split_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0801d9afd546e752d0dabf63c4cab92125f67cb7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/split_utils.h @@ -0,0 +1,94 @@ +/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_SPLIT_UTILS_H_ +#define TENSORFLOW_CORE_DATA_SPLIT_UTILS_H_ + +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/tensor.h" +#include "tsl/platform/mutex.h" +#include "tsl/platform/thread_annotations.h" + +namespace tensorflow { +namespace data { + +// A class which produces splits for a dataset of size N that can be indexed +// into. +class IndexSplitProvider : public SplitProvider { + public: + explicit IndexSplitProvider(int64_t n); + absl::Status GetNext(Tensor* split, bool* end_of_splits) override; + absl::Status Reset() override; + absl::Status Save(std::function full_name, + IteratorStateWriter* writer) override; + absl::Status Restore(std::function full_name, + IteratorStateReader* reader) override; + + private: + tsl::mutex mu_; + int64_t i_ TF_GUARDED_BY(mu_); + const int64_t n_; +}; + +// A SplitProvider which wraps another split provider, but drops all splits +// where `index != shard_index % num_shards` +class ShardingSplitProvider : public SplitProvider { + public: + ShardingSplitProvider(int64_t num_shards, int64_t shard_index, + std::shared_ptr split_provider); + + absl::Status GetNext(Tensor* split, bool* end_of_splits) override; + absl::Status Reset() override; + absl::Status Save(std::function full_name, + IteratorStateWriter* writer) override; + absl::Status Restore(std::function full_name, + IteratorStateReader* reader) override; + + private: + const int64_t num_shards_; + const int64_t shard_index_; + tsl::mutex mu_; + std::shared_ptr split_provider_ TF_GUARDED_BY(mu_); + int64_t num_to_skip_ TF_GUARDED_BY(mu_); +}; + +// Returns split providers for all sources of the given dataset. +absl::StatusOr>> GetSplitProviders( + const DatasetBase* dataset); + +// Gets the single split provider from the context, or returns an error if the +// context has zero or multiple split providers. The `dataset` argument is used +// to produce a more useful error message. +absl::StatusOr> GetSingleSplitProvider( + IteratorContext* ctx, const DatasetBase* dataset); + +// Creates iterator contexts for datasets inputs. The split providers +// in `ctx` will be divided among the inputs of `dataset`, so that each input +// gets a number of split providers that matches its number of source datasets. +// If no split providers are defined, the contexts will be the same as `ctx`. +absl::StatusOr> CreateInputIteratorContexts( + IteratorContext* ctx, const DatasetBase* dataset); + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_SPLIT_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/stats_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/stats_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..5fa1eae397b39e9b03dcc1fb6a51f2dbdca7f1f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/stats_utils.h @@ -0,0 +1,68 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DATA_STATS_UTILS_H_ +#define TENSORFLOW_CORE_DATA_STATS_UTILS_H_ + +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace data { +namespace stats_utils { +extern const char kDelimiter[]; +extern const char kExecutionTime[]; +extern const char kThreadUtilization[]; +extern const char kBufferSize[]; +extern const char kBufferCapacity[]; +extern const char kBufferUtilization[]; +extern const char kFilteredElements[]; +extern const char kDroppedElements[]; +extern const char kFeaturesCount[]; +extern const char kFeatureValuesCount[]; +extern const char kExamplesCount[]; + +// Name for tf.data function execution time (in ns) histogram metrics. +string ExecutionTimeHistogramName(const string& prefix); + +// Name for thread utilization (ratio of threads being used and maximum number +// of threads allocated) scalar metrics. +string ThreadUtilizationScalarName(const string& prefix); + +// Name for buffer size scalar metrics. +string BufferSizeScalarName(const string& prefix); + +// Name for buffer capacity (maximum allocated buffer size) scalar metrics. +string BufferCapacityScalarName(const string& prefix); + +// Name for buffer utilization (ratio of buffer size and maximum allocated +// buffer size.) histogram metrics. +string BufferUtilizationHistogramName(const string& prefix); + +// Name for filtered elements scalar metrics. +string FilterdElementsScalarName(const string& prefix); + +// Name for dropped elements scalar mereics. +string DroppedElementsScalarName(const string& prefix); + +// Name for features count histogram metrics. +string FeatureHistogramName(const string& prefix); + +// Name for feature-values count histogram metrics. +string FeatureValueHistogramName(const string& prefix); + +} // namespace stats_utils +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_STATS_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/tfdataz_metrics.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/tfdataz_metrics.h new file mode 100644 index 0000000000000000000000000000000000000000..bb59a73f8d04fd40b88a5bb6562390ca4a51ba62 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/tfdataz_metrics.h @@ -0,0 +1,144 @@ +/* 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_DATA_TFDATAZ_METRICS_H_ +#define TENSORFLOW_CORE_DATA_TFDATAZ_METRICS_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/time/time.h" +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" + +namespace tensorflow { +namespace data { + +// Calculates the approximate average latency for past 1, 5 and 60 minutes. +// The implementation uses ring buffers to maintain the cumulative latency +// values and count for the past 60 minutes. +class ApproximateLatencyEstimator { + public: + enum class Duration { + kMinute = 1, + kFiveMinutes = 5, + kSixtyMinutes = 60, + }; + + explicit ApproximateLatencyEstimator(const Env& env); + + // Records the latency with the current timestamp. + void AddLatency(int64_t latency_usec); + + // Returns the average latency for the duration (1,5 and 60 minutes) + // specified. + absl::Duration GetAverageLatency(Duration duration); + + private: + static constexpr int64_t kSecondsPerMinute = 60; + static constexpr int64_t kMinutesPerHour = 60; + static constexpr int64_t kSlots = kMinutesPerHour; + + // Updates the latency value and count ring buffers with the latest cumulative + // value and count. Resets the entire ring buffer with the last cumulative + // values stored if the elapsed time duration is greater than 60 minutes. + void UpdateRingBuffer() TF_LOCKS_EXCLUDED(mu_); + // Moves the `next_slot_` to the next index in the ring buffer. + void IncrementNextSlot() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + // Returns the slot index which is behind the current slot in ring buffer by + // `steps` indices. + int PrevSlot(int steps) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + const Env& env_; + + // The time when the ring buffer was last updated. + int64_t last_updated_time_mins_ TF_GUARDED_BY(mu_); + + mutex mu_; + + // Counters storing the cumulative sums of latency values and counts recorded + // so far. + int64_t latency_value_counter_ TF_GUARDED_BY(mu_); + int64_t latency_count_counter_ TF_GUARDED_BY(mu_); + + // Next slot in the ring buffer. + int next_slot_ TF_GUARDED_BY(mu_); + + // Ring buffer storing the cumulative sum of latency values and counts for the + // last 60 minutes. + int64_t latency_value_[kSlots] TF_GUARDED_BY(mu_); + int64_t latency_count_[kSlots] TF_GUARDED_BY(mu_); +}; + +// Collects and exports the tf.data performance metrics to /tfdataz. +class TfDatazMetricsCollector { + public: + // Constructs a `TfDatazMetricsCollector`. + // We only collect metrics for CPU devices. This is a heuristic to avoid + // collecting metrics for device-side iterators created by the multi-device + // iterator mechanism. + TfDatazMetricsCollector(const Env& env, IteratorBase* iterator); + + // Records `GetNext` call latency. + void RecordGetNextLatency(int64_t get_next_latency_usec); + + // Returns the average `GetNext` latency for past 1 minute. + absl::Duration GetAverageLatencyForLastOneMinute(); + + // Returns the average `GetNext` latency for past 5 minutes. + absl::Duration GetAverageLatencyForLastFiveMinutes(); + + // Returns the average `GetNext` latency for past 60 minutes. + absl::Duration GetAverageLatencyForLastSixtyMinutes(); + + // Returns the total memory (in bytes) used by the iterator. + // Total memory used by the iterator includes the total number of bytes + // buffered in all nodes in the subtree. + int64_t GetIteratorTotalMemoryUsage(); + + private: + IteratorBase* iterator_; // not owned + ApproximateLatencyEstimator latency_estimator_; +}; + +// Thread-safe global registry for the /tfdataz metrics. All callers to +// `TfDatazMetricsRegistry` use the same instance to register and deregister +// iterator's `TfDatazMetricsCollector`. +class TfDatazMetricsRegistry { + public: + // Registers the iterator specific `TfDatazMetricsCollector` in the global + // TfDatazMetricsRegistry. + static void Register(std::shared_ptr collector); + + // Deregisters the iterator specific `TfDatazMetricsCollector` from the global + // TfDatazMetricsRegistry. + static void Deregister(std::shared_ptr collector); + + // Returns all the registered `TfDatazMetricsCollector`s. + static absl::flat_hash_set> + GetIteratorMetricCollectors(); +}; + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_TFDATAZ_METRICS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/unbounded_thread_pool.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/unbounded_thread_pool.h new file mode 100644 index 0000000000000000000000000000000000000000..f790c938c050dd59491e614e17b9c5bd524ee31b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/unbounded_thread_pool.h @@ -0,0 +1,66 @@ +/* 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_DATA_UNBOUNDED_THREAD_POOL_H_ +#define TENSORFLOW_CORE_DATA_UNBOUNDED_THREAD_POOL_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/framework/thread_factory.h" +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/core/threadpool_interface.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/unbounded_work_queue.h" + +namespace tensorflow { +namespace data { + +// An `UnboundedThreadPool` provides a mechanism for temporally multiplexing a +// potentially large number of "logical" threads onto a smaller number of +// "physical" threads. The multiplexing is achieved by using an +// `UnboundedWorkQueue`. +class UnboundedThreadPool : public thread::ThreadPoolInterface { + public: + UnboundedThreadPool(Env* env, const string& thread_name) + : unbounded_work_queue_(env, thread_name) {} + UnboundedThreadPool(Env* env, const string& thread_name, + const ThreadOptions& thread_options) + : unbounded_work_queue_(env, thread_name, thread_options) {} + ~UnboundedThreadPool() override = default; + + // Returns an implementation of `ThreadFactory` that can be used to create + // logical threads in this pool. + std::shared_ptr get_thread_factory(); + + void Schedule(std::function fn) override; + int NumThreads() const override; + int CurrentThreadId() const override; + + private: + class LogicalThreadFactory; + class LogicalThreadWrapper; + + void ScheduleOnWorkQueue(std::function fn, + std::shared_ptr done); + + UnboundedWorkQueue unbounded_work_queue_; +}; + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_UNBOUNDED_THREAD_POOL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..d80431c9680ab8f2ce7347ba6c38f4868cf51214 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/data/utils.h @@ -0,0 +1,54 @@ +/* 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_DATA_UTILS_H_ +#define TENSORFLOW_CORE_DATA_UTILS_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/status/statusor.h" +#include "tensorflow/core/protobuf/data_service.pb.h" + +namespace tensorflow { +namespace data { + +// Records latency of fetching data from tf.data iterator. +void AddLatencySample(int64_t microseconds); + +// Records bytes produced by a tf.data iterator. +void IncrementThroughput(int64_t bytes); + +// Returns a modified file name that can be used to do implementation specific +// file name manipulation/optimization. +std::string TranslateFileName(const std::string& fname); + +// Returns the data transfer protocol to use if one is not specified by the +// user. +std::string DefaultDataTransferProtocol(); + +// Returns a path pointing to the same file as `path` with a potential locality +// optimization. +std::string LocalityOptimizedPath(const std::string& path); + +// Returns `true` if tf.data service compression should be disabled at runtime +// based on (1) the inputs or (2) the properties of the calling trainer. +absl::StatusOr DisableCompressionAtRuntime( + const std::string& data_transfer_protocol, DeploymentMode deployment_mode); + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DATA_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_callback_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_callback_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..94b57401418eb9a9bb454455b716eb356f82b531 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_callback_registry.h @@ -0,0 +1,71 @@ +/* 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_DEBUG_DEBUG_CALLBACK_REGISTRY_H_ +#define TENSORFLOW_CORE_DEBUG_DEBUG_CALLBACK_REGISTRY_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/debug/debug_node_key.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { + +// Supports exporting observed debug events to clients using registered +// callbacks. Users can register a callback for each debug_url stored using +// DebugTensorWatch. The callback key be equivalent to what follows +// "memcbk:///". +// +// All events generated for a watched node will be sent to the call back in the +// order that they are observed. +// +// This callback router should not be used in production or training steps. It +// is optimized for deep inspection of graph state rather than performance. +class DebugCallbackRegistry { + public: + using EventCallback = std::function; + + // Provides singleton access to the in memory event store. + static DebugCallbackRegistry* singleton(); + + // Returns the registered callback, or nullptr, for key. + EventCallback* GetCallback(const string& key); + + // Associates callback with key. This must be called by clients observing + // nodes to be exported by this callback router before running a session. + void RegisterCallback(const string& key, EventCallback callback); + + // Removes the callback associated with key. + void UnregisterCallback(const string& key); + + private: + DebugCallbackRegistry(); + + // Mutex to ensure that keyed events are never updated in parallel. + mutex mu_; + + // Maps debug_url keys to callbacks for routing observed tensors. + std::map keyed_callback_ TF_GUARDED_BY(mu_); + + static DebugCallbackRegistry* instance_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DEBUG_DEBUG_CALLBACK_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_graph_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_graph_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..86dc90a13483fb8cee13ecc5fc1e38994f586235 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_graph_utils.h @@ -0,0 +1,126 @@ +/* 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_DEBUG_DEBUG_GRAPH_UTILS_H_ +#define TENSORFLOW_CORE_DEBUG_DEBUG_GRAPH_UTILS_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/debugger_state_interface.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/protobuf/debug.pb.h" + +namespace tensorflow { + +class DebugNodeInserter { + public: + // EXPERIMENTAL: Insert special debug ops (e.g., DebugIdentity) to graph for + // debugging. Currently, such ops need to take exactly one input and has the + // string attribute "tensor_name" to indicate what tensor it watches. + // For example, before the node insertion, the graph may look like: + // + // A:0 -----------1----------> B + // | + // ---------2-----------> C + // + // wherein the output slot 0 of node A feeds as the input to nodes B through + // edge 1 and to node C through edge 2. + // After the node insertion, assuming both B and C have non-Ref input, the + // graph becomes: + // A:0 ---3---> Copy -----------4----------> B + // | + // ---------5--------> C + // | + // ---------6--------> X + // + // If a node (e.g., B) has Ref input, the graph becomes: + // + // --------------------------------> B + // | + // A:0 ---3-----> Copy -----------4----------> C + // | + // -----------5--------> X + // + // In other words, we do not feed Refs to deep-copies to downstream nodes. + // + // Copy is the inserted deep-copy node that copies the input tensor on-device + // (e.g., CPU-to-CPU or GPU-to-GPU deep copy) that reduces the likelihood of + // racy updates during the debug watches. X is the newly created debug node + // that transforms the input (copy of the watched tensor) into a debug signal. + // + // DebugIdentity is the simplest debugging paradigm, in which the debug signal + // (i.e., X:0) equals the tensor itself. More sophisticated debug ops can be + // used to transform the tensor into other debug signals. An example is the + // DebugNanCounter op. + // + // If the nodes (A, B and C) are located on GPU and the edges from A to B or C + // is HOST_MEMORY, then the CopyHost op will be used instead of the Copy op. + static Status InsertNodes( + const protobuf::RepeatedPtrField& watches, Graph* graph, + Device* device); + + // Set the parallel_iterations attribute of TensorFlow while loops + // (specifically the nodes for which IsEnter() returns true) to 1 to prevent + // any node from being executed multiple times concurrently and + // generating temporally-overlapping debug Tensor dumps. + static void DeparallelizeWhileLoops(Graph* graph, Device* device); + + // Get canonical name of a copy node. + static const string GetCopyNodeName(const string& node_name, + const int output_slot); + + // Get canonical name of a debug node. + static const string GetDebugNodeName(const string& tensor_name, + const int debug_op_num, + const string& debug_op_name); + + private: + static Status CreateCopyNode( + Graph* graph, const DeviceType device_type, const bool is_host_memory, + const string& src_node_name, const int src_output, const DataType src_dt, + const string& tensor_name, const std::vector& debug_ops, + const std::vector& debug_urls, Node** copy_node); + + // Parse the debug_op_name string to extract proper op name and attributes. + // debug_op_name can be the proper op name only, e.g., "DebugNumericSummary". + // It can also contain customizable keys and values. Each key-value pair is + // connected with an equal sign ("="). Multiple key-value pairs are separated + // with semicolons (";"), which optional whitespace in between, e.g., + // "DebugNumericSummary(mute_if_healthy=true, lower_bound=-100.0)". + static Status ParseDebugOpName( + const string& debug_op_name, string* debug_op_name_proper, + std::unordered_map* attributes); + + static Status SetDebugNodeAttributes( + Node* debug_node, const std::unordered_map& attributes); + + static Status CreateDebugNode(Graph* graph, const Device& device, + const string& src_copy_node_name, + const DataType src_dt, + const string& tensor_name, + const std::vector& debug_urls, + const int debug_op_num, + const string& debug_op_name, Node** debug_node); + // TODO(cais): Cut down the number of args to this method. + + friend class DebugGraphUtilsTest; +}; +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DEBUG_DEBUG_GRAPH_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_io_utils.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_io_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0f0054eaa03e5d9da62790680e31e174a7b519fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_io_utils.h @@ -0,0 +1,447 @@ +/* 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_DEBUG_DEBUG_IO_UTILS_H_ +#define TENSORFLOW_CORE_DEBUG_DEBUG_IO_UTILS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tensorflow/core/debug/debug_node_key.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/array_slice.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/util/event.pb.h" + +namespace tensorflow { + +Status ReadEventFromFile(const string& dump_file_path, Event* event); + +struct DebugWatchAndURLSpec { + DebugWatchAndURLSpec(const string& watch_key, const string& url, + const bool gated_grpc) + : watch_key(watch_key), url(url), gated_grpc(gated_grpc) {} + + const string watch_key; + const string url; + const bool gated_grpc; +}; + +// TODO(cais): Put static functions and members in a namespace, not a class. +class DebugIO { + public: + static const char* const kDebuggerPluginName; + + static const char* const kCoreMetadataTag; + static const char* const kGraphTag; + static const char* const kHashTag; + + static const char* const kFileURLScheme; + static const char* const kGrpcURLScheme; + static const char* const kMemoryURLScheme; + + static Status PublishDebugMetadata( + const int64_t global_step, const int64_t session_run_index, + const int64_t executor_step_index, const std::vector& input_names, + const std::vector& output_names, + const std::vector& target_nodes, + const std::unordered_set& debug_urls); + + // Publishes a tensor to a debug target URL. + // + // Args: + // debug_node_key: A DebugNodeKey identifying the debug node. If + // `debug_node_key.io_of_node` is non-empty, publish for node + // inputs/outputs dumping feature. + // tensor: The Tensor object being published. + // wall_time_us: Time stamp for the Tensor. Unit: microseconds (us). + // debug_urls: An array of debug target URLs, e.g., + // "file:///foo/tfdbg_dump", "grpc://localhost:11011" + // gated_grpc: Whether this call is subject to gRPC gating. + // step_id: Step ID associated with the tensor. + static Status PublishDebugTensor(const DebugNodeKey& debug_node_key, + const Tensor& tensor, + const uint64 wall_time_us, + const gtl::ArraySlice debug_urls, + bool gated_grpc, int64_t step_id = -1); + + // Convenience overload of the method above for no gated_grpc by default. + static Status PublishDebugTensor(const DebugNodeKey& debug_node_key, + const Tensor& tensor, + const uint64 wall_time_us, + const gtl::ArraySlice debug_urls); + + // Publishes a graph to a set of debug URLs. + // + // Args: + // graph: The graph to be published. + // debug_urls: The set of debug URLs to publish the graph to. + static Status PublishGraph(const Graph& graph, const string& device_name, + const std::unordered_set& debug_urls); + + // Determines whether a copy node needs to perform deep-copy of input tensor. + // + // The input arguments contain sufficient information about the attached + // downstream debug ops for this method to determine whether all the said + // ops are disabled given the current status of the gRPC gating. + // + // Args: + // specs: A vector of DebugWatchAndURLSpec carrying information about the + // debug ops attached to the Copy node, their debug URLs and whether + // they have the attribute value gated_grpc == True. + // + // Returns: + // Whether any of the attached downstream debug ops is enabled given the + // current status of the gRPC gating. + static bool IsCopyNodeGateOpen( + const std::vector& specs); + + // Determines whether a debug node needs to proceed given the current gRPC + // gating status. + // + // Args: + // watch_key: debug tensor watch key, in the format of + // tensor_name:debug_op, e.g., "Weights:0:DebugIdentity". + // debug_urls: the debug URLs of the debug node. + // + // Returns: + // Whether this debug op should proceed. + static bool IsDebugNodeGateOpen(const string& watch_key, + const std::vector& debug_urls); + + // Determines whether debug information should be sent through a grpc:// + // debug URL given the current gRPC gating status. + // + // Args: + // watch_key: debug tensor watch key, in the format of + // tensor_name:debug_op, e.g., "Weights:0:DebugIdentity". + // debug_url: the debug URL, e.g., "grpc://localhost:3333", + // "file:///tmp/tfdbg_1". + // + // Returns: + // Whether the sending of debug data to the debug_url should + // proceed. + static bool IsDebugURLGateOpen(const string& watch_key, + const string& debug_url); + + static Status CloseDebugURL(const string& debug_url); +}; + +// Helper class for debug ops. +class DebugFileIO { + public: + // Encapsulates the Tensor in an Event protobuf and write it to a directory. + // The actual path of the dump file will be a contactenation of + // dump_root_dir, tensor_name, along with the wall_time. + // + // For example: + // let dump_root_dir = "/tmp/tfdbg_dump", + // node_name = "foo/bar", + // output_slot = 0, + // debug_op = DebugIdentity, + // and wall_time_us = 1467891234512345, + // the dump file will be generated at path: + // /tmp/tfdbg_dump/foo/bar_0_DebugIdentity_1467891234512345. + // + // Args: + // debug_node_key: A DebugNodeKey identifying the debug node. + // wall_time_us: Wall time at which the Tensor is generated during graph + // execution. Unit: microseconds (us). + // dump_root_dir: Root directory for dumping the tensor. + // dump_file_path: The actual dump file path (passed as reference). + static Status DumpTensorToDir(const DebugNodeKey& debug_node_key, + const Tensor& tensor, const uint64 wall_time_us, + const string& dump_root_dir, + string* dump_file_path); + + // Similar to the above, but for node inputs/outputs dumping feature. + static Status DumpTensorToDirForNodeDumping( + const DebugNodeKey& debug_node_key, const Tensor& tensor, + uint64 wall_time_us, const string& dump_root_dir, string* dump_file_path, + int64_t step_id); + + // Get the full path to the dump file. + // + // Args: + // dump_root_dir: The dump root directory, e.g., /tmp/tfdbg_dump + // node_name: Name of the node from which the dumped tensor is generated, + // e.g., foo/bar/node_a + // output_slot: Output slot index of the said node, e.g., 0. + // debug_op: Name of the debug op, e.g., DebugIdentity. + // wall_time_us: Time stamp of the dumped tensor, in microseconds (us). + static string GetDumpFilePath(const string& dump_root_dir, + const DebugNodeKey& debug_node_key, + const uint64 wall_time_us); + + // Similar to the above, but for node inputs/outputs dumping feature. + static string GetDumpFilePathForNodeDumping( + const string& dump_root_dir, const DebugNodeKey& debug_node_key, + uint64 wall_time_us, int64_t step_id); + + // Dumps an Event proto to a file. + // + // Args: + // event_prot: The Event proto to be dumped. + // dir_name: Directory path. + // file_name: Base file name. + static Status DumpEventProtoToFile(const Event& event_proto, + const string& dir_name, + const string& file_name); + + // Request additional bytes to be dumped to the file system. + // + // Does not actually dump the bytes, but instead just performs the + // bookkeeping necessary to prevent the total dumped amount of data from + // exceeding the limit (default 100 GBytes or set customly through the + // environment variable TFDBG_DISK_BYTES_LIMIT). + // + // Args: + // bytes: Number of bytes to request. + // + // Returns: + // Whether the request is approved given the total dumping + // limit. + static bool requestDiskByteUsage(uint64 bytes); + + // Reset the disk byte usage to zero. + static void resetDiskByteUsage(); + + static uint64 global_disk_bytes_limit_; + + private: + // Encapsulates the Tensor in an Event protobuf and write it to file. + static Status DumpTensorToEventFile(const DebugNodeKey& debug_node_key, + const Tensor& tensor, + const uint64 wall_time_us, + const string& file_path); + + // Implemented ad hoc here for now. + // TODO(cais): Replace with shared implementation once http://b/30497715 is + // fixed. + static Status RecursiveCreateDir(Env* env, const string& dir); + + // Tracks how much disk has been used so far. + static uint64 disk_bytes_used_; + // Mutex for thread-safe access to disk_bytes_used_. + static mutex bytes_mu_; + // Default limit for the disk space. + static const uint64 kDefaultGlobalDiskBytesLimit; + + friend class DiskUsageLimitTest; +}; + +} // namespace tensorflow + +namespace std { + +template <> +struct hash<::tensorflow::DebugNodeKey> { + size_t operator()(const ::tensorflow::DebugNodeKey& k) const { + return ::tensorflow::Hash64( + ::tensorflow::strings::StrCat(k.device_name, ":", k.node_name, ":", + k.output_slot, ":", k.debug_op, ":")); + } +}; + +} // namespace std + +// TODO(cais): Support grpc:// debug URLs in open source once Python grpc +// genrule becomes available. See b/23796275. +#ifndef PLATFORM_WINDOWS +#include "grpcpp/channel.h" +#include "tensorflow/core/debug/debug_service.grpc.pb.h" + +namespace tensorflow { + +class DebugGrpcChannel { + public: + // Constructor of DebugGrpcChannel. + // + // Args: + // server_stream_addr: Address (host name and port) of the debug stream + // server implementing the EventListener service (see + // debug_service.proto). E.g., "127.0.0.1:12345". + explicit DebugGrpcChannel(const string& server_stream_addr); + + virtual ~DebugGrpcChannel() {} + + // Attempt to establish connection with server. + // + // Args: + // timeout_micros: Timeout (in microseconds) for the attempt to establish + // the connection. + // + // Returns: + // OK Status iff connection is successfully established before timeout, + // otherwise return an error Status. + Status Connect(const int64_t timeout_micros); + + // Write an Event proto to the debug gRPC stream. + // + // Thread-safety: Safe with respect to other calls to the same method and + // calls to ReadEventReply() and Close(). + // + // Args: + // event: The event proto to be written to the stream. + // + // Returns: + // True iff the write is successful. + bool WriteEvent(const Event& event); + + // Read an EventReply proto from the debug gRPC stream. + // + // This method blocks and waits for an EventReply from the server. + // Thread-safety: Safe with respect to other calls to the same method and + // calls to WriteEvent() and Close(). + // + // Args: + // event_reply: the to-be-modified EventReply proto passed as reference. + // + // Returns: + // True iff the read is successful. + bool ReadEventReply(EventReply* event_reply); + + // Receive and process EventReply protos from the gRPC debug server. + // + // The processing includes setting debug watch key states using the + // DebugOpStateChange fields of the EventReply. + // + // Args: + // max_replies: Maximum number of replies to receive. Will receive all + // remaining replies iff max_replies == 0. + void ReceiveAndProcessEventReplies(size_t max_replies); + + // Receive EventReplies from server (if any) and close the stream and the + // channel. + Status ReceiveServerRepliesAndClose(); + + private: + string server_stream_addr_; + string url_; + ::grpc::ClientContext ctx_; + std::shared_ptr<::grpc::Channel> channel_; + std::unique_ptr stub_; + std::unique_ptr<::grpc::ClientReaderWriterInterface> + reader_writer_; + + mutex mu_; +}; + +class DebugGrpcIO { + public: + static const size_t kGrpcMessageSizeLimitBytes; + static const size_t kGrpcMaxVarintLengthSize; + + // Sends a tensor through a debug gRPC stream. + static Status SendTensorThroughGrpcStream(const DebugNodeKey& debug_node_key, + const Tensor& tensor, + const uint64 wall_time_us, + const string& grpc_stream_url, + const bool gated); + + // Sends an Event proto through a debug gRPC stream. + // Thread-safety: Safe with respect to other calls to the same method and + // calls to CloseGrpcStream(). + // + // Args: + // event_proto: The Event proto to be sent. + // grpc_stream_url: The grpc:// URL of the stream to use, e.g., + // "grpc://localhost:11011", "localhost:22022". + // receive_reply: Whether an EventReply proto will be read after event_proto + // is sent and before the function returns. + // + // Returns: + // The Status of the operation. + static Status SendEventProtoThroughGrpcStream( + const Event& event_proto, const string& grpc_stream_url, + const bool receive_reply = false); + + // Receive an EventReply proto through a debug gRPC stream. + static Status ReceiveEventReplyProtoThroughGrpcStream( + EventReply* event_reply, const string& grpc_stream_url); + + // Check whether a debug watch key is read-activated at a given gRPC URL. + static bool IsReadGateOpen(const string& grpc_debug_url, + const string& watch_key); + + // Check whether a debug watch key is write-activated (i.e., read- and + // write-activated) at a given gRPC URL. + static bool IsWriteGateOpen(const string& grpc_debug_url, + const string& watch_key); + + // Closes a gRPC stream to the given address, if it exists. + // Thread-safety: Safe with respect to other calls to the same method and + // calls to SendTensorThroughGrpcStream(). + static Status CloseGrpcStream(const string& grpc_stream_url); + + // Set the gRPC state of a debug node key. + // TODO(cais): Include device information in watch_key. + static void SetDebugNodeKeyGrpcState( + const string& grpc_debug_url, const string& watch_key, + const EventReply::DebugOpStateChange::State new_state); + + private: + using DebugNodeName2State = + std::unordered_map; + + // Returns a global map from grpc debug URLs to the corresponding + // DebugGrpcChannels. + static std::unordered_map>* + GetStreamChannels(); + + // Get a DebugGrpcChannel object at a given URL, creating one if necessary. + // + // Args: + // grpc_stream_url: grpc:// URL of the stream, e.g., "grpc://localhost:6064" + // debug_grpc_channel: A pointer to the DebugGrpcChannel object, passed as a + // a pointer to the pointer. The DebugGrpcChannel object is owned + // statically elsewhere, not by the caller of this function. + // + // Returns: + // Status of this operation. + static Status GetOrCreateDebugGrpcChannel( + const string& grpc_stream_url, DebugGrpcChannel** debug_grpc_channel); + + // Returns a map from debug URL to a map from debug op name to enabled state. + static std::unordered_map* + GetEnabledDebugOpStates(); + + // Returns a map from debug op names to enabled state, for a given debug URL. + static DebugNodeName2State* GetEnabledDebugOpStatesAtUrl( + const string& grpc_debug_url); + + // Clear enabled debug op state from all debug URLs (if any). + static void ClearEnabledWatchKeys(); + + static mutex streams_mu_; + static int64_t channel_connection_timeout_micros_; + + friend class GrpcDebugTest; + friend class DebugNumericSummaryOpTest; +}; + +} // namespace tensorflow +#endif // #ifndef(PLATFORM_WINDOWS) + +#endif // TENSORFLOW_CORE_DEBUG_DEBUG_IO_UTILS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_node_key.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_node_key.h new file mode 100644 index 0000000000000000000000000000000000000000..5decb5cc68364359f130ff76ae962789f730b513 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_node_key.h @@ -0,0 +1,56 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DEBUG_DEBUG_NODE_KEY_H_ +#define TENSORFLOW_CORE_DEBUG_DEBUG_NODE_KEY_H_ + +#include + +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// Encapsulates debug information for a node that was observed. +struct DebugNodeKey { + static const char* const kMetadataFilePrefix; + static const char* const kDeviceTag; + + DebugNodeKey(const string& device_name, const string& node_name, + int32_t output_slot, const string& debug_op, + const string& io_of_node = "", bool is_input = false, + int32_t io_index = -1); + + // Converts a device name string to a device path string. + // E.g., /job:localhost/replica:0/task:0/cpu:0 will be converted to + // ,job_localhost,replica_0,task_0,cpu_0. + static const string DeviceNameToDevicePath(const string& device_name); + + bool operator==(const DebugNodeKey& other) const; + bool operator!=(const DebugNodeKey& other) const; + + const string device_name; + const string node_name; + const int32 output_slot; + const string debug_op; + const string debug_node_name; + const string device_path; + const string io_of_node; + const bool is_input; + const int32 io_index; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DEBUG_DEBUG_NODE_KEY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service.grpc.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service.grpc.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..eaa2227279f7b4d830a64ceb3c6f9977361530c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service.grpc.pb.h @@ -0,0 +1,722 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: tensorflow/core/debug/debug_service.proto +// Original file comments: +// 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 GRPC_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto__INCLUDED +#define GRPC_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto__INCLUDED + +#include "tensorflow/core/debug/debug_service.pb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace tensorflow { + + +namespace grpc { + +// EventListener: Receives Event protos, e.g., from debugged TensorFlow +// runtime(s). +class EventListener final { + public: + static constexpr char const* service_full_name() { + return "tensorflow.EventListener"; + } + class StubInterface { + public: + virtual ~StubInterface() {} + // Client(s) can use this RPC method to send the EventListener Event protos. + // The Event protos can hold information such as: + // 1) intermediate tensors from a debugged graph being executed, which can + // be sent from DebugIdentity ops configured with grpc URLs. + // 2) GraphDefs of partition graphs, which can be sent from special debug + // ops that get executed immediately after the beginning of the graph + // execution. + std::unique_ptr< ::grpc::ClientReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>> SendEvents(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>>(SendEventsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>> AsyncSendEvents(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>>(AsyncSendEventsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>> PrepareAsyncSendEvents(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>>(PrepareAsyncSendEventsRaw(context, cq)); + } + // Send the tracebacks of a TensorFlow execution call. + virtual ::grpc::Status SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::tensorflow::EventReply* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>> AsyncSendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>>(AsyncSendTracebacksRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>> PrepareAsyncSendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>>(PrepareAsyncSendTracebacksRaw(context, request, cq)); + } + // Send a collection of source code files being debugged. + virtual ::grpc::Status SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::tensorflow::EventReply* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>> AsyncSendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>>(AsyncSendSourceFilesRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>> PrepareAsyncSendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>>(PrepareAsyncSendSourceFilesRaw(context, request, cq)); + } + class experimental_async_interface { + public: + virtual ~experimental_async_interface() {} + // Client(s) can use this RPC method to send the EventListener Event protos. + // The Event protos can hold information such as: + // 1) intermediate tensors from a debugged graph being executed, which can + // be sent from DebugIdentity ops configured with grpc URLs. + // 2) GraphDefs of partition graphs, which can be sent from special debug + // ops that get executed immediately after the beginning of the graph + // execution. + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual void SendEvents(::grpc::ClientContext* context, ::grpc::ClientBidiReactor< ::tensorflow::Event,::tensorflow::EventReply>* reactor) = 0; + #else + virtual void SendEvents(::grpc::ClientContext* context, ::grpc::experimental::ClientBidiReactor< ::tensorflow::Event,::tensorflow::EventReply>* reactor) = 0; + #endif + // Send the tracebacks of a TensorFlow execution call. + virtual void SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response, std::function) = 0; + virtual void SendTracebacks(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, std::function) = 0; + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual void SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) = 0; + #else + virtual void SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) = 0; + #endif + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual void SendTracebacks(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) = 0; + #else + virtual void SendTracebacks(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) = 0; + #endif + // Send a collection of source code files being debugged. + virtual void SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response, std::function) = 0; + virtual void SendSourceFiles(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, std::function) = 0; + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual void SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) = 0; + #else + virtual void SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) = 0; + #endif + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual void SendSourceFiles(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) = 0; + #else + virtual void SendSourceFiles(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) = 0; + #endif + }; + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + typedef class experimental_async_interface async_interface; + #endif + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + async_interface* async() { return experimental_async(); } + #endif + virtual class experimental_async_interface* experimental_async() { return nullptr; } + private: + virtual ::grpc::ClientReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>* SendEventsRaw(::grpc::ClientContext* context) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>* AsyncSendEventsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>* PrepareAsyncSendEventsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>* AsyncSendTracebacksRaw(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>* PrepareAsyncSendTracebacksRaw(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>* AsyncSendSourceFilesRaw(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>* PrepareAsyncSendSourceFilesRaw(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + std::unique_ptr< ::grpc::ClientReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>> SendEvents(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>>(SendEventsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>> AsyncSendEvents(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>>(AsyncSendEventsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>> PrepareAsyncSendEvents(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>>(PrepareAsyncSendEventsRaw(context, cq)); + } + ::grpc::Status SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::tensorflow::EventReply* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>> AsyncSendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>>(AsyncSendTracebacksRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>> PrepareAsyncSendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>>(PrepareAsyncSendTracebacksRaw(context, request, cq)); + } + ::grpc::Status SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::tensorflow::EventReply* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>> AsyncSendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>>(AsyncSendSourceFilesRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>> PrepareAsyncSendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>>(PrepareAsyncSendSourceFilesRaw(context, request, cq)); + } + class experimental_async final : + public StubInterface::experimental_async_interface { + public: + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + void SendEvents(::grpc::ClientContext* context, ::grpc::ClientBidiReactor< ::tensorflow::Event,::tensorflow::EventReply>* reactor) override; + #else + void SendEvents(::grpc::ClientContext* context, ::grpc::experimental::ClientBidiReactor< ::tensorflow::Event,::tensorflow::EventReply>* reactor) override; + #endif + void SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response, std::function) override; + void SendTracebacks(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, std::function) override; + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + void SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) override; + #else + void SendTracebacks(::grpc::ClientContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) override; + #endif + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + void SendTracebacks(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) override; + #else + void SendTracebacks(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) override; + #endif + void SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response, std::function) override; + void SendSourceFiles(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, std::function) override; + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + void SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) override; + #else + void SendSourceFiles(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) override; + #endif + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + void SendSourceFiles(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::ClientUnaryReactor* reactor) override; + #else + void SendSourceFiles(::grpc::ClientContext* context, const ::grpc::ByteBuffer* request, ::tensorflow::EventReply* response, ::grpc::experimental::ClientUnaryReactor* reactor) override; + #endif + private: + friend class Stub; + explicit experimental_async(Stub* stub): stub_(stub) { } + Stub* stub() { return stub_; } + Stub* stub_; + }; + class experimental_async_interface* experimental_async() override { return &async_stub_; } + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + class experimental_async async_stub_{this}; + ::grpc::ClientReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>* SendEventsRaw(::grpc::ClientContext* context) override; + ::grpc::ClientAsyncReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>* AsyncSendEventsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReaderWriter< ::tensorflow::Event, ::tensorflow::EventReply>* PrepareAsyncSendEventsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>* AsyncSendTracebacksRaw(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>* PrepareAsyncSendTracebacksRaw(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>* AsyncSendSourceFilesRaw(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< ::tensorflow::EventReply>* PrepareAsyncSendSourceFilesRaw(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq) override; + const ::grpc::internal::RpcMethod rpcmethod_SendEvents_; + const ::grpc::internal::RpcMethod rpcmethod_SendTracebacks_; + const ::grpc::internal::RpcMethod rpcmethod_SendSourceFiles_; + }; + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class Service : public ::grpc::Service { + public: + Service(); + virtual ~Service(); + // Client(s) can use this RPC method to send the EventListener Event protos. + // The Event protos can hold information such as: + // 1) intermediate tensors from a debugged graph being executed, which can + // be sent from DebugIdentity ops configured with grpc URLs. + // 2) GraphDefs of partition graphs, which can be sent from special debug + // ops that get executed immediately after the beginning of the graph + // execution. + virtual ::grpc::Status SendEvents(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* stream); + // Send the tracebacks of a TensorFlow execution call. + virtual ::grpc::Status SendTracebacks(::grpc::ServerContext* context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response); + // Send a collection of source code files being debugged. + virtual ::grpc::Status SendSourceFiles(::grpc::ServerContext* context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response); + }; + template + class WithAsyncMethod_SendEvents : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithAsyncMethod_SendEvents() { + ::grpc::Service::MarkMethodAsync(0); + } + ~WithAsyncMethod_SendEvents() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendEvents(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* /*stream*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestSendEvents(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(0, context, stream, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_SendTracebacks : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithAsyncMethod_SendTracebacks() { + ::grpc::Service::MarkMethodAsync(1); + } + ~WithAsyncMethod_SendTracebacks() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendTracebacks(::grpc::ServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestSendTracebacks(::grpc::ServerContext* context, ::tensorflow::CallTraceback* request, ::grpc::ServerAsyncResponseWriter< ::tensorflow::EventReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_SendSourceFiles : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithAsyncMethod_SendSourceFiles() { + ::grpc::Service::MarkMethodAsync(2); + } + ~WithAsyncMethod_SendSourceFiles() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendSourceFiles(::grpc::ServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestSendSourceFiles(::grpc::ServerContext* context, ::tensorflow::DebuggedSourceFiles* request, ::grpc::ServerAsyncResponseWriter< ::tensorflow::EventReply>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag); + } + }; + typedef WithAsyncMethod_SendEvents > > AsyncService; + template + class ExperimentalWithCallbackMethod_SendEvents : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + ExperimentalWithCallbackMethod_SendEvents() { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::Service:: + #else + ::grpc::Service::experimental(). + #endif + MarkMethodCallback(0, + new ::grpc_impl::internal::CallbackBidiHandler< ::tensorflow::Event, ::tensorflow::EventReply>( + [this]( + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::CallbackServerContext* + #else + ::grpc::experimental::CallbackServerContext* + #endif + context) { return this->SendEvents(context); })); + } + ~ExperimentalWithCallbackMethod_SendEvents() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendEvents(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* /*stream*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual ::grpc::ServerBidiReactor< ::tensorflow::Event, ::tensorflow::EventReply>* SendEvents( + ::grpc::CallbackServerContext* /*context*/) + #else + virtual ::grpc::experimental::ServerBidiReactor< ::tensorflow::Event, ::tensorflow::EventReply>* SendEvents( + ::grpc::experimental::CallbackServerContext* /*context*/) + #endif + { return nullptr; } + }; + template + class ExperimentalWithCallbackMethod_SendTracebacks : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + ExperimentalWithCallbackMethod_SendTracebacks() { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::Service:: + #else + ::grpc::Service::experimental(). + #endif + MarkMethodCallback(1, + new ::grpc_impl::internal::CallbackUnaryHandler< ::tensorflow::CallTraceback, ::tensorflow::EventReply>( + [this]( + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::CallbackServerContext* + #else + ::grpc::experimental::CallbackServerContext* + #endif + context, const ::tensorflow::CallTraceback* request, ::tensorflow::EventReply* response) { return this->SendTracebacks(context, request, response); }));} + void SetMessageAllocatorFor_SendTracebacks( + ::grpc::experimental::MessageAllocator< ::tensorflow::CallTraceback, ::tensorflow::EventReply>* allocator) { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::internal::MethodHandler* const handler = ::grpc::Service::GetHandler(1); + #else + ::grpc::internal::MethodHandler* const handler = ::grpc::Service::experimental().GetHandler(1); + #endif + static_cast<::grpc_impl::internal::CallbackUnaryHandler< ::tensorflow::CallTraceback, ::tensorflow::EventReply>*>(handler) + ->SetMessageAllocator(allocator); + } + ~ExperimentalWithCallbackMethod_SendTracebacks() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendTracebacks(::grpc::ServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual ::grpc::ServerUnaryReactor* SendTracebacks( + ::grpc::CallbackServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) + #else + virtual ::grpc::experimental::ServerUnaryReactor* SendTracebacks( + ::grpc::experimental::CallbackServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) + #endif + { return nullptr; } + }; + template + class ExperimentalWithCallbackMethod_SendSourceFiles : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + ExperimentalWithCallbackMethod_SendSourceFiles() { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::Service:: + #else + ::grpc::Service::experimental(). + #endif + MarkMethodCallback(2, + new ::grpc_impl::internal::CallbackUnaryHandler< ::tensorflow::DebuggedSourceFiles, ::tensorflow::EventReply>( + [this]( + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::CallbackServerContext* + #else + ::grpc::experimental::CallbackServerContext* + #endif + context, const ::tensorflow::DebuggedSourceFiles* request, ::tensorflow::EventReply* response) { return this->SendSourceFiles(context, request, response); }));} + void SetMessageAllocatorFor_SendSourceFiles( + ::grpc::experimental::MessageAllocator< ::tensorflow::DebuggedSourceFiles, ::tensorflow::EventReply>* allocator) { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::internal::MethodHandler* const handler = ::grpc::Service::GetHandler(2); + #else + ::grpc::internal::MethodHandler* const handler = ::grpc::Service::experimental().GetHandler(2); + #endif + static_cast<::grpc_impl::internal::CallbackUnaryHandler< ::tensorflow::DebuggedSourceFiles, ::tensorflow::EventReply>*>(handler) + ->SetMessageAllocator(allocator); + } + ~ExperimentalWithCallbackMethod_SendSourceFiles() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendSourceFiles(::grpc::ServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual ::grpc::ServerUnaryReactor* SendSourceFiles( + ::grpc::CallbackServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) + #else + virtual ::grpc::experimental::ServerUnaryReactor* SendSourceFiles( + ::grpc::experimental::CallbackServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) + #endif + { return nullptr; } + }; + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + typedef ExperimentalWithCallbackMethod_SendEvents > > CallbackService; + #endif + + typedef ExperimentalWithCallbackMethod_SendEvents > > ExperimentalCallbackService; + template + class WithGenericMethod_SendEvents : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithGenericMethod_SendEvents() { + ::grpc::Service::MarkMethodGeneric(0); + } + ~WithGenericMethod_SendEvents() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendEvents(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* /*stream*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_SendTracebacks : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithGenericMethod_SendTracebacks() { + ::grpc::Service::MarkMethodGeneric(1); + } + ~WithGenericMethod_SendTracebacks() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendTracebacks(::grpc::ServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_SendSourceFiles : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithGenericMethod_SendSourceFiles() { + ::grpc::Service::MarkMethodGeneric(2); + } + ~WithGenericMethod_SendSourceFiles() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendSourceFiles(::grpc::ServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithRawMethod_SendEvents : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithRawMethod_SendEvents() { + ::grpc::Service::MarkMethodRaw(0); + } + ~WithRawMethod_SendEvents() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendEvents(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* /*stream*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestSendEvents(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< ::grpc::ByteBuffer, ::grpc::ByteBuffer>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(0, context, stream, new_call_cq, notification_cq, tag); + } + }; + template + class WithRawMethod_SendTracebacks : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithRawMethod_SendTracebacks() { + ::grpc::Service::MarkMethodRaw(1); + } + ~WithRawMethod_SendTracebacks() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendTracebacks(::grpc::ServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestSendTracebacks(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithRawMethod_SendSourceFiles : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithRawMethod_SendSourceFiles() { + ::grpc::Service::MarkMethodRaw(2); + } + ~WithRawMethod_SendSourceFiles() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendSourceFiles(::grpc::ServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestSendSourceFiles(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncResponseWriter< ::grpc::ByteBuffer>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class ExperimentalWithRawCallbackMethod_SendEvents : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + ExperimentalWithRawCallbackMethod_SendEvents() { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::Service:: + #else + ::grpc::Service::experimental(). + #endif + MarkMethodRawCallback(0, + new ::grpc_impl::internal::CallbackBidiHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>( + [this]( + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::CallbackServerContext* + #else + ::grpc::experimental::CallbackServerContext* + #endif + context) { return this->SendEvents(context); })); + } + ~ExperimentalWithRawCallbackMethod_SendEvents() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendEvents(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>* /*stream*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual ::grpc::ServerBidiReactor< ::grpc::ByteBuffer, ::grpc::ByteBuffer>* SendEvents( + ::grpc::CallbackServerContext* /*context*/) + #else + virtual ::grpc::experimental::ServerBidiReactor< ::grpc::ByteBuffer, ::grpc::ByteBuffer>* SendEvents( + ::grpc::experimental::CallbackServerContext* /*context*/) + #endif + { return nullptr; } + }; + template + class ExperimentalWithRawCallbackMethod_SendTracebacks : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + ExperimentalWithRawCallbackMethod_SendTracebacks() { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::Service:: + #else + ::grpc::Service::experimental(). + #endif + MarkMethodRawCallback(1, + new ::grpc_impl::internal::CallbackUnaryHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>( + [this]( + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::CallbackServerContext* + #else + ::grpc::experimental::CallbackServerContext* + #endif + context, const ::grpc::ByteBuffer* request, ::grpc::ByteBuffer* response) { return this->SendTracebacks(context, request, response); })); + } + ~ExperimentalWithRawCallbackMethod_SendTracebacks() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendTracebacks(::grpc::ServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual ::grpc::ServerUnaryReactor* SendTracebacks( + ::grpc::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/, ::grpc::ByteBuffer* /*response*/) + #else + virtual ::grpc::experimental::ServerUnaryReactor* SendTracebacks( + ::grpc::experimental::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/, ::grpc::ByteBuffer* /*response*/) + #endif + { return nullptr; } + }; + template + class ExperimentalWithRawCallbackMethod_SendSourceFiles : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + ExperimentalWithRawCallbackMethod_SendSourceFiles() { + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::Service:: + #else + ::grpc::Service::experimental(). + #endif + MarkMethodRawCallback(2, + new ::grpc_impl::internal::CallbackUnaryHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>( + [this]( + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + ::grpc::CallbackServerContext* + #else + ::grpc::experimental::CallbackServerContext* + #endif + context, const ::grpc::ByteBuffer* request, ::grpc::ByteBuffer* response) { return this->SendSourceFiles(context, request, response); })); + } + ~ExperimentalWithRawCallbackMethod_SendSourceFiles() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status SendSourceFiles(::grpc::ServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL + virtual ::grpc::ServerUnaryReactor* SendSourceFiles( + ::grpc::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/, ::grpc::ByteBuffer* /*response*/) + #else + virtual ::grpc::experimental::ServerUnaryReactor* SendSourceFiles( + ::grpc::experimental::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/, ::grpc::ByteBuffer* /*response*/) + #endif + { return nullptr; } + }; + template + class WithStreamedUnaryMethod_SendTracebacks : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithStreamedUnaryMethod_SendTracebacks() { + ::grpc::Service::MarkMethodStreamed(1, + new ::grpc::internal::StreamedUnaryHandler< ::tensorflow::CallTraceback, ::tensorflow::EventReply>(std::bind(&WithStreamedUnaryMethod_SendTracebacks::StreamedSendTracebacks, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_SendTracebacks() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status SendTracebacks(::grpc::ServerContext* /*context*/, const ::tensorflow::CallTraceback* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedSendTracebacks(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::tensorflow::CallTraceback,::tensorflow::EventReply>* server_unary_streamer) = 0; + }; + template + class WithStreamedUnaryMethod_SendSourceFiles : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service* /*service*/) {} + public: + WithStreamedUnaryMethod_SendSourceFiles() { + ::grpc::Service::MarkMethodStreamed(2, + new ::grpc::internal::StreamedUnaryHandler< ::tensorflow::DebuggedSourceFiles, ::tensorflow::EventReply>(std::bind(&WithStreamedUnaryMethod_SendSourceFiles::StreamedSendSourceFiles, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_SendSourceFiles() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status SendSourceFiles(::grpc::ServerContext* /*context*/, const ::tensorflow::DebuggedSourceFiles* /*request*/, ::tensorflow::EventReply* /*response*/) override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedSendSourceFiles(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::tensorflow::DebuggedSourceFiles,::tensorflow::EventReply>* server_unary_streamer) = 0; + }; + typedef WithStreamedUnaryMethod_SendTracebacks > StreamedUnaryService; + typedef Service SplitStreamedService; + typedef WithStreamedUnaryMethod_SendTracebacks > StreamedService; +}; + +} // namespace grpc + +} // namespace tensorflow + + +#endif // GRPC_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto__INCLUDED diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..bcfa50d76a8736a7d22670d58b6361a44aa3103a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service.pb.h @@ -0,0 +1,1440 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/debug/debug_service.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include +#include "tensorflow/core/framework/tensor.pb.h" +#include "tensorflow/core/profiler/tfprof_log.pb.h" +#include "tensorflow/core/protobuf/debug.pb.h" +#include "tensorflow/core/util/event.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fdebug_2fdebug_5fservice_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_2fdebug_2fdebug_5fservice_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto; +namespace tensorflow { +class CallTraceback; +struct CallTracebackDefaultTypeInternal; +extern CallTracebackDefaultTypeInternal _CallTraceback_default_instance_; +class CallTraceback_OriginIdToStringEntry_DoNotUse; +struct CallTraceback_OriginIdToStringEntry_DoNotUseDefaultTypeInternal; +extern CallTraceback_OriginIdToStringEntry_DoNotUseDefaultTypeInternal _CallTraceback_OriginIdToStringEntry_DoNotUse_default_instance_; +class EventReply; +struct EventReplyDefaultTypeInternal; +extern EventReplyDefaultTypeInternal _EventReply_default_instance_; +class EventReply_DebugOpStateChange; +struct EventReply_DebugOpStateChangeDefaultTypeInternal; +extern EventReply_DebugOpStateChangeDefaultTypeInternal _EventReply_DebugOpStateChange_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::CallTraceback* Arena::CreateMaybeMessage<::tensorflow::CallTraceback>(Arena*); +template<> ::tensorflow::CallTraceback_OriginIdToStringEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::CallTraceback_OriginIdToStringEntry_DoNotUse>(Arena*); +template<> ::tensorflow::EventReply* Arena::CreateMaybeMessage<::tensorflow::EventReply>(Arena*); +template<> ::tensorflow::EventReply_DebugOpStateChange* Arena::CreateMaybeMessage<::tensorflow::EventReply_DebugOpStateChange>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +enum EventReply_DebugOpStateChange_State : int { + EventReply_DebugOpStateChange_State_STATE_UNSPECIFIED = 0, + EventReply_DebugOpStateChange_State_DISABLED = 1, + EventReply_DebugOpStateChange_State_READ_ONLY = 2, + EventReply_DebugOpStateChange_State_READ_WRITE = 3, + EventReply_DebugOpStateChange_State_EventReply_DebugOpStateChange_State_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + EventReply_DebugOpStateChange_State_EventReply_DebugOpStateChange_State_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool EventReply_DebugOpStateChange_State_IsValid(int value); +constexpr EventReply_DebugOpStateChange_State EventReply_DebugOpStateChange_State_State_MIN = EventReply_DebugOpStateChange_State_STATE_UNSPECIFIED; +constexpr EventReply_DebugOpStateChange_State EventReply_DebugOpStateChange_State_State_MAX = EventReply_DebugOpStateChange_State_READ_WRITE; +constexpr int EventReply_DebugOpStateChange_State_State_ARRAYSIZE = EventReply_DebugOpStateChange_State_State_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* EventReply_DebugOpStateChange_State_descriptor(); +template +inline const std::string& EventReply_DebugOpStateChange_State_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function EventReply_DebugOpStateChange_State_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + EventReply_DebugOpStateChange_State_descriptor(), enum_t_value); +} +inline bool EventReply_DebugOpStateChange_State_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, EventReply_DebugOpStateChange_State* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + EventReply_DebugOpStateChange_State_descriptor(), name, value); +} +enum CallTraceback_CallType : int { + CallTraceback_CallType_UNSPECIFIED = 0, + CallTraceback_CallType_GRAPH_EXECUTION = 1, + CallTraceback_CallType_EAGER_EXECUTION = 2, + CallTraceback_CallType_CallTraceback_CallType_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + CallTraceback_CallType_CallTraceback_CallType_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool CallTraceback_CallType_IsValid(int value); +constexpr CallTraceback_CallType CallTraceback_CallType_CallType_MIN = CallTraceback_CallType_UNSPECIFIED; +constexpr CallTraceback_CallType CallTraceback_CallType_CallType_MAX = CallTraceback_CallType_EAGER_EXECUTION; +constexpr int CallTraceback_CallType_CallType_ARRAYSIZE = CallTraceback_CallType_CallType_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CallTraceback_CallType_descriptor(); +template +inline const std::string& CallTraceback_CallType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CallTraceback_CallType_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + CallTraceback_CallType_descriptor(), enum_t_value); +} +inline bool CallTraceback_CallType_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CallTraceback_CallType* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + CallTraceback_CallType_descriptor(), name, value); +} +// =================================================================== + +class EventReply_DebugOpStateChange final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.EventReply.DebugOpStateChange) */ { + public: + inline EventReply_DebugOpStateChange() : EventReply_DebugOpStateChange(nullptr) {} + ~EventReply_DebugOpStateChange() override; + explicit PROTOBUF_CONSTEXPR EventReply_DebugOpStateChange(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EventReply_DebugOpStateChange(const EventReply_DebugOpStateChange& from); + EventReply_DebugOpStateChange(EventReply_DebugOpStateChange&& from) noexcept + : EventReply_DebugOpStateChange() { + *this = ::std::move(from); + } + + inline EventReply_DebugOpStateChange& operator=(const EventReply_DebugOpStateChange& from) { + CopyFrom(from); + return *this; + } + inline EventReply_DebugOpStateChange& operator=(EventReply_DebugOpStateChange&& 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 EventReply_DebugOpStateChange& default_instance() { + return *internal_default_instance(); + } + static inline const EventReply_DebugOpStateChange* internal_default_instance() { + return reinterpret_cast( + &_EventReply_DebugOpStateChange_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(EventReply_DebugOpStateChange& a, EventReply_DebugOpStateChange& b) { + a.Swap(&b); + } + inline void Swap(EventReply_DebugOpStateChange* 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(EventReply_DebugOpStateChange* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EventReply_DebugOpStateChange* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EventReply_DebugOpStateChange& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const EventReply_DebugOpStateChange& from) { + EventReply_DebugOpStateChange::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(EventReply_DebugOpStateChange* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.EventReply.DebugOpStateChange"; + } + protected: + explicit EventReply_DebugOpStateChange(::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 EventReply_DebugOpStateChange_State State; + static constexpr State STATE_UNSPECIFIED = + EventReply_DebugOpStateChange_State_STATE_UNSPECIFIED; + static constexpr State DISABLED = + EventReply_DebugOpStateChange_State_DISABLED; + static constexpr State READ_ONLY = + EventReply_DebugOpStateChange_State_READ_ONLY; + static constexpr State READ_WRITE = + EventReply_DebugOpStateChange_State_READ_WRITE; + static inline bool State_IsValid(int value) { + return EventReply_DebugOpStateChange_State_IsValid(value); + } + static constexpr State State_MIN = + EventReply_DebugOpStateChange_State_State_MIN; + static constexpr State State_MAX = + EventReply_DebugOpStateChange_State_State_MAX; + static constexpr int State_ARRAYSIZE = + EventReply_DebugOpStateChange_State_State_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + State_descriptor() { + return EventReply_DebugOpStateChange_State_descriptor(); + } + template + static inline const std::string& State_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function State_Name."); + return EventReply_DebugOpStateChange_State_Name(enum_t_value); + } + static inline bool State_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + State* value) { + return EventReply_DebugOpStateChange_State_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kNodeNameFieldNumber = 2, + kDebugOpFieldNumber = 4, + kStateFieldNumber = 1, + kOutputSlotFieldNumber = 3, + }; + // string node_name = 2; + void clear_node_name(); + const std::string& node_name() const; + template + void set_node_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_node_name(); + PROTOBUF_NODISCARD std::string* release_node_name(); + void set_allocated_node_name(std::string* node_name); + private: + const std::string& _internal_node_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_node_name(const std::string& value); + std::string* _internal_mutable_node_name(); + public: + + // string debug_op = 4; + void clear_debug_op(); + const std::string& debug_op() const; + template + void set_debug_op(ArgT0&& arg0, ArgT... args); + std::string* mutable_debug_op(); + PROTOBUF_NODISCARD std::string* release_debug_op(); + void set_allocated_debug_op(std::string* debug_op); + private: + const std::string& _internal_debug_op() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_debug_op(const std::string& value); + std::string* _internal_mutable_debug_op(); + public: + + // .tensorflow.EventReply.DebugOpStateChange.State state = 1; + void clear_state(); + ::tensorflow::EventReply_DebugOpStateChange_State state() const; + void set_state(::tensorflow::EventReply_DebugOpStateChange_State value); + private: + ::tensorflow::EventReply_DebugOpStateChange_State _internal_state() const; + void _internal_set_state(::tensorflow::EventReply_DebugOpStateChange_State value); + public: + + // int32 output_slot = 3; + void clear_output_slot(); + int32_t output_slot() const; + void set_output_slot(int32_t value); + private: + int32_t _internal_output_slot() const; + void _internal_set_output_slot(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.EventReply.DebugOpStateChange) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr node_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr debug_op_; + int state_; + int32_t output_slot_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto; +}; +// ------------------------------------------------------------------- + +class EventReply final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.EventReply) */ { + public: + inline EventReply() : EventReply(nullptr) {} + ~EventReply() override; + explicit PROTOBUF_CONSTEXPR EventReply(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + EventReply(const EventReply& from); + EventReply(EventReply&& from) noexcept + : EventReply() { + *this = ::std::move(from); + } + + inline EventReply& operator=(const EventReply& from) { + CopyFrom(from); + return *this; + } + inline EventReply& operator=(EventReply&& 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 EventReply& default_instance() { + return *internal_default_instance(); + } + static inline const EventReply* internal_default_instance() { + return reinterpret_cast( + &_EventReply_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(EventReply& a, EventReply& b) { + a.Swap(&b); + } + inline void Swap(EventReply* 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(EventReply* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + EventReply* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const EventReply& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const EventReply& from) { + EventReply::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(EventReply* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.EventReply"; + } + protected: + explicit EventReply(::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 EventReply_DebugOpStateChange DebugOpStateChange; + + // accessors ------------------------------------------------------- + + enum : int { + kDebugOpStateChangesFieldNumber = 1, + kTensorFieldNumber = 2, + }; + // repeated .tensorflow.EventReply.DebugOpStateChange debug_op_state_changes = 1; + int debug_op_state_changes_size() const; + private: + int _internal_debug_op_state_changes_size() const; + public: + void clear_debug_op_state_changes(); + ::tensorflow::EventReply_DebugOpStateChange* mutable_debug_op_state_changes(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::EventReply_DebugOpStateChange >* + mutable_debug_op_state_changes(); + private: + const ::tensorflow::EventReply_DebugOpStateChange& _internal_debug_op_state_changes(int index) const; + ::tensorflow::EventReply_DebugOpStateChange* _internal_add_debug_op_state_changes(); + public: + const ::tensorflow::EventReply_DebugOpStateChange& debug_op_state_changes(int index) const; + ::tensorflow::EventReply_DebugOpStateChange* add_debug_op_state_changes(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::EventReply_DebugOpStateChange >& + debug_op_state_changes() const; + + // .tensorflow.TensorProto tensor = 2; + bool has_tensor() const; + private: + bool _internal_has_tensor() const; + public: + void clear_tensor(); + const ::tensorflow::TensorProto& tensor() const; + PROTOBUF_NODISCARD ::tensorflow::TensorProto* release_tensor(); + ::tensorflow::TensorProto* mutable_tensor(); + void set_allocated_tensor(::tensorflow::TensorProto* tensor); + private: + const ::tensorflow::TensorProto& _internal_tensor() const; + ::tensorflow::TensorProto* _internal_mutable_tensor(); + public: + void unsafe_arena_set_allocated_tensor( + ::tensorflow::TensorProto* tensor); + ::tensorflow::TensorProto* unsafe_arena_release_tensor(); + + // @@protoc_insertion_point(class_scope:tensorflow.EventReply) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::EventReply_DebugOpStateChange > debug_op_state_changes_; + ::tensorflow::TensorProto* tensor_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto; +}; +// ------------------------------------------------------------------- + +class CallTraceback_OriginIdToStringEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + CallTraceback_OriginIdToStringEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR CallTraceback_OriginIdToStringEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit CallTraceback_OriginIdToStringEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const CallTraceback_OriginIdToStringEntry_DoNotUse& other); + static const CallTraceback_OriginIdToStringEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_CallTraceback_OriginIdToStringEntry_DoNotUse_default_instance_); } + static bool ValidateKey(void*) { return true; } + static bool ValidateValue(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.CallTraceback.OriginIdToStringEntry.value"); + } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto; +}; + +// ------------------------------------------------------------------- + +class CallTraceback final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CallTraceback) */ { + public: + inline CallTraceback() : CallTraceback(nullptr) {} + ~CallTraceback() override; + explicit PROTOBUF_CONSTEXPR CallTraceback(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CallTraceback(const CallTraceback& from); + CallTraceback(CallTraceback&& from) noexcept + : CallTraceback() { + *this = ::std::move(from); + } + + inline CallTraceback& operator=(const CallTraceback& from) { + CopyFrom(from); + return *this; + } + inline CallTraceback& operator=(CallTraceback&& 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 CallTraceback& default_instance() { + return *internal_default_instance(); + } + static inline const CallTraceback* internal_default_instance() { + return reinterpret_cast( + &_CallTraceback_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(CallTraceback& a, CallTraceback& b) { + a.Swap(&b); + } + inline void Swap(CallTraceback* 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(CallTraceback* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CallTraceback* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CallTraceback& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CallTraceback& from) { + CallTraceback::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(CallTraceback* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CallTraceback"; + } + protected: + explicit CallTraceback(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + typedef CallTraceback_CallType CallType; + static constexpr CallType UNSPECIFIED = + CallTraceback_CallType_UNSPECIFIED; + static constexpr CallType GRAPH_EXECUTION = + CallTraceback_CallType_GRAPH_EXECUTION; + static constexpr CallType EAGER_EXECUTION = + CallTraceback_CallType_EAGER_EXECUTION; + static inline bool CallType_IsValid(int value) { + return CallTraceback_CallType_IsValid(value); + } + static constexpr CallType CallType_MIN = + CallTraceback_CallType_CallType_MIN; + static constexpr CallType CallType_MAX = + CallTraceback_CallType_CallType_MAX; + static constexpr int CallType_ARRAYSIZE = + CallTraceback_CallType_CallType_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + CallType_descriptor() { + return CallTraceback_CallType_descriptor(); + } + template + static inline const std::string& CallType_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CallType_Name."); + return CallTraceback_CallType_Name(enum_t_value); + } + static inline bool CallType_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + CallType* value) { + return CallTraceback_CallType_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kOriginIdToStringFieldNumber = 4, + kCallKeyFieldNumber = 2, + kOriginStackFieldNumber = 3, + kGraphTracebackFieldNumber = 5, + kGraphVersionFieldNumber = 6, + kCallTypeFieldNumber = 1, + }; + // map origin_id_to_string = 4; + int origin_id_to_string_size() const; + private: + int _internal_origin_id_to_string_size() const; + public: + void clear_origin_id_to_string(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >& + _internal_origin_id_to_string() const; + ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >* + _internal_mutable_origin_id_to_string(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >& + origin_id_to_string() const; + ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >* + mutable_origin_id_to_string(); + + // string call_key = 2; + void clear_call_key(); + const std::string& call_key() const; + template + void set_call_key(ArgT0&& arg0, ArgT... args); + std::string* mutable_call_key(); + PROTOBUF_NODISCARD std::string* release_call_key(); + void set_allocated_call_key(std::string* call_key); + private: + const std::string& _internal_call_key() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_call_key(const std::string& value); + std::string* _internal_mutable_call_key(); + public: + + // .tensorflow.tfprof.CodeDef origin_stack = 3; + bool has_origin_stack() const; + private: + bool _internal_has_origin_stack() const; + public: + void clear_origin_stack(); + const ::tensorflow::tfprof::CodeDef& origin_stack() const; + PROTOBUF_NODISCARD ::tensorflow::tfprof::CodeDef* release_origin_stack(); + ::tensorflow::tfprof::CodeDef* mutable_origin_stack(); + void set_allocated_origin_stack(::tensorflow::tfprof::CodeDef* origin_stack); + private: + const ::tensorflow::tfprof::CodeDef& _internal_origin_stack() const; + ::tensorflow::tfprof::CodeDef* _internal_mutable_origin_stack(); + public: + void unsafe_arena_set_allocated_origin_stack( + ::tensorflow::tfprof::CodeDef* origin_stack); + ::tensorflow::tfprof::CodeDef* unsafe_arena_release_origin_stack(); + + // .tensorflow.tfprof.OpLogProto graph_traceback = 5; + bool has_graph_traceback() const; + private: + bool _internal_has_graph_traceback() const; + public: + void clear_graph_traceback(); + const ::tensorflow::tfprof::OpLogProto& graph_traceback() const; + PROTOBUF_NODISCARD ::tensorflow::tfprof::OpLogProto* release_graph_traceback(); + ::tensorflow::tfprof::OpLogProto* mutable_graph_traceback(); + void set_allocated_graph_traceback(::tensorflow::tfprof::OpLogProto* graph_traceback); + private: + const ::tensorflow::tfprof::OpLogProto& _internal_graph_traceback() const; + ::tensorflow::tfprof::OpLogProto* _internal_mutable_graph_traceback(); + public: + void unsafe_arena_set_allocated_graph_traceback( + ::tensorflow::tfprof::OpLogProto* graph_traceback); + ::tensorflow::tfprof::OpLogProto* unsafe_arena_release_graph_traceback(); + + // int64 graph_version = 6; + void clear_graph_version(); + int64_t graph_version() const; + void set_graph_version(int64_t value); + private: + int64_t _internal_graph_version() const; + void _internal_set_graph_version(int64_t value); + public: + + // .tensorflow.CallTraceback.CallType call_type = 1; + void clear_call_type(); + ::tensorflow::CallTraceback_CallType call_type() const; + void set_call_type(::tensorflow::CallTraceback_CallType value); + private: + ::tensorflow::CallTraceback_CallType _internal_call_type() const; + void _internal_set_call_type(::tensorflow::CallTraceback_CallType value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.CallTraceback) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + CallTraceback_OriginIdToStringEntry_DoNotUse, + int64_t, std::string, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT64, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING> origin_id_to_string_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr call_key_; + ::tensorflow::tfprof::CodeDef* origin_stack_; + ::tensorflow::tfprof::OpLogProto* graph_traceback_; + int64_t graph_version_; + int call_type_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// EventReply_DebugOpStateChange + +// .tensorflow.EventReply.DebugOpStateChange.State state = 1; +inline void EventReply_DebugOpStateChange::clear_state() { + _impl_.state_ = 0; +} +inline ::tensorflow::EventReply_DebugOpStateChange_State EventReply_DebugOpStateChange::_internal_state() const { + return static_cast< ::tensorflow::EventReply_DebugOpStateChange_State >(_impl_.state_); +} +inline ::tensorflow::EventReply_DebugOpStateChange_State EventReply_DebugOpStateChange::state() const { + // @@protoc_insertion_point(field_get:tensorflow.EventReply.DebugOpStateChange.state) + return _internal_state(); +} +inline void EventReply_DebugOpStateChange::_internal_set_state(::tensorflow::EventReply_DebugOpStateChange_State value) { + + _impl_.state_ = value; +} +inline void EventReply_DebugOpStateChange::set_state(::tensorflow::EventReply_DebugOpStateChange_State value) { + _internal_set_state(value); + // @@protoc_insertion_point(field_set:tensorflow.EventReply.DebugOpStateChange.state) +} + +// string node_name = 2; +inline void EventReply_DebugOpStateChange::clear_node_name() { + _impl_.node_name_.ClearToEmpty(); +} +inline const std::string& EventReply_DebugOpStateChange::node_name() const { + // @@protoc_insertion_point(field_get:tensorflow.EventReply.DebugOpStateChange.node_name) + return _internal_node_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void EventReply_DebugOpStateChange::set_node_name(ArgT0&& arg0, ArgT... args) { + + _impl_.node_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.EventReply.DebugOpStateChange.node_name) +} +inline std::string* EventReply_DebugOpStateChange::mutable_node_name() { + std::string* _s = _internal_mutable_node_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.EventReply.DebugOpStateChange.node_name) + return _s; +} +inline const std::string& EventReply_DebugOpStateChange::_internal_node_name() const { + return _impl_.node_name_.Get(); +} +inline void EventReply_DebugOpStateChange::_internal_set_node_name(const std::string& value) { + + _impl_.node_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* EventReply_DebugOpStateChange::_internal_mutable_node_name() { + + return _impl_.node_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* EventReply_DebugOpStateChange::release_node_name() { + // @@protoc_insertion_point(field_release:tensorflow.EventReply.DebugOpStateChange.node_name) + return _impl_.node_name_.Release(); +} +inline void EventReply_DebugOpStateChange::set_allocated_node_name(std::string* node_name) { + if (node_name != nullptr) { + + } else { + + } + _impl_.node_name_.SetAllocated(node_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.node_name_.IsDefault()) { + _impl_.node_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.EventReply.DebugOpStateChange.node_name) +} + +// int32 output_slot = 3; +inline void EventReply_DebugOpStateChange::clear_output_slot() { + _impl_.output_slot_ = 0; +} +inline int32_t EventReply_DebugOpStateChange::_internal_output_slot() const { + return _impl_.output_slot_; +} +inline int32_t EventReply_DebugOpStateChange::output_slot() const { + // @@protoc_insertion_point(field_get:tensorflow.EventReply.DebugOpStateChange.output_slot) + return _internal_output_slot(); +} +inline void EventReply_DebugOpStateChange::_internal_set_output_slot(int32_t value) { + + _impl_.output_slot_ = value; +} +inline void EventReply_DebugOpStateChange::set_output_slot(int32_t value) { + _internal_set_output_slot(value); + // @@protoc_insertion_point(field_set:tensorflow.EventReply.DebugOpStateChange.output_slot) +} + +// string debug_op = 4; +inline void EventReply_DebugOpStateChange::clear_debug_op() { + _impl_.debug_op_.ClearToEmpty(); +} +inline const std::string& EventReply_DebugOpStateChange::debug_op() const { + // @@protoc_insertion_point(field_get:tensorflow.EventReply.DebugOpStateChange.debug_op) + return _internal_debug_op(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void EventReply_DebugOpStateChange::set_debug_op(ArgT0&& arg0, ArgT... args) { + + _impl_.debug_op_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.EventReply.DebugOpStateChange.debug_op) +} +inline std::string* EventReply_DebugOpStateChange::mutable_debug_op() { + std::string* _s = _internal_mutable_debug_op(); + // @@protoc_insertion_point(field_mutable:tensorflow.EventReply.DebugOpStateChange.debug_op) + return _s; +} +inline const std::string& EventReply_DebugOpStateChange::_internal_debug_op() const { + return _impl_.debug_op_.Get(); +} +inline void EventReply_DebugOpStateChange::_internal_set_debug_op(const std::string& value) { + + _impl_.debug_op_.Set(value, GetArenaForAllocation()); +} +inline std::string* EventReply_DebugOpStateChange::_internal_mutable_debug_op() { + + return _impl_.debug_op_.Mutable(GetArenaForAllocation()); +} +inline std::string* EventReply_DebugOpStateChange::release_debug_op() { + // @@protoc_insertion_point(field_release:tensorflow.EventReply.DebugOpStateChange.debug_op) + return _impl_.debug_op_.Release(); +} +inline void EventReply_DebugOpStateChange::set_allocated_debug_op(std::string* debug_op) { + if (debug_op != nullptr) { + + } else { + + } + _impl_.debug_op_.SetAllocated(debug_op, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.debug_op_.IsDefault()) { + _impl_.debug_op_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.EventReply.DebugOpStateChange.debug_op) +} + +// ------------------------------------------------------------------- + +// EventReply + +// repeated .tensorflow.EventReply.DebugOpStateChange debug_op_state_changes = 1; +inline int EventReply::_internal_debug_op_state_changes_size() const { + return _impl_.debug_op_state_changes_.size(); +} +inline int EventReply::debug_op_state_changes_size() const { + return _internal_debug_op_state_changes_size(); +} +inline void EventReply::clear_debug_op_state_changes() { + _impl_.debug_op_state_changes_.Clear(); +} +inline ::tensorflow::EventReply_DebugOpStateChange* EventReply::mutable_debug_op_state_changes(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.EventReply.debug_op_state_changes) + return _impl_.debug_op_state_changes_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::EventReply_DebugOpStateChange >* +EventReply::mutable_debug_op_state_changes() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.EventReply.debug_op_state_changes) + return &_impl_.debug_op_state_changes_; +} +inline const ::tensorflow::EventReply_DebugOpStateChange& EventReply::_internal_debug_op_state_changes(int index) const { + return _impl_.debug_op_state_changes_.Get(index); +} +inline const ::tensorflow::EventReply_DebugOpStateChange& EventReply::debug_op_state_changes(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.EventReply.debug_op_state_changes) + return _internal_debug_op_state_changes(index); +} +inline ::tensorflow::EventReply_DebugOpStateChange* EventReply::_internal_add_debug_op_state_changes() { + return _impl_.debug_op_state_changes_.Add(); +} +inline ::tensorflow::EventReply_DebugOpStateChange* EventReply::add_debug_op_state_changes() { + ::tensorflow::EventReply_DebugOpStateChange* _add = _internal_add_debug_op_state_changes(); + // @@protoc_insertion_point(field_add:tensorflow.EventReply.debug_op_state_changes) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::EventReply_DebugOpStateChange >& +EventReply::debug_op_state_changes() const { + // @@protoc_insertion_point(field_list:tensorflow.EventReply.debug_op_state_changes) + return _impl_.debug_op_state_changes_; +} + +// .tensorflow.TensorProto tensor = 2; +inline bool EventReply::_internal_has_tensor() const { + return this != internal_default_instance() && _impl_.tensor_ != nullptr; +} +inline bool EventReply::has_tensor() const { + return _internal_has_tensor(); +} +inline const ::tensorflow::TensorProto& EventReply::_internal_tensor() const { + const ::tensorflow::TensorProto* p = _impl_.tensor_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorProto_default_instance_); +} +inline const ::tensorflow::TensorProto& EventReply::tensor() const { + // @@protoc_insertion_point(field_get:tensorflow.EventReply.tensor) + return _internal_tensor(); +} +inline void EventReply::unsafe_arena_set_allocated_tensor( + ::tensorflow::TensorProto* tensor) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.tensor_); + } + _impl_.tensor_ = tensor; + if (tensor) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.EventReply.tensor) +} +inline ::tensorflow::TensorProto* EventReply::release_tensor() { + + ::tensorflow::TensorProto* temp = _impl_.tensor_; + _impl_.tensor_ = 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::TensorProto* EventReply::unsafe_arena_release_tensor() { + // @@protoc_insertion_point(field_release:tensorflow.EventReply.tensor) + + ::tensorflow::TensorProto* temp = _impl_.tensor_; + _impl_.tensor_ = nullptr; + return temp; +} +inline ::tensorflow::TensorProto* EventReply::_internal_mutable_tensor() { + + if (_impl_.tensor_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorProto>(GetArenaForAllocation()); + _impl_.tensor_ = p; + } + return _impl_.tensor_; +} +inline ::tensorflow::TensorProto* EventReply::mutable_tensor() { + ::tensorflow::TensorProto* _msg = _internal_mutable_tensor(); + // @@protoc_insertion_point(field_mutable:tensorflow.EventReply.tensor) + return _msg; +} +inline void EventReply::set_allocated_tensor(::tensorflow::TensorProto* tensor) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.tensor_); + } + if (tensor) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(tensor)); + if (message_arena != submessage_arena) { + tensor = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, tensor, submessage_arena); + } + + } else { + + } + _impl_.tensor_ = tensor; + // @@protoc_insertion_point(field_set_allocated:tensorflow.EventReply.tensor) +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// CallTraceback + +// .tensorflow.CallTraceback.CallType call_type = 1; +inline void CallTraceback::clear_call_type() { + _impl_.call_type_ = 0; +} +inline ::tensorflow::CallTraceback_CallType CallTraceback::_internal_call_type() const { + return static_cast< ::tensorflow::CallTraceback_CallType >(_impl_.call_type_); +} +inline ::tensorflow::CallTraceback_CallType CallTraceback::call_type() const { + // @@protoc_insertion_point(field_get:tensorflow.CallTraceback.call_type) + return _internal_call_type(); +} +inline void CallTraceback::_internal_set_call_type(::tensorflow::CallTraceback_CallType value) { + + _impl_.call_type_ = value; +} +inline void CallTraceback::set_call_type(::tensorflow::CallTraceback_CallType value) { + _internal_set_call_type(value); + // @@protoc_insertion_point(field_set:tensorflow.CallTraceback.call_type) +} + +// string call_key = 2; +inline void CallTraceback::clear_call_key() { + _impl_.call_key_.ClearToEmpty(); +} +inline const std::string& CallTraceback::call_key() const { + // @@protoc_insertion_point(field_get:tensorflow.CallTraceback.call_key) + return _internal_call_key(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CallTraceback::set_call_key(ArgT0&& arg0, ArgT... args) { + + _impl_.call_key_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CallTraceback.call_key) +} +inline std::string* CallTraceback::mutable_call_key() { + std::string* _s = _internal_mutable_call_key(); + // @@protoc_insertion_point(field_mutable:tensorflow.CallTraceback.call_key) + return _s; +} +inline const std::string& CallTraceback::_internal_call_key() const { + return _impl_.call_key_.Get(); +} +inline void CallTraceback::_internal_set_call_key(const std::string& value) { + + _impl_.call_key_.Set(value, GetArenaForAllocation()); +} +inline std::string* CallTraceback::_internal_mutable_call_key() { + + return _impl_.call_key_.Mutable(GetArenaForAllocation()); +} +inline std::string* CallTraceback::release_call_key() { + // @@protoc_insertion_point(field_release:tensorflow.CallTraceback.call_key) + return _impl_.call_key_.Release(); +} +inline void CallTraceback::set_allocated_call_key(std::string* call_key) { + if (call_key != nullptr) { + + } else { + + } + _impl_.call_key_.SetAllocated(call_key, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.call_key_.IsDefault()) { + _impl_.call_key_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CallTraceback.call_key) +} + +// .tensorflow.tfprof.CodeDef origin_stack = 3; +inline bool CallTraceback::_internal_has_origin_stack() const { + return this != internal_default_instance() && _impl_.origin_stack_ != nullptr; +} +inline bool CallTraceback::has_origin_stack() const { + return _internal_has_origin_stack(); +} +inline const ::tensorflow::tfprof::CodeDef& CallTraceback::_internal_origin_stack() const { + const ::tensorflow::tfprof::CodeDef* p = _impl_.origin_stack_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::tfprof::_CodeDef_default_instance_); +} +inline const ::tensorflow::tfprof::CodeDef& CallTraceback::origin_stack() const { + // @@protoc_insertion_point(field_get:tensorflow.CallTraceback.origin_stack) + return _internal_origin_stack(); +} +inline void CallTraceback::unsafe_arena_set_allocated_origin_stack( + ::tensorflow::tfprof::CodeDef* origin_stack) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.origin_stack_); + } + _impl_.origin_stack_ = origin_stack; + if (origin_stack) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CallTraceback.origin_stack) +} +inline ::tensorflow::tfprof::CodeDef* CallTraceback::release_origin_stack() { + + ::tensorflow::tfprof::CodeDef* temp = _impl_.origin_stack_; + _impl_.origin_stack_ = 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::tfprof::CodeDef* CallTraceback::unsafe_arena_release_origin_stack() { + // @@protoc_insertion_point(field_release:tensorflow.CallTraceback.origin_stack) + + ::tensorflow::tfprof::CodeDef* temp = _impl_.origin_stack_; + _impl_.origin_stack_ = nullptr; + return temp; +} +inline ::tensorflow::tfprof::CodeDef* CallTraceback::_internal_mutable_origin_stack() { + + if (_impl_.origin_stack_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::tfprof::CodeDef>(GetArenaForAllocation()); + _impl_.origin_stack_ = p; + } + return _impl_.origin_stack_; +} +inline ::tensorflow::tfprof::CodeDef* CallTraceback::mutable_origin_stack() { + ::tensorflow::tfprof::CodeDef* _msg = _internal_mutable_origin_stack(); + // @@protoc_insertion_point(field_mutable:tensorflow.CallTraceback.origin_stack) + return _msg; +} +inline void CallTraceback::set_allocated_origin_stack(::tensorflow::tfprof::CodeDef* origin_stack) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.origin_stack_); + } + if (origin_stack) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(origin_stack)); + if (message_arena != submessage_arena) { + origin_stack = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, origin_stack, submessage_arena); + } + + } else { + + } + _impl_.origin_stack_ = origin_stack; + // @@protoc_insertion_point(field_set_allocated:tensorflow.CallTraceback.origin_stack) +} + +// map origin_id_to_string = 4; +inline int CallTraceback::_internal_origin_id_to_string_size() const { + return _impl_.origin_id_to_string_.size(); +} +inline int CallTraceback::origin_id_to_string_size() const { + return _internal_origin_id_to_string_size(); +} +inline void CallTraceback::clear_origin_id_to_string() { + _impl_.origin_id_to_string_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >& +CallTraceback::_internal_origin_id_to_string() const { + return _impl_.origin_id_to_string_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >& +CallTraceback::origin_id_to_string() const { + // @@protoc_insertion_point(field_map:tensorflow.CallTraceback.origin_id_to_string) + return _internal_origin_id_to_string(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >* +CallTraceback::_internal_mutable_origin_id_to_string() { + return _impl_.origin_id_to_string_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< int64_t, std::string >* +CallTraceback::mutable_origin_id_to_string() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.CallTraceback.origin_id_to_string) + return _internal_mutable_origin_id_to_string(); +} + +// .tensorflow.tfprof.OpLogProto graph_traceback = 5; +inline bool CallTraceback::_internal_has_graph_traceback() const { + return this != internal_default_instance() && _impl_.graph_traceback_ != nullptr; +} +inline bool CallTraceback::has_graph_traceback() const { + return _internal_has_graph_traceback(); +} +inline const ::tensorflow::tfprof::OpLogProto& CallTraceback::_internal_graph_traceback() const { + const ::tensorflow::tfprof::OpLogProto* p = _impl_.graph_traceback_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::tfprof::_OpLogProto_default_instance_); +} +inline const ::tensorflow::tfprof::OpLogProto& CallTraceback::graph_traceback() const { + // @@protoc_insertion_point(field_get:tensorflow.CallTraceback.graph_traceback) + return _internal_graph_traceback(); +} +inline void CallTraceback::unsafe_arena_set_allocated_graph_traceback( + ::tensorflow::tfprof::OpLogProto* graph_traceback) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.graph_traceback_); + } + _impl_.graph_traceback_ = graph_traceback; + if (graph_traceback) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CallTraceback.graph_traceback) +} +inline ::tensorflow::tfprof::OpLogProto* CallTraceback::release_graph_traceback() { + + ::tensorflow::tfprof::OpLogProto* temp = _impl_.graph_traceback_; + _impl_.graph_traceback_ = 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::tfprof::OpLogProto* CallTraceback::unsafe_arena_release_graph_traceback() { + // @@protoc_insertion_point(field_release:tensorflow.CallTraceback.graph_traceback) + + ::tensorflow::tfprof::OpLogProto* temp = _impl_.graph_traceback_; + _impl_.graph_traceback_ = nullptr; + return temp; +} +inline ::tensorflow::tfprof::OpLogProto* CallTraceback::_internal_mutable_graph_traceback() { + + if (_impl_.graph_traceback_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::tfprof::OpLogProto>(GetArenaForAllocation()); + _impl_.graph_traceback_ = p; + } + return _impl_.graph_traceback_; +} +inline ::tensorflow::tfprof::OpLogProto* CallTraceback::mutable_graph_traceback() { + ::tensorflow::tfprof::OpLogProto* _msg = _internal_mutable_graph_traceback(); + // @@protoc_insertion_point(field_mutable:tensorflow.CallTraceback.graph_traceback) + return _msg; +} +inline void CallTraceback::set_allocated_graph_traceback(::tensorflow::tfprof::OpLogProto* graph_traceback) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.graph_traceback_); + } + if (graph_traceback) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(graph_traceback)); + if (message_arena != submessage_arena) { + graph_traceback = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, graph_traceback, submessage_arena); + } + + } else { + + } + _impl_.graph_traceback_ = graph_traceback; + // @@protoc_insertion_point(field_set_allocated:tensorflow.CallTraceback.graph_traceback) +} + +// int64 graph_version = 6; +inline void CallTraceback::clear_graph_version() { + _impl_.graph_version_ = int64_t{0}; +} +inline int64_t CallTraceback::_internal_graph_version() const { + return _impl_.graph_version_; +} +inline int64_t CallTraceback::graph_version() const { + // @@protoc_insertion_point(field_get:tensorflow.CallTraceback.graph_version) + return _internal_graph_version(); +} +inline void CallTraceback::_internal_set_graph_version(int64_t value) { + + _impl_.graph_version_ = value; +} +inline void CallTraceback::set_graph_version(int64_t value) { + _internal_set_graph_version(value); + // @@protoc_insertion_point(field_set:tensorflow.CallTraceback.graph_version) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::tensorflow::EventReply_DebugOpStateChange_State> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::EventReply_DebugOpStateChange_State>() { + return ::tensorflow::EventReply_DebugOpStateChange_State_descriptor(); +} +template <> struct is_proto_enum< ::tensorflow::CallTraceback_CallType> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::CallTraceback_CallType>() { + return ::tensorflow::CallTraceback_CallType_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fdebug_2fdebug_5fservice_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service_mock.grpc.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service_mock.grpc.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..76035d35b1fe5d6fd7247c2c977d0ac63018d21c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debug_service_mock.grpc.pb.h @@ -0,0 +1,32 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: tensorflow/core/debug/debug_service.proto + +#include "tensorflow/core/debug/debug_service.pb.h" +#include "tensorflow/core/debug/debug_service.grpc.pb.h" + +#include +#include +#include +namespace tensorflow { + + +namespace grpc { + +class MockEventListenerStub : public EventListener::StubInterface { + public: + MOCK_METHOD1(SendEventsRaw, ::grpc::ClientReaderWriterInterface< ::tensorflow::Event, ::tensorflow::EventReply>*(::grpc::ClientContext* context)); + MOCK_METHOD3(AsyncSendEventsRaw, ::grpc::ClientAsyncReaderWriterInterface<::tensorflow::Event, ::tensorflow::EventReply>*(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag)); + MOCK_METHOD2(PrepareAsyncSendEventsRaw, ::grpc::ClientAsyncReaderWriterInterface<::tensorflow::Event, ::tensorflow::EventReply>*(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq)); + MOCK_METHOD3(SendTracebacks, ::grpc::Status(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::tensorflow::EventReply* response)); + MOCK_METHOD3(AsyncSendTracebacksRaw, ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>*(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq)); + MOCK_METHOD3(PrepareAsyncSendTracebacksRaw, ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>*(::grpc::ClientContext* context, const ::tensorflow::CallTraceback& request, ::grpc::CompletionQueue* cq)); + MOCK_METHOD3(SendSourceFiles, ::grpc::Status(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::tensorflow::EventReply* response)); + MOCK_METHOD3(AsyncSendSourceFilesRaw, ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>*(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq)); + MOCK_METHOD3(PrepareAsyncSendSourceFilesRaw, ::grpc::ClientAsyncResponseReaderInterface< ::tensorflow::EventReply>*(::grpc::ClientContext* context, const ::tensorflow::DebuggedSourceFiles& request, ::grpc::CompletionQueue* cq)); +}; + +} // namespace grpc + +} // namespace tensorflow + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debugger_event_metadata.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debugger_event_metadata.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..dae2ec3229234a89efd1a85e13a09b19fc0d9ae7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debugger_event_metadata.pb.h @@ -0,0 +1,387 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/debug/debugger_event_metadata.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fdebug_2fdebugger_5fevent_5fmetadata_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fdebug_2fdebugger_5fevent_5fmetadata_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_2fdebug_2fdebugger_5fevent_5fmetadata_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_2fdebug_2fdebugger_5fevent_5fmetadata_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fdebug_2fdebugger_5fevent_5fmetadata_2eproto; +namespace third_party { +namespace tensorflow { +namespace core { +namespace debug { +class DebuggerEventMetadata; +struct DebuggerEventMetadataDefaultTypeInternal; +extern DebuggerEventMetadataDefaultTypeInternal _DebuggerEventMetadata_default_instance_; +} // namespace debug +} // namespace core +} // namespace tensorflow +} // namespace third_party +PROTOBUF_NAMESPACE_OPEN +template<> ::third_party::tensorflow::core::debug::DebuggerEventMetadata* Arena::CreateMaybeMessage<::third_party::tensorflow::core::debug::DebuggerEventMetadata>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace third_party { +namespace tensorflow { +namespace core { +namespace debug { + +// =================================================================== + +class DebuggerEventMetadata final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:third_party.tensorflow.core.debug.DebuggerEventMetadata) */ { + public: + inline DebuggerEventMetadata() : DebuggerEventMetadata(nullptr) {} + ~DebuggerEventMetadata() override; + explicit PROTOBUF_CONSTEXPR DebuggerEventMetadata(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DebuggerEventMetadata(const DebuggerEventMetadata& from); + DebuggerEventMetadata(DebuggerEventMetadata&& from) noexcept + : DebuggerEventMetadata() { + *this = ::std::move(from); + } + + inline DebuggerEventMetadata& operator=(const DebuggerEventMetadata& from) { + CopyFrom(from); + return *this; + } + inline DebuggerEventMetadata& operator=(DebuggerEventMetadata&& 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 DebuggerEventMetadata& default_instance() { + return *internal_default_instance(); + } + static inline const DebuggerEventMetadata* internal_default_instance() { + return reinterpret_cast( + &_DebuggerEventMetadata_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(DebuggerEventMetadata& a, DebuggerEventMetadata& b) { + a.Swap(&b); + } + inline void Swap(DebuggerEventMetadata* 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(DebuggerEventMetadata* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DebuggerEventMetadata* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DebuggerEventMetadata& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DebuggerEventMetadata& from) { + DebuggerEventMetadata::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(DebuggerEventMetadata* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "third_party.tensorflow.core.debug.DebuggerEventMetadata"; + } + protected: + explicit DebuggerEventMetadata(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kDeviceFieldNumber = 1, + kOutputSlotFieldNumber = 2, + kNumChunksFieldNumber = 3, + kChunkIndexFieldNumber = 4, + }; + // string device = 1; + void clear_device(); + const std::string& device() const; + template + void set_device(ArgT0&& arg0, ArgT... args); + std::string* mutable_device(); + PROTOBUF_NODISCARD std::string* release_device(); + void set_allocated_device(std::string* device); + private: + const std::string& _internal_device() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device(const std::string& value); + std::string* _internal_mutable_device(); + public: + + // int32 output_slot = 2; + void clear_output_slot(); + int32_t output_slot() const; + void set_output_slot(int32_t value); + private: + int32_t _internal_output_slot() const; + void _internal_set_output_slot(int32_t value); + public: + + // int32 num_chunks = 3; + void clear_num_chunks(); + int32_t num_chunks() const; + void set_num_chunks(int32_t value); + private: + int32_t _internal_num_chunks() const; + void _internal_set_num_chunks(int32_t value); + public: + + // int32 chunk_index = 4; + void clear_chunk_index(); + int32_t chunk_index() const; + void set_chunk_index(int32_t value); + private: + int32_t _internal_chunk_index() const; + void _internal_set_chunk_index(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:third_party.tensorflow.core.debug.DebuggerEventMetadata) + 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_; + int32_t output_slot_; + int32_t num_chunks_; + int32_t chunk_index_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fdebug_2fdebugger_5fevent_5fmetadata_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// DebuggerEventMetadata + +// string device = 1; +inline void DebuggerEventMetadata::clear_device() { + _impl_.device_.ClearToEmpty(); +} +inline const std::string& DebuggerEventMetadata::device() const { + // @@protoc_insertion_point(field_get:third_party.tensorflow.core.debug.DebuggerEventMetadata.device) + return _internal_device(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void DebuggerEventMetadata::set_device(ArgT0&& arg0, ArgT... args) { + + _impl_.device_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:third_party.tensorflow.core.debug.DebuggerEventMetadata.device) +} +inline std::string* DebuggerEventMetadata::mutable_device() { + std::string* _s = _internal_mutable_device(); + // @@protoc_insertion_point(field_mutable:third_party.tensorflow.core.debug.DebuggerEventMetadata.device) + return _s; +} +inline const std::string& DebuggerEventMetadata::_internal_device() const { + return _impl_.device_.Get(); +} +inline void DebuggerEventMetadata::_internal_set_device(const std::string& value) { + + _impl_.device_.Set(value, GetArenaForAllocation()); +} +inline std::string* DebuggerEventMetadata::_internal_mutable_device() { + + return _impl_.device_.Mutable(GetArenaForAllocation()); +} +inline std::string* DebuggerEventMetadata::release_device() { + // @@protoc_insertion_point(field_release:third_party.tensorflow.core.debug.DebuggerEventMetadata.device) + return _impl_.device_.Release(); +} +inline void DebuggerEventMetadata::set_allocated_device(std::string* device) { + if (device != nullptr) { + + } else { + + } + _impl_.device_.SetAllocated(device, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_.IsDefault()) { + _impl_.device_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:third_party.tensorflow.core.debug.DebuggerEventMetadata.device) +} + +// int32 output_slot = 2; +inline void DebuggerEventMetadata::clear_output_slot() { + _impl_.output_slot_ = 0; +} +inline int32_t DebuggerEventMetadata::_internal_output_slot() const { + return _impl_.output_slot_; +} +inline int32_t DebuggerEventMetadata::output_slot() const { + // @@protoc_insertion_point(field_get:third_party.tensorflow.core.debug.DebuggerEventMetadata.output_slot) + return _internal_output_slot(); +} +inline void DebuggerEventMetadata::_internal_set_output_slot(int32_t value) { + + _impl_.output_slot_ = value; +} +inline void DebuggerEventMetadata::set_output_slot(int32_t value) { + _internal_set_output_slot(value); + // @@protoc_insertion_point(field_set:third_party.tensorflow.core.debug.DebuggerEventMetadata.output_slot) +} + +// int32 num_chunks = 3; +inline void DebuggerEventMetadata::clear_num_chunks() { + _impl_.num_chunks_ = 0; +} +inline int32_t DebuggerEventMetadata::_internal_num_chunks() const { + return _impl_.num_chunks_; +} +inline int32_t DebuggerEventMetadata::num_chunks() const { + // @@protoc_insertion_point(field_get:third_party.tensorflow.core.debug.DebuggerEventMetadata.num_chunks) + return _internal_num_chunks(); +} +inline void DebuggerEventMetadata::_internal_set_num_chunks(int32_t value) { + + _impl_.num_chunks_ = value; +} +inline void DebuggerEventMetadata::set_num_chunks(int32_t value) { + _internal_set_num_chunks(value); + // @@protoc_insertion_point(field_set:third_party.tensorflow.core.debug.DebuggerEventMetadata.num_chunks) +} + +// int32 chunk_index = 4; +inline void DebuggerEventMetadata::clear_chunk_index() { + _impl_.chunk_index_ = 0; +} +inline int32_t DebuggerEventMetadata::_internal_chunk_index() const { + return _impl_.chunk_index_; +} +inline int32_t DebuggerEventMetadata::chunk_index() const { + // @@protoc_insertion_point(field_get:third_party.tensorflow.core.debug.DebuggerEventMetadata.chunk_index) + return _internal_chunk_index(); +} +inline void DebuggerEventMetadata::_internal_set_chunk_index(int32_t value) { + + _impl_.chunk_index_ = value; +} +inline void DebuggerEventMetadata::set_chunk_index(int32_t value) { + _internal_set_chunk_index(value); + // @@protoc_insertion_point(field_set:third_party.tensorflow.core.debug.DebuggerEventMetadata.chunk_index) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace debug +} // namespace core +} // namespace tensorflow +} // namespace third_party + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fdebug_2fdebugger_5fevent_5fmetadata_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debugger_state_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debugger_state_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..9de9bdc2f290c38d0c552a8261a8b70d079b864a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/debug/debugger_state_impl.h @@ -0,0 +1,61 @@ +/* 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_DEBUG_DEBUGGER_STATE_IMPL_H_ +#define TENSORFLOW_CORE_DEBUG_DEBUGGER_STATE_IMPL_H_ + +#include "tensorflow/core/common_runtime/debugger_state_interface.h" + +#include +#include + +namespace tensorflow { + +class DebuggerState : public DebuggerStateInterface { + public: + DebuggerState(const DebugOptions& debug_options); + virtual ~DebuggerState(); + + // Publish metadata about the debugged Session::Run() call. + // + // See the doc string of DebuggerStateInterface::PublishDebugMetadata() for + // details. + Status PublishDebugMetadata(const int64_t global_step, + const int64_t session_run_count, + const int64_t executor_step_count, + const std::vector& input_names, + const std::vector& output_names, + const std::vector& target_names) override; + + private: + std::unordered_set debug_urls_; +}; + +class DebugGraphDecorator : public DebugGraphDecoratorInterface { + public: + DebugGraphDecorator(const DebugOptions& debug_options) + : debug_options_(debug_options) {} + virtual ~DebugGraphDecorator() {} + + Status DecorateGraph(Graph* graph, Device* device) override; + Status PublishGraph(const Graph& graph, const string& device_name) override; + + private: + DebugOptions debug_options_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DEBUG_DEBUGGER_STATE_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/base_rendezvous_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/base_rendezvous_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..3b5c99b16988d36e0e8591efa32545a543d2dee3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/base_rendezvous_mgr.h @@ -0,0 +1,296 @@ +/* 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_DISTRIBUTED_RUNTIME_BASE_RENDEZVOUS_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_BASE_RENDEZVOUS_MGR_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/common_runtime/eager/rendezvous_cache.h" +#include "tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h" +#include "tensorflow/core/distributed_runtime/worker_env.h" +#include "tensorflow/core/distributed_runtime/worker_session.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/control_flow.h" +#include "tensorflow/core/framework/local_rendezvous.h" +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/hash/hash.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/device_name_utils.h" +#include "tsl/platform/refcount.h" + +namespace tensorflow { + +class BaseRemoteRendezvous; +class BaseRecvTensorCall; + +// RendezvousMgr keeps track of a set of local rendezvous instances. +// All tensors sent by this worker are buffered in a RendezvousMgr +// until the tensor is received. Each global unique "step_id" +// corresponds to one local rendezvous instance managed by a +// RendezvousMgr. +// RendezvousMgr holds weak references to rendezvous. When a rendezvous is +// destructed, it will create a new instance to fulfill the Find. +// +// E.g., +// Rendezvous* rendez = worker_env->rendezvous_mgr->Find(0x8935); +// fork execution of a graph executor using "rendez" on thread 1; +// fork execution of another graph executor using "rendez" on thread 2; +// ... +// join threads 1 and 2; +// +// In the example above, execution in thread 1 and 2 communicates with +// each other by send/recv operations through `rendez`. +// +// Tensors sent and received through a rendezvous managed by this +// RendezvousMgr must have keys generated by Rendezvous::CreateKey(). +class BaseRendezvousMgr : public RendezvousMgrInterface { + public: + explicit BaseRendezvousMgr(const WorkerEnv* worker_env); + + ~BaseRendezvousMgr() override; + + // Returns Rendezvous supporting send and recv among workers in the + // "step_id". The caller takes ownership of one reference on the + // returned Rendezvous instance. + // + // Note: the caller must guarantee to eventually call Initialize on the + // returned RemoteRendezvous + tsl::core::RefCountPtr Find(int64_t step_id) override; + + // Finds the local rendezvous instance for the "step_id". Runs + // "done" when the tensor for "key" is produced or an error occurs. + // + // This method is used by the rpc handler of RecvTensor. + void RecvLocalAsync(int64_t step_id, const Rendezvous::ParsedKey& parsed, + Rendezvous::DoneCallback done) override; + + // Synchronous wrapper for RecvLocalAsync. + Status RecvLocal(int64_t step_id, const Rendezvous::ParsedKey& parsed, + Tensor* val, bool* is_dead) override; + + // Removes rendezvous for "step_id". + void Cleanup(int64_t step_id) override { cache_->RemoveAndAbort(step_id); } + + // Remove all rendezvous instances owned by the rendezvous_mgr. + void CleanupAll() override { cache_->RemoveAll(); } + + protected: + virtual tsl::core::RefCountPtr Create( + int64_t step_id, const WorkerEnv* worker_env) = 0; + + private: + tsl::core::RefCountPtr> cache_; + + // Not owned. + const WorkerEnv* const worker_env_; + + tsl::core::RefCountPtr FindOrCreate(int64_t step_id); + + BaseRendezvousMgr(const BaseRendezvousMgr&) = delete; + void operator=(const BaseRendezvousMgr&) = delete; +}; + +// RemoteRendezvous is a Rendezvous which can handle either +// the producer or consumer being in a remote process. +// +// Buffering of Tensor values is delegated to a "local" Rendezvous +// obtained from NewLocalRendezvous(). This class just adds +// functionality to coordinate with remote workers. +class BaseRemoteRendezvous : public RemoteRendezvous { + public: + BaseRemoteRendezvous(const WorkerEnv* env, int64_t step_id); + + // Upgrades the BaseRemoteRendezvous to full initialization. + Status Initialize(WorkerSession* session) override; + + void SetRemoteEagerContextDefault() override { + remote_eager_context_default_ = true; + } + bool IsRemoteEagerContextDefault() override { + return remote_eager_context_default_; + } + + // Forwards to local_, where the Tensor "val" will be buffered and + // any waiting callback stored. + Status Send(const ParsedKey& key, const Rendezvous::Args& args, + const Tensor& val, const bool is_dead) override; + + // This method is called only by the RecvOp. It tests to see + // whether the value will be produced by a local or remote device + // and handles accordingly. In the local case it forwards to + // local_, in the remote case it initiates an RPC request. + void RecvAsync(const ParsedKey& key, const Rendezvous::Args& args, + DoneCallback done) override; + + void StartAbort(const Status& status) override; + + // This method is called only by the local Worker, forwarded through + // the same method on RendezvousMgr. This occurs when the Worker + // has received a RecvTensor request, either locally or over the + // network. In either case it needs to retrieve a locally buffered + // value from local_, and give it to its caller. + // + // Runs "done" as soon as the tensor for "parsed" is available or an error + // is detected. + // + // REQUIRES: "parsed" is one that will be Saved into the local rendezvous. + void RecvLocalAsync(const ParsedKey& parsed, DoneCallback done); + + protected: + virtual void RecvFromRemoteAsync(const Rendezvous::ParsedKey& parsed, + const Rendezvous::Args& args, + DoneCallback done) = 0; + + // Returns true if "src" and "dst" are located in the same worker, + // and hence may use a local rendezvous. + virtual bool IsSameWorker(DeviceNameUtils::ParsedName src, + DeviceNameUtils::ParsedName dst); + + // If aborted, aborts "call". Otherwise, adds "call" into calls_. + void RegisterCall(BaseRecvTensorCall* call, const Rendezvous::Args& args); + + // Removes "call" from calls_ if "call" is in calls_. + void DeregisterCall(BaseRecvTensorCall* call, const Rendezvous::Args& args); + + WorkerSession* session(); + + bool is_initialized(); + + ~BaseRemoteRendezvous() override; + + const WorkerEnv* const env_; // Not owned. + const int64_t step_id_; + + private: + int num_shards_; + LocalRendezvous local_; + // Indicates whether this remote rendezvous instance is used as the default + // rendezvous for remote eager op-by-op execution. Errors in eager op-by-op + // execution should not abort the rendezvous since it is a context-wide + // instance and needs to be reused; instead, the errors are propagated through + // eager executors. + bool remote_eager_context_default_ = false; + + mutable mutex mu_; + mutable mutex calls_mu_; + + // Status given by StartAbort() if any. + Status status_ TF_GUARDED_BY(mu_); + + WorkerSession* session_ TF_GUARDED_BY(mu_); // Not owned. + + // Data structures to handle calls when partially initialized. + struct DeferredCall { + const ParsedKey parsed; + DoneCallback done; + + // Keeps a reference to the rendezvous, to keep it alive. + tsl::core::RefCountPtr rendezvous; + + DeferredCall(const ParsedKey& parsed, DoneCallback done, + tsl::core::RefCountPtr rendez); + }; + std::vector deferred_calls_ TF_GUARDED_BY(mu_); + + struct CallBucket { + mutex mu; + + absl::flat_hash_set calls TF_GUARDED_BY(mu); + }; + + struct PendingCalls { + PendingCalls(CancellationToken token, int num_calls, int num_buckets, + tsl::core::RefCountPtr rendez) + : token(token), + num_calls(num_calls), + buckets(num_buckets), + rendezvous(std::move(rendez)) {} + CancellationToken token = CancellationManager::kInvalidToken; + std::atomic num_calls = 0; + std::vector buckets; + + // Keeps a reference to the rendezvous, to keep it alive. + tsl::core::RefCountPtr rendezvous; + }; + + // "CancellationToken" is stored here so that when there's no active + // RecvTensorCalls, we can de-register the callback in the cancellation + // manager. RecvTensorCalls are managed in multiple buckets since in large + // scaled distributed training, lots of Send/Recv may be triggered + // concurrently. + // + // Note: pointer to CancellationManager can be nullptr in certain use cases. + absl::flat_hash_map> + calls_ TF_GUARDED_BY(calls_mu_); + + // Callback for CancellationManager. + void CancelledByManager(CancellationManager* cm); + + bool is_initialized_locked() TF_SHARED_LOCKS_REQUIRED(mu_) { + return session_ != nullptr; + } + + // If "is_src" is true, checks that the rendezvous key "parsed"'s + // source is in this process. If "is_src" is false, checks that the + // rendezvous key "parsed"'s destination is in this process. + Status ValidateDevices(const Rendezvous::ParsedKey& parsed, bool is_src); + + // Callback handling the case when a rendezvous has been + // accomplished in local_ and the consumer is local to this process. + // Tensor "in" will be copied into "out". The key "parsed" encodes + // the src and dst devices. + void SameWorkerRecvDone(const Rendezvous::ParsedKey& parsed, + const Rendezvous::Args& in_args, + const Rendezvous::Args& out_args, const Tensor& in, + Tensor* out, StatusCallback done); + + // Must be called only if fully initialized. + void RecvLocalAsyncInternal(const ParsedKey& parsed, DoneCallback done); + + BaseRemoteRendezvous(const BaseRemoteRendezvous&) = delete; + void operator=(const BaseRemoteRendezvous&) = delete; +}; + +class BaseRecvTensorCall { + public: + BaseRecvTensorCall() {} + virtual ~BaseRecvTensorCall() {} + + virtual void Start(std::function recv_done) = 0; + + virtual void StartAbort(const Status& s) = 0; + + virtual Status status() const = 0; + + private: + BaseRecvTensorCall(const BaseRecvTensorCall&) = delete; + void operator=(const BaseRecvTensorCall&) = delete; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_BASE_RENDEZVOUS_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/call_options.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/call_options.h new file mode 100644 index 0000000000000000000000000000000000000000..3cff6ccd0f8ad4a3e402ed8f8a096598ebb9602a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/call_options.h @@ -0,0 +1,27 @@ +/* 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_DISTRIBUTED_RUNTIME_CALL_OPTIONS_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CALL_OPTIONS_H_ + +#include "tsl/distributed_runtime/call_options.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::CallOptions; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CALL_OPTIONS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/cancellable_call.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/cancellable_call.h new file mode 100644 index 0000000000000000000000000000000000000000..7311c8e3a44f4202c84171c03213feb67aacb69f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/cancellable_call.h @@ -0,0 +1,61 @@ +/* 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_DISTRIBUTED_RUNTIME_CANCELLABLE_CALL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CANCELLABLE_CALL_H_ + +#include +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { + +// Supports client side cancellation of WorkerInterface calls via +// registration with a CancellationManager. +class CancellableCall { + public: + CancellableCall(CancellationManager* cancel_mgr, const string& remote_worker, + WorkerCacheInterface* wc) + : is_cancelled_(false), + cancel_mgr_(cancel_mgr), + remote_worker_(remote_worker), + wc_(wc), + wi_(wc_->GetOrCreateWorker(remote_worker_)) {} + + virtual ~CancellableCall() { wc_->ReleaseWorker(remote_worker_, wi_); } + + virtual void IssueCall(const StatusCallback& done) = 0; + + void Start(const StatusCallback& done); + + // Cancels the RPC if it's not cancelled yet. This must be called after + // Start(). This is normally used if there's a needed to cancel the RPC from a + // sideband. If appliable, pass a cancellation manager to the constructor + // instead of using this method. + void Cancel() TF_LOCKS_EXCLUDED(mu_); + + protected: + mutex mu_; + bool is_cancelled_; + CancellationManager* const cancel_mgr_; // Not owned + const string remote_worker_; + WorkerCacheInterface* const wc_; // Not owned + WorkerInterface* const wi_; // Owned by wc_, must be released. + CallOptions opts_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CANCELLABLE_CALL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/cluster_function_library_runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/cluster_function_library_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..eaad4301576570c37a36854dc10ee6468a12ec71 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/cluster_function_library_runtime.h @@ -0,0 +1,106 @@ +/* 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_DISTRIBUTED_RUNTIME_CLUSTER_FUNCTION_LIBRARY_RUNTIME_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CLUSTER_FUNCTION_LIBRARY_RUNTIME_H_ + +#include +#include +#include + +#include "absl/types/optional.h" +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/distributed_runtime/worker_interface.h" +#include "tensorflow/core/framework/function.h" + +namespace tensorflow { + +class WorkerSession; + +// ClusterFunctionLibraryRuntime contains methods to Instantiate and Run +// functions across processes by making RPCs through worker service. +class ClusterFunctionLibraryRuntime : public DistributedFunctionLibraryRuntime { + public: + ClusterFunctionLibraryRuntime(WorkerSession* worker_session, + bool create_worker_session_called, + DeviceMgr* remote_device_mgr) + : worker_session_(worker_session), + create_worker_session_called_(create_worker_session_called), + remote_device_mgr_(remote_device_mgr) {} + + ~ClusterFunctionLibraryRuntime() override; + + void Instantiate(const string& function_name, + const FunctionLibraryDefinition& lib_def, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + FunctionLibraryRuntime::LocalHandle* handle, + FunctionLibraryRuntime::DoneCallback done) override; + + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::LocalHandle handle, + gtl::ArraySlice args, std::vector* rets, + FunctionLibraryRuntime::DoneCallback done) override; + + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::LocalHandle handle, + gtl::ArraySlice args, std::vector* rets, + FunctionLibraryRuntime::DoneCallback done) override; + + void CleanUp(uint64 step_id, FunctionLibraryRuntime::LocalHandle handle, + FunctionLibraryRuntime::DoneCallback done) override; + + DeviceMgr* remote_device_mgr() const override { return remote_device_mgr_; } + + private: + static Status ConstructFunctionGraph( + const OpDef& sig, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + const FunctionLibraryDefinition& flib_def, GraphDef* g, + std::vector* send_keys, std::vector* recv_keys); + friend class ClusterFunctionLibraryRuntimeTest; + + mutable mutex mu_; + WorkerSession* const worker_session_ = nullptr; // not owned. + const bool create_worker_session_called_; + + DeviceMgr* remote_device_mgr_; // not owned. + + struct FunctionData { + const string graph_handle; + const string target; + // Hold a shared pointer to the underlying worker cache to avoid it being + // deleted in potential cluster update. + const std::shared_ptr worker_cache; + WorkerInterface* wi = nullptr; + const std::vector send_keys; + const std::vector recv_keys; + + FunctionData(const string& graph_handle, const string& target, + std::shared_ptr worker_cache, + WorkerInterface* wi, const std::vector& send_keys, + const std::vector& recv_keys) + : graph_handle(graph_handle), + target(target), + worker_cache(std::move(worker_cache)), + wi(wi), + send_keys(send_keys), + recv_keys(recv_keys) {} + }; + + std::vector function_data_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_CLUSTER_FUNCTION_LIBRARY_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h new file mode 100644 index 0000000000000000000000000000000000000000..4d75e9d4e18e2f11e2239e23c0cc553cd2fe73a8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/collective_param_resolver_distributed.h @@ -0,0 +1,96 @@ +/* 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_DISTRIBUTED_RUNTIME_COLLECTIVE_PARAM_RESOLVER_DISTRIBUTED_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COLLECTIVE_PARAM_RESOLVER_DISTRIBUTED_H_ + +#include "tensorflow/core/common_runtime/collective_param_resolver_local.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +class ConfigProto; +class WorkerCacheInterface; +class DeviceResolverDistributed; +class DeviceMgr; + +class CollectiveParamResolverDistributed : public CollectiveParamResolverLocal { + public: + CollectiveParamResolverDistributed( + const ConfigProto& config, const DeviceMgr* dev_mgr, + DeviceResolverDistributed* dev_resolver, + NcclCommunicatorInterface* nccl_communicator, + WorkerCacheInterface* worker_cache, const string& task_name); + + void CompleteParamsAsync(const DeviceAttributes& device, CollectiveParams* cp, + CancellationManager* cancel_mgr, + const StatusCallback& done) override; + + void CompleteGroupAsync(const DeviceAttributes& device, + CollGroupParams* group_params, + CancellationManager* cancel_mgr, + const StatusCallback& done) override; + + void CompleteInstanceAsync(const CompleteInstanceRequest* request, + CompleteInstanceResponse* response, + CancellationManager* cancel_mgr, + const StatusCallback& done) override; + + void StartAbort(const Status& s) override; + + protected: + // Returns the cached group iff there's an entry for this group_key in the + // local group_table_; returns nullptr otherwise. + GroupRec* GetCachedGroup(int32_t group_key) TF_LOCKS_EXCLUDED(group_mu_); + + // Updates group_table_ with contents of resp. + Status UpdateGroupCache(const CompleteGroupResponse& resp) + TF_LOCKS_EXCLUDED(group_mu_); + + // Finds the GroupRec that corresponds to cp->group_key and also + // populates cp->group from that GroupRec. + // + // Semantics are like those of CompleteGroupLocal but will make a + // remote call to the group leader if necessary. + void CompleteGroupDistributed(const DeviceAttributes& device, + CollGroupParams* group_params, + CancellationManager* cancel_mgr, + const StatusCallback& done); + + // Returns true iff there's an entry for this instance_key in the + // local instance_table_. + bool InstanceIsCached(int32_t group_key, const CollInstanceParams& instance) + TF_LOCKS_EXCLUDED(instance_mu_); + + // Updates instance_table_ with contents of resp. + Status UpdateInstanceCache(CollectiveParams* cp, + const CompleteInstanceResponse& resp) + TF_LOCKS_EXCLUDED(instance_mu_, group_mu_); + + // Finish populating *cp. Semantics are like those of + // CompleteInstanceLocal but will make a remote call to the group + // leader if necessary. + void CompleteInstanceDistributed(const string& device, CollectiveParams* cp, + CancellationManager* cancel_mgr, + const StatusCallback& done) + TF_LOCKS_EXCLUDED(instance_mu_, group_mu_); + + WorkerCacheInterface* worker_cache_; // Not owned + const string group_leader_; + CancellationManager abortion_cancel_mgr_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COLLECTIVE_PARAM_RESOLVER_DISTRIBUTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/collective_rma_distributed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/collective_rma_distributed.h new file mode 100644 index 0000000000000000000000000000000000000000..31eab9dba2f904477ca05073919cc706c26a1838 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/collective_rma_distributed.h @@ -0,0 +1,64 @@ +/* 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_DISTRIBUTED_RUNTIME_COLLECTIVE_RMA_DISTRIBUTED_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COLLECTIVE_RMA_DISTRIBUTED_H_ + +#include "tensorflow/core/common_runtime/collective_rma_local.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/unbounded_work_queue.h" + +namespace tensorflow { +class WorkerCacheInterface; + +// Extend CollectiveRemoteAccessLocal with access to remote peers. +class CollectiveRemoteAccessDistributed : public CollectiveRemoteAccessLocal { + public: + CollectiveRemoteAccessDistributed( + const DeviceMgr* dev_mgr, DeviceResolverInterface* dev_resolver, + std::shared_ptr work_queue, + WorkerCacheInterface* worker_cache, int64_t step_id, string task_name) + : CollectiveRemoteAccessLocal(dev_mgr, dev_resolver, step_id), + worker_cache_(worker_cache), + work_queue_(std::move(work_queue)), + task_name_(std::move(task_name)) {} + + ~CollectiveRemoteAccessDistributed() override {} + + void RecvFromPeer(const string& peer_device, const string& peer_task, + bool peer_is_local, const string& key, Device* to_device, + DeviceContext* to_device_ctx, + const AllocatorAttributes& to_alloc_attr, Tensor* to_tensor, + const DeviceLocality& client_locality, + int dev_to_dev_stream_index, + CancellationManager* cancellation_manager, + const StatusCallback& done) override; + + void CheckPeerHealth(const string& peer_task, int64_t timeout_in_ms, + const StatusCallback& done) override; + + void StartAbort(const Status& s) override; + + protected: + WorkerCacheInterface* worker_cache_; // Not owned + // Ownership of `work_queue_` is shared between `this` and + // `CollectiveExecutorMgr`. + std::shared_ptr work_queue_; + CancellationManager abortion_cancel_mgr_; + string task_name_; +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COLLECTIVE_RMA_DISTRIBUTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_client.h new file mode 100644 index 0000000000000000000000000000000000000000..95907778e7012b442c169eae10756188975a1a28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_client.h @@ -0,0 +1,31 @@ +/* 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_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_CLIENT_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_CLIENT_H_ + +#include +#include + +#include "tsl/distributed_runtime/coordination/coordination_client.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::CoordinationClient; +using tsl::CoordinationClientCache; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_service_error_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_service_error_util.h new file mode 100644 index 0000000000000000000000000000000000000000..bbc263e1deb82662bd8ab01e464b73ff05a17fae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/coordination/coordination_service_error_util.h @@ -0,0 +1,27 @@ +/* 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_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_ERROR_UTIL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_ERROR_UTIL_H_ + +#include "tsl/distributed_runtime/coordination/coordination_service_error_util.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using ::tsl::CoordinationErrorPayloadKey; +using ::tsl::MakeCoordinationError; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_COORDINATION_COORDINATION_SERVICE_ERROR_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/device_resolver_distributed.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/device_resolver_distributed.h new file mode 100644 index 0000000000000000000000000000000000000000..299cbc95b01f9bb9eeba801db34a1657fcad00f5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/device_resolver_distributed.h @@ -0,0 +1,50 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_DEVICE_RESOLVER_DISTRIBUTED_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_DEVICE_RESOLVER_DISTRIBUTED_H_ + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +class DeviceMgr; +class WorkerCacheInterface; + +class DeviceResolverDistributed : public DeviceResolverInterface { + public: + explicit DeviceResolverDistributed(const DeviceMgr* dev_mgr); + + Status GetDeviceAttributes(const string& device, + DeviceAttributes* attributes) override; + + Status GetAllDeviceAttributes( + const string& task, std::vector* attributes) override; + + Status UpdateDeviceAttributes( + const std::vector& attributes) override; + + protected: + const string task_name_; + mutex mu_; + absl::flat_hash_map attr_table_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_DEVICE_RESOLVER_DISTRIBUTED_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/cluster_function_library_runtime.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/cluster_function_library_runtime.h new file mode 100644 index 0000000000000000000000000000000000000000..ed0cb32348f3d57a352c23f0b84c509ca75051c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/cluster_function_library_runtime.h @@ -0,0 +1,115 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_CLUSTER_FUNCTION_LIBRARY_RUNTIME_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_CLUSTER_FUNCTION_LIBRARY_RUNTIME_H_ + +#include +#include +#include + +#include "absl/types/optional.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/common_runtime/eager/eager_operation.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/protobuf/remote_tensor_handle.pb.h" + +namespace tensorflow { + +class WorkerSession; + +namespace eager { + +// EagerClusterFunctionLibraryRuntime contains methods to Instantiate and Run +// functions across processes by making RPCs through eager service. +class EagerClusterFunctionLibraryRuntime + : public DistributedFunctionLibraryRuntime { + public: + EagerClusterFunctionLibraryRuntime(const uint64 context_id, EagerContext* ctx, + DeviceMgr* remote_device_mgr) + : context_id_(context_id), + ctx_(ctx), + remote_device_mgr_(remote_device_mgr) {} + + ~EagerClusterFunctionLibraryRuntime() override{}; + + // Register a partition (i.e., component function) of a multi-device function + // on the remote target specified in `options.target`. This should be + // triggered as part of instantiating a multi-device function in + // ProcessFunctionLibraryRuntime. + void Instantiate(const string& function_name, + const FunctionLibraryDefinition& lib_def, AttrSlice attrs, + const FunctionLibraryRuntime::InstantiateOptions& options, + FunctionLibraryRuntime::LocalHandle* handle, + FunctionLibraryRuntime::DoneCallback done) override; + + // Execute the component function specified by `handle` on its instantiated + // remote target. This should be triggered as part of driving a multi-device + // function execution in ProcessFunctionLibraryRuntime. Running the component + // function remotely is purely asynchronous, and multiple component functions + // with the same remote target are not executed in any particular ordering. + // The main function side must wait for all component functions to finish + // (i.e., the done callbacks triggered) before finishing its execution. + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::LocalHandle handle, + gtl::ArraySlice args, std::vector* rets, + FunctionLibraryRuntime::DoneCallback done) override; + + // The component function inputs `args` and outputs `rets` may refer to remote + // tensors on a remote device, which will be lazily resolved remotely where + // the inputs/outputs are actually consumed. + void Run(const FunctionLibraryRuntime::Options& opts, + FunctionLibraryRuntime::LocalHandle handle, + gtl::ArraySlice args, std::vector* rets, + FunctionLibraryRuntime::DoneCallback done) override; + + void CleanUp(uint64 step_id, FunctionLibraryRuntime::LocalHandle handle, + FunctionLibraryRuntime::DoneCallback done) override; + + DeviceMgr* remote_device_mgr() const override { return remote_device_mgr_; } + + private: + const uint64 context_id_; + EagerContext* ctx_; + DeviceMgr* remote_device_mgr_; // not owned. + + struct FunctionData { + const string target; + const absl::optional> ret_indices; + core::RefCountPtr eager_client; + std::unique_ptr op; + + FunctionData(const string& target, + const absl::optional>& ret_indices, + EagerClient* eager_client, std::unique_ptr op) + : target(target), + ret_indices(ret_indices), + eager_client(core::RefCountPtr(eager_client)), + op(std::move(op)) { + eager_client->Ref(); + } + }; + + mutable mutex mu_; + std::vector function_data_ TF_GUARDED_BY(mu_); +}; + +DistributedFunctionLibraryRuntime* CreateClusterFLR( + const uint64 context_id, EagerContext* ctx, WorkerSession* worker_session); + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_CLUSTER_FUNCTION_LIBRARY_RUNTIME_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/destroy_tensor_handle_node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/destroy_tensor_handle_node.h new file mode 100644 index 0000000000000000000000000000000000000000..45aab6e5f840ea8c01ff385aa1d9beae90cbb54c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/destroy_tensor_handle_node.h @@ -0,0 +1,90 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_DESTROY_TENSOR_HANDLE_NODE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_DESTROY_TENSOR_HANDLE_NODE_H_ + +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/distributed_runtime/eager/eager_client.h" +#include "tensorflow/core/protobuf/eager_service.pb.h" + +namespace tensorflow { +namespace eager { + +// DestroyTensorHandleNode is an implementation of EagerNode which enqueues a +// request to destroy a remote tensor handle. +class DestroyTensorHandleNode : public tensorflow::AsyncEagerNode { + public: + DestroyTensorHandleNode(std::unique_ptr request, + core::RefCountPtr eager_client, + bool ready) + : tensorflow::AsyncEagerNode(), + request_(std::move(request)), + eager_client_(std::move(eager_client)), + ready_(ready) {} + + ~DestroyTensorHandleNode() override {} + + void RunAsync(StatusCallback done) override { + EnqueueResponse* response = new EnqueueResponse; + bool ready = ready_; + // NOTE(fishx): Don't use StreamingEnqueueAsync here. When a + // StreamingEnqueueAsync request fails all following requests will fail as + // well. We don't want this request poison following requests since it is + // safe to ignore a failing destroy tensor handle request. + eager_client_->EnqueueAsync( + /*call_opts=*/nullptr, request_.get(), response, + [response, ready, done](const tensorflow::Status& s) { + // Omit the warning if: + // 1. The remote tensor isn't ready. + // 2. Lost connection to remote worker. In this case client will + // crash. We don't want to spam user with redundant warning logs. + if (!s.ok() && ready && !absl::IsUnavailable(s)) { + LOG_EVERY_N_SEC(WARNING, 60) + << "Ignoring an error encountered when deleting " + "remote tensors handles: " + << s.ToString(); + } + done(OkStatus()); + delete response; + }); + } + + void Abort(Status status) override {} + + // Remote node deletions are best effort + bool Fatal() const override { return false; } + + string DebugString() const override { + string out = "[DestroyTensorHandleNode]"; + strings::StrAppend(&out, " request: ", request_->DebugString()); + return out; + } + + private: + std::unique_ptr request_; + core::RefCountPtr eager_client_; + const string remote_task_; + bool ready_; +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_DESTROY_TENSOR_HANDLE_NODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_client.h new file mode 100644 index 0000000000000000000000000000000000000000..a2265d51a1f5d3e5f477661836843b6a7a7d34c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_client.h @@ -0,0 +1,102 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_EAGER_CLIENT_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_EAGER_CLIENT_H_ + +#include + +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/protobuf/eager_service.pb.h" + +namespace tensorflow { +namespace eager { + +// This is a base class that can be implemented by a variety of +// transports (e.g. gRPC which for each of the client methods makes an RPC). +class EagerClient : public core::RefCounted { + public: + ~EagerClient() override {} +#define CLIENT_METHOD(method) \ + virtual void method##Async(const method##Request* request, \ + method##Response* response, \ + StatusCallback done) = 0; + + CLIENT_METHOD(CreateContext); + CLIENT_METHOD(UpdateContext); + CLIENT_METHOD(WaitQueueDone); + CLIENT_METHOD(KeepAlive); + CLIENT_METHOD(CloseContext); + +#undef CLIENT_METHOD + +#define CLIENT_METHOD_WITH_TIMEOUT_AND_RETRIES(method) \ + virtual void method##Async(const method##Request* request, \ + method##Response* response, StatusCallback done, \ + int64_t init_timeout_in_ms, int retries) = 0; + + CLIENT_METHOD_WITH_TIMEOUT_AND_RETRIES(CreateContext); + +#undef CLIENT_METHOD_WITH_TIMEOUT_AND_RETRIES + +#define CLIENT_CANCELABLE_METHOD(method) \ + virtual void method##Async( \ + CallOptions* call_opts, const method##Request* request, \ + method##Response* response, StatusCallback done) = 0; + + CLIENT_CANCELABLE_METHOD(Enqueue); + CLIENT_CANCELABLE_METHOD(RunComponentFunction); + +#undef CLIENT_CANCELABLE_METHOD + + // Feeds `request` into the request stream of EagerService::StreamingEnqueue. + // `response` will be filled with the response for this `request`. The + // 1-to-1 correspondence between requests and responses is a property + // of the current service implementation. When the response is received, + // `done` is invoked with the current status of the StreamingEnqueue call. + // The status can contain an error because of an earlier request in the + // current streaming call. + // The client initiates a streaming call the first time StreamingEnqueueAsync + // is invoked and keeps it open until some error condition. + // Similarly to the methods above, the request can be deleted as soon as + // StreamingEnqueueAsync returns. + virtual void StreamingEnqueueAsync(bool enable_streaming_enqueue, + CallOptions* call_opts, + const EnqueueRequest* request, + EnqueueResponse* response, + StatusCallback done) = 0; + + virtual bool allow_multiple_pending_requests() const = 0; +}; + +// Simple wrapper class that can be used to retrieve EagerClients. +class EagerClientCache { + public: + virtual ~EagerClientCache() {} + + // If the `target` exists, assign the EagerClient pointer to `client` and + // increment the refcount of the client. The reference ownership is + // transferred to the caller, and the unref should automatically happen when + // destructing the RefCountPtr object from the caller's side. + virtual Status GetClient(const string& target, + core::RefCountPtr* client) = 0; +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_EAGER_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_service_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_service_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..8239b361b48ef572270b899d5aeb9affe427834e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/eager_service_impl.h @@ -0,0 +1,242 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_EAGER_SERVICE_IMPL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_EAGER_SERVICE_IMPL_H_ + +#include +#include +#include + +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/distributed_runtime/eager/remote_mgr.h" +#include "tensorflow/core/distributed_runtime/eager/remote_tensor_handle.h" +#include "tensorflow/core/distributed_runtime/worker_env.h" + +namespace tensorflow { +namespace eager { + +// A TensorFlow Eager Worker runs ops and supports worker to worker +// Tensor transfer. +// +// See eager_service.proto for more details about each method. +// This class can be wrapped by specific classes that implement rpc transports +// over this (e.g. gRPC). +class EagerServiceImpl { + public: + explicit EagerServiceImpl(WorkerEnv* env) : env_(env) { + gc_thread_.reset( + env_->env->StartThread({}, "EagerServiceContextGC", [this]() { + while (true) { + { + mutex_lock l(gc_thread_shutdown_mu_); + gc_thread_cv_.wait_for(l, std::chrono::seconds(1)); + + if (shutting_down_) { + return; + } + } + { + mutex_lock l(contexts_mu_); + for (auto it = contexts_.begin(); it != contexts_.end();) { + if (it->second->IsStale()) { + it->second->Unref(); + it = contexts_.erase(it); + } else { + it++; + } + } + } + } + })); + } + virtual ~EagerServiceImpl() { + { + mutex_lock l(gc_thread_shutdown_mu_); + shutting_down_ = true; + gc_thread_cv_.notify_all(); + } + gc_thread_.reset(); + + mutex_lock l(contexts_mu_); + for (auto& entry : contexts_) { + entry.second->Unref(); + } + } + + Status CreateContext(const CreateContextRequest* request, + CreateContextResponse* response); + + Status UpdateContext(const UpdateContextRequest* request, + UpdateContextResponse* response); + + // Create a ServerContext for master eager context. + Status CreateMasterContext(const tensorflow::uint64 context_id, + EagerContext* context); + + static constexpr uint64 kInvalidStreamId = 0; + + // Used by both Enqueue and StreamingEnqueue RPCs. + Status Enqueue(CallOptions* call_opts, const EnqueueRequest* request, + EnqueueResponse* response, + uint64 stream_id = kInvalidStreamId); + + Status WaitQueueDone(const WaitQueueDoneRequest* request, + WaitQueueDoneResponse* response); + + void RunComponentFunction(CallOptions* call_opts, + const RunComponentFunctionRequest* request, + RunComponentFunctionResponse* response, + StatusCallback done); + + Status KeepAlive(const KeepAliveRequest* request, + KeepAliveResponse* response); + + Status CloseContext(const CloseContextRequest* request, + CloseContextResponse* response); + + protected: + // This is the server-side execution context. All state regarding execution of + // a client's ops is held in this server-side context (all generated tensors, + // and the EagerContext). + class ServerContext : public core::RefCounted { + public: + // Create a ServerContext for local master. + static ServerContext* CreateMasterContext(tensorflow::EagerContext* ctx, + const WorkerEnv* env) { + return new ServerContext(ctx, -1, env, /* is_master= */ true); + } + + explicit ServerContext(tensorflow::EagerContext* ctx, + int64_t destroy_after_secs, const WorkerEnv* env, + const bool is_master = false) + : ctx_(ctx), env_(env), is_master_(is_master) { + ctx->Ref(); + destroy_after_micros_ = + destroy_after_secs * tensorflow::EnvTime::kSecondsToMicros; + RecordAccess(); + } + + ~ServerContext() override { + // TFE_Context is responsible for shutting down master eager context. + if (!is_master_) { + ctx_->WaitForAndCloseRemoteContexts(); + } + // ctx_->RefCountIsOne() should be true here when is_master_ = false. + // TODO(iga): Remove EagerContext refcounting. + ctx_->Unref(); + } + + tensorflow::EagerContext* Context() const { return ctx_; } + + void RecordAccess() { + mutex_lock l(last_accessed_mu_); + last_accessed_micros_ = env_->env->NowMicros(); + } + + bool IsStale() { + mutex_lock l(last_accessed_mu_); + const int64_t time_passed = + env_->env->NowMicros() - last_accessed_micros_; + return (destroy_after_micros_ > 0 && time_passed > destroy_after_micros_); + } + + private: + // The context for this execution. + tensorflow::EagerContext* ctx_; + + const WorkerEnv* const env_; // Not owned. + + mutex last_accessed_mu_; + int64_t last_accessed_micros_ TF_GUARDED_BY(last_accessed_mu_); + int64_t destroy_after_micros_; + + const bool is_master_; + }; + // The returned ServerContext will need to be Unrefed. + tensorflow::Status GetServerContext(uint64, ServerContext**); + + class ClientTensorHandleDeleteNode : public EagerNode { + public: + ClientTensorHandleDeleteNode( + ServerContext* context, + std::unique_ptr handle_to_delete) + : tensorflow::EagerNode(), + context_(context), + handle_to_delete_(std::move(handle_to_delete)) { + context_->Ref(); + } + + ~ClientTensorHandleDeleteNode() override { context_->Unref(); } + + Status Run() override { + VLOG(3) << "ServerContext: Deleting tensor handle " + << handle_to_delete_->op_id << ":" + << handle_to_delete_->output_num; + return context_->Context()->RemoteMgr()->DeleteTensorHandle( + *handle_to_delete_); + } + + void Abort(Status status) override {} + + // Remote node deletions are best effort + bool Fatal() const override { return false; } + + string DebugString() const override { + string out = "[ClientTensorHandleDeleteNode]"; + strings::StrAppend(&out, " op_id: ", handle_to_delete_->op_id); + strings::StrAppend(&out, ", output_num: ", handle_to_delete_->output_num); + return out; + } + + private: + // Owns one reference. + ServerContext* const context_; + const std::unique_ptr handle_to_delete_; + }; + + private: + Status ExecuteOp(CallOptions* call_opts, const Operation& operation, + EagerContext* eager_context, EagerExecutor* eager_executor, + QueueResponse* queue_response); + Status SendTensor(const SendTensorOp& send_tensor, + EagerContext* eager_context); + Status SendPackedHandle(const SendPackedHandleOp& send_packed_handle, + EagerContext* eager_context); + Status RegisterFunction(const RegisterFunctionOp& register_function, + EagerContext* eager_context); + Status RemoveFunction(const RemoveFunctionOp& remove_function, + EagerContext* eager_context); + Status CleanupFunction(const CleanupFunctionOp& cleanup_function); + + WorkerEnv* const env_; // Not owned. + + mutex contexts_mu_; + std::unordered_map contexts_ + TF_GUARDED_BY(contexts_mu_); + + std::unique_ptr gc_thread_; + mutex gc_thread_shutdown_mu_; + condition_variable gc_thread_cv_; + bool shutting_down_ TF_GUARDED_BY(gc_thread_shutdown_mu_) = false; + + EagerServiceImpl(const EagerServiceImpl&) = delete; + void operator=(const EagerServiceImpl&) = delete; +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_EAGER_SERVICE_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_copy_node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_copy_node.h new file mode 100644 index 0000000000000000000000000000000000000000..0f5297e855933e00c8832818c6d3ebfcd00a3e14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_copy_node.h @@ -0,0 +1,179 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_REMOTE_COPY_NODE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_COPY_NODE_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/eager_operation.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { +namespace eager { + +// This node supports copying a tensor in the following way: +// - Remote -> Local: +// We don't block on the remote _Send op and start executing the local +// _Recv immediately after issuing the remote _Send. The local _Recv +// kernel (or rather the special _Recv handling in KernelAndDeviceOp::Run) +// blocks until the tensor is received. If the remote _Send (or some op +// before it) fails, the local callback we give to EnqueueAsync will run +// and call CancellationManager.StartCancel(). The blocked local _Recv will +// get this notification and return with a cancelled error. +// +// - Local -> Remote: +// The local _Send op is synchronous and non-blocking, thus it should complete +// quickly. We issue remote _Recv RPC only after local _Send completes +// successfully. At this point, the tensor to be sent is in the local +// Rendezvous, hence, remote _Recv op will not deadlock waiting for the tensor +// to appear. +// When ctx->UseSendTensorRPC() is true, we use EagerService::Enqueue +// SendTensor instead of _Send/_Recv. +// +// - Remote -> Remote: +// We could issue both remote ops asynchronously, but if remote _Send (or some +// op before it) fails, we don't have a good way of cancelling the remote +// _Recv. The remote _Recv will deadlock in this case. The current approach +// to deal with this issue is to wait for remote _Send to complete before +// issuing remote _Recv RPC. Another option is to close the whole streaming +// RPC that contains the deadlocked remote _Recv. This would not unblock the +// deadlocked RPC on the remote machine without some extra code. Luckily, the +// remote -> remote case seems to be fairly rare at this point. So, the +// current partially synchronous approach seems fine. +// +// To copy a tensor within a host, please use copy_to_device_node instead. +class RemoteCopyNode : public AsyncEagerNode { + public: + RemoteCopyNode(EagerContext* ctx, EagerExecutor* executor, TensorHandle* src, + TensorHandle* dst, Device* recv_device, uint64 recv_op_id); + + ~RemoteCopyNode() override; + + Status Prepare() override; + + void RunAsync(StatusCallback done) override; + + void Abort(Status status) override; + + string DebugString() const override { + string out = "[RemoteCopyNode]"; + strings::StrAppend(&out, " send_device: ", send_device_->name()); + strings::StrAppend(&out, ", recv_device: ", recv_device_->name()); + strings::StrAppend(&out, ", send_tensor: ", src_->DebugString()); + strings::StrAppend( + &out, ", recv_tensor: ", captured_state_->dst()->DebugString()); + return out; + } + + private: + // Runs the _Send operation locally or remotely. + // StartSend() makes sure that captured_state_->send_status_ is set to the + // final _Send status after captured_state->send_done_.WaitForNotification() + // returns. + void StartSend(); + + // Synchronously runs local send `op` and returns its status. + Status RunLocalSend(EagerOperation* op); + + // Runs the _Recv operation locally or remotely. + // An error return value indicates that _Recv did not run successfully. It + // does not indicate that _Send op has completed since StartRecv could have + // encountered an error before waiting for _Send's completion. + // An OK return value does NOT necessarily indicate that _Recv has completed + // successfully (it does now, but won't when streaming RPCs are turned on). + // StartRecv() makes sure that dst_ tensor handle is handled correctly + // (potentially after this methods returns); a tensor is set in the local + // case, a remote shape is set in the remote case, the dst_ handle is + // poisoned in either case if there is an error. + void StartRecv(StatusCallback done); + + // Synchronously runs local receive `op` and returns its status. + // Does not wait for the send to complete before running receive. + Status RunLocalRecv(EagerOperation* op, std::vector* outputs); + + // Waits for send to complete, then issues remote receive `op` and + // returns its status. + void RunRemoteRecv(EagerOperation* op, StatusCallback done); + + // When !ctx->UseSendTensorRPC(), then tensors are shipped between remote + // devices by the receiver invoking the WorkerService.RecvTensor RPC *on the + // sender* (Rendezvous::RecvAsync() invoked by the _Recv kernel). + // + // However, in some configurations the node that has the tensor to be copied + // isn't running a server (WorkerService RPC interface). For such cases, + // this function enables sending tensors using the EagerService.Enqueue + // SendTensor RPC *on the receiver*. + void StartRemoteSendTensor(StatusCallback done); + + // Send a local packed TensorHandle to a remote device. + void StartSendPackedHandle(StatusCallback done); + + // State that is captured by Send and/or Recv callbacks (depending on which + // one(s) is remote) and outlives this node in the case of remote->remote + // copy. + class CapturedSharedState { + public: + explicit CapturedSharedState(TensorHandle* d) : dst_(d) { dst_->Ref(); } + ~CapturedSharedState() { dst_->Unref(); } + + void SetSendStatus(Status status) { + send_status_.Update(status); + send_done_.Notify(); + } + + Status GetSendStatus() { + send_done_.WaitForNotification(); + return send_status_; + } + + // src_shape_ is not thread-safe. It should only be set in one thread. + void SetSrcShape(const TensorShape& shape) { src_shape_ = shape; } + + const TensorShape& GetSrcShape() { return src_shape_; } + + TensorHandle* dst() { return dst_; } + CancellationManager* recv_cancellation() { return &recv_cancellation_; } + + private: + TensorHandle* const dst_; + CancellationManager recv_cancellation_; + // send_status_ is safe to read only after send_done_.WaitForNotification() + // has returned. + Status send_status_; + Notification send_done_; + TensorShape src_shape_; + }; + + TensorHandle* const src_; + EagerContext* const ctx_; + EagerExecutor* const executor_; + Device* const send_device_; + Device* const recv_device_; + const string wire_id_; + const uint64 recv_op_id_; + + std::shared_ptr captured_state_; + bool started_; +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_COPY_NODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_execute_node.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_execute_node.h new file mode 100644 index 0000000000000000000000000000000000000000..6aabf3ce209d7d4fefc59d59cf9fa9f20901cd0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_execute_node.h @@ -0,0 +1,142 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_REMOTE_EXECUTE_NODE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_EXECUTE_NODE_H_ + +#include +#include +#include + +#include "absl/types/span.h" +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/shape_inference.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/distributed_runtime/eager/eager_client.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/protobuf/eager_service.pb.h" + +namespace tensorflow { +namespace eager { + +// RemoteExecuteNode is an implementation of EagerNode which enqueues +// an operation via RPC in a remote EagerService. +class RemoteExecuteNode : public AsyncRemoteExecuteNode { + public: + RemoteExecuteNode(EagerContext* eager_context, + std::unique_ptr request, Device* device, + uint64 context_view_id, EagerClient* eager_client, + CancellationManager* cancellation_manager, + const NodeDef& ndef, FunctionLibraryDefinition* lib_def, + const gtl::InlinedVector& inputs, + absl::Span retvals) + : AsyncRemoteExecuteNode(), + eager_context_(eager_context), + request_(std::move(request)), + device_(device), + context_view_id_(context_view_id), + eager_client_(eager_client), + cancellation_manager_(cancellation_manager), + ndef_(ndef), + lib_def_(lib_def), + inputs_(inputs) { + // Copy the output handles, since the container for them might get + // destroyed. + for (auto handle : retvals) { + handle->Ref(); + retvals_.push_back(handle); + } + + // This is required to ensure that the tensor handles stay alive across the + // execution. + for (auto handle : inputs_) { + handle->Ref(); + } + eager_client_->Ref(); + + needs_remote_inputs_ = false; + for (const TensorHandle* input : inputs_) { + // TODO(bramandia): Should this be op_device() instead? + if (input->resource_device() != nullptr && + input->resource_device() != device_) { + needs_remote_inputs_ = true; + break; + } + } + } + + ~RemoteExecuteNode() override { + for (auto handle : retvals_) { + handle->Unref(); + } + + for (auto handle : inputs_) { + handle->Unref(); + } + eager_client_->Unref(); + } + + Status Prepare() override { + return RunShapeInference(ndef_, *lib_def_, inputs_, retvals_); + } + + void RunAsync(StatusCallback done) override; + + Status SyncExecutors() override { return eager_context_->SyncExecutors(); } + + void Abort(Status status) override { + int i = 0; + for (auto handle : retvals_) { + handle->PoisonRemote(status, device_, context_view_id_); + ++i; + } + } + + const EagerClient* eager_client() const override { return eager_client_; } + + bool needs_remote_inputs() const override { return needs_remote_inputs_; } + + bool allow_multiple_pending_requests() const override { + return eager_client_->allow_multiple_pending_requests(); + } + + string DebugString() const override { + string out = "[RemoteExecuteNode]"; + strings::StrAppend(&out, " request: ", request_->DebugString()); + strings::StrAppend(&out, ", target_device: ", device_->name()); + return out; + } + + private: + EagerContext* eager_context_; // Not owned, and must outlive this node. + std::unique_ptr request_; + Device* device_; // Not owned + uint64 context_view_id_; + bool needs_remote_inputs_; + EagerClient* eager_client_; // Not owned, and must outlive this node. + CancellationManager* cancellation_manager_; + const NodeDef ndef_; + const FunctionLibraryDefinition* lib_def_; + gtl::InlinedVector inputs_; + gtl::InlinedVector retvals_; +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_EXECUTE_NODE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..06893b54399d7f2f5742809848568789549f4c60 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_mgr.h @@ -0,0 +1,136 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_REMOTE_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_MGR_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/eager/eager_executor.h" +#include "tensorflow/core/common_runtime/eager/tensor_handle.h" +#include "tensorflow/core/distributed_runtime/eager/remote_tensor_handle.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { +namespace eager { + +// This class manages the states required to setup an eager cluster. +// TODO(fishx): Move remote state from context to this class. +class RemoteMgr { + public: + RemoteMgr(bool is_master, EagerContext* ctx) + : is_master_(is_master), parent_(ctx) {} + + ~RemoteMgr() { + for (const auto& entry : remote_tensor_handle_map_) { + entry.second->Unref(); + } + } + + bool IsMaster() { return is_master_; } + + void AddOperationOutputs( + const gtl::ArraySlice handles, + int64_t operation_id); + + void AddOperationOutput(tensorflow::TensorHandle* handles, + int64_t operation_id, int32_t output_num); + + Status GetTensorHandle(const RemoteTensorHandleInternal& remote_handle, + tensorflow::TensorHandle** handle); + + Status DeleteTensorHandle(const RemoteTensorHandleInternal& remote_handle); + + // Helper function to create monotonically increasing ids unique to this + // context. + uint64 NextOpId() { + DCHECK(is_master_); + mutex_lock l(next_id_mutex_); + return next_op_id_++; + } + + // Serialize a remote TensorHandle to a RemoteTensorHandle. + // If wait_until_ready is true, block until the remote handle is ready on a + // remote worker. + Status SerializeRemoteTensorHandle( + TensorHandle* in, const bool wait_until_ready, RemoteTensorHandle* out, + Device* device, const string& device_name, + const bool serialize_resource_dtype_and_shape = false); + + // Deserialize a RemoteTensorHandle to a TensorHandle(local/remote). + // The output holds a reference to the TensorHandle. + Status DeserializeRemoteTensorHandle(const RemoteTensorHandle& in, + TensorHandle** out); + + EagerExecutor& GetOrCreateExecutorForStream(uint64 stream_id); + + void DeleteExecutorForStream(uint64 stream_id); + + protected: + mutex next_id_mutex_; + uint64 next_op_id_ TF_GUARDED_BY(next_id_mutex_) = 1; + + private: + // Returns the op_id and output_num if the given local TensorHandle exists in + // remote_tensor_handle_map_. + Status GetRemoteTensorHandle(const tensorflow::TensorHandle* handle, + const bool wait_until_ready, int64_t* op_id, + int32* output_num) + TF_SHARED_LOCKS_REQUIRED(remote_tensor_handle_mu_); + + Status GetTensorHandleImpl(const RemoteTensorHandleInternal& remote_handle, + tensorflow::TensorHandle** handle) + TF_SHARED_LOCKS_REQUIRED(remote_tensor_handle_mu_); + + Status GetMirroredResourceShape( + const RemoteTensorHandleInternal& remote_handle, + std::vector* handle); + + bool is_master_; + + using RemoteTensorHandleMap = + gtl::FlatMap; + using MirroredResourceShapeMap = gtl::FlatMap< + RemoteTensorHandleInternal, std::vector, + RemoteTensorHandleInternalHash, RemoteTensorHandleInternalEquals>; + + mutex remote_tensor_handle_mu_; + // This map maintains the TensorHandles that are required by remote workers + // in the cluster. Each map key is generated by the master, so it should be + // globally unique. This map owns references on the handles it contains. + RemoteTensorHandleMap remote_tensor_handle_map_ + TF_GUARDED_BY(remote_tensor_handle_mu_); + + mutex mirrored_resource_shape_mu_; + // This map maintains the data types and shapes of resource variables required + // by remote workers in the cluster. Each map key is generated by the master, + // so it should be globally unique. + MirroredResourceShapeMap mirrored_resource_shape_map_ + TF_GUARDED_BY(mirrored_resource_shape_mu_); + + EagerContext* parent_; // not owned. + + mutex executor_map_mu_; + std::unordered_map executor_map_ + TF_GUARDED_BY(executor_map_mu_); +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle.h new file mode 100644 index 0000000000000000000000000000000000000000..903d019172a45756ff9292a1ab20816a91735fa1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle.h @@ -0,0 +1,50 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_H_ + +#include "tensorflow/core/platform/fingerprint.h" +#include "tensorflow/core/protobuf/remote_tensor_handle.pb.h" + +namespace tensorflow { +namespace eager { + +struct RemoteTensorHandleInternal { + explicit RemoteTensorHandleInternal(const RemoteTensorHandle& tensor_handle) + : op_id(tensor_handle.op_id()), output_num(tensor_handle.output_num()) {} + RemoteTensorHandleInternal(int64_t op_id, int32_t output_num) + : op_id(op_id), output_num(output_num) {} + int64_t op_id; + int32 output_num; +}; + +struct RemoteTensorHandleInternalHash { + std::size_t operator()(const RemoteTensorHandleInternal& handle) const { + return FingerprintCat64(handle.op_id, handle.output_num); + } +}; + +struct RemoteTensorHandleInternalEquals { + bool operator()(const RemoteTensorHandleInternal& first, + const RemoteTensorHandleInternal& second) const { + return first.op_id == second.op_id && first.output_num == second.output_num; + } +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h new file mode 100644 index 0000000000000000000000000000000000000000..85a30913760d88f59b7ec5196420f0b148f05fe6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h @@ -0,0 +1,84 @@ +/* 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_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_DATA_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_DATA_H_ + +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +// Remote Tensor Handle: A handle to a Tensor on a remote host. Note that only +// the shape is known. +class RemoteTensorHandleData { + public: + // Constructor for lazy remote handles. A lazy remote handle is created on + // a remote worker with an op_id and an output_num. It doesn't control the + // lifetime of a remote handle that it refers to. If it refers to a remote + // function input, it's sent by a client which won't serialize it until + // the corresponding remote tensor is ready. So the remote tensor should be + // ready when we create a lazy remote handle. If it refers to a remote output, + // it's not ready until the shape is set. + RemoteTensorHandleData(int64_t op_id, int output_num, uint64 context_view_id, + bool is_ready); + // Constructor for unshaped remote handles. It controls the lifetime of a + // remote handel that it refers to. + RemoteTensorHandleData(int64_t op_id, int output_num, + const string& remote_task, EagerContext* ctx); + ~RemoteTensorHandleData(); + + // A remote tensor handle does not have a Tensor object, hence it can only + // support the shape requests. + Status Shape(TensorShape* shape) const; + Status NumDims(int* num_dims) const; + Status Dim(int dim_index, int64_t* dim) const; + Status NumElements(int64_t* num_elements) const; + Status Unprotect() { return OkStatus(); } + + bool IsReady() const; + Status WaitReady(const char* caller) const; + Status SetShape(const TensorShape& shape); + Status SetShapeAndRemoteTask(const TensorShape& shape, + const string& remote_task); + void Poison(Status status); + Status IsPoisoned() const; + + string DebugString() const; + + // Return the op id and output num. If wait_util_ready is true, block until + // the remote tensor is ready on a remote worker. + Status OpIdAndOutputNum(const bool wait_util_ready, int64_t* op_id, + int32* output_num) const; + + uint64 context_view_id() const { return context_view_id_; } + + private: + mutable mutex mu_; + bool is_ready_ TF_GUARDED_BY(mu_); + Status is_poisoned_ TF_GUARDED_BY(mu_); + TensorShape shape_ TF_GUARDED_BY(mu_); + + // IDs required when this class is representing a remote tensor handle. + const int64_t op_id_; + const int32 output_num_; + string remote_task_ TF_GUARDED_BY(mu_); + uint64 context_id_; + uint64 context_view_id_; + EagerContext* ctx_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_EAGER_REMOTE_TENSOR_HANDLE_DATA_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/error_payloads.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/error_payloads.h new file mode 100644 index 0000000000000000000000000000000000000000..ae3b3e5e8013e13b5054405c68b1f7796e521b68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/error_payloads.h @@ -0,0 +1,34 @@ +/* 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_DISTRIBUTED_RUNTIME_ERROR_PAYLOADS_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_ERROR_PAYLOADS_H_ + +// This file lists the proto payloads that may be inserted by the code within +// `tensorflow/core/distributed_runtime/` into Status instances. + +namespace tensorflow { +// Proto: tensorflow::distributed_runtime::WorkerPossiblyRestarted +// Location: tensorflow/core/protobuf/distributed_runtime_payloads.proto +// Usage: Flags the Status to be a possible outcome of a worker restart. +constexpr char kWorkerPossiblyRestarted[] = + "type.googleapis.com/" + "tensorflow.distributed_runtime.WorkerPossiblyRestarted"; + +constexpr char kWorkerPreemption[] = + "type.googleapis.com/tensorflow.distributed_runtime.WorkerPreemption"; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_ERROR_PAYLOADS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/graph_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/graph_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..d394178f597554760609f3fb4ad3500d3627c8d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/graph_mgr.h @@ -0,0 +1,203 @@ +/* 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_DISTRIBUTED_RUNTIME_GRAPH_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_GRAPH_MGR_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/costmodel_manager.h" +#include "tensorflow/core/common_runtime/executor.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/distributed_runtime/message_wrappers.h" +#include "tensorflow/core/distributed_runtime/worker_env.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/cost_graph.pb.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/protobuf/debug.pb.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace tsl { +class CoordinationServiceAgent; +} + +namespace tensorflow { + +class ExecutorOpts; +class StepStatsCollector; +class RendezvousMgrInterface; +class DeviceMgr; +class WorkerSession; + +// GraphMgr keeps track of a set of graphs that are registered with a +// TensorFlow worker. Each registered graph is identified by a handle +// that is generated by GraphMgr and returned to the caller. +// +// After a successful registration, the caller executes a graph using +// the graph handle. Each execution is distinguished from others by a +// caller generated global unique id "step_id". Multiple executions +// can use the same graph concurrently and independently as long as +// "step_id" used are different. +// +// Multiple threads can call GraphMgr methods concurrently. +// +// E.g., +// GraphMgr gmgr(worker_env); +// string handle; +// TF_CHECK_OK(gmgr.Register("session", { graph computes c = a + b }, +// &handle)); +// GraphMgr::NamedTensors in = { { "a", Tensor({1, 2}) }, +// { "b", Tensor({3, 4}) } }; +// GraphMgr::NamedTensors out = { { "c", Tensor() } }; +// TF_CHECK_OK(gmgr.Execute(handle, 0x0001, in, &out)); +// EXPECT_EQ(out["c"], Tensor({4, 6})); +class GraphMgr { + public: + explicit GraphMgr(const WorkerEnv* worker_env, const DeviceMgr* device_mgr); + ~GraphMgr(); + + // Registers a graph. Fills in "handle". The registered graph retains a + // reference to cluster_flr to do cross process function calls. + Status Register(const string& handle, const GraphDef& gdef, + const GraphOptions& graph_options, + const DebugOptions& debug_options, + const ConfigProto& config_proto, int64_t collective_graph_key, + WorkerSession* session, + DistributedFunctionLibraryRuntime* cluster_flr, + string* graph_handle); + + // Executes one step of a registered graph "handle". + // + // If "out" is not nullptr, "out" specifies all keys the execution + // should receive upon finish. + typedef std::map NamedTensors; + typedef std::function StatusCallback; + void ExecuteAsync(const string& handle, const int64_t step_id, + const ExecutorOpts& opts, const NamedTensors& in, + WorkerSession* session, StepStatsCollector* collector, + MutableRunGraphResponseWrapper* response, + CancellationManager* cancellation_manager, + tsl::CoordinationServiceAgent* coordination_service_agent, + StatusCallback done); + + Status SendInputs(const int64_t step_id, const NamedTensors& in); + Status RecvOutputs(const int64_t step_id, NamedTensors* out); + void RecvOutputsAsync(const int64_t step_id, NamedTensors* out, + StatusCallback done); + + // Deregisters a graph. + Status Deregister(const string& handle); + + // Deregister all graphs. + Status DeregisterAll(); + + private: + typedef GraphMgr ME; + + struct ExecutionUnit { + std::unique_ptr graph = nullptr; + Device* device = nullptr; // not owned. + Executor* root = nullptr; // not owned. + FunctionLibraryRuntime* lib = nullptr; // not owned. + // Build the cost model if this value is strictly positive. + int64_t build_cost_model = 0; + }; + + struct Item : public core::RefCounted { + // TODO(zhifengc): Keeps a copy of the original graph if the need arises. + // TODO(zhifengc): Stats, updated by multiple runs potentially. + // TODO(zhifengc): Dup-detection. Ensure step_id only run once. + ~Item() override; + + // Session handle. + string session; + + // Graph handle. + string handle; + + std::unique_ptr lib_def; + // Owns the FunctionLibraryRuntime objects needed to execute functions, one + // per device. + std::unique_ptr proc_flr; + // A graph is partitioned over multiple devices. Each partition + // has a root executor which may call into the runtime library. + std::vector units; + + // Used to deregister a cost model when cost model is required in graph + // manager. + GraphMgr* graph_mgr; + + int64_t collective_graph_key; + }; + + const WorkerEnv* worker_env_; // Not owned. + const DeviceMgr* device_mgr_; + + CostModelManager cost_model_manager_; + + // Owned. + mutex mu_; + int64_t next_id_ TF_GUARDED_BY(mu_) = 0; + + // If true, blocks until device has finished all queued operations in a step. + bool sync_on_finish_ = true; + + // Table mapping graph handles to registered graphs. + // + // TODO(zhifengc): If the client does not call Deregister, we'll + // lose memory over time. We should implement a timeout-based + // mechanism to gc these graphs. + std::unordered_map table_; + + void StartParallelExecutors( + const string& handle, int64_t step_id, Item* item, Rendezvous* rendezvous, + CollectiveExecutor::Handle* ce_handle, StepStatsCollector* collector, + CostGraphDef* cost_graph, CancellationManager* cancellation_manager, + WorkerSession* session, int64_t start_time_usecs, + tsl::CoordinationServiceAgent* coordination_service_agent, + StatusCallback done); + + // Don't attempt to process cost models unless explicitly requested for at + // least one of the items. + bool skip_cost_models_ = true; + + void BuildCostModel(Item* item, StepStatsCollector* collector, + CostGraphDef* cost_graph); + + Status InitItem(const string& handle, const GraphDef& gdef, + const GraphOptions& graph_options, + const DebugOptions& debug_options, + const ConfigProto& config_proto, int64_t collective_graph_key, + WorkerSession* session, + DistributedFunctionLibraryRuntime* cluster_flr, Item* item); + + Status DecorateAndPublishGraphForDebug(const DebugOptions& debug_options, + Graph* graph, Device* device); + + GraphMgr(const GraphMgr&) = delete; + void operator=(const GraphMgr&) = delete; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_GRAPH_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/local_master.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/local_master.h new file mode 100644 index 0000000000000000000000000000000000000000..32b8e7cc065eb9db7b733ec49fb99f4a402cfac1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/local_master.h @@ -0,0 +1,112 @@ +/* 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_DISTRIBUTED_RUNTIME_LOCAL_MASTER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_LOCAL_MASTER_H_ + +#include + +#include "tensorflow/core/distributed_runtime/master_interface.h" + +namespace tensorflow { + +class Master; + +// An implementation of the TensorFlow master interface that enables direct +// intraprocess communication between the client and the master implementation. +// +// This master implementation is intended to provide more efficient access to +// a master service that has been created in the same process as the client. +// +// TODO(mrry): Add methods that avoid protobuf encoding the request/response +// objects where this affects performance. +// TODO(mrry): Avoid closure creation/context switch overhead for synchronous +// invocation of Master methods. +// TODO(mrry): Make all potentially blocking Master methods take CallOptions +// for cancellation. +class LocalMaster : public MasterInterface { + public: + ~LocalMaster() {} + + Status CreateSession(CallOptions* call_options, + const CreateSessionRequest* request, + CreateSessionResponse* response) override; + + Status ExtendSession(CallOptions* call_options, + const ExtendSessionRequest* request, + ExtendSessionResponse* response) override; + + Status PartialRunSetup(CallOptions* call_options, + const PartialRunSetupRequest* request, + PartialRunSetupResponse* response) override; + + Status RunStep(CallOptions* call_options, RunStepRequestWrapper* request, + MutableRunStepResponseWrapper* response) override; + + MutableRunStepRequestWrapper* CreateRunStepRequest() override; + + MutableRunStepResponseWrapper* CreateRunStepResponse() override; + + Status CloseSession(CallOptions* call_options, + const CloseSessionRequest* request, + CloseSessionResponse* response) override; + + Status ListDevices(CallOptions* call_options, + const ListDevicesRequest* request, + ListDevicesResponse* response) override; + + // See tensorflow::Reset() and the comment on ResetRequest. + Status Reset(CallOptions* call_options, const ResetRequest* request, + ResetResponse* response) override; + + Status MakeCallable(CallOptions* call_options, + const MakeCallableRequest* request, + MakeCallableResponse* response) override; + Status RunCallable(CallOptions* call_options, + const RunCallableRequest* request, + RunCallableResponse* response) override; + Status ReleaseCallable(CallOptions* call_options, + const ReleaseCallableRequest* request, + ReleaseCallableResponse* response) override; + + // Registers the mapping from the given `target` to the given `master`. + // + // WARNING: The `master` pointer remains owned by the caller. It is + // the responsibility of the caller to ensure that `master` outlives + // any LocalMaster objects that may wrap this master. There is no + // corresponding deregister method, since clean server shutdown is + // not currently implemented for any server type. + static void Register(const string& target, Master* master, + int64_t default_timeout_in_ms); + + // Returns a pointer to the local master associated with the given + // `target`, or nullptr if none exists. + static std::unique_ptr Lookup(const string& target); + + private: + Master* master_impl_; // Not owned. + const int64_t default_timeout_in_ms_; + + // See `LocalMaster::Lookup` for the factory function that creates + // objects of this type. + LocalMaster(Master* master_impl, const int64_t default_timeout_in_ms); + + LocalMaster(const LocalMaster&) = delete; + void operator=(const LocalMaster&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_LOCAL_MASTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master.h new file mode 100644 index 0000000000000000000000000000000000000000..8cdbe6fccedd0a986f9b2ccdfadfb60a77177913 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master.h @@ -0,0 +1,118 @@ +/* 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_DISTRIBUTED_RUNTIME_MASTER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_H_ + +#include + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/distributed_runtime/master_env.h" +#include "tensorflow/core/distributed_runtime/master_session.h" +#include "tensorflow/core/distributed_runtime/recent_request_ids.h" +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/gtl/map_util.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/master.pb.h" +#include "tensorflow/core/util/util.h" + +namespace tensorflow { + +class Master { + public: + explicit Master(MasterEnv* env, double session_gc_seconds); + virtual ~Master(); + + // Convenient typedef for a closure passing a Status. + typedef std::function MyClosure; + + void CreateSession(const CreateSessionRequest* req, + CreateSessionResponse* resp, MyClosure done); + + void ExtendSession(const ExtendSessionRequest* req, + ExtendSessionResponse* resp, MyClosure done); + + void PartialRunSetup(const PartialRunSetupRequest* req, + PartialRunSetupResponse* resp, MyClosure done); + + void RunStep(CallOptions* opts, const RunStepRequestWrapper* req, + MutableRunStepResponseWrapper* resp, MyClosure done); + + void CloseSession(const CloseSessionRequest* req, CloseSessionResponse* resp, + MyClosure done); + + void ListDevices(const ListDevicesRequest* req, ListDevicesResponse* resp, + MyClosure done); + + // See tensorflow::Reset() and the comment on ResetRequest. + void Reset(const ResetRequest* req, ResetResponse* resp, MyClosure done); + + void MakeCallable(const MakeCallableRequest* req, MakeCallableResponse* resp, + MyClosure done); + void RunCallable(CallOptions* opts, const RunCallableRequest* req, + RunCallableResponse* resp, MyClosure done); + void ReleaseCallable(const ReleaseCallableRequest* req, + ReleaseCallableResponse* resp, MyClosure done); + + private: + typedef Master ME; + + // Not owned. + MasterEnv* env_ = nullptr; + + // Owned. + mutex mu_; + + // shutdown_ is set to true by the dtor. + condition_variable shutdown_cv_; + bool shutdown_ TF_GUARDED_BY(mu_) = false; + Thread* gc_thread_; + + // Maps session handles to sessions. + std::unordered_map sessions_ TF_GUARDED_BY(mu_); + + // Moving average of step times. + MovingAverage last_1000_steps_ TF_GUARDED_BY(mu_); + + // Cumulative number of steps executed. + int64_t step_count_ TF_GUARDED_BY(mu_); + + // If a session is not active for this many seconds, it will be + // closed automatically. + const double session_gc_seconds_; + + // Used to track ids for incoming requests so we can detect duplicates. + RecentRequestIds recent_request_ids_; + + // Call CleanupAll on all workers. + void CleanupWorkers(const ResetRequest& reset); + + // Cleanup unused session. + void GC(); + + // Find master session by session handle, and increments the reference count + // on the returned MasterSession if not null. + MasterSession* FindMasterSession(const string& handle); + + Master(const Master&) = delete; + void operator=(const Master&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_env.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_env.h new file mode 100644 index 0000000000000000000000000000000000000000..633e21df361386226f3cc8d58317adc9f068287f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_env.h @@ -0,0 +1,113 @@ +/* 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_DISTRIBUTED_RUNTIME_MASTER_ENV_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_ENV_H_ + +#include +#include + +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/protobuf/cluster.pb.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/protobuf/tensorflow_server.pb.h" +#include "tensorflow/core/public/session_options.h" +#include "tsl/protobuf/rpc_options.pb.h" + +namespace tsl { +class Env; +} // namespace tsl +namespace tensorflow { +using Env = tsl::Env; + +class CollectiveExecutorMgrInterface; +class Device; +class DeviceSet; +class MasterSession; +class OpRegistryInterface; + +// Options passed to the worker_cache_factory function. +struct WorkerCacheFactoryOptions { + ClusterDef cluster_def; + string job_name; + int task_index; + int replica_index = 0; + RPCOptions rpc_options; + + explicit WorkerCacheFactoryOptions() = default; + + // Construct from a ServerDef proto. + explicit WorkerCacheFactoryOptions(const ServerDef& server_def) { + if (server_def.has_cluster() && !server_def.job_name().empty()) { + cluster_def = server_def.cluster(); + job_name = server_def.job_name(); + task_index = server_def.task_index(); + rpc_options = server_def.default_session_config().rpc_options(); + replica_index = server_def.replica(); + } + } +}; + +// The master environment class, which holds a bag of pointers to +// per-master state. +// +// MasterEnv does not own its member pointers. +struct MasterEnv { + Env* env = nullptr; + + // Object from which WorkerInterface instances can be obtained. Not owned. + WorkerCacheInterface* worker_cache = nullptr; + + // The operation definitions to use. Must be filled before use. + const OpRegistryInterface* ops = nullptr; + + // Local devices co-located with this master. Devices are not owned + // by the master service. + // + // REQUIRES: !local_devices.empty(). + std::vector local_devices; + + // In large scaled distributed training, many singleton components (e.g. + // Rendezvous) can becomes the bottleneck of the system. This field allows + // us to shard the single components. This number will scale up with number + // of tasks in this cluster. It is always greater than 1. + int experimental_num_shards = 1; + + // Factory for creating master sessions, given session options and a + // vector of devices. + // + // The caller of the function takes ownership of the returned + // `MasterSession`, which may not be null. Ownership of the + // `MasterEnv*` is retained by the caller. + std::function>>, + std::unique_ptr, + std::unique_ptr device_set, + std::vector filtered_worker_list)> + master_session_factory; + + std::function + worker_cache_factory; + + // Generates per-step CollectiveExecutors and has access to utilities + // supporting collective operations. Not owned. + CollectiveExecutorMgrInterface* collective_executor_mgr = nullptr; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_ENV_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..cde47fb9caf55f35db481fec8ae69ad6e6fcd8ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_interface.h @@ -0,0 +1,117 @@ +/* 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_DISTRIBUTED_RUNTIME_MASTER_INTERFACE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_INTERFACE_H_ + +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/distributed_runtime/message_wrappers.h" +#include "tensorflow/core/distributed_runtime/request_id.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/protobuf/master.pb.h" + +namespace tensorflow { + +// Abstract interface for communicating with the TensorFlow Master service. +// +// This interface supports both RPC-based master implementations, and +// in-process master implementations that do not require an RPC +// roundtrip. +class MasterInterface { + public: + virtual ~MasterInterface() {} + virtual Status CreateSession(CallOptions* call_options, + const CreateSessionRequest* request, + CreateSessionResponse* response) = 0; + + virtual Status ExtendSession(CallOptions* call_options, + const ExtendSessionRequest* request, + ExtendSessionResponse* response) = 0; + + virtual Status PartialRunSetup(CallOptions* call_options, + const PartialRunSetupRequest* request, + PartialRunSetupResponse* response) { + return errors::Unimplemented("Partial run not implemented for this master"); + } + + virtual Status RunStep(CallOptions* call_options, + RunStepRequestWrapper* request, + MutableRunStepResponseWrapper* response) = 0; + + virtual Status RunStep(CallOptions* call_options, + const RunStepRequest* request, + RunStepResponse* response) { + std::unique_ptr wrapped_request( + new ProtoRunStepRequest(request)); + std::unique_ptr wrapped_response( + new NonOwnedProtoRunStepResponse(response)); + return RunStep(call_options, wrapped_request.get(), wrapped_response.get()); + } + + // Returns a request object for use in calls to + // `RunStep()`. Ownership is transferred to the caller. + // + // The message returned from this method must only be used in a + // `RunStep()` call on the same `MasterInterface` instance. + virtual MutableRunStepRequestWrapper* CreateRunStepRequest() { + MutableProtoRunStepRequest* ret = new MutableProtoRunStepRequest; + ret->request_.set_request_id(GetUniqueRequestId()); + return ret; + } + + // Returns a response object for use in calls to + // `RunStep()`. Ownership is transferred to the caller. + // + // The message returned from this method must only be used in a + // `RunStep()` call on the same `MasterInterface` instance. + virtual MutableRunStepResponseWrapper* CreateRunStepResponse() { + return new OwnedProtoRunStepResponse; + } + + virtual Status CloseSession(CallOptions* call_options, + const CloseSessionRequest* request, + CloseSessionResponse* response) = 0; + + virtual Status ListDevices(CallOptions* call_options, + const ListDevicesRequest* request, + ListDevicesResponse* response) = 0; + + virtual Status Reset(CallOptions* call_options, const ResetRequest* request, + ResetResponse* response) = 0; + + virtual Status MakeCallable(CallOptions* call_options, + const MakeCallableRequest* request, + MakeCallableResponse* response) = 0; + virtual Status RunCallable(CallOptions* call_options, + const RunCallableRequest* request, + RunCallableResponse* response) = 0; + virtual Status ReleaseCallable(CallOptions* call_options, + const ReleaseCallableRequest* request, + ReleaseCallableResponse* response) = 0; + + protected: + // NOTE: This should only be called by implementations of this + // interface whose CreateRunStepResponse() method returns a + // proto-based wrappers for the RunStepResponse message. + RunStepResponse* get_proto_from_wrapper( + MutableRunStepResponseWrapper* wrapper) { + return wrapper->get_proto(); + } +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_session.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_session.h new file mode 100644 index 0000000000000000000000000000000000000000..ab63dea86842e21afe6438a62b8a726609adc96b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/master_session.h @@ -0,0 +1,263 @@ +/* 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_DISTRIBUTED_RUNTIME_MASTER_SESSION_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_SESSION_H_ + +#include +#include + +#include "tensorflow/core/common_runtime/debugger_state_interface.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/graph_execution_state.h" +#include "tensorflow/core/common_runtime/stats_publisher_interface.h" +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/distributed_runtime/master_env.h" +#include "tensorflow/core/distributed_runtime/message_wrappers.h" +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/master.pb.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { + +class Device; +struct MasterEnv; + +// A session encapsulates a graph computation (resource allocation, +// placement, execution, etc.). +class MasterSession : public core::RefCounted { + public: + // This session encapsulates the graph computation for a graph. + // + // The session places nodes on devices in "remote_devs" and executes + // operations on these devices. + // + // The caller takes ownership of all remote devices. + MasterSession( + const SessionOptions& options, const MasterEnv* env, + std::unique_ptr>> remote_devs, + std::unique_ptr worker_cache, + std::unique_ptr device_set, + std::vector filtered_worker_list, + StatsPublisherFactory stats_publisher_factory); + + // Initialize the MasterSession for "def". Must be called before Extend(), + // Run(), or Close(). + Status Create(GraphDef&& def, const ClusterDef& cluster_def); + + // Returns the session handle. + const string& handle() const { return handle_; } + + // Returns the last access time (the number of micro-seconds since + // some fixed point in time) of this session. + uint64 last_access_time_usec() const { return last_access_time_usec_.load(); } + + // Attempt to extend the graph according to the given "req". + // (See master.proto for details of valid extensions.) + // + // PRECONDITION: The current version of this session's graph + // is "req->current_graph_version". + // + // POSTCONDITION: The current version of this session's graph + // is "resp->new_graph_version". + // + // Extend() may block the caller thread for a long time. + Status Extend(const ExtendSessionRequest* req, ExtendSessionResponse* resp); + + // Setup a partial run call. + Status PartialRunSetup(const PartialRunSetupRequest* req, + PartialRunSetupResponse* resp); + + // Run one step. + Status Run(CallOptions* opts, const RunStepRequestWrapper& req, + MutableRunStepResponseWrapper* resp); + + Status ListDevices(ListDevicesResponse* resp) const; + + Status MakeCallable(const MakeCallableRequest& req, + MakeCallableResponse* resp); + + Status RunCallable(CallOptions* opts, const RunCallableRequest& req, + RunCallableResponse* resp); + + Status ReleaseCallable(const ReleaseCallableRequest& req, + ReleaseCallableResponse* resp); + + // Close this session and delete "*this". Returns OK if all known + // states are cleanup successfully. + // + // Close() may block the caller thread for a long time. + Status Close(); + + // Close this session and release a reference on "*this". + // + // Note that, unlike Close(), this method does not block on the + // completion of all work. + void GarbageCollect(); + + private: + SessionOptions session_opts_; + + // Not owned. + const MasterEnv* env_; + + // The opaque session handle. + const string handle_; + + std::unique_ptr>> remote_devs_; + + // The optional session-specific worker cluster. + // TODO(saeta): Convert to std::optional when available. + const std::unique_ptr worker_cache_; + // Retrieves either worker_cache_ or the env_->worker_cache as appropriate. + WorkerCacheInterface* get_worker_cache() const; + + // The device set used by this session. + std::unique_ptr devices_; + + // The (partial device) names of remote worker tasks that this + // session will contact. + const std::vector filtered_worker_list_; + + StatsPublisherFactory stats_publisher_factory_; + + std::atomic_ulong last_access_time_usec_; + + std::atomic partial_run_handle_counter_ = {0}; + + uint64 NewStepId(int64_t graph_key); + + mutex mu_; + std::unique_ptr execution_state_ TF_GUARDED_BY(mu_); + int64_t graph_version_; + + // We keep a map from a signature of a run request to the + // ReffedClientGraph the can execute it. We keep up to one old copy + // of each ReffedClientGraph around because if it gets deallocated + // before a new substitute has been created, Variables can go out of + // scope and lose their state. + class ReffedClientGraph; + typedef std::unordered_map RCGMap; + RCGMap run_graphs_ TF_GUARDED_BY(mu_); + RCGMap partial_run_graphs_ TF_GUARDED_BY(mu_); + int64_t next_callable_handle_ TF_GUARDED_BY(mu_) = 0; + RCGMap callables_ TF_GUARDED_BY(mu_); + + struct PerStepState { + bool collect_costs = false; + bool collect_timeline = false; + bool collect_rpcs = false; + bool collect_partition_graphs = false; + bool report_tensor_allocations_upon_oom = false; + Microseconds start_micros = Microseconds(0); + Microseconds end_micros = Microseconds(0); + std::vector step_stats; // per partition + StepStats rpc_stats; // for RPC layer + CostGraphDef cost_graph; + }; + + struct RunState { + std::unordered_map pending_inputs; // true if fed + std::unordered_map pending_outputs; // true if fetched + ReffedClientGraph* rcg = nullptr; + uint64 step_id; + int64_t collective_graph_key; + int64_t count = 0; + PerStepState pss; + std::unique_ptr ph; + bool step_started = false; + + RunState(const std::vector& input_names, + const std::vector& output_names, ReffedClientGraph* rcg, + const uint64 step_id, const int64_t count); + + bool PendingDone() const; + + ~RunState(); + }; + std::unordered_map> partial_runs_ + TF_GUARDED_BY(mu_); + + // Active RunStep calls. + condition_variable num_running_is_zero_; + int32 num_running_ TF_GUARDED_BY(mu_) = 0; + + bool closed_ TF_GUARDED_BY(mu_) = false; + bool garbage_collected_ TF_GUARDED_BY(mu_) = false; + + std::unordered_map subgraph_execution_counts_ + TF_GUARDED_BY(mu_); + + // We need to ensure that certain nodes added (e.g., send and recv + // nodes) are unique across all sub-graphs within this session. + int64_t next_node_id_ TF_GUARDED_BY(mu_) = 0; + + // Used to cancel running steps on Close(). + CancellationManager cancellation_manager_; + + // Private dtor. The client must call Close(). + virtual ~MasterSession(); + + // Creates sessions on all workers. + // + // If this session is operating using the new ClusterSpec propagation behavior + // call this method in order to propagate the cluster membership to all + // workers. + Status CreateWorkerSessions(const ClusterDef& cluster_def); + + bool should_delete_worker_sessions_ = false; + Status DeleteWorkerSessions(); + + Status StartStep(const BuildGraphOptions& opts, bool is_partial, + ReffedClientGraph** out_rcg, int64_t* out_count); + void ClearRunsTable(std::vector* to_unref, + RCGMap* rcg_map) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + void FillPerStepState(MasterSession::ReffedClientGraph* rcg, + const RunOptions& run_options, uint64 step_id, + int64_t count, PerStepState* out_pss, + std::unique_ptr* out_ph); + Status DoRunWithLocalExecution(CallOptions* opts, + const RunStepRequestWrapper& req, + MutableRunStepResponseWrapper* resp); + Status DoPartialRun(CallOptions* opts, const RunStepRequestWrapper& req, + MutableRunStepResponseWrapper* resp); + Status DoRunCallable(CallOptions* opts, ReffedClientGraph* rcg, + const RunCallableRequest& req, + RunCallableResponse* resp); + Status PostRunCleanup(MasterSession::ReffedClientGraph* rcg, uint64 step_id, + const RunOptions& run_options, PerStepState* pss, + const std::unique_ptr& ph, + const Status& run_status, + RunMetadata* out_run_metadata); + + void MarkRunCompletion(); + void UpdateLastAccessTime(); + + Status BuildAndRegisterPartitions(ReffedClientGraph* rcg); + + Status CreateDebuggerState( + const DebugOptions& debug_options, const RunStepRequestWrapper& req, + int64_t rcg_execution_count, + std::unique_ptr* debugger_state); + + MasterSession(const MasterSession&) = delete; + void operator=(const MasterSession&) = delete; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MASTER_SESSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/message_wrappers.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/message_wrappers.h new file mode 100644 index 0000000000000000000000000000000000000000..5370df8a06c54a72f87c1147dfec8923e93b7e1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/message_wrappers.h @@ -0,0 +1,746 @@ +/* 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_DISTRIBUTED_RUNTIME_MESSAGE_WRAPPERS_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MESSAGE_WRAPPERS_H_ + +#include "absl/status/status.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/cost_graph.pb.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/step_stats.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor.pb.h" +#include "tensorflow/core/framework/versions.pb.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/protobuf/master.pb.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace tensorflow { + +//////////////////////////////////////////////////////////////////////////////// +// +// Wrapper classes for the `MasterService.RunStep` request message. +// +// The `RunStepRequest` message can contain potentially large tensor +// data as part of its `feed` submessages. Here we provide specialized +// wrappers that avoid copying the tensor data wherever possible. +// +// See `RunStepRequest` in tensorflow/core/protobuf/master.proto for the +// protocol buffer definition. +// +//////////////////////////////////////////////////////////////////////////////// + +// Abstract interface for an immutable RunStepRequest message. +// +// This interface is typically used by server-side components in the +// TensorFlow master. +class RunStepRequestWrapper { + public: + virtual ~RunStepRequestWrapper() {} + + // REQUIRED: session_handle must be returned by a CreateSession call + // to the same master service. + virtual const string& session_handle() const = 0; + + // Partial run handle (optional). If specified, this will be a partial run + // execution, run up to the specified fetches. + virtual const string& partial_run_handle() const = 0; + + // Tensors to be fed in the step. Each feed is a named tensor. + virtual size_t num_feeds() const = 0; + virtual const string& feed_name(size_t i) const = 0; + + // Stores the content of the feed value at index `i` in `tensor`. + virtual Status FeedValue(size_t i, Tensor* out_tensor) const = 0; + virtual Status FeedValue(size_t i, TensorProto* out_tensor) const = 0; + + // Fetches. A list of tensor names. The caller expects a tensor to + // be returned for each fetch[i] (see RunStepResponse.tensor). The + // order of specified fetches does not change the execution order. + virtual size_t num_fetches() const = 0; + virtual const string& fetch_name(size_t i) const = 0; + + // Target Nodes. A list of node names. The named nodes will be run + // to but their outputs will not be fetched. + virtual size_t num_targets() const = 0; + virtual const string& target_name(size_t i) const = 0; + + // Options for the run call. + virtual const RunOptions& options() const = 0; + + // If true then some errors, e.g., execution errors that have long + // error messages, may return an OK RunStepResponse with the actual + // error saved in the status_code/status_error_message fields of the + // response body. This is a workaround since the RPC subsystem may + // truncate long metadata messages. + virtual bool store_errors_in_response_body() const = 0; + + // Unique identifier for this request. Every RunGraphRequest must have a + // unique request_id, and retried RunGraphRequests must have the same + // request_id. If request_id is zero, retry detection is disabled. + virtual int64_t request_id() const = 0; + + // Returns a human-readable representation of this message for debugging. + virtual string DebugString() const = 0; + + // Returns the wrapped data as a protocol buffer message. + virtual const RunStepRequest& ToProto() const = 0; +}; + +// Abstract interface for a mutable RunStepRequest message. +// +// See `RunStepRequestWrapper` above for a description of the fields. +class MutableRunStepRequestWrapper : public RunStepRequestWrapper { + public: + virtual void set_session_handle(const string& handle) = 0; + virtual void set_partial_run_handle(const string& handle) = 0; + virtual void add_feed(const string& name, const Tensor& value) = 0; + virtual void add_fetch(const string& name) = 0; + virtual void add_target(const string& name) = 0; + virtual RunOptions* mutable_options() = 0; + virtual void set_store_errors_in_response_body(bool store_errors) = 0; +}; + +// Specialized (and mutable) wrapper for RunStep requests between a client and +// master in the same address space. +class InMemoryRunStepRequest : public MutableRunStepRequestWrapper { + public: + // RunStepRequestWrapper methods. + const string& session_handle() const override; + const string& partial_run_handle() const override; + size_t num_feeds() const override; + const string& feed_name(size_t i) const override; + Status FeedValue(size_t i, Tensor* out_tensor) const override; + Status FeedValue(size_t i, TensorProto* out_tensor) const override; + size_t num_fetches() const override; + const string& fetch_name(size_t i) const override; + size_t num_targets() const override; + const string& target_name(size_t i) const override; + const RunOptions& options() const override; + string DebugString() const override; + const RunStepRequest& ToProto() const override; + bool store_errors_in_response_body() const override; + int64_t request_id() const override; + + // MutableRunStepRequestWrapper methods. + void set_session_handle(const string& handle) override; + void set_partial_run_handle(const string& handle) override; + void add_feed(const string& name, const Tensor& value) override; + void add_fetch(const string& name) override; + void add_target(const string& name) override; + RunOptions* mutable_options() override; + void set_store_errors_in_response_body(bool store_errors) override; + + private: + string session_handle_; + string partial_run_handle_; + gtl::InlinedVector, 4> feeds_; + gtl::InlinedVector fetches_; + gtl::InlinedVector targets_; + RunOptions options_; + bool store_errors_in_response_body_ = false; + + // Holds a cached and owned representation of the proto + // representation of this request, if needed, so that `ToProto()` + // can return a const RunStepRequest&. + // NOTE(mrry): Although calls to `ToProto()` on this class are + // expected to be rare, retaining ownership of the returned message + // makes it easier to return a reference from the proto-backed + // representations. + mutable std::unique_ptr proto_version_; +}; + +// Wrapper for mutable RunStep requests that uses a protobuf message. +// +// This wrapper class should be used for RunStep requests between a +// client and master in different address spaces. +class MutableProtoRunStepRequest : public MutableRunStepRequestWrapper { + public: + // RunStepRequestWrapper methods. + const string& session_handle() const override; + const string& partial_run_handle() const override; + size_t num_feeds() const override; + const string& feed_name(size_t i) const override; + Status FeedValue(size_t i, Tensor* out_tensor) const override; + Status FeedValue(size_t i, TensorProto* out_tensor) const override; + size_t num_fetches() const override; + const string& fetch_name(size_t i) const override; + size_t num_targets() const override; + const string& target_name(size_t i) const override; + const RunOptions& options() const override; + string DebugString() const override; + const RunStepRequest& ToProto() const override; + bool store_errors_in_response_body() const override; + int64_t request_id() const override; + + // MutableRunStepRequestWrapper methods. + void set_session_handle(const string& handle) override; + void set_partial_run_handle(const string& handle) override; + void add_feed(const string& name, const Tensor& value) override; + void add_fetch(const string& name) override; + void add_target(const string& name) override; + RunOptions* mutable_options() override; + void set_store_errors_in_response_body(bool store_errors) override; + + private: + RunStepRequest request_; + friend class MasterInterface; +}; + +// Wrapper for immutable RunStep requests that use a non-owned +// protobuf message. +// +// This interface is typically used by server-side components in the +// TensorFlow master, where the incoming message is a (possibly const) +// `RunStepRequest*`. +class ProtoRunStepRequest : public RunStepRequestWrapper { + public: + ProtoRunStepRequest(const RunStepRequest* request); + + // RunStepRequestWrapper methods. + const string& session_handle() const override; + const string& partial_run_handle() const override; + size_t num_feeds() const override; + const string& feed_name(size_t i) const override; + Status FeedValue(size_t i, Tensor* out_tensor) const override; + Status FeedValue(size_t i, TensorProto* out_tensor) const override; + size_t num_fetches() const override; + const string& fetch_name(size_t i) const override; + size_t num_targets() const override; + const string& target_name(size_t i) const override; + const RunOptions& options() const override; + string DebugString() const override; + const RunStepRequest& ToProto() const override; + bool store_errors_in_response_body() const override; + int64_t request_id() const override; + + private: + const RunStepRequest* const request_; // Not owned. +}; + +//////////////////////////////////////////////////////////////////////////////// +// +// Wrapper classes for the `WorkerService.RunGraph` request message. +// +// The `RunGraphRequest` message can contain potentially large tensor +// data as part of its `send` submessages. Here we provide specialized +// wrappers that avoid copying the tensor data wherever possible. +// +// See `RunGraphRequest` in tensorflow/core/protobuf/worker.proto for the +// protocol buffer definition. +// +//////////////////////////////////////////////////////////////////////////////// + +// Abstract interface for an immutable RunGraphRequest message. +// +// This interface is typically used by server-side components in the +// TensorFlow worker. +class RunGraphRequestWrapper { + public: + virtual ~RunGraphRequestWrapper() {} + + // The session handle used to register the graph. If empty, a single global + // namespace is used. + virtual const string& session_handle() const = 0; + + // Set to true if `CreateWorkerSession` was called for `session_handle`. + virtual bool create_worker_session_called() const = 0; + + // REQUIRED: graph_handle must be returned by a RegisterGraph call + // to the same WorkerService. + virtual const string& graph_handle() const = 0; + + // A unique ID to distinguish different runs of the same graph. + // + // The master generates a global unique `step_id` to distinguish + // different runs of the graph computation. Subgraphs communicate + // (e.g., send/recv ops) with each other using `step_id` to + // distinguish tensors generated by different runs. + virtual int64_t step_id() const = 0; + + // Options for this step. + virtual const ExecutorOpts& exec_opts() const = 0; + + // Sends the tensors in "send" into the graph before the run. + virtual size_t num_sends() const = 0; + virtual const string& send_key(size_t i) const = 0; + virtual Status SendValue(size_t i, Tensor* out_tensor) const = 0; + + // Fetches the keys into `RunGraphResponse.recv` after the run. + virtual size_t num_recvs() const = 0; + virtual const string& recv_key(size_t i) const = 0; + + // True if the RunGraphRequest is a partial run request. + virtual bool is_partial() const = 0; + + // True if this is the last partial run request in a sequence of requests. + virtual bool is_last_partial_run() const = 0; + + // If true then some errors, e.g., execution errors that have long + // error messages, may return an OK RunStepResponse with the actual + // error saved in the status_code/status_error_message fields of the + // response body. This is a workaround since the RPC subsystem may + // truncate long metadata messages. + virtual bool store_errors_in_response_body() const = 0; + + virtual int64_t request_id() const = 0; + + // Returns the wrapped data as a protocol buffer message. + virtual const RunGraphRequest& ToProto() const = 0; +}; + +// Abstract interface for a mutable RunGraphRequest message. +// +// See `RunGraphRequestWrapper` above for a description of the fields. +class MutableRunGraphRequestWrapper : public RunGraphRequestWrapper { + public: + virtual void set_session_handle(const string& handle) = 0; + virtual void set_create_worker_session_called(bool called) = 0; + virtual void set_graph_handle(const string& handle) = 0; + virtual void set_step_id(int64_t step_id) = 0; + virtual ExecutorOpts* mutable_exec_opts() = 0; + + // Stores the i^{th} feed value in `run_step_request` in this + // request with the given `send_key`. + virtual Status AddSendFromRunStepRequest( + const RunStepRequestWrapper& run_step_request, size_t i, + const string& send_key) = 0; + virtual Status AddSendFromRunCallableRequest( + const RunCallableRequest& run_callable_request, size_t i, + const string& send_key) = 0; + + virtual void add_recv_key(const string& recv_key) = 0; + virtual void set_is_partial(bool is_partial) = 0; + virtual void set_is_last_partial_run(bool is_last_partial_run) = 0; + virtual void set_store_errors_in_response_body(bool store_errors) = 0; + virtual void set_request_id(int64_t request_id) = 0; +}; + +class InMemoryRunGraphRequest : public MutableRunGraphRequestWrapper { + public: + // RunGraphRequestWrapper methods. + const string& session_handle() const override; + const string& graph_handle() const override; + bool create_worker_session_called() const override; + int64_t step_id() const override; + const ExecutorOpts& exec_opts() const override; + size_t num_sends() const override; + const string& send_key(size_t i) const override; + Status SendValue(size_t i, Tensor* out_tensor) const override; + size_t num_recvs() const override; + const string& recv_key(size_t i) const override; + bool is_partial() const override; + bool is_last_partial_run() const override; + const RunGraphRequest& ToProto() const override; + bool store_errors_in_response_body() const override; + int64_t request_id() const override; + + // MutableRunGraphRequestWrapper methods. + void set_session_handle(const string& handle) override; + void set_create_worker_session_called(bool called) override; + void set_graph_handle(const string& handle) override; + void set_step_id(int64_t step_id) override; + ExecutorOpts* mutable_exec_opts() override; + Status AddSendFromRunStepRequest( + const RunStepRequestWrapper& run_step_request, size_t i, + const string& send_key) override; + Status AddSendFromRunCallableRequest( + const RunCallableRequest& run_callable_request, size_t i, + const string& send_key) override; + void add_recv_key(const string& recv_key) override; + void set_is_partial(bool is_partial) override; + void set_is_last_partial_run(bool is_last_partial_run) override; + void set_store_errors_in_response_body(bool store_errors) override; + void set_request_id(int64_t request_id) override; + + private: + string session_handle_; + bool create_worker_session_called_ = false; + string graph_handle_; + int64_t step_id_; + ExecutorOpts exec_opts_; + gtl::InlinedVector, 4> sends_; + gtl::InlinedVector recvs_; + bool is_partial_ = false; + bool is_last_partial_run_ = false; + bool store_errors_in_response_body_ = false; + int64_t request_id_ = 0; + + // Holds a cached and owned representation of the proto + // representation of this request, if needed, so that `ToProto()` + // can return a const RunGraphRequest&. + // NOTE(mrry): Although calls to `ToProto()` on this class are + // expected to be rare, retaining ownership of the returned message + // makes it easier to return a reference from the proto-backed + // representations. + mutable std::unique_ptr proto_version_; +}; + +class MutableProtoRunGraphRequest : public MutableRunGraphRequestWrapper { + public: + // RunGraphRequestWrapper methods. + const string& session_handle() const override; + bool create_worker_session_called() const override; + const string& graph_handle() const override; + int64_t step_id() const override; + const ExecutorOpts& exec_opts() const override; + size_t num_sends() const override; + const string& send_key(size_t i) const override; + Status SendValue(size_t i, Tensor* out_tensor) const override; + size_t num_recvs() const override; + const string& recv_key(size_t i) const override; + bool is_partial() const override; + bool is_last_partial_run() const override; + bool store_errors_in_response_body() const override; + int64_t request_id() const override; + const RunGraphRequest& ToProto() const override; + + // MutableRunGraphRequestWrapper methods. + void set_session_handle(const string& handle) override; + void set_create_worker_session_called(bool called) override; + void set_graph_handle(const string& handle) override; + void set_step_id(int64_t step_id) override; + ExecutorOpts* mutable_exec_opts() override; + Status AddSendFromRunStepRequest( + const RunStepRequestWrapper& run_step_request, size_t i, + const string& send_key) override; + Status AddSendFromRunCallableRequest( + const RunCallableRequest& run_callable_request, size_t i, + const string& send_key) override; + void add_recv_key(const string& recv_key) override; + void set_is_partial(bool is_partial) override; + void set_is_last_partial_run(bool is_last_partial_run) override; + void set_store_errors_in_response_body(bool store_errors) override; + void set_request_id(int64_t request_id) override; + + private: + RunGraphRequest request_; +}; + +class ProtoRunGraphRequest : public RunGraphRequestWrapper { + public: + ProtoRunGraphRequest(const RunGraphRequest* request); + + // RunGraphRequestWrapper methods. + const string& session_handle() const override; + bool create_worker_session_called() const override; + const string& graph_handle() const override; + int64_t step_id() const override; + const ExecutorOpts& exec_opts() const override; + size_t num_sends() const override; + const string& send_key(size_t i) const override; + Status SendValue(size_t i, Tensor* out_tensor) const override; + size_t num_recvs() const override; + const string& recv_key(size_t i) const override; + bool is_partial() const override; + bool is_last_partial_run() const override; + bool store_errors_in_response_body() const override; + int64_t request_id() const override; + const RunGraphRequest& ToProto() const override; + + private: + const RunGraphRequest* const request_; // Not owned. +}; + +//////////////////////////////////////////////////////////////////////////////// +// +// Wrapper classes for the `WorkerService.RunGraph` response message. +// +// The `RunGraphResponse` message can contain potentially large tensor +// data as part of its `recv` submessages. Here we provide specialized +// wrappers that avoid copying the tensor data wherever possible. +// +// See `RunGraphResponse` in tensorflow/core/protobuf/worker.proto for the +// protocol buffer definition. +// +//////////////////////////////////////////////////////////////////////////////// + +// Abstract interface for a mutable RunGraphResponse message. +// +// Note that there is no corresponding (immutable) +// RunGraphResponseWrapper class, because the RunGraphResponse object +// is always used as a mutable pointer. +class MutableRunGraphResponseWrapper { + public: + virtual ~MutableRunGraphResponseWrapper() {} + + // A list of tensors corresponding to those requested by + // `RunGraphRequest.recv_key`. + virtual size_t num_recvs() const = 0; + virtual const string& recv_key(size_t i) const = 0; + // NOTE: The following methods may perform a destructive read, for + // efficiency. + virtual Status RecvValue(size_t i, TensorProto* out_tensor) = 0; + virtual Status RecvValue(size_t i, Tensor* out_tensor) = 0; + virtual void AddRecv(const string& key, const Tensor& value) = 0; + + // Submessages that store performance statistics about the subgraph + // execution, if necessary. + virtual StepStats* mutable_step_stats() = 0; + virtual CostGraphDef* mutable_cost_graph() = 0; + virtual size_t num_partition_graphs() const = 0; + virtual GraphDef* mutable_partition_graph(size_t i) = 0; + virtual void AddPartitionGraph(const GraphDef& partition_graph) = 0; + + // Returned status if requested. + virtual Status status() const = 0; + virtual absl::StatusCode status_code() const = 0; + virtual void set_status(const Status& status) = 0; + + protected: + // Returns a mutable protobuf message that represents the contents of + // this wrapper, for passing to an RPC subsystem that will populate + // the message. + // + // NOTE: Only `WorkerInterface` subclasses may call this method. The + // `InMemoryRunGraphResponse` subclass does not implement this + // method, and attempts to call it will fail with a fatal + // error. However, as long as callers always call + // `WorkerInterface::RunGraphAsync()` with a wrapper object returned + // from `WorkerInterface::CreateRunGraphResponse()` called on the + // *same* WorkerInterface object, this error will never trigger. + virtual RunGraphResponse* get_proto() = 0; + friend class WorkerInterface; +}; + +class InMemoryRunGraphResponse : public MutableRunGraphResponseWrapper { + public: + // MutableRunGraphResponseWrapper methods. + size_t num_recvs() const override; + const string& recv_key(size_t i) const override; + Status RecvValue(size_t i, TensorProto* out_tensor) override; + Status RecvValue(size_t i, Tensor* out_tensor) override; + void AddRecv(const string& key, const Tensor& value) override; + StepStats* mutable_step_stats() override; + CostGraphDef* mutable_cost_graph() override; + size_t num_partition_graphs() const override; + GraphDef* mutable_partition_graph(size_t i) override; + void AddPartitionGraph(const GraphDef& partition_graph) override; + Status status() const override; + absl::StatusCode status_code() const override; + void set_status(const Status& status) override; + + protected: + // NOTE: This method is not implemented. See + // MutableRunGraphResponseWrapper for an explanation. + RunGraphResponse* get_proto() override; + + private: + gtl::InlinedVector, 4> recvs_; + StepStats step_stats_; + CostGraphDef cost_graph_; + std::vector partition_graphs_; + // Store the code and message separately so that they can be updated + // independently by setters. + Status status_; +}; + +// Proto-based message wrapper for use on the client side of the RunGraph RPC. +class OwnedProtoRunGraphResponse : public MutableRunGraphResponseWrapper { + public: + // MutableRunGraphResponseWrapper methods. + size_t num_recvs() const override; + const string& recv_key(size_t i) const override; + Status RecvValue(size_t i, TensorProto* out_tensor) override; + Status RecvValue(size_t i, Tensor* out_tensor) override; + void AddRecv(const string& key, const Tensor& value) override; + StepStats* mutable_step_stats() override; + CostGraphDef* mutable_cost_graph() override; + size_t num_partition_graphs() const override; + GraphDef* mutable_partition_graph(size_t i) override; + void AddPartitionGraph(const GraphDef& partition_graph) override; + Status status() const override; + absl::StatusCode status_code() const override; + void set_status(const Status& status) override; + + protected: + RunGraphResponse* get_proto() override; + + private: + RunGraphResponse response_; +}; + +// Proto-based message wrapper for use on the server side of the RunGraph RPC. +class NonOwnedProtoRunGraphResponse : public MutableRunGraphResponseWrapper { + public: + NonOwnedProtoRunGraphResponse(RunGraphResponse* response); + + // MutableRunGraphResponseWrapper methods. + size_t num_recvs() const override; + const string& recv_key(size_t i) const override; + Status RecvValue(size_t i, TensorProto* out_tensor) override; + Status RecvValue(size_t i, Tensor* out_tensor) override; + void AddRecv(const string& key, const Tensor& value) override; + StepStats* mutable_step_stats() override; + CostGraphDef* mutable_cost_graph() override; + size_t num_partition_graphs() const override; + GraphDef* mutable_partition_graph(size_t i) override; + void AddPartitionGraph(const GraphDef& partition_graph) override; + Status status() const override; + absl::StatusCode status_code() const override; + void set_status(const Status& status) override; + + protected: + RunGraphResponse* get_proto() override; + + private: + RunGraphResponse* const response_; +}; + +//////////////////////////////////////////////////////////////////////////////// +// +// Wrapper classes for the `MasterService.RunStep` response message. +// +// The `RunStepResponse` message can contain potentially large tensor +// data as part of its `tensor` submessages. Here we provide specialized +// wrappers that avoid copying the tensor data wherever possible. +// +// See `RunStepResponse` in tensorflow/core/protobuf/master.proto for the +// protocol buffer definition. +// +//////////////////////////////////////////////////////////////////////////////// + +// Abstract interface for a mutable RunStepResponse message. +// +// Note that there is no corresponding (immutable) +// RunStepResponseWrapper class, because the RunStepResponse object is +// always used as a mutable pointer. +class MutableRunStepResponseWrapper { + public: + virtual ~MutableRunStepResponseWrapper(); + + // The values of the tensors whose fetching was requested in the + // RunStep call. + // + // NOTE: The order of the returned tensors may or may not match + // the fetch order specified in RunStepRequest. + virtual size_t num_tensors() const = 0; + virtual const string& tensor_name(size_t i) const = 0; + virtual Status TensorValue(size_t i, Tensor* out_tensor) const = 0; + + // Stores the i^{th} recv value in `run_graph_response` in this + // response with the given `name`. + virtual Status AddTensorFromRunGraphResponse( + const string& name, MutableRunGraphResponseWrapper* run_graph_response, + size_t i) = 0; + + // Returned metadata if requested in the options. + virtual const RunMetadata& metadata() const = 0; + virtual RunMetadata* mutable_metadata() = 0; + + // Returned status if requested. + virtual Status status() const = 0; + virtual absl::StatusCode status_code() const = 0; + virtual void set_status(const Status& status) = 0; + + protected: + // Returns a mutable protobuf message that represents the contents of + // this wrapper, for passing to an RPC subsystem that will populate + // the message. + // + // NOTE: Only `MasterInterface` subclasses may call this method. The + // `InMemoryRunStepResponse` subclass does not implement this + // method, and attempts to call it will fail with a fatal + // error. However, as long as callers always call + // `MasterInterface::RunStep()` with a wrapper object returned + // from `MasterInterface::CreateRunStepResponse()` called on the + // *same* MasterInterface object, this error will never trigger. + virtual RunStepResponse* get_proto() = 0; + friend class MasterInterface; +}; + +class InMemoryRunStepResponse : public MutableRunStepResponseWrapper { + public: + // MutableRunStepResponseWrapper methods. + size_t num_tensors() const override; + const string& tensor_name(size_t i) const override; + Status TensorValue(size_t i, Tensor* out_tensor) const override; + Status AddTensorFromRunGraphResponse( + const string& name, MutableRunGraphResponseWrapper* run_graph_response, + size_t i) override; + const RunMetadata& metadata() const override; + RunMetadata* mutable_metadata() override; + Status status() const override; + absl::StatusCode status_code() const override; + void set_status(const Status& status) override; + + protected: + // NOTE: This method is not implemented. See + // MutableRunGraphResponseWrapper for an explanation. + RunStepResponse* get_proto() override; + + private: + gtl::InlinedVector, 4> tensors_; + RunMetadata metadata_; + // Store the code and message separately so that they can be updated + // independently by setters. + Status status_; +}; + +// Proto-based message wrapper for use on the client side of the RunStep RPC. +class OwnedProtoRunStepResponse : public MutableRunStepResponseWrapper { + public: + // MutableRunStepResponseWrapper methods. + size_t num_tensors() const override; + const string& tensor_name(size_t i) const override; + Status TensorValue(size_t i, Tensor* out_tensor) const override; + Status AddTensorFromRunGraphResponse( + const string& name, MutableRunGraphResponseWrapper* run_graph_response, + size_t i) override; + const RunMetadata& metadata() const override; + RunMetadata* mutable_metadata() override; + Status status() const override; + absl::StatusCode status_code() const override; + void set_status(const Status& status) override; + + protected: + RunStepResponse* get_proto() override; + + private: + RunStepResponse response_; +}; + +// Proto-based message wrapper for use on the server side of the RunStep RPC. +class NonOwnedProtoRunStepResponse : public MutableRunStepResponseWrapper { + public: + NonOwnedProtoRunStepResponse(RunStepResponse* response); + + // MutableRunStepResponseWrapper methods. + size_t num_tensors() const override; + const string& tensor_name(size_t i) const override; + Status TensorValue(size_t i, Tensor* out_tensor) const override; + Status AddTensorFromRunGraphResponse( + const string& name, MutableRunGraphResponseWrapper* run_graph_response, + size_t i) override; + const RunMetadata& metadata() const override; + RunMetadata* mutable_metadata() override; + Status status() const override; + absl::StatusCode status_code() const override; + void set_status(const Status& status) override; + + protected: + RunStepResponse* get_proto() override; + + private: + RunStepResponse* response_; // Not owned. +}; + +bool ParseTensorProtoToTensor(const TensorProto& tensor_proto, + Tensor* out_tensor); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_MESSAGE_WRAPPERS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/partial_run_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/partial_run_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..5c1041250296916835c379f94b65cd50d98ad024 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/partial_run_mgr.h @@ -0,0 +1,87 @@ +/* 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_DISTRIBUTED_RUNTIME_PARTIAL_RUN_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_PARTIAL_RUN_MGR_H_ + +#include + +#include "tensorflow/core/distributed_runtime/worker_interface.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// PartialRunMgr keeps track of pending partial run requests, and ensures that +// the partial run is only marked complete when the corresponding executor is +// run to completion. +// +// In tensorflow workers, the executor runs operations asynchronously until +// specified fetches (operations that return tensors) or targets (operations +// that don't return tensors) are reached. A PartialRun has two components: a +// setup which specifies all desired fetches and targets, and run calls that +// specify fetch values (from the setup calls) to retrieve. +// On the last partial run call, it is possible to satisfy the +// required fetches before the executor has completed running the graph to all +// the desired targets. +// PartialRunMgr is used to ensure that we don't complete and return the final +// partial run call to the user until both the partial run and executor have +// completed. +// +// PartialRunMgr is thread-safe. +class PartialRunMgr { + public: + // Find or create the CancellationManager associated with step_id. + // The PartialRunMgr owns the cancellation_manager. + // Returns true if a new CancellationManager was created + // (i.e this is a new partial run). + bool FindOrCreate(int step_id, CancellationManager** cancellation_manager); + + // Calls the final callback if the PartialRunRequest has already completed. + // Otherwise stores the executor_status to be propagated when the + // PartialRunRequest completes (PartialRunDone has been called). + void ExecutorDone(int step_id, const Status& executor_status); + + // Calls done if the executor has already completed (ExecutorDone has been + // called). Otherwise, stores the status and done callback, calling them when + // ExecutorDone is called. The callback will either be called by the calling + // thread of either PartialRunDone or ExecutorDone. + // If executor_status in ExecutorDone is not OK, it takes precedence over + // status and is passed to the done callback. + void PartialRunDone(int step_id, StatusCallback done, const Status& status); + + private: + // PartialRunState stores state associated with a pending partial run request. + // This is protected by the mutex in PartialRunMgr. + struct PartialRunState { + std::unique_ptr cancellation_manager; + + bool executor_done = false; + StatusCallback final_callback = nullptr; + Status final_status; + }; + + mutex mu_; + + std::unordered_map> + step_id_to_partial_run_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_PARTIAL_RUN_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/recent_request_ids.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/recent_request_ids.h new file mode 100644 index 0000000000000000000000000000000000000000..5cb8b82634f82dd302a2a8b1f7e1fb01fb9a3adf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/recent_request_ids.h @@ -0,0 +1,104 @@ +/* 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_DISTRIBUTED_RUNTIME_RECENT_REQUEST_IDS_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RECENT_REQUEST_IDS_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/distributed_runtime/message_wrappers.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace tensorflow { + +// RecentRequestIds tracks recent 64-bit request_ids. When maximum capacity is +// reached, the oldest request_id is evicted. Thread safe. +// +// Some RPCs like RecvTensor are unsafe to retry. For example, RecvTensor pairs +// one sender and one receiver, and the receiver waits for the sender's tensor. +// Retried RecvTensor requests are problematic, because the original RecvTensor +// request may have consumed the sender's tensor, so a retried request might +// block forever. RecentRequestIds identifies retried requests, so we can fail +// them instead of blocking forever. +// +// Internally, recent request_ids are stored in two data structures: a set and a +// circular buffer. The set is used for efficient lookups, and the circular +// buffer tracks the oldest request_id. When the buffer is full, the new +// request_id replaces the oldest request_id in the circular buffer, and the +// oldest request_id is removed from the set. +class RecentRequestIds { + public: + // num_tracked_request_ids should be much larger than the number of RPCs that + // can be received in a small time window. For example, we observed a peak RPC + // rate of ~700 RecvTensor RPC/s when training inception v3 on TPUs, so we + // currently set num_tracked_request_ids to 100,000 for RecvTensor. + // Having a large `num_shars` can prevent run into lock contention in this + // class. + explicit RecentRequestIds(int num_tracked_request_ids, int num_shards = 1); + + // Returns OK iff request_id has not been seen in the last + // num_tracked_request_ids insertions. For backwards compatibility, this + // always returns OK for request_id 0. The method_name and the request's + // ShortDebugString are added to returned errors. + Status TrackUnique(int64_t request_id, const string& method_name, + const protobuf::Message& request); + // Overloaded version of the above function for wrapped protos. + template + Status TrackUnique(int64_t request_id, const string& method_name, + const RequestWrapper* wrapper); + + private: + bool Insert(int64_t request_id); + + struct IndexBucket { + mutex mu; + // next_index indexes into circular_buffer_, and points to the next storage + // space to use. When the buffer is full, next_index_ points at the oldest + // request_id. + int next_index TF_GUARDED_BY(mu) = 0; + std::vector circular_buffer TF_GUARDED_BY(mu); + absl::flat_hash_set set TF_GUARDED_BY(mu); + }; + + // This vector is immutable so we don't need to use a mutex to protect it. + std::vector index_buckets_; +}; + +// Implementation details + +template +Status RecentRequestIds::TrackUnique(int64_t request_id, + const string& method_name, + const RequestWrapper* wrapper) { + if (Insert(request_id)) { + return OkStatus(); + } else { + return errors::Aborted("The same ", method_name, + " request was received twice. ", + wrapper->ToProto().ShortDebugString()); + } +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RECENT_REQUEST_IDS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/remote_device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/remote_device.h new file mode 100644 index 0000000000000000000000000000000000000000..2b7a8eb55b5d12b6fae15b8011845c79394ee99d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/remote_device.h @@ -0,0 +1,72 @@ +/* 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_DISTRIBUTED_RUNTIME_REMOTE_DEVICE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REMOTE_DEVICE_H_ + +#include +#include +#include + +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/stringpiece.h" + +namespace tsl { +class Env; +} // namespace tsl +namespace tensorflow { +using Env = tsl::Env; +class DeviceAttributes; +class Device; +class WorkerCacheInterface; + +// This callback should have the same definition as DeviceMgr::LookupDevice +// It assigns *device with pointer to Device of the given 'name', where 'name' +// is either a full device name, or just the replica-local suffix. +typedef std::function + LookupLocalDevice; + +// Creates Remote Devices for the provided device attributes. Helpful when the +// list of attributes is known, and doesn't need to be discovered via RPC. +void AsRemoteDevices( + Env* env, + const protobuf::RepeatedPtrField& device_attributes, + LookupLocalDevice lookup_local_device, + std::vector>* remote_devices); + +// NewRemoteDevices discovers available devices on the +// 'worker_name'. The implementation uses 'channel_cache' to +// discover how to communicate with the 'worker_name' (via gRPC, for +// example). +// +// NewRemoteDevices does not block. +// +// On success, the 'done' callback is given the OK status and a vector +// of Device*. The caller should take ownership of these devices. +// +// Otherwise, the 'done' callback is given an error status and the +// vector is empty. +typedef std::function*)> + NewRemoteDevicesDone; +void NewRemoteDevices(Env* env, WorkerCacheInterface* worker_cache, + const string& worker_name, NewRemoteDevicesDone done); + +// Create Remote Device based on the given attributes. +std::unique_ptr NewRemoteDevice(Env* env, + DeviceAttributes device_attribute); +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REMOTE_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..2308d8abc9c46d5eb32dcd80b67b5217e3419376 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rendezvous_mgr_interface.h @@ -0,0 +1,109 @@ +/* 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_DISTRIBUTED_RUNTIME_RENDEZVOUS_MGR_INTERFACE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RENDEZVOUS_MGR_INTERFACE_H_ + +#include + +#include "tensorflow/core/distributed_runtime/worker_env.h" +#include "tensorflow/core/framework/rendezvous.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +class WorkerSession; + +// RemoteRendezvous follow a 2-part initialization. First the objects are +// constructed. Eventually, they will be initialized. Clients of the +// RendezvousMgrInterface must guarantee to call Initialize on the returned +// RemoteRendezvous eventually. +// +// Partially initialized RemoteRendezvous must respect the Rendezvous interface +// (i.e. Send() must never block), however implementations are not expected to +// actually perform the underlying operations until after the RemoteRendezvous +// has been Initialize'd. +class RemoteRendezvous : public Rendezvous { + public: + // Fully construct the RemoteRendezvous. + virtual Status Initialize(WorkerSession* session) = 0; + + // In remote eager, set current instance as context default rendezvous which + // will be used for eager op-by-op execution. + virtual void SetRemoteEagerContextDefault() = 0; + // In remote eager, get if current instance is context default rendezvous. + virtual bool IsRemoteEagerContextDefault() = 0; + + protected: + bool is_cross_process() override { return true; } +}; + +// RendezvousMgr keeps track of a set of local rendezvous instances. +// All tensors sent by this worker are buffered in a RendezvousMgr +// until the tensor is received. Each global unique "step_id" +// corresponds to one local rendezvous instance managed by a +// RendezvousMgr. +// +// E.g., +// Rendezvous* rendez = worker_env->rendezvous_mgr->Find(0x8935); +// fork execution of an graph executor using "rendez" on thread 1; +// fork execution of another graph executor using "rendez" on thread 2; +// ... +// join threads 1 and 2; +// +// In the example above, execution in thread 1 and 2 communicates with +// each other by send/recv operations through the "rend". +// +// Tensors sent and recved through rendezvous managed by this +// RendezvousMgr must have keys generated by Rendezvous::CreateKey. +class RendezvousMgrInterface { + public: + RendezvousMgrInterface() = default; + virtual ~RendezvousMgrInterface() {} + + // Returns Rendezvous supporting send and recv among workers in the + // "step_id". The caller takes ownership of one reference on the + // returned Rendezvous instance. + // + // Note: the caller must guarantee to eventually call Initialize on the + // returned RemoteRendezvous + virtual tsl::core::RefCountPtr Find(int64_t step_id) = 0; + + // Finds the local rendezvous instance for the "step_id". Runs + // "done" when the tensor for "key" is produced or an error occurs. + // + // This method is used by the rpc handler of RecvTensor. + virtual void RecvLocalAsync(int64_t step_id, + const Rendezvous::ParsedKey& parsed, + Rendezvous::DoneCallback done) = 0; + + // Synchronous wrapper for RecvLocalAsync. + virtual Status RecvLocal(int64_t step_id, const Rendezvous::ParsedKey& parsed, + Tensor* val, bool* is_dead) = 0; + + // Removes rendezvous for "step_id". + // + // TODO(zhifengc): Have a background thread in worker that + // periodically calls CleanupAll(). + virtual void Cleanup(int64_t step_id) = 0; + + // Remove all rendezvous instances owned by the rendezvous_mgr. + virtual void CleanupAll() = 0; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RENDEZVOUS_MGR_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/request_id.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/request_id.h new file mode 100644 index 0000000000000000000000000000000000000000..2f7b3b462c3d24f7aedb9a61815e372c7dd8f2be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/request_id.h @@ -0,0 +1,31 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REQUEST_ID_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REQUEST_ID_H_ + +#include "tensorflow/core/platform/types.h" +#include "tsl/platform/random.h" + +namespace tensorflow { + +// Returns a request_id for use with RecentRequestIds. This number will not be +// zero, and must be unique over RecentRequestIds' window of +// num_tracked_request_ids. See recent_request_ids.h for more details. +int64_t GetUniqueRequestId(); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REQUEST_ID_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_client.h new file mode 100644 index 0000000000000000000000000000000000000000..4d301ee8018e37b588f36b3f84ae205949235654 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_client.h @@ -0,0 +1,31 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_COORDINATION_GRPC_COORDINATION_CLIENT_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COORDINATION_GRPC_COORDINATION_CLIENT_H_ + +#include + +#include "tsl/distributed_runtime/rpc/coordination/grpc_coordination_client.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::NewGrpcCoordinationClient; +using tsl::NewGrpcCoordinationClientCache; +// NOLINTEND(misc-unused-using-decls) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COORDINATION_GRPC_COORDINATION_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d914583c44c2183f59b523c8e378f8248374c00f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h @@ -0,0 +1,27 @@ +/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COORDINATION_GRPC_COORDINATION_SERVICE_IMPL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COORDINATION_GRPC_COORDINATION_SERVICE_IMPL_H_ + +#include "tsl/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::GrpcCoordinationServiceImpl; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COORDINATION_GRPC_COORDINATION_SERVICE_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_client.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_client.h new file mode 100644 index 0000000000000000000000000000000000000000..8a926da488477b3c88b11b822ef6d332457e3cc0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_client.h @@ -0,0 +1,30 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_CLIENT_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_CLIENT_H_ + +#include "tensorflow/core/distributed_runtime/eager/eager_client.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h" + +namespace tensorflow { +namespace eager { +// The GrpcChannelCache is not owned. +EagerClientCache* NewGrpcEagerClientCache( + std::shared_ptr channel); +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_CLIENT_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service.h new file mode 100644 index 0000000000000000000000000000000000000000..4ef8131feef362eea7a6c07fc001580528568d03 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service.h @@ -0,0 +1,22 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_H_ + +#include "xla/stream_executor/platform/port.h" +#include "tensorflow/core/protobuf/eager_service.grpc.pb.h" + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d310424c92f5886fa11d8e2fcb05c5ebf6ea760b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service_impl.h @@ -0,0 +1,170 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_IMPL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_IMPL_H_ + +#include "grpcpp/alarm.h" +#include "grpcpp/completion_queue.h" +#include "grpcpp/server_builder.h" +#include "tensorflow/core/distributed_runtime/eager/eager_service_impl.h" +#include "tensorflow/core/distributed_runtime/rpc/eager/grpc_eager_service.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" +#include "tsl/distributed_runtime/rpc/async_service_interface.h" +#include "tsl/distributed_runtime/rpc/grpc_call.h" + +namespace tensorflow { +namespace eager { + +// This class is a wrapper that handles communication for gRPC. +class GrpcEagerServiceImpl : public tsl::AsyncServiceInterface { + public: + template + using EagerCall = + tsl::Call; + template + using StreamingCall = + tsl::ServerBidirectionalStreamingCall; + + GrpcEagerServiceImpl(WorkerEnv* env, ::grpc::ServerBuilder* server_builder); + virtual ~GrpcEagerServiceImpl() {} + + // Create a master context in eager service. + Status CreateMasterContext(const tensorflow::uint64 context_id, + EagerContext* context); + + void HandleRPCsLoop() override; + void Shutdown() override; + + private: +#define HANDLER(method) \ + void method##Handler(EagerCall* call) { \ + env_->compute_pool->Schedule([this, call]() { \ + call->SendResponse( \ + ToGrpcStatus(local_impl_.method(&call->request, &call->response))); \ + }); \ + tsl::Call:: \ + EnqueueRequest(&service_, cq_.get(), \ + &grpc::EagerService::AsyncService::Request##method, \ + &GrpcEagerServiceImpl::method##Handler, false); \ + } + HANDLER(CreateContext); + HANDLER(UpdateContext); + HANDLER(WaitQueueDone); + HANDLER(KeepAlive); + HANDLER(CloseContext); +#undef HANDLER + + void EnqueueHandler(EagerCall* call) { + env_->compute_pool->Schedule([this, call]() { + auto call_opts = std::make_shared(); + call->SetCancelCallback([call_opts]() { call_opts->StartCancel(); }); + call->SendResponse(ToGrpcStatus(local_impl_.Enqueue( + call_opts.get(), &call->request, &call->response))); + }); + tsl::Call:: + EnqueueRequest(&service_, cq_.get(), + &grpc::EagerService::AsyncService::RequestEnqueue, + &GrpcEagerServiceImpl::EnqueueHandler, + /*supports_cancel=*/true); + } + + void RunComponentFunctionHandler( + EagerCall* + call) { + env_->compute_pool->Schedule([this, call]() { + auto call_opts = std::make_shared(); + call->SetCancelCallback([call_opts]() { call_opts->StartCancel(); }); + local_impl_.RunComponentFunction(call_opts.get(), &call->request, + &call->response, + [call, call_opts](const Status& s) { + call->ClearCancelCallback(); + call->SendResponse(ToGrpcStatus(s)); + }); + }); + tsl::Call:: + EnqueueRequest( + &service_, cq_.get(), + &grpc::EagerService::AsyncService::RequestRunComponentFunction, + &GrpcEagerServiceImpl::RunComponentFunctionHandler, + /*supports_cancel=*/true); + } + + // Called when a new request has been received as part of a StreamingEnqueue + // call. + // StreamingEnqueueHandler gets the request from the `call` and fills the + // response (also found in `call`) by invoking the local EagerServiceImpl. + // The local EagerServiceImpl is invoked in a single-threaded thread pool. We + // do this to preserve request order. The local service can parallelize based + // on context_id in request if necessary. Remote contexts are created in async + // mode by default, so the local service impl just puts the request on eager + // executor queue. + void StreamingEnqueueHandler( + StreamingCall* call) { + call->Ref(); + enqueue_streaming_thread_.Schedule([this, call]() { + if (call->RefCountIsOne()) { + // This StreamingCall has already been shutdown. Don't need to anything. + call->Unref(); + return; + } + // NOTE(fishx): Use the address of StreamingCall as the stream_id since we + // reuse the same StreamingCall for multiple requests in the same + // streaming connection. + Status status = local_impl_.Enqueue( + /*call_opts=*/nullptr, &call->request(), call->mutable_response(), + reinterpret_cast(static_cast(call))); + + if (status.ok()) { + VLOG(1) << "local_impl_.Enqueue completed successfully"; + call->SendResponse(); + } else { + VLOG(1) << "local_impl_.Enqueue failed with " << status.ToString() + << " on request " << call->request().DebugString(); + call->Finish(ToGrpcStatus(status)); + } + call->Unref(); + + // We do not tell gRPC to accept a new StreamingEnqueue request because + // this method can be called multiple times for a given streaming call. + // The StreamingCall does this per call instead, after a call has been + // opened. + }); + } + + WorkerEnv* const env_; // Not owned. + EagerServiceImpl local_impl_; + + // A single-threaded thread pool to handle streaming enqueue rpc request. + thread::ThreadPool enqueue_streaming_thread_; + std::unique_ptr<::grpc::Alarm> shutdown_alarm_; + + std::unique_ptr<::grpc::ServerCompletionQueue> cq_; + grpc::EagerService::AsyncService service_; + + GrpcEagerServiceImpl(const GrpcEagerServiceImpl&) = delete; + void operator=(const GrpcEagerServiceImpl&) = delete; +}; + +} // namespace eager +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_EAGER_GRPC_EAGER_SERVICE_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_channel.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_channel.h new file mode 100644 index 0000000000000000000000000000000000000000..c98ad7a074dd6fbc33b27ed86b846de3a5c46fbf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_channel.h @@ -0,0 +1,33 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_CHANNEL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CHANNEL_H_ + +#include "tsl/distributed_runtime/rpc/grpc_channel.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::ChannelCreationFunction; +using tsl::ConvertToChannelCreationFunction; +using tsl::GetChannelArguments; +using tsl::GrpcChannelCache; +using tsl::GrpcChannelSpec; +using tsl::NewGrpcChannelCache; +using tsl::NewHostPortGrpcChannel; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CHANNEL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h new file mode 100644 index 0000000000000000000000000000000000000000..accb50857d579e7950ce02e79d572c3bb3e3753c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h @@ -0,0 +1,27 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_CLIENT_CQ_TAG_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CLIENT_CQ_TAG_H_ + +#include "tsl/distributed_runtime/rpc/grpc_client_cq_tag.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::GrpcClientCQTag; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_CLIENT_CQ_TAG_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service.h new file mode 100644 index 0000000000000000000000000000000000000000..bd2031639e960872f4f07dc576b391c6be548680 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service.h @@ -0,0 +1,36 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_MASTER_SERVICE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_MASTER_SERVICE_H_ + +#include +#include "grpcpp/server_builder.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/master.pb.h" + +namespace tsl { +class AsyncServiceInterface; +} +namespace tensorflow { +class Master; + +tsl::AsyncServiceInterface* NewGrpcMasterService( + Master* master, const ConfigProto& default_session_config, + ::grpc::ServerBuilder* builder); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_MASTER_SERVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..bdf683fd939219f11bf342423077ff3787491e46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_master_service_impl.h @@ -0,0 +1,218 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_MASTER_SERVICE_IMPL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_MASTER_SERVICE_IMPL_H_ + +#include "grpcpp/impl/codegen/async_stream.h" +#include "grpcpp/impl/codegen/async_unary_call.h" +#include "grpcpp/impl/codegen/client_context.h" +#include "grpcpp/impl/codegen/completion_queue.h" +#include "grpcpp/impl/codegen/proto_utils.h" +#include "grpcpp/impl/codegen/rpc_method.h" +#include "grpcpp/impl/codegen/server_context.h" +#include "grpcpp/impl/codegen/service_type.h" +#include "grpcpp/impl/codegen/status.h" +#include "grpcpp/impl/codegen/stub_options.h" +#include "grpcpp/impl/codegen/sync_stream.h" +#include "tensorflow/core/protobuf/master.pb.h" + +namespace tensorflow { + +namespace grpc { + +// Implementation of `tensorflow.MasterService`, based on the +// definition in "//tensorflow/core/protobuf/master_service.proto", +// and the gRPC generated stub and service classes. +// See that file for the definition of methods and messages. +class MasterService final { + public: + class StubInterface { + public: + virtual ~StubInterface() {} + virtual ::grpc::Status CreateSession(::grpc::ClientContext* context, + const CreateSessionRequest& request, + CreateSessionResponse* response) = 0; + virtual ::grpc::Status ExtendSession(::grpc::ClientContext* context, + const ExtendSessionRequest& request, + ExtendSessionResponse* response) = 0; + virtual ::grpc::Status PartialRunSetup( + ::grpc::ClientContext* context, const PartialRunSetupRequest& request, + PartialRunSetupResponse* response) = 0; + virtual ::grpc::Status RunStep(::grpc::ClientContext* context, + const RunStepRequest& request, + RunStepResponse* response) = 0; + virtual ::grpc::Status CloseSession(::grpc::ClientContext* context, + const CloseSessionRequest& request, + CloseSessionResponse* response) = 0; + virtual ::grpc::Status ListDevices(::grpc::ClientContext* context, + const ListDevicesRequest& request, + ListDevicesResponse* response) = 0; + virtual ::grpc::Status Reset(::grpc::ClientContext* context, + const ResetRequest& request, + ResetResponse* response) = 0; + virtual ::grpc::Status MakeCallable(::grpc::ClientContext* context, + const MakeCallableRequest& request, + MakeCallableResponse* response) = 0; + virtual ::grpc::Status RunCallable(::grpc::ClientContext* context, + const RunCallableRequest& request, + RunCallableResponse* response) = 0; + virtual ::grpc::Status ReleaseCallable( + ::grpc::ClientContext* context, const ReleaseCallableRequest& request, + ReleaseCallableResponse* response) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + ::grpc::Status CreateSession(::grpc::ClientContext* context, + const CreateSessionRequest& request, + CreateSessionResponse* response) override; + ::grpc::Status ExtendSession(::grpc::ClientContext* context, + const ExtendSessionRequest& request, + ExtendSessionResponse* response) override; + ::grpc::Status PartialRunSetup(::grpc::ClientContext* context, + const PartialRunSetupRequest& request, + PartialRunSetupResponse* response) override; + ::grpc::Status RunStep(::grpc::ClientContext* context, + const RunStepRequest& request, + RunStepResponse* response) override; + ::grpc::Status CloseSession(::grpc::ClientContext* context, + const CloseSessionRequest& request, + CloseSessionResponse* response) override; + ::grpc::Status ListDevices(::grpc::ClientContext* context, + const ListDevicesRequest& request, + ListDevicesResponse* response) override; + ::grpc::Status Reset(::grpc::ClientContext* context, + const ResetRequest& request, + ResetResponse* response) override; + ::grpc::Status MakeCallable(::grpc::ClientContext* context, + const MakeCallableRequest& request, + MakeCallableResponse* response) override; + ::grpc::Status RunCallable(::grpc::ClientContext* context, + const RunCallableRequest& request, + RunCallableResponse* response) override; + ::grpc::Status ReleaseCallable(::grpc::ClientContext* context, + const ReleaseCallableRequest& request, + ReleaseCallableResponse* response) override; + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + const ::grpc::internal::RpcMethod rpcmethod_CreateSession_; + const ::grpc::internal::RpcMethod rpcmethod_ExtendSession_; + const ::grpc::internal::RpcMethod rpcmethod_PartialRunSetup_; + const ::grpc::internal::RpcMethod rpcmethod_RunStep_; + const ::grpc::internal::RpcMethod rpcmethod_CloseSession_; + const ::grpc::internal::RpcMethod rpcmethod_ListDevices_; + const ::grpc::internal::RpcMethod rpcmethod_Reset_; + const ::grpc::internal::RpcMethod rpcmethod_MakeCallable_; + const ::grpc::internal::RpcMethod rpcmethod_RunCallable_; + const ::grpc::internal::RpcMethod rpcmethod_ReleaseCallable_; + }; + static std::unique_ptr NewStub( + const std::shared_ptr< ::grpc::ChannelInterface>& channel, + const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class AsyncService : public ::grpc::Service { + public: + AsyncService(); + virtual ~AsyncService(); + void RequestCreateSession( + ::grpc::ServerContext* context, CreateSessionRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(0, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestExtendSession( + ::grpc::ServerContext* context, ExtendSessionRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(1, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestPartialRunSetup( + ::grpc::ServerContext* context, PartialRunSetupRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(2, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestRunStep( + ::grpc::ServerContext* context, RunStepRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(3, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestCloseSession( + ::grpc::ServerContext* context, CloseSessionRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(4, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestListDevices( + ::grpc::ServerContext* context, ListDevicesRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(5, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestReset( + ::grpc::ServerContext* context, ResetRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(6, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestMakeCallable( + ::grpc::ServerContext* context, MakeCallableRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(7, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestRunCallable( + ::grpc::ServerContext* context, RunCallableRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(8, context, request, response, + new_call_cq, notification_cq, tag); + } + void RequestReleaseCallable( + ::grpc::ServerContext* context, ReleaseCallableRequest* request, + ::grpc::ServerAsyncResponseWriter* response, + ::grpc::CompletionQueue* new_call_cq, + ::grpc::ServerCompletionQueue* notification_cq, void* tag) { + ::grpc::Service::RequestAsyncUnary(9, context, request, response, + new_call_cq, notification_cq, tag); + } + }; +}; + +} // namespace grpc + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_MASTER_SERVICE_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h new file mode 100644 index 0000000000000000000000000000000000000000..97e590e0ad180006d4538409c0addea715c7dd50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h @@ -0,0 +1,37 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ + +#include + +#include "grpcpp/completion_queue.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" +#include "tensorflow/core/lib/core/threadpool.h" + +namespace tensorflow { +class WorkerCacheLogger; +class WorkerInterface; + +WorkerInterface* NewGrpcRemoteWorker(SharedGrpcChannelPtr channel, + ::grpc::CompletionQueue* completion_queue, + thread::ThreadPool* callback_threadpool, + WorkerCacheLogger* logger, + const string& target); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..f588f291960a37e5a815c74f68738fc9cca2134f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h @@ -0,0 +1,241 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_SERVER_LIB_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_SERVER_LIB_H_ + +// GrpcServer manages the lifecycle of an Eager, Worker and Master service. + +#include +#include +#include + +#include "grpcpp/grpcpp.h" +#include "grpcpp/security/credentials.h" +#include "tensorflow/core/common_runtime/eager/context.h" +#include "tensorflow/core/common_runtime/process_util.h" +#include "tensorflow/core/common_runtime/stats_publisher_interface.h" +#include "tensorflow/core/distributed_runtime/master_env.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h" +#include "tensorflow/core/distributed_runtime/server_lib.h" +#include "tensorflow/core/distributed_runtime/session_mgr.h" +#include "tensorflow/core/distributed_runtime/worker_env.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/platform/env.h" +#include "tsl/distributed_runtime/rpc/async_service_interface.h" +#include "tsl/profiler/protobuf/profiler_service.grpc.pb.h" + +namespace tensorflow { + +class GrpcWorker; +class Master; + +// function that creates a RendezvousMgr. +typedef std::function + RendezvousMgrCreationFunction; + +// function that creates a CollectiveExecutorMgr. +typedef std::function + CollectiveMgrCreationFunction; + +// function that registers a service to the server. The service needs to +// be registered before builder.BuildAndStart(). +typedef std::function + ServiceInitFunction; + +// function that creates a grpc based worker implementation. +typedef std::function(WorkerEnv*, + const ConfigProto& config)> + WorkerCreationFunction; + +struct GrpcServerOptions { + ServiceInitFunction service_func = nullptr; + RendezvousMgrCreationFunction rendezvous_mgr_func = nullptr; + CollectiveMgrCreationFunction collective_mgr_func = nullptr; + WorkerCreationFunction worker_func = nullptr; + StatsPublisherFactory stats_factory = CreateNoOpStatsPublisher; + GrpcWorkerServiceOptions worker_service_options; + DeviceMgr* local_device_mgr = nullptr; +}; + +class GrpcServer : public ServerInterface { + protected: + GrpcServer(const ServerDef& server_def, Env* env); + GrpcServer(const ServerDef& server_def, DeviceMgr* local_device_mgr, + Env* env); + // Allow children classes to override this and provide custom args to the + // server before it is constructed. Default behavior is to do nothing. + // requested_port provides the port requested by caller as bound_port() is + // not available till BuildAndStart has been called. + virtual void MaybeMutateBuilder(::grpc::ServerBuilder* builder, + int requested_port) {} + + public: + static Status Create(const ServerDef& server_def, Env* env, + std::unique_ptr* out_server); + static Status Create(const ServerDef& server_def, Env* env, + std::unique_ptr* out_server); + // Reuse the local_device_mgr. + static Status Create(const ServerDef& server_def, Env* env, + DeviceMgr* local_device_mgr, + std::unique_ptr* out_server); + + // Destruction is only supported in the factory method. Clean + // shutdown is not currently implemented for this server type. + virtual ~GrpcServer(); + + // Implementations of ServerInterface methods. + Status Start() override; + Status Stop() override; + Status Join() override; + const string target() const override; + + WorkerEnv* worker_env() override { return &worker_env_; } + MasterEnv* master_env() override { return &master_env_; } + + // Add master eager context to local eager service in order to handle enqueue + // requests from remote workers. + Status AddMasterEagerContextToEagerService( + const tensorflow::uint64 context_id, + tensorflow::EagerContext* context) override; + // Update the set of workers that can be reached by the GRPC server + Status UpdateServerDef(const ServerDef& server_def) override; + // Pass coordination service agent instance to server's RPC handler + Status SetCoordinationServiceAgentInstance( + tsl::CoordinationServiceAgent* agent) override; + // TODO(hanyangtay): Remove this method once gRPC server clean shutdown is + // supported. + Status StopCoordinationService() override; + + protected: + virtual Status GetHostAndPort(const ServerDef& server_def, string* host_name, + int* port) const; + Status Init(const GrpcServerOptions& opts = GrpcServerOptions()); + + // A subclass can override this method to support secure credentials. + virtual std::shared_ptr<::grpc::ServerCredentials> GetServerCredentials( + const ServerDef& server_def) const; + + virtual ChannelCreationFunction GetChannelCreationFunction() const; + + virtual std::unique_ptr CreateMaster(MasterEnv* master_env); + + // Creates a WorkerCacheInterface for a session. + virtual Status WorkerCacheFactory(const WorkerCacheFactoryOptions& options, + WorkerCacheInterface** worker_cache); + + // Override to return extra services to be brought up and managed along with + // the standard {master, worker, eager} services. The map key is an aribtrary + // string and the value is a pointer to the service to be brought up. + // Ownership of the pointer is transferred to GrpcServer after this call + // returns, and the service will be destroyed during the destruction of + // GrpcServer. Each service will have its HandleRPCsLoop called in a separate + // thread. An example usage would be to add a RDMA based partial worker + // service to offload tensor and data buffer transfers. + virtual std::map ExtraServices( + ::grpc::ServerBuilder*) { + return {}; + } + + virtual std::map + GetExtraServices() { + return extra_services_; + } + + // Parses a WorkerCacheFactoryOptions into a GrpcChannelSpec. + Status ParseChannelSpec(const WorkerCacheFactoryOptions& options, + GrpcChannelSpec* channel_spec); + + // Returns the port to which this server is bound. + // This method may only be called after `this->Init()` returns successfully. + int bound_port() const { return bound_port_; } + + // Returns hostname. + const string& host_name() const { return host_name_; } + + const ServerDef& server_def() const { return server_def_; } + GrpcWorker* worker_impl() const { return worker_impl_.get(); } + GrpcWorkerEnv* grpc_worker_env() const { return grpc_worker_env_.get(); } + + Status SetCoordinationServiceInstance( + tsl::CoordinationServiceInterface* service); + + private: + Env* env_; + + // The port to which this server is bound. + int bound_port_ = 0; + + // The host name of this server + string host_name_; + + // Guards server configuration, server, and state. + mutex mu_; + + // Represents the current state of the server, which changes as follows: + // + // Join() Join() + // ___ ___ + // Start() \ / Stop() \ / + // NEW ---------> STARTED --------> STOPPED + // \ / + // \________________________/ + // Stop(), Join() + enum State { NEW, STARTED, STOPPED }; + State state_ TF_GUARDED_BY(mu_); + + // Implementation of a TensorFlow master, and RPC polling thread. + MasterEnv master_env_; + std::unique_ptr master_impl_; + tsl::AsyncServiceInterface* master_service_ = nullptr; + std::unique_ptr master_thread_ TF_GUARDED_BY(mu_); + + std::map extra_services_; + std::vector> extra_service_threads_ + TF_GUARDED_BY(mu_); + + // Implementation of a TensorFlow worker, and RPC polling thread. + WorkerEnv worker_env_; + std::unique_ptr owned_device_manager_; + std::unique_ptr worker_impl_; + tsl::AsyncServiceInterface* worker_service_ = nullptr; + std::unique_ptr worker_thread_ TF_GUARDED_BY(mu_); + std::unique_ptr grpc_worker_env_; + + // TensorFlow Eager implementation, and RPC polling thread. + tsl::AsyncServiceInterface* eager_service_ = nullptr; + std::unique_ptr eager_thread_ TF_GUARDED_BY(mu_); + std::shared_ptr worker_session_; + + // Experimental coordination service implementation, and RPC polling thread. + tsl::AsyncServiceInterface* coordination_service_ = nullptr; + std::unique_ptr coordination_thread_ TF_GUARDED_BY(mu_); + + // TensorFlow profiler service implementation. + std::unique_ptr profiler_service_ = nullptr; + + // The overall server configuration. + ServerDef server_def_ TF_GUARDED_BY(mu_); + + std::unique_ptr<::grpc::Server> server_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_SERVER_LIB_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_state.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_state.h new file mode 100644 index 0000000000000000000000000000000000000000..bcf044ff0b87c40fb3da27f90f286347e1fbf293 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_state.h @@ -0,0 +1,541 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_STATE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_STATE_H_ + +#include +#include + +#include "grpcpp/generic/generic_stub.h" +#include "grpcpp/grpcpp.h" +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" +#include "tensorflow/core/distributed_runtime/tensor_coding.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/notification.h" +#include "tensorflow/core/util/env_var.h" +#include "tsl/distributed_runtime/rpc/grpc_state.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::RPCState; +// NOLINTEND(misc-unused-using-decls) + +// Represents state associated with one streaming RPC call. +// Similarly to above, we extract the methods of StreamingRPCState that don't +// need to be templated into this abstract class. +// Currently, *StreamingRPCState does not support client closing the call as +// there is no use case for it - current clients keep the streaming call open +// as long as possible. If/when the need arises, support can be added +// by calling GenericClientAsyncReaderWriter::WritesDone with a new tag +// TagType::kClientFinished and handling the completion in a new callback. +class UntypedStreamingRPCState : public core::RefCounted { + public: + virtual void CallStarted(bool ok) = 0; + virtual void RequestWriteCompleted(bool ok) = 0; + virtual void ResponseReadCompleted(bool ok) = 0; + virtual void CallFinished(bool ok) = 0; + + virtual string DebugString() const = 0; + + class Tag : public GrpcClientCQTag { + public: + // One enum value per supported callback. + enum class TagType { + kCallStarted, + kRequestWriteCompleted, + kResponseReadCompleted, + kCallFinished, + }; + + Tag(UntypedStreamingRPCState* streaming_state, Tag::TagType type); + + // Calls the callback associated with this tag and Unrefs + // `this->streaming_state_`. + void OnCompleted(bool ok) override; + + private: + // OnCompleted() consumes on reference each time it is called. + UntypedStreamingRPCState* const streaming_state_; + const Tag::TagType type_; + }; +}; + +const char* ToString(UntypedStreamingRPCState::Tag::TagType tag_type); + +// Represents a single request/response exchange between client and the server. +// A single streaming call contains a sequence of exchanges. Besides the +// messages, exchange contains: +// - the user callback to invoke when exchange completes (response is received +// or an error occurs). +// - The current state of the exchange. +class Exchange { + public: + enum class State { + kExchangeCreated, + kRequestWriteIssued, + kRequestWriteCompleted, + kResponseReadIssued, + }; + + Exchange(const ::grpc::ByteBuffer& request_buf, protobuf::Message* response, + StatusCallback cb, string debug_string) + : state_(State::kExchangeCreated), + request_buf_(request_buf), + response_(response), + cb_(std::move(cb)), + debug_string_(std::move(debug_string)) {} + + const ::grpc::ByteBuffer& request_buf() { return request_buf_; } + ::grpc::ByteBuffer* response_buf() { return &response_buf_; } + + void MarkRequestWriteIssued() { + DCHECK(state_ == State::kExchangeCreated); + state_ = State::kRequestWriteIssued; + } + void MarkRequestWriteCompleted() { + DCHECK(state_ == State::kRequestWriteIssued); + state_ = State::kRequestWriteCompleted; + } + void MarkResponseReadIssued() { + DCHECK(state_ == State::kRequestWriteCompleted); + state_ = State::kResponseReadIssued; + } + + // If `status` is success, completes this exchange by parsing the + // response_buf_ and invoking cb_ with OkStatus(). Else, invokes the + // callback with `status`. + void Complete(Status status); + + const State& state() const { return state_; } + + string DebugString() const; + + private: + State state_; + ::grpc::ByteBuffer request_buf_; + ::grpc::ByteBuffer response_buf_; + protobuf::Message* response_; + StatusCallback cb_; + string debug_string_; +}; + +const char* ToString(Exchange::State s); + +std::ostream& operator<<(std::ostream& os, const Exchange::State& state); + +// Represents a queue of exchanges. +// When a client sends a new request a new exchange is created and added to the +// end of the queue. Completed exchanges are popped from the front of the queue. +// An explicit exchange queue is needed to brdige the client, which can send new +// requests at any time, with gRPC infrastructure, which can handle a single +// read and a single write request at a time. +// +// As the exchange progresses (request sending initiated, request sending +// completed, response reading initiated) the queue helps to make sure that the +// right operation is issued on the right exchange at the right time. +// +// To satisfy gRPC constraints, the states of exchanges must be as follows +// starting from the front of the queue: +// - 0 or 1 exchange in kResponseReadIssued state +// - 0 or more exchanges in kRequestWriteCompleted state +// - 0 or 1 exchange in kRequestWriteIssued state +// - 0 or more exchanges in kExchangeCreated state +// +// Thread-compatible. +class ExchangeQueue { + public: + // Creates a new exchange and adds it to the end of the queue. + void Emplace(const ::grpc::ByteBuffer& request_buf, + protobuf::Message* response, StatusCallback cb, + std::string debug_string); + + // Returns an exchange for which we can initiate request writing, if any. + // Returns nullptr if there is no such exchange. + Exchange* GetReadyForRequestWriting(); + + // Returns an exchange for which we can initiate response reading, if any. + // Returns nullptr if there is no such exchange. + Exchange* GetReadyForResponseReading(); + + // Changes the state of the exchange that is current in kRequestWriteIssued + // state to kRequestWriteCompleted state. + // REQUIRES: There is an exchange in kRequestWriteIssued state. + void MarkRequestWriteCompleted(); + + // Returns the exchange at the front of the queue. + // REQUIRES: ExchangeQueue is not empty. + Exchange& GetFront(); + + // Removes the exchange at the front of the queue. + // REQUIRES: ExchangeQueue is not empty. + void PopFront(); + + // Returns a string containing addresses and states of all exchanges in this + // queue. + string DebugString() const; + + // Swaps the contents of this and `other`. + void Swap(ExchangeQueue* other); + + // Completes all exchanges in this with `status`. + void CompleteAll(Status status); + + void CallStarted() { call_started_ = true; } + + private: + // Does nothing by default. Turn on VLOG(5) to enable. + // Checks that this ExchangeQueue is in a valid state. + // Kills the process if not. + void CheckInvariants(); + + // We can't process any exchanges until the call has started. + bool call_started_ = false; + + // std::queue is based on std::deque by default. std::deque provides + // fairly strong iterator stability. + std::deque exchanges_; +}; // namespace tensorflow + +// Represents state associated with one streaming RPC call. +// Thread-safe +template +class StreamingRPCState : public UntypedStreamingRPCState { + public: + // Default behavior is to set fail_fast = False and handle timeouts + // manually. + StreamingRPCState( + std::unique_ptr<::grpc::GenericClientAsyncReaderWriter> call, + const std::shared_ptr<::grpc::ClientContext>& context) + : context_(context), call_(std::move(call)), call_state_(State::kActive) { + Ref(); + VLOG(3) << "Created new StreamingRPCState " << this; + VLOG(3) << "StreamingRPCState(" << this << ") calling grpc::StartCall"; + call_->StartCall(&call_started_tag_); + } + + ~StreamingRPCState() override { + VLOG(3) << "Destructing StreamingRPCState " << this; + } + + // Attempts to send the next request. `done` is invoked when + // `response` has been filled with the data from the server, or if there + // is an error. `done` can be invoked before SendNextRequest returns. + // Return `true` if the call is alive and the `done` callback has or + // will be invoked. If the call is dead, returns `false`. `done` callback + // will not be invoked in this case. + // REQUIRES: The call has been started, i.e. WaitForCallStarted() has + // returned. + bool SendNextRequest(const protobuf::Message& request, Response* response, + const StatusCallback& done) { + ::grpc::ByteBuffer request_buf; + ::grpc::Status s = tsl::GrpcMaybeUnparseProto(request, &request_buf); + if (!s.ok()) { + Status status = FromGrpcStatus(s); + LOG(ERROR) << "GrpcMaybeUnparseProto returned with non-ok status: " + << status.ToString(); + done(status); + return true; + } + + mutex_lock l(mu_); + if (call_state_ != State::kActive) { + // `done` is not invoked intentionally. + return false; + } + if (VLOG_IS_ON(3)) { + // If vlog 3 is enabled, include first 100 chars of request as debug + // string. + exchanges_.Emplace(request_buf, response, done, + request.ShortDebugString().substr(0, 100)); + } else { + exchanges_.Emplace(request_buf, response, done, ""); + } + MaybeIssueRequestWriteLocked(); + return true; + } + + void CallStarted(bool ok) override { + VLOG(3) << "StreamingRPCState(" << this << ")::CallStarted(ok=" << ok + << ")"; + mutex_lock l(mu_); + if (!ok) { + call_state_ = State::kDone; + return; + } + exchanges_.CallStarted(); + // Now that the call has started, we can write our first request, if any. + MaybeIssueRequestWriteLocked(); + } + + void RequestWriteCompleted(bool ok) override { + VLOG(3) << "StreamingRPCState(" << this + << ")::RequestWriteCompleted(ok=" << ok << ")"; + mu_.lock(); + if (call_state_ != State::kActive) { + mu_.unlock(); + return; + } + exchanges_.MarkRequestWriteCompleted(); + // Issue ResponseRead regardless of OK status on completing RequestWrite. + // If the underlying completion queue is in Not-OK status due to previous + // request failuress (i.e., `ok` from `Next` call on completion queue is + // False), delay the error in ResponseRead so we can get the remote error + // message from response buffer. + MaybeIssueResponseReadLocked(); + + if (ok) { + MaybeIssueRequestWriteLocked(); + } + mu_.unlock(); + } + + void ResponseReadCompleted(bool ok) override { + VLOG(3) << "StreamingRPCState(" << this + << ")::ResponseReadCompleted(ok=" << ok << ")"; + mu_.lock(); + if (call_state_ != State::kActive) { + mu_.unlock(); + return; + } + if (!ok) { + IssueCallFinishLocked(); + mu_.unlock(); + return; + } + + // Complete the exchange without holding the lock because user's + // callback can call back into this RPC code resulting in a deadlock. + // No other thread can pop this exchange while we release the lock because + // this is the only method that pops exchanges and it is called from a + // single thread that waits on completion queue events. + Exchange* e; + e = &exchanges_.GetFront(); + mu_.unlock(); + + e->Complete(OkStatus()); + + { + mutex_lock l(mu_); + exchanges_.PopFront(); + MaybeIssueResponseReadLocked(); + } + } + + void CallFinished(bool ok) override { + VLOG(3) << "StreamingRPCState(" << this << ")::CallFinished(ok=" << ok + << ")"; + mu_.lock(); + DCHECK(call_state_ != State::kActive); + if (call_state_ != State::kFinishing) { + mu_.unlock(); + return; + } + + Status s = FromGrpcStatus(call_status_); + if (s.ok() && !ok) { + s.Update( + errors::Internal("GRPC status is okay but CompletionQueueStatus is " + "not. This should never happen.", + context_->debug_error_string())); + } + // unlocks mu_ + MarkDoneAndCompleteExchanges(s); + } + + string DebugString() const override { + mutex_lock l(mu_); + return exchanges_.DebugString(); + } + + private: + enum class State { + kActive, + kFinishing, + kDone, + }; + + void MarkDoneAndCompleteExchanges(Status status) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) TF_UNLOCK_FUNCTION(mu_) { + call_state_ = State::kDone; + VLOG(2) << "Ending gRPC streaming call on the client side due to " + << status.ToString(); + // Swap the exchanges_ into a temporary ExchangeQueue so that we can + // complete all exchanges without holding mu_ in case user callback + // reach back into this. This should be impossible now, but safer for + // the future. + ExchangeQueue queue; + exchanges_.Swap(&queue); + mu_.unlock(); + queue.CompleteAll(status); + } + + void MaybeIssueRequestWriteLocked() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { + Exchange* exchange = exchanges_.GetReadyForRequestWriting(); + if (exchange == nullptr) { + // There are no queued exchanges, there is already an outstanding write, + // or there are no just created exchanges. + return; + } + exchange->MarkRequestWriteIssued(); + Ref(); + VLOG(3) << "StreamingRPCState(" << this << ") calling grpc::Write"; + call_->Write(exchange->request_buf(), &request_write_completed_tag_); + } + + void MaybeIssueResponseReadLocked() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { + Exchange* exchange = exchanges_.GetReadyForResponseReading(); + if (exchange == nullptr) { + return; + } + exchange->MarkResponseReadIssued(); + Ref(); + VLOG(3) << "StreamingRPCState(" << this << ") calling grpc::Read"; + call_->Read(exchange->response_buf(), &response_read_completed_tag_); + } + + void IssueCallFinishLocked() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { + call_state_ = State::kFinishing; + Ref(); + VLOG(3) << "StreamingRPCState(" << this << ") calling grpc::Finish"; + // We call finish in response to completed (with error) response reading tag + // on some exchange. We let this exchange hang in ResponseReadIssued state. + // ExchangeQueue makes sure that there is at most one exchange in this + // state. So, no new reads will be issued. + call_->Finish(&call_status_, &finished_tag_); + } + + // Holds state for a single request/response exchange between the client + // and the server. + typedef typename UntypedStreamingRPCState::Tag Tag; + + // Order of context_ and call_ is important because context_ must outlive + // call_. + const std::shared_ptr context_; + std::unique_ptr<::grpc::GenericClientAsyncReaderWriter> call_; + + mutable mutex mu_; + ExchangeQueue exchanges_ TF_GUARDED_BY(mu_); + State call_state_ TF_GUARDED_BY(mu_); + ::grpc::Status call_status_ TF_GUARDED_BY(mu_); + + // We can get away with having single instances of these tags per + // StreamingRPCState because we make sure (as gRPC requires) that + // there is at most one outstanding Read and at most one outstanding Write + // in the completion queue. + // Tags are immutable. No need to guard them. + Tag call_started_tag_{this, Tag::TagType::kCallStarted}; + Tag request_write_completed_tag_{this, Tag::TagType::kRequestWriteCompleted}; + Tag response_read_completed_tag_{this, Tag::TagType::kResponseReadCompleted}; + Tag finished_tag_{this, Tag::TagType::kCallFinished}; +}; + +// Creates streaming calls and dispatches requests to them. +// In the common case, the client would create a StreamingRPCDispatcher for +// each bidirectional streaming RPC it might want to make. The first time, it +// calls SendNextRequest, a streaming call is initiated and the request is +// sent within this call. Initiation of the call blocks the client. If there are +// no errors, subsequent calls to SendNextRequest would use the already active +// call. If there was an error, the call object will be destroyed after all +// the callbacks for outstanding requests have been invoked. The next call to +// SendNextRequest will initiate a new call. +// +// Callbacks that are part of the same call, are invoked in the order they were +// provided, but callbacks across calls (a failed and a new one) can be invoked +// in any order. +// +// Thread-safe. +template +class StreamingRPCDispatcher { + public: + StreamingRPCDispatcher(::grpc::GenericStub* stub, ::grpc::CompletionQueue* cq, + const ::grpc::string& method) + : stub_(stub), cq_(cq), method_(method) {} + + // Attempts to send the next request. If there is no active streaming call, + // starts one and sends the request on top of it. `done` is invoked when + // `response` has been filled with the data from the server, or if there + // is an error. `done` can be invoked before SendNextRequest returns. + void SendNextRequest(const protobuf::Message& request, Response* response, + StatusCallback done) { + mutex_lock l(mu_); + if (state_ == nullptr) { + CreateStreamingState(); + } + + bool is_call_alive = state_->SendNextRequest(request, response, done); + if (is_call_alive) { + return; + } + + // The attempt to send failed because the call was dead, create a new + // call and try again. When the call is dead SendNextRequest does not call + // `done`. + CreateStreamingState(); + + is_call_alive = state_->SendNextRequest(request, response, done); + if (!is_call_alive) { + // Consider retrying to create and start a call few more times. + done(errors::Unknown("gRPC call failed right after it was created")); + } + } + + // Request to cancel the current streaming call. Non-blocking. + void CancelCall() { + mutex_lock l(mu_); + if (state_ == nullptr) { + return; + } + context_->TryCancel(); + state_ = nullptr; + } + + private: + void CreateStreamingState() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { + // ClientContext cannot be reused across calls. + context_ = std::make_shared<::grpc::ClientContext>(); + // Don't immediately fail StartCall if the channel is not ready. Wait for + // the channel to become ready. + context_->set_wait_for_ready(true); + + std::unique_ptr<::grpc::GenericClientAsyncReaderWriter> call = + stub_->PrepareCall(context_.get(), method_, cq_); + + state_.reset(new StreamingRPCState(std::move(call), context_)); + } + + mutable mutex mu_; + + // Both are thread-safe + ::grpc::GenericStub* const stub_; + ::grpc::CompletionQueue* const cq_; + + // Does not need synchronization since it is constant. + const ::grpc::string method_; + + std::shared_ptr<::grpc::ClientContext> context_ TF_GUARDED_BY(mu_); + core::RefCountPtr> state_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_STATE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_tensor_coding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_tensor_coding.h new file mode 100644 index 0000000000000000000000000000000000000000..ffcc4a2bbfa7f48a9475e6345162ec997a4b51e5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_tensor_coding.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. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_TENSOR_CODING_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_TENSOR_CODING_H_ + +#include "grpcpp/impl/codegen/byte_buffer.h" + +namespace tensorflow { +class Tensor; +class RecvTensorResponse; + +// TODO(jeff,sanjay): this should not be grpc specific. Instead of +// grpc::ByteBuffer*, it should accept an object of an interface type +// to which owned byte-arrays can be added. +namespace grpc { + +// Encode a RecvTensorResponse protocol buffer into a byte buffer in a +// format that is parseable as a RecvTensorResponse protocol buffer +// holding "proto". +// +// Discards original contents of *result. +void EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto, + ::grpc::ByteBuffer* result); + +// Encode a Tensor into a byte buffer in a format that is parseable +// as a RecvTensorResponse protocol buffer holding "val". +// +// "is_dead" is the value to encode for "RecvTensorResponse::is_dead" +// (tensor is the output of a dead node and content is invalid because +// control flow operations elsewhere caused the path on which this +// Tensor exists to not be taken). +// +// "val" holds the tensor value to be encoded. +// +// Discards original contents of *result. +void EncodeTensorToByteBuffer(bool is_dead, const Tensor& val, bool require_ack, + ::grpc::ByteBuffer* result); + +} // namespace grpc +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_TENSOR_CODING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_util.h new file mode 100644 index 0000000000000000000000000000000000000000..a54dfec1542411771137ccd6c7b26c212886d948 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_util.h @@ -0,0 +1,73 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_UTIL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_UTIL_H_ + +#include +#include + +#include "grpcpp/grpcpp.h" +#include "grpcpp/impl/codegen/proto_utils.h" +#include "grpcpp/support/byte_buffer.h" +#include "tensorflow/core/distributed_runtime/tensor_coding.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/stringprintf.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tsl/distributed_runtime/rpc/grpc_util.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::ComputeBackoffMicroseconds; +using tsl::FromGrpcStatus; +using tsl::SharedGrpcChannelPtr; +using tsl::ToGrpcStatus; +// NOLINTEND(misc-unused-using-decls) + +// Thin wrapper around ::grpc::ProtoBufferReader to give TensorResponse +// an efficient byte reader from which to decode a RecvTensorResponse. +class GrpcByteSource : public TensorResponse::Source { + public: + explicit GrpcByteSource(::grpc::ByteBuffer* buffer) : buffer_(buffer) {} + ~GrpcByteSource() override { DeleteStream(); } + + typedef ::grpc::ProtoBufferReader Reader; + + protobuf::io::ZeroCopyInputStream* contents() override { + DeleteStream(); + stream_ = new (&space_) Reader(buffer_); + return stream_; + } + + private: + void DeleteStream() { + if (stream_) { + stream_->~Reader(); + } + } + + ::grpc::ByteBuffer* buffer_; // Not owned + Reader* stream_ = nullptr; // Points into space_ if non-nullptr + char space_[sizeof(Reader)]; +}; + +inline string GrpcIdKey() { return "tf-rpc"; } + +// Decode a TensorResponse without extra copying. This function is an optimized +// variant of tsl::GrpcMaybeParseProto. +bool GrpcMaybeParseTensorResponse(::grpc::ByteBuffer* src, TensorResponse* dst); +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..2dfbc79aa8aad68a48e2f3a2dd3d12eecccf85df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h @@ -0,0 +1,76 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_CACHE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_CACHE_H_ + +#include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h" +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/threadpool.h" + +namespace tensorflow { + +class GrpcWorkerEnv { + public: + GrpcWorkerEnv(size_t num_completion_queues, size_t num_threads); + + ~GrpcWorkerEnv(); + + thread::ThreadPool* GetThreadPool() const { return threadpool_.get(); } + + size_t CompletionQueueSize() const { return threads_.size(); } + + ::grpc::CompletionQueue* GetCompletionQueue(size_t index) const { + return threads_.at(index).completion_queue(); + } + + private: + // Thread wrapping class that drives work over a single gRPC + // CompletionQueue. + class GrpcWorkerCacheThread { + public: + GrpcWorkerCacheThread(); + + ~GrpcWorkerCacheThread(); + + ::grpc::CompletionQueue* completion_queue() const { + return &completion_queue_; + } + + private: + mutable ::grpc::CompletionQueue completion_queue_; + std::unique_ptr thread_; + }; + + std::unique_ptr threadpool_; + std::vector threads_; +}; + +// Create a GrpcWorkerEnv instance that can be used as argument to create +// gRPC worker cache. Caller should take the ownership of the returned instance. +GrpcWorkerEnv* CreateGrpcWorkerEnv(); + +// The returned WorkerCacheInterface object takes the ownership of "cc". +WorkerCacheInterface* NewGrpcWorkerCache(std::shared_ptr cc, + GrpcWorkerEnv* worker_env); + +WorkerCacheInterface* NewGrpcWorkerCacheWithLocalWorker( + std::shared_ptr cc, GrpcWorkerEnv* worker_env, + WorkerInterface* local_worker, const string& local_target); + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h new file mode 100644 index 0000000000000000000000000000000000000000..6fd9f6ba61c40113c1abca1ad735931143337112 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h @@ -0,0 +1,92 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_SERVICE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_SERVICE_H_ + +#include +#include + +#include "grpcpp/server_builder.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h" +#include "tensorflow/core/distributed_runtime/rpc/rpc_response_cache.h" +#include "tensorflow/core/distributed_runtime/worker.h" +#include "tensorflow/core/protobuf/worker.pb.h" +#include "tsl/distributed_runtime/rpc/async_service_interface.h" + +namespace grpc { +class ByteBuffer; +} // namespace grpc + +namespace tsl { +class AsyncServiceInterface; +} + +namespace tensorflow { + +class ConfigProto; +struct WorkerEnv; +class WorkerSession; +class RpcResponseCache; + +class GrpcWorker : public Worker { + public: + GrpcWorker(WorkerEnv* env, const ConfigProto& config); + + // Specialized version of RecvTensor for gRPC, which avoids a copy. + virtual void GrpcRecvTensorAsync(CallOptions* opts, + const RecvTensorRequest* request, + ::grpc::ByteBuffer* response, + StatusCallback done); + + void LoggingAsync(const LoggingRequest* request, LoggingResponse* response, + StatusCallback done) override; + + void RecvBufAsync(CallOptions* opts, const RecvBufRequest* request, + RecvBufResponse* response, StatusCallback done) override; + + void CleanupGraphAsync(const CleanupGraphRequest* request, + CleanupGraphResponse* response, + StatusCallback done) override; + + WorkerEnv* env(); + + void EnableResponseCache(); + + void RemoveCacheEntryForId(int64_t request_id); + + private: + std::unique_ptr response_cache_; + const int32 recv_buf_max_chunk_; +}; + +std::unique_ptr NewGrpcWorker(WorkerEnv* worker_env, + const ConfigProto& config); + +struct GrpcWorkerServiceOptions { + // Map from GrpcWorkerMethod id to queue depth. If set this overrides the + // default queue depth for a method. + std::unordered_map queue_depth; + int num_serving_threads = 8; +}; + +// Returns an implementation of WorkerService rpc service. +std::unique_ptr NewGrpcWorkerService( + GrpcWorker* worker, ::grpc::ServerBuilder* builder, + GrpcWorkerServiceOptions options = GrpcWorkerServiceOptions()); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_SERVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..25f5ec9774dfcdc3a9d673c15568292e9b9a8f9f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/grpc_worker_service_impl.h @@ -0,0 +1,118 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_SERVICE_IMPL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_SERVICE_IMPL_H_ + +#include "grpcpp/impl/codegen/async_stream.h" +#include "grpcpp/impl/codegen/async_unary_call.h" +#include "grpcpp/impl/codegen/proto_utils.h" +#include "grpcpp/impl/codegen/rpc_method.h" +#include "grpcpp/impl/codegen/service_type.h" +#include "grpcpp/impl/codegen/status.h" +#include "grpcpp/impl/codegen/stub_options.h" +#include "grpcpp/impl/codegen/sync_stream.h" +#include "grpcpp/support/byte_buffer.h" + +#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" +#include "tensorflow/core/distributed_runtime/tensor_coding.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace grpc { + +// Support parsing/unparsing of tensorflow::TensorResponse. +// Wire-format is identical to RecvTensorResponse. +// This is specializing an existing template, so it's okay to do this in a +// namespace that we don't own. +template <> +class SerializationTraits { + public: + static Status Serialize(const tensorflow::TensorResponse& msg, ByteBuffer* bp, + bool* own_buffer) { + LOG(FATAL) << "TODO(sanjay,jeff): Implement"; + return Status(); + } + static Status Deserialize(ByteBuffer* buffer, + tensorflow::TensorResponse* msg) { + if (buffer == nullptr) { + return Status(StatusCode::INTERNAL, "No payload"); + } + Status result = Status::OK; + if (result.ok()) { + ::tensorflow::GrpcByteSource source(buffer); + auto s = msg->ParseFrom(&source); + if (!s.ok()) { + result = Status(StatusCode::INTERNAL, + ::tensorflow::strings::StrCat( + "TensorResponse parse error", s.message())); + } + } + buffer->Clear(); + return result; + } +}; + +} // namespace grpc + +namespace tensorflow { + +// Names of worker methods. +enum class GrpcWorkerMethod { + kGetStatus, + kCreateWorkerSession, + kDeleteWorkerSession, + kRegisterGraph, + kDeregisterGraph, + kRunGraph, + kCleanupGraph, + kCleanupAll, + kRecvTensor, + kRecvBuf, + kLogging, + kTracing, + kCompleteGroup, + kCompleteInstance, + kGetStepSequence, + kMarkRecvFinished, +}; + +static const int kGrpcNumWorkerMethods = + static_cast(GrpcWorkerMethod::kMarkRecvFinished) + 1; + +const char* GrpcWorkerMethodName(GrpcWorkerMethod id); + +namespace grpc { + +// Implementation of `tensorflow.WorkerService`, based on the +// definition in "//tensorflow/core/protobuf/worker_service.proto", +// and the gRPC generated stub and service classes. +// See the proto file for the definition of methods and messages. +class WorkerService final { + public: + class AsyncService : public ::grpc::Service { + public: + AsyncService(); + virtual ~AsyncService(); + + // Make RequestAsyncUnary public for grpc_call.h + using ::grpc::Service::RequestAsyncUnary; + }; +}; + +} // namespace grpc + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_WORKER_SERVICE_IMPL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..42eda4ea71aef7cdf2bf8ea06928ed25169360f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h @@ -0,0 +1,60 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_RPC_RENDEZVOUS_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_RPC_RENDEZVOUS_MGR_H_ + +#include "tensorflow/core/distributed_runtime/base_rendezvous_mgr.h" +#include "tensorflow/core/distributed_runtime/worker_env.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +class DeviceMgr; + +// RendezvousMgr keeps track of a set of local rendezvous instances. +// All tensors sent by this worker are buffered in a RendezvousMgr +// until the tensor is received. Each global unique "step_id" +// corresponds to one local rendezvous instance managed by a +// RendezvousMgr. +// +// E.g., +// Rendezvous* rendez = worker_env->rendezvous_mgr->Find(0x8935); +// fork execution of an graph executor using "rendez" on thread 1; +// fork execution of another graph executor using "rendez" on thread 2; +// ... +// join threads 1 and 2; +// +// In the example above, execution in thread 1 and 2 communicates with +// each other by send/recv operations through the "rend". +// +// Tensors sent and recved through rendezvous managed by this +// RendezvousMgr must have keys generated by Rendezvous::CreateKey. +class RpcRendezvousMgr : public BaseRendezvousMgr { + public: + explicit RpcRendezvousMgr(const WorkerEnv* env); + + protected: + tsl::core::RefCountPtr Create( + int64_t step_id, const WorkerEnv* worker_env) override; + + private: + RpcRendezvousMgr(const RpcRendezvousMgr&) = delete; + void operator=(const RpcRendezvousMgr&) = delete; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_RPC_RENDEZVOUS_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_response_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_response_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..c7c7567fa2ba2f6fa6ea4ccd09b15e0aa49164c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc/rpc_response_cache.h @@ -0,0 +1,97 @@ +/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_RPC_RESPONSE_CACHE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_RPC_RESPONSE_CACHE_H_ + +#include +#include +#include + +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/flatmap.h" +#include "tensorflow/core/platform/mutex.h" + +// gRPC response caching. Most WorkerService methods cannot be retried directly +// as they will fail or deadlock. To enable retrying, we can instead cache +// responses and reply to duplicate requests from the cache. The cache will be +// cleaned when the MarkRecvFinishedRequest is received from the receiver or the +// session step is completed. +namespace tensorflow { + +// Track and cache the state of worker service RPCs. An RPC can be in 3 states: +// +// * PENDING: this is the first call of the RPC, and it will transition to +// * ACTIVE: another thread is active processing this RPC +// * FINISHED: the worker has finished processing the method + +class RpcResponseCache { + public: + using FinishResponseCB = std::function; + + // Add the given request to the cache. + // If the request is in the cache, + // If it is finished, invoke `cb` immediately + // If active, cb will be invoked when the current call completes. + // In either case, return true. + // Otherwise, store the request and cb in the cache, and return false. + // Note FinishResponseCB is assumed to be thread-safe. + bool QueueRequest(int64_t request_id, int64_t step_id, + const FinishResponseCB& cb); + + // Fill the response cache for the given request_id and respond to all + // pending request. + void RequestFinished(int64_t request_id, const Tensor& tensor, bool is_dead, + const Status& status); + + // Erase the cache entry with the given request_id + void EraseRequestId(int64_t request_id); + + // Erase cache entries with the given step_id + void CleanEntriesForStep(int64_t step_id); + + int64_t size(); + + private: + struct ResponseCacheEntry { + enum class State { + PENDING = 0, + ACTIVE = 1, + FINISHED = 2, + }; + + State state = State::PENDING; + int64_t step_id = -1; + Tensor tensor; + bool is_dead = false; + Status response_status; + + void FinishResponse(const FinishResponseCB& cb) const { + cb(tensor, is_dead, response_status); + } + std::vector callbacks; + }; + + mutex mu_; + // response_cache_ is expected to be small, as entries are cleared immediately + // on ack from the receiver. + gtl::FlatMap response_cache_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_RPC_RESPONSE_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc_collective_executor_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc_collective_executor_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..0e775093813e31d8c294d69b65adbedeee9a679d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/rpc_collective_executor_mgr.h @@ -0,0 +1,94 @@ +/* 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_DISTRIBUTED_RUNTIME_RPC_COLLECTIVE_EXECUTOR_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COLLECTIVE_EXECUTOR_MGR_H_ + +#include "tensorflow/core/common_runtime/collective_executor_mgr.h" +#include "tensorflow/core/framework/collective.h" + +namespace tensorflow { +class CollectiveParamResolverDistributed; +class ConfigProto; +class DeviceMgr; +class DeviceResolverDistributed; +class WorkerCacheInterface; +class StepSequenceRequest; +class StepSequenceResponse; + +// An implementation of CollectiveExecutorMgr for a distributed environment +// that uses WorkerInterface::RecvBufAsync to route data transfers over RPCs. +// +// In some execution environments it may be possible to implement a +// higher-performance solution and use it in place of this class. +class RpcCollectiveExecutorMgr : public CollectiveExecutorMgr { + public: + RpcCollectiveExecutorMgr( + const ConfigProto& config, const DeviceMgr* dev_mgr, + std::unique_ptr dev_resolver, + std::unique_ptr param_resolver, + std::unique_ptr nccl_communicator, + WorkerCacheInterface* worker_cache, const string& task_name); + + virtual ~RpcCollectiveExecutorMgr(); + + // This function should only be called at the group_leader, by an RPC. + // Other needs for StepIds should be satisfied by NextStepId. + void GetStepSequenceAsync(const GetStepSequenceRequest* request, + GetStepSequenceResponse* response, + const StatusCallback& done) override; + + void RefreshStepIdSequenceAsync(int64_t graph_key, + const StatusCallback& done) override; + + int64_t NextStepId(int64_t graph_key) override; + + void RetireStepId(int64_t graph_key, int64_t step_id) override; + + protected: + virtual CollectiveExecutor* Create(int64_t step_id) override; + + WorkerCacheInterface* const worker_cache_; // Not owned. + const string task_name_; + string group_leader_; + friend class RpcCollectiveExecutorMgrTest; + + private: + Status UpdateStepSequences(const GetStepSequenceResponse& resp); + + // This class maintains the step_id sequencing for a single + // collective_graph_key. + struct GraphKeySequence { + explicit GraphKeySequence(int64_t k) + : graph_key_(k), next_step_id_(CollectiveExecutor::kInvalidId) {} + + const int64_t graph_key_; + int64_t next_step_id_; + }; + + mutex sequence_mu_; + gtl::FlatMap sequence_table_ + TF_GUARDED_BY(sequence_mu_); +}; + +// Creates a distributed CollectiveExecutorMgr with production implementations +// of each components. Cases that need to inject other implementations of these +// components should call CollectiveExecutorMgr constructor directly. +std::unique_ptr CreateProdRpcCollectiveExecutorMgr( + const ConfigProto& config, const DeviceMgr* device_mgr, + std::unique_ptr nccl_communicator, + WorkerCacheInterface* worker_cache, const string& default_worker_name); + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_COLLECTIVE_EXECUTOR_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/scheduler.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/scheduler.h new file mode 100644 index 0000000000000000000000000000000000000000..4385db786ff38ac75aa883ea2a67455562ac1ddc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/scheduler.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. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SCHEDULER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SCHEDULER_H_ + +#include +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/graph/costmodel.h" + +namespace tensorflow { + +class SlackAnalysis { + public: + SlackAnalysis(const Graph* g, const CostModel* cost_model); + + ~SlackAnalysis() {} + + // Compute the earliest possible start time for each node, based on + // a given cost model. 'asap_time' is indexed by node id. + Microseconds ComputeAsap(std::vector* asap_times); + + // Compute the latest possible start time for each node, based on + // a given cost model. 'alap_time' is indexed by node id. + Microseconds ComputeAlap(std::vector* alap_times); + + // Compute the "slack" of each node. 'slacks' is indexed by node id. + void ComputeSlack(std::vector* slacks); + + private: + const Graph* graph_; + const CostModel* cost_model_; + + SlackAnalysis(const SlackAnalysis&) = delete; + void operator=(const SlackAnalysis&) = delete; +}; + +class GreedyScheduler { + public: + struct Sim { + int degree_parallelism; + int num_running; + std::vector ready_nodes; + }; + + struct Event { + const Node* node; + Microseconds time; + bool is_completion; + + bool operator<(const Event& other) const { return time < other.time; } + }; + + GreedyScheduler(const DeviceSet* devices, const CostModel* cost_model, + const Graph* g, std::vector* priority); + + ~GreedyScheduler(); + + // Computes the start time of each node given the priorities of + // the nodes. + Microseconds ComputeSchedule(std::vector* start_times); + + private: + // Returns the ready node with the highest priority for a sim. + const Node* GetNodeWithHighestPriority(const std::vector& nodes); + + const DeviceSet* devices_; + const CostModel* cost_model_; + const Graph* graph_; + std::vector* priority_; + std::unordered_map device_states_; + + GreedyScheduler(const GreedyScheduler&) = delete; + void operator=(const GreedyScheduler&) = delete; +}; + +class PriorityScheduler { + public: + PriorityScheduler(const DeviceSet* devices, const CostModel* cost_model, + const Graph* g); + + ~PriorityScheduler() {} + + // Computes a schedule of the ideal start time for each node. + // Returns the makespan (the total running time). + Microseconds ComputeSchedule(std::vector* start_times); + + // Computes a schedule and assigns priorities to the nodes based on + // the schedule. Returns the makespan. + Microseconds AssignPriorities(std::vector* priorities); + + private: + const DeviceSet* devices_; + const CostModel* cost_model_; + const Graph* graph_; + + PriorityScheduler(const PriorityScheduler&) = delete; + void operator=(const PriorityScheduler&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SCHEDULER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/server_lib.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/server_lib.h new file mode 100644 index 0000000000000000000000000000000000000000..3a5ca1853889bc387789ecd36dfd610b437093da --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/server_lib.h @@ -0,0 +1,134 @@ +/* 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_DISTRIBUTED_RUNTIME_SERVER_LIB_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SERVER_LIB_H_ + +#include + +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/protobuf/tensorflow_server.pb.h" + +namespace tsl { +class CoordinationServiceAgent; +} // namespace tsl + +namespace tensorflow { + +class DeviceMgr; +class EagerContext; +class WorkerEnv; +class MasterEnv; + +// This library supports a registration/factory-based mechanism for +// creating TensorFlow server objects. Each server implementation must +// have an accompanying implementation of ServerFactory, and create a +// static "registrar" object that calls `ServerFactory::Register()` +// with an instance of the factory class. See "rpc/grpc_server_lib.cc" +// for an example. + +// Represents a single TensorFlow server that exports Master and Worker +// services. +class ServerInterface { + public: + ServerInterface() {} + virtual ~ServerInterface() {} + + // Starts the server running asynchronously. Returns OK on success, otherwise + // returns an error. + virtual Status Start() = 0; + + // Stops the server asynchronously. Returns OK on success, otherwise returns + // an error. + // + // After calling `Stop()`, the caller may call `Join()` to block until the + // server has stopped. + virtual Status Stop() = 0; + + // Blocks until the server has stopped. Returns OK on success, otherwise + // returns an error. + virtual Status Join() = 0; + + // Returns a target string that can be used to connect to this server using + // `tensorflow::NewSession()`. + virtual const string target() const = 0; + + virtual WorkerEnv* worker_env() = 0; + virtual MasterEnv* master_env() = 0; + + // Update the set of workers that can be reached by the server + virtual Status UpdateServerDef(const ServerDef& server_def) = 0; + + // Functions to operate on service-specific properties. + // + // Add master eager context to local eager service in order to handle enqueue + // requests from remote workers. + virtual Status AddMasterEagerContextToEagerService( + const tensorflow::uint64 context_id, EagerContext* context) = 0; + // Set coordination service agent instance to coordination service RPC handler + virtual Status SetCoordinationServiceAgentInstance( + tsl::CoordinationServiceAgent* agent) = 0; + // TODO(hanyangtay): Remove this method once gRPC server clean shutdown is + // supported. + virtual Status StopCoordinationService() = 0; + + private: + ServerInterface(const ServerInterface&) = delete; + void operator=(const ServerInterface&) = delete; +}; + +class ServerFactory { + public: + struct Options { + // Local DeviceMgr to use. + tensorflow::DeviceMgr* local_device_mgr; + }; + // Creates a new server based on the given `server_def`, and stores + // it in `*out_server`. Returns OK on success, otherwise returns an + // error. + virtual Status NewServer(const ServerDef& server_def, const Options& options, + std::unique_ptr* out_server) = 0; + + // Returns true if and only if this factory can create a server + // based on the given `server_def`. + virtual bool AcceptsOptions(const ServerDef& server_def) = 0; + + virtual ~ServerFactory() {} + + // For each `ServerFactory` subclass, an instance of that class must + // be registered by calling this method. + // + // The `server_type` must be unique to the server factory. + static void Register(const string& server_type, ServerFactory* factory); + + // Looks up a factory that can create a server based on the given + // `server_def`, and stores it in `*out_factory`. Returns OK on + // success, otherwise returns an error. + static Status GetFactory(const ServerDef& server_def, + ServerFactory** out_factory); +}; + +// Creates a server based on the given `server_def`, and stores it in +// `*out_server`. Returns OK on success, otherwise returns an error. +Status NewServer(const ServerDef& server_def, + std::unique_ptr* out_server); +Status NewServerWithOptions(const ServerDef& server_def, + const ServerFactory::Options& options, + std::unique_ptr* out_server); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SERVER_LIB_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/session_mgr.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/session_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..fc16faa9ccbc2bf540f6fbb567df1ad3e0795657 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/session_mgr.h @@ -0,0 +1,164 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SESSION_MGR_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SESSION_MGR_H_ + +#include +#include + +#include "tensorflow/core/distributed_runtime/worker_session.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/protobuf/tensorflow_server.pb.h" +#include "tensorflow/core/protobuf/worker.pb.h" +#include "tsl/distributed_runtime/coordination/coordination_service.h" +#include "tsl/distributed_runtime/coordination/coordination_service_agent.h" +#include "tsl/distributed_runtime/coordination/coordination_service_rpc_handler.h" + +namespace tensorflow { + +class WorkerCacheInterface; +struct WorkerEnv; + +// SessionMgr keeps track of information related to a given session. +// +// SessionMgr runs on the workers. +// +// SessionMgr is threadsafe. +class SessionMgr { + public: + typedef std::function + WorkerCacheFactory; + + explicit SessionMgr( + WorkerEnv* worker_env, const std::string& default_worker_name, + std::unique_ptr default_worker_cache, + WorkerCacheFactory worker_cache_factory, + tsl::CoordinationServiceRpcHandler* coordination_handler); + ~SessionMgr() {} + + // Allocates state for a new session. + Status CreateSession( + const std::string& session, const ServerDef& server_def, + bool isolate_session_state, + StatusCallback coordination_error_callback = [](Status s) { + LOG(ERROR) << "Coordination agent is set to error: " << s; + }); + Status CreateSession( + const std::string& session, const ServerDef& server_def, + const protobuf::RepeatedPtrField& device_attributes, + bool isolate_session_state); + + // Create WorkerSession from the master with the given `master_task` and + // `master_incarnation`. We first look for existing WorkerSessions associated + // with the specified master task. If there are sessions created by the same + // master but with a different incarnation, it indicates that the remote + // master has restarted before deleting the sessions on worker. When it + // happens, old sessions associated with the master will be automatically + // removed before the new session is created. + Status CreateSession( + const std::string& session, const ServerDef& server_def, + const protobuf::RepeatedPtrField& device_attributes, + bool isolate_session_state, std::string master_task, + int64_t master_incarnation, + StatusCallback coordination_error_callback = [](Status s) { + LOG(ERROR) << "Coordination agent is set to error: " << s; + }); + + void ResetDefaultWorkerCache(WorkerCacheInterface* worker_cache); + + // Updates state (worker cache, devices) of worker session identified by + // session name (`session`) based on a new server_def and set of devices. + Status UpdateSession(const std::string& session, const ServerDef& server_def, + const protobuf::RepeatedPtrField& + cluster_device_attributes); + + // Locates the worker session for a given session handle + Status WorkerSessionForSession(const std::string& session_handle, + std::shared_ptr* out_session); + std::shared_ptr LegacySession(); + + Status DeleteSession(const std::string& session); + + // Provides access to the coordination service agent. This method should only + // be called after the agent has been initialized during session creation, or + // an invalid nullptr is returned. Note: the agent is thread-safe and mutable. + tsl::CoordinationServiceAgent* GetCoordinationServiceAgent(); + + static std::string WorkerNameFromServerDef(const ServerDef& server_def); + + void SetLogging(bool active); + + void RetrieveLogs(int64_t step_id, LoggingResponse* response); + + void ClearLogs(); + + // Agent should be torn down before service as it needs to disconnect first. + void TeardownCoordinationServiceAgent(); + void TeardownCoordinationService(); + + private: + WorkerEnv* const worker_env_; // Not owned. + + // A note about destruction: + // We must delete graph_mgr before device_mgr, due to shared + // ownership of OpKernels in the executors. (The graph_mgr will + // free all stateless OpKernels, and pass over borrowed stateful + // OpKernels, which are also held in their respective devices' + // OpSegments.) + // + // legacy_session_ owns the worker_env_.device_mgr, and so we must ensure + // that sessions_'s WorkerSessions are deleted (which do not own the + // underlying devices, but instead own RenamedDevices) before + // legacy_session_ is deleted. Further, we must ensure that WorkerSession's + // device_mgr is deleted after WorkerSession's graph_mgr. + + std::unique_ptr default_worker_cache_; + std::shared_ptr legacy_session_; + std::unique_ptr coordination_service_; + std::unique_ptr coordination_service_agent_; + + bool is_logging_active_ = false; + + const WorkerCacheFactory worker_cache_factory_; + + // Not owned. And should only be used for setting the coordination service. + tsl::CoordinationServiceRpcHandler* coordination_handler_ = nullptr; + + Status WorkerSessionForSessionLocked( + const std::string& session_handle, + std::shared_ptr* out_session) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); + + mutex mu_; + // A map from session identifier to internal session structure. + std::map> sessions_ + TF_GUARDED_BY(mu_); + + // Incarnation and WorkerSession handle associated with a master task. + struct MasterAssociatedSession { + const int64_t master_incarnation; + const std::string session_handle; + }; + // A map from master task name to its associated worker sessions. + std::unordered_multimap + master_to_associated_sessions_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_SESSION_MGR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/tensor_coding.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/tensor_coding.h new file mode 100644 index 0000000000000000000000000000000000000000..b517bac4222956e2e87efbae188b9339ae1efabd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/tensor_coding.h @@ -0,0 +1,110 @@ +/* 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_DISTRIBUTED_RUNTIME_TENSOR_CODING_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_TENSOR_CODING_H_ + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace tensorflow { + +class DeviceBase; +class TensorProto; + +// TensorResponse can be used as the destination of an RPC that returns +// a RecvTensorResponse. It efficiently decodes the incoming data +// into Tensor contents as well as associated metadata. +class TensorResponse { + public: + TensorResponse() {} + + // Reset to initial state. + void Clear(); + + // Clear just tensor_ and meta_ members without setting allocation + // related members. + void ClearTensor(); + + // Initialize memory allocation related members. + void InitAlloc(DeviceBase* d, const AllocatorAttributes& aa); + + // Source provides a way for a particular RPC implementation to provide + // received data to ParseFrom. + class Source { + public: + virtual ~Source(); + + // Return the stream that contains the data to be parsed. + // Note that this method might be invoked more than once if + // ParseFrom needs to fall back to a more expensive parsing method. + // Every call must return a stream pointing at the beginning of + // the serialized RecvTensorResponse. + // + // Note that a subsequent call to contents() invalidates previous + // results of contents(). + // + // Ownership of the returned stream is retained by the Source and + // should not be deleted by the caller. + virtual ::tensorflow::protobuf::io::ZeroCopyInputStream* contents() = 0; + }; + + // Parse the RecvTensorResponse encoded in the data yielded by + // source->contents() into *this. + Status ParseFrom(Source* source); + + // Initialize tensor from *response. + // Leaves *response with unspecified contents. + Status InitFrom(RecvTensorResponse* response); + + // Initialize tensor metadata from response and allocate + // uninitialized backing storage for actual contents. + void InitPartial(const RecvTensorResponse& response, + const AllocationAttributes& allocation_attr); + + // Return a reference to the parsed tensor. The tensor will remain + // live only until *this is destroyed or modified. + const Tensor& tensor() const { return tensor_; } + + // Return a reference to the parsed tensor metadata (no contents). + // The result will remain live only until *this is destroyed or + // modified. + const RecvTensorResponse& metadata() const { return meta_; } + + // Return pointer to the device hosting the tensor. + DeviceBase* device() const { return device_; } + + private: + bool ParseTensorSubmessage(protobuf::io::CodedInputStream* input, + TensorProto* tensor_meta); + bool ParseFast(Source* source); + bool ParseSlow(Source* source); + + bool on_host_ = false; + DeviceBase* device_ = nullptr; + AllocatorAttributes alloc_attrs_; + Allocator* allocator_ = nullptr; + bool already_used_ = false; + Tensor tensor_; + RecvTensorResponse meta_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_TENSOR_CODING_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker.h new file mode 100644 index 0000000000000000000000000000000000000000..780976dcab3b190a67990b2139aa43e7198577d7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker.h @@ -0,0 +1,143 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_H_ + +#include + +#include "tensorflow/core/distributed_runtime/graph_mgr.h" +#include "tensorflow/core/distributed_runtime/partial_run_mgr.h" +#include "tensorflow/core/distributed_runtime/recent_request_ids.h" +#include "tensorflow/core/distributed_runtime/session_mgr.h" +#include "tensorflow/core/distributed_runtime/worker_interface.h" +#include "tensorflow/core/framework/cancellation.h" + +namespace tensorflow { + +class Device; +struct WorkerEnv; +class WorkerSession; + +// A TensorFlow Worker runs registered graphs and supports worker-to-worker +// Tensor transfer. +// +// See `../protobuf/worker_service.proto` for more details about each method. +// +// This class may be subclassed to provide specialized implementations of +// particular methods for different transport mechanism. For example, +// `GrpcWorker` specializes the `RecvTensorAsync()` method to support a more +// efficient gRPC data structure for handling large binary data. +class Worker : public WorkerInterface { + public: + Worker(WorkerEnv* env); + virtual ~Worker() {} + + void GetStatusAsync(CallOptions* opts, const GetStatusRequest* request, + GetStatusResponse* response, bool fail_fast, + StatusCallback done) override; + + void CreateWorkerSessionAsync(const CreateWorkerSessionRequest* request, + CreateWorkerSessionResponse* response, + StatusCallback done) override; + + void DeleteWorkerSessionAsync(CallOptions* opts, + const DeleteWorkerSessionRequest* request, + DeleteWorkerSessionResponse* response, + StatusCallback done) override; + + void RegisterGraphAsync(const RegisterGraphRequest* request, + RegisterGraphResponse* response, + StatusCallback done) override; + + void DeregisterGraphAsync(const DeregisterGraphRequest* request, + DeregisterGraphResponse* response, + StatusCallback done) override; + + void RunGraphAsync(CallOptions* opts, RunGraphRequestWrapper* request, + MutableRunGraphResponseWrapper* response, + StatusCallback done) override; + + MutableRunGraphRequestWrapper* CreateRunGraphRequest() override; + + MutableRunGraphResponseWrapper* CreateRunGraphResponse() override; + + void CleanupGraphAsync(const CleanupGraphRequest* request, + CleanupGraphResponse* response, + StatusCallback done) override; + + void CleanupAllAsync(const CleanupAllRequest* request, + CleanupAllResponse* response, + StatusCallback done) override; + + void RecvTensorAsync(CallOptions* opts, const RecvTensorRequest* request, + TensorResponse* response, StatusCallback done) override; + + void LoggingAsync(const LoggingRequest* request, LoggingResponse* response, + StatusCallback done) override; + + void TracingAsync(const TracingRequest* request, TracingResponse* response, + StatusCallback done) override; + + void RecvBufAsync(CallOptions* opts, const RecvBufRequest* request, + RecvBufResponse* response, StatusCallback done) override; + + void CompleteGroupAsync(CallOptions* opts, + const CompleteGroupRequest* request, + CompleteGroupResponse* response, + StatusCallback done) override; + + void CompleteInstanceAsync(CallOptions* opts, + const CompleteInstanceRequest* request, + CompleteInstanceResponse* response, + StatusCallback done) override; + + void GetStepSequenceAsync(const GetStepSequenceRequest* request, + GetStepSequenceResponse* response, + StatusCallback done) override; + + protected: + WorkerEnv* const env_; // Not owned. + RecentRequestIds recent_request_ids_; + + Status PrepareRecvTensor(const Rendezvous::ParsedKey& parsed, + Device** src_dev); + + void AbortStep(int64_t); + + private: + PartialRunMgr partial_run_mgr_; + + CancellationManager cancellation_manager_; + + Status PrepareRunGraph(RunGraphRequestWrapper* req, + GraphMgr::NamedTensors* in, + GraphMgr::NamedTensors* out); + + void DoRunGraph(CallOptions* opts, RunGraphRequestWrapper* request, + MutableRunGraphResponseWrapper* response, + StatusCallback done); + + void DoPartialRunGraph(CallOptions* opts, RunGraphRequestWrapper* request, + MutableRunGraphResponseWrapper* response, + StatusCallback done); + + Worker(const Worker&) = delete; + void operator=(const Worker&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..542ac79334da1753a958b5552dc6a8095f5c6432 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache.h @@ -0,0 +1,96 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_CACHE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_H_ + +#include +#include + +#include "tensorflow/core/distributed_runtime/coordination/coordination_client.h" +#include "tensorflow/core/distributed_runtime/eager/eager_client.h" +#include "tensorflow/core/distributed_runtime/worker_interface.h" +#include "tensorflow/core/framework/device_attributes.pb.h" // for DeviceLocality +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +typedef std::function StatusCallback; + +class ChannelCache; +class StepStats; + +class WorkerCacheInterface { + public: + virtual ~WorkerCacheInterface() {} + + // Updates *workers with strings naming the remote worker tasks to + // which open channels have been established. + virtual void ListWorkers(std::vector* workers) const = 0; + virtual void ListWorkersInJob(const string& job_name, + std::vector* workers) const = 0; + + // If "target" names a remote task for which an RPC channel exists + // or can be constructed, returns a pointer to a WorkerInterface object + // wrapping that channel. The returned value must be destroyed by + // calling `this->ReleaseWorker(target, ret)` + virtual WorkerInterface* GetOrCreateWorker(const string& target) = 0; + + // Release a worker previously returned by this->GetOrCreateWorker(target). + // + // TODO(jeff,sanjay): Consider moving target into WorkerInterface. + // TODO(jeff,sanjay): Unify all worker-cache impls and factor out a + // per-rpc-subsystem WorkerInterface creator. + virtual void ReleaseWorker(const string& target, WorkerInterface* worker) { + // Subclasses may override to reuse worker objects. + delete worker; + } + + // Set *locality with the DeviceLocality of the specified remote device + // within its local environment. Returns true if *locality + // was set, using only locally cached data. Returns false + // if status data for that device was not available. Never blocks. + virtual bool GetDeviceLocalityNonBlocking(const string& device, + DeviceLocality* locality) = 0; + + // Set *locality with the DeviceLocality of the specified remote device + // within its local environment. Callback gets Status::OK if *locality + // was set. + virtual void GetDeviceLocalityAsync(const string& device, + DeviceLocality* locality, + StatusCallback done) = 0; + + // TODO(b/189159585): Define a general client cache maker function to + // construct client cache of different types sharing the same underling RPC + // channels, to replace the eager and coordination cache function. + // Build and return a EagerClientCache object wrapping that channel. + virtual Status GetEagerClientCache( + std::unique_ptr* eager_client_cache) = 0; + + // Build and return a CoordinationClientCache object wrapping that channel. + virtual Status GetCoordinationClientCache( + std::unique_ptr* coordination_client_cache) = 0; + + // Start/stop logging activity. + virtual void SetLogging(bool active) {} + + // Discard any saved log data. + virtual void ClearLogs() {} + + // Return logs for the identified step in *ss. Any returned data will no + // longer be stored. + virtual bool RetrieveLogs(int64_t step_id, StepStats* ss) { return false; } +}; +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_logger.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_logger.h new file mode 100644 index 0000000000000000000000000000000000000000..f5ef19bf6646f7c32291b70f03f5391c79a1117e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_logger.h @@ -0,0 +1,89 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_CACHE_LOGGER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_LOGGER_H_ + +#include +#include + +#include "tensorflow/core/framework/step_stats.pb.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +class StepStatsCollector; + +// WorkerCacheLogger is a thread-safe utility for use by a WorkerCache +// to optionally log some selected RPC activity. A single instance +// should be owned by a WorkerCache, for use by its RemoteWorker +// instances. + +class WorkerCacheLogger { + public: + // Start/Stop logging activity. This function increments/decrements + // a counter so that if two separate steps turn logging on/off, + // logging should be on for the union of the durations of both, + // regardless of relative timing. + void SetLogging(bool v); + + // Discard any saved log data. + void ClearLogs(); + + // Return logs for the identified step in *ss. Any returned data will no + // longer be stored. Returns true iff *ss was modified. + bool RetrieveLogs(int64_t step_id, StepStats* ss); + + // Return true if there is any outstanding request for logging on + // the RPC channels. + bool LoggingActive() { + mutex_lock l(count_mu_); + return want_logging_count_ > 0; + } + + // Generates a NodeExecStats record with the given data, and saves for + // later retrieval by RetrieveLogs(). + void RecordRecvTensor(int64_t step_id, int64_t start_usecs, int64_t end_usecs, + const string& tensor_name, const string& src_device, + const string& dst_device, int64_t bytes); + + // Generates a NodeExecStats record with the given data, and saves for + // later retrieval by RetrieveLogs(). + void RecordDataTransfer(int64_t step_id, int64_t start_usecs, + int64_t end_usecs, const string& tensor_name, + const string& src_device, const string& dst_device, + int64_t bytes, const string& details, + const string& transfer_method_name); + + private: + mutex count_mu_; + int32 want_logging_count_ TF_GUARDED_BY(count_mu_) = 0; + + struct StepLog { + StepStats step_stats; + StepStatsCollector* collector; + }; + typedef std::unordered_map LogMap; + mutex mu_; + LogMap log_map_ TF_GUARDED_BY(mu_); + + // Records "ns" in log_map_ under the given device and step. + void Save(const string& device, int64_t step_id, NodeExecStats* ns); + + void ClearLogsWithLock() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_); +}; +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_LOGGER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_partial.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_partial.h new file mode 100644 index 0000000000000000000000000000000000000000..57f2aca898bef632f8ecc8ddbd6ccaec7cae2c97 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_partial.h @@ -0,0 +1,57 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_CACHE_PARTIAL_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_PARTIAL_H_ + +#include +#include + +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace tensorflow { + +// Implements the part of the interface that caches and returns remote +// device status attributes. +class WorkerCachePartial : public WorkerCacheInterface { + public: + bool GetDeviceLocalityNonBlocking(const string& device, + DeviceLocality* locality) override; + + void GetDeviceLocalityAsync(const string& device, DeviceLocality* locality, + StatusCallback) override; + + ~WorkerCachePartial() override {} + + // Clear all entries from the DeviceStatus cache. + void FlushStatusCache(); + + private: + mutex mu_; + + // Initiate a GetStatusAsync to the remote task named by "task", and + // update the cache with all the DeviceAttributes reported. + Status RefreshDeviceStatus(const string& device_name); + + typedef std::unordered_map StatusMap; + StatusMap device_status_cache_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_PARTIAL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_wrapper.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..195da534b45ce62c45347d2e384a86d546c55c28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_cache_wrapper.h @@ -0,0 +1,100 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_WRAPPER_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_WRAPPER_H_ + +#include +#include + +#include "tensorflow/core/distributed_runtime/worker_cache.h" + +namespace tensorflow { + +class WorkerCacheWrapper : public WorkerCacheInterface { + public: + WorkerCacheWrapper(WorkerCacheInterface* wrapped) : wrapped_(wrapped) {} + + // Updates *workers with strings naming the remote worker tasks to + // which open channels have been established. + void ListWorkers(std::vector* workers) const override { + return wrapped_->ListWorkers(workers); + } + void ListWorkersInJob(const string& job_name, + std::vector* workers) const override { + return wrapped_->ListWorkersInJob(job_name, workers); + } + + // If "target" names a remote task for which an RPC channel exists + // or can be constructed, returns a pointer to a WorkerInterface object + // wrapping that channel. The returned value must be destroyed by + // calling `this->ReleaseWorker(target, ret)` + WorkerInterface* GetOrCreateWorker(const string& target) override { + return wrapped_->GetOrCreateWorker(target); + } + + // Release a worker previously returned by this->GetOrCreateWorker(target). + // + // TODO(jeff,sanjay): Consider moving target into WorkerInterface. + // TODO(jeff,sanjay): Unify all worker-cache impls and factor out a + // per-rpc-subsystem WorkerInterface creator. + void ReleaseWorker(const string& target, WorkerInterface* worker) override { + return wrapped_->ReleaseWorker(target, worker); + } + + Status GetEagerClientCache( + std::unique_ptr* eager_client_cache) override { + return wrapped_->GetEagerClientCache(eager_client_cache); + } + + Status GetCoordinationClientCache(std::unique_ptr* + coordination_client_cache) override { + return wrapped_->GetCoordinationClientCache(coordination_client_cache); + } + + // Set *locality with the DeviceLocality of the specified remote device + // within its local environment. Returns true if *locality + // was set, using only locally cached data. Returns false + // if status data for that device was not available. Never blocks. + bool GetDeviceLocalityNonBlocking(const string& device, + DeviceLocality* locality) override { + return wrapped_->GetDeviceLocalityNonBlocking(device, locality); + } + + // Set *locality with the DeviceLocality of the specified remote device + // within its local environment. Callback gets Status::OK if *locality + // was set. + void GetDeviceLocalityAsync(const string& device, DeviceLocality* locality, + StatusCallback done) override { + return wrapped_->GetDeviceLocalityAsync(device, locality, std::move(done)); + } + + // Start/stop logging activity. + void SetLogging(bool active) override { wrapped_->SetLogging(active); } + + // Discard any saved log data. + void ClearLogs() override { wrapped_->ClearLogs(); } + + // Return logs for the identified step in *ss. Any returned data will no + // longer be stored. + bool RetrieveLogs(int64_t step_id, StepStats* ss) override { + return wrapped_->RetrieveLogs(step_id, ss); + } + + private: + WorkerCacheInterface* wrapped_; // Not owned. +}; +} // namespace tensorflow +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_CACHE_WRAPPER_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_env.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_env.h new file mode 100644 index 0000000000000000000000000000000000000000..350c3e5fa16399743baa55d0a2e717efb79985d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_env.h @@ -0,0 +1,79 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_ENV_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_ENV_H_ + +#include + +#include "tensorflow/core/platform/types.h" + +namespace tsl { +class Env; +namespace thread { +class ThreadPool; +} // namespace thread +} // namespace tsl +namespace tensorflow { +using Env = tsl::Env; + +namespace thread { +using tsl::thread::ThreadPool; +} // namespace thread + +class CollectiveExecutorMgrInterface; +class Device; +class DeviceMgr; +class RendezvousMgrInterface; +class SessionMgr; + +// The worker environment class, which holds a bag of pointers to +// per-worker singletons. +// +// WorkerEnv does not own its member pointers. +struct WorkerEnv { + Env* env = nullptr; + + // session_mgr encapsulates state for each session. + SessionMgr* session_mgr = nullptr; + + // In large scaled distributed training, many singleton components (e.g. + // Rendezvous) can becomes the bottleneck of the system. This field allows + // us to shard the single components. This number will scale up with number + // of tasks in this cluster. It is always greater than 1. + int experimental_num_shards = 1; + + // device_mgr manages local devices (cpu and gpu). The WorkerService + // is the network interface for managed devices. + // + // Note: Please use the device_mgr associated with your session if appropriate + // instead of this one. Using this device_mgr does not support ClusterSpec + // propagated sessions. + DeviceMgr* device_mgr = nullptr; + + // A set of rendezvous keyed by step ids. + RendezvousMgrInterface* rendezvous_mgr = nullptr; + + // Generates per-step CollectiveExecutors and has access to utilities + // supporting collective operations. + std::unique_ptr collective_executor_mgr; + + // A pool of threads for scheduling compute work. + thread::ThreadPool* compute_pool = nullptr; +}; + +} // end namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_ENV_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_interface.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..7b759eef95b9dfbe8f9a57df8b82c09a16823b88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_interface.h @@ -0,0 +1,234 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_INTERFACE_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_INTERFACE_H_ + +#include + +#include "tensorflow/core/distributed_runtime/call_options.h" +#include "tensorflow/core/distributed_runtime/message_wrappers.h" +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/worker.pb.h" + +namespace tensorflow { + +// Status callback. +typedef std::function StatusCallback; + +// Custom decoder for a response to RecvTensorAsync. +class TensorResponse; + +// Interface for talking with the TensorFlow Worker service. +class WorkerInterface { + public: + virtual void GetStatusAsync(CallOptions* opts, + const GetStatusRequest* request, + GetStatusResponse* response, bool fail_fast, + StatusCallback done) = 0; + + virtual void CreateWorkerSessionAsync( + const CreateWorkerSessionRequest* request, + CreateWorkerSessionResponse* response, StatusCallback done) = 0; + + virtual void DeleteWorkerSessionAsync( + CallOptions* opts, const DeleteWorkerSessionRequest* request, + DeleteWorkerSessionResponse* response, StatusCallback done) = 0; + + virtual void RegisterGraphAsync(const RegisterGraphRequest* request, + RegisterGraphResponse* response, + StatusCallback done) = 0; + + virtual void DeregisterGraphAsync(const DeregisterGraphRequest* request, + DeregisterGraphResponse* response, + StatusCallback done) = 0; + + virtual void RunGraphAsync(CallOptions* opts, RunGraphRequestWrapper* request, + MutableRunGraphResponseWrapper* response, + StatusCallback done) = 0; + + virtual void RunGraphAsync(CallOptions* opts, const RunGraphRequest* request, + RunGraphResponse* response, StatusCallback done) { + RunGraphRequestWrapper* wrapped_request = new ProtoRunGraphRequest(request); + MutableRunGraphResponseWrapper* wrapped_response = + new NonOwnedProtoRunGraphResponse(response); + RunGraphAsync(opts, wrapped_request, wrapped_response, + [wrapped_request, wrapped_response, + done = std::move(done)](const Status& s) { + done(s); + delete wrapped_request; + delete wrapped_response; + }); + } + + // Returns a request object for use in calls to + // `RunGraphAsync()`. Ownership is transferred to the caller. + // + // The message returned from this method must only be used in a + // `RunGraph()` call on the same `WorkerInterface` instance. + virtual MutableRunGraphRequestWrapper* CreateRunGraphRequest() { + return new MutableProtoRunGraphRequest; + } + + // Returns a response object for use in calls to + // `RunGraphAsync()`. Ownership is transferred to the caller. + // + // The message returned from this method must only be used in a + // `RunGraph()` call on the same `WorkerInterface` instance. + virtual MutableRunGraphResponseWrapper* CreateRunGraphResponse() { + return new OwnedProtoRunGraphResponse; + } + + virtual void CleanupGraphAsync(const CleanupGraphRequest* request, + CleanupGraphResponse* response, + StatusCallback done) = 0; + + virtual void CleanupAllAsync(const CleanupAllRequest* request, + CleanupAllResponse* response, + StatusCallback done) = 0; + + virtual void RecvTensorAsync(CallOptions* opts, + const RecvTensorRequest* request, + TensorResponse* response, + StatusCallback done) = 0; + + virtual void LoggingAsync(const LoggingRequest* request, + LoggingResponse* response, StatusCallback done) = 0; + + virtual void TracingAsync(const TracingRequest* request, + TracingResponse* response, StatusCallback done) = 0; + + virtual void RecvBufAsync(CallOptions* opts, const RecvBufRequest* request, + RecvBufResponse* response, StatusCallback done) = 0; + + virtual void CompleteGroupAsync(CallOptions* opts, + const CompleteGroupRequest* request, + CompleteGroupResponse* response, + StatusCallback done) = 0; + + virtual void CompleteInstanceAsync(CallOptions* ops, + const CompleteInstanceRequest* request, + CompleteInstanceResponse* response, + StatusCallback done) = 0; + + virtual void GetStepSequenceAsync(const GetStepSequenceRequest* request, + GetStepSequenceResponse* response, + StatusCallback done) = 0; + + Status GetStatus(const GetStatusRequest* request, + GetStatusResponse* response) { + Status ret; + Notification n; + GetStatusAsync(/*opts=*/nullptr, request, response, /*fail_fast=*/true, + [&ret, &n](const Status& s) { + ret = s; + n.Notify(); + }); + n.WaitForNotification(); + return ret; + } + + Status CreateWorkerSession(const CreateWorkerSessionRequest* request, + CreateWorkerSessionResponse* response) { + return CallAndWait(&ME::CreateWorkerSessionAsync, request, response); + } + + Status DeleteWorkerSession(const DeleteWorkerSessionRequest* request, + DeleteWorkerSessionResponse* response) { + return CallAndWaitWithOptions(&ME::DeleteWorkerSessionAsync, request, + response); + } + + Status RegisterGraph(const RegisterGraphRequest* request, + RegisterGraphResponse* response) { + return CallAndWait(&ME::RegisterGraphAsync, request, response); + } + + Status DeregisterGraph(const DeregisterGraphRequest* request, + DeregisterGraphResponse* response) { + return CallAndWait(&ME::DeregisterGraphAsync, request, response); + } + + Status CleanupGraph(const CleanupGraphRequest* request, + CleanupGraphResponse* response) { + return CallAndWait(&ME::CleanupGraphAsync, request, response); + } + + Status CleanupAll(const CleanupAllRequest* request, + CleanupAllResponse* response) { + return CallAndWait(&ME::CleanupAllAsync, request, response); + } + + Status Logging(const LoggingRequest* request, LoggingResponse* response) { + return CallAndWait(&ME::LoggingAsync, request, response); + } + + Status Tracing(const TracingRequest* request, TracingResponse* response) { + return CallAndWait(&ME::TracingAsync, request, response); + } + + Status GetStepSequence(const GetStepSequenceRequest* request, + GetStepSequenceResponse* response) { + return CallAndWait(&ME::GetStepSequenceAsync, request, response); + } + + protected: + // Instances of WorkerInterface must be deleted by a call to + // WorkerCacheInterface::ReleaseWorker(). + virtual ~WorkerInterface() {} + friend class WorkerCacheInterface; + + // NOTE: This should only be called by implementations of this + // interface whose CreateRunGraphResponse() method returns a + // proto-based wrappers for the RunGraphResponse message. + RunGraphResponse* get_proto_from_wrapper( + MutableRunGraphResponseWrapper* wrapper) { + return wrapper->get_proto(); + } + + private: + typedef WorkerInterface ME; + + template + Status CallAndWait(Method func, const Req* req, Resp* resp) { + Status ret; + Notification n; + (this->*func)(req, resp, [&ret, &n](const Status& s) { + ret = s; + n.Notify(); + }); + n.WaitForNotification(); + return ret; + } + + template + Status CallAndWaitWithOptions(Method func, const Req* req, Resp* resp) { + CallOptions call_opts; + Status ret; + Notification n; + (this->*func)(&call_opts, req, resp, [&ret, &n](const Status& s) { + ret = s; + n.Notify(); + }); + n.WaitForNotification(); + return ret; + } +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_INTERFACE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_session.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_session.h new file mode 100644 index 0000000000000000000000000000000000000000..b97fe1a99292d9428d4d34ccf72d4b6de5033194 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/distributed_runtime/worker_session.h @@ -0,0 +1,134 @@ +/* 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_DISTRIBUTED_RUNTIME_WORKER_SESSION_H_ +#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_SESSION_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/distributed_runtime/graph_mgr.h" +#include "tensorflow/core/distributed_runtime/worker_cache.h" +#include "tensorflow/core/framework/function.h" + +namespace tensorflow { + +class ClusterFunctionLibraryRuntime; +class GraphMgr; +class WorkerCacheInterface; + +// WorkerSession encapsulates all of the state relating to a given session. +class WorkerSession { + public: + using DistributedFunctionLibraryRuntimeCreator = + std::function( + WorkerSession* worker_session, bool create_worker_session_called, + DeviceMgr* remote_device_mgr)>; + + // Collection of local devices. These devices are typically + // RenamedDevices in all except the SessionMgr.legacy_session_ and + // sessions created with `isolate_session_state == false`. In the + // those cases, this method returns a pointer to a borrowed + // DeviceMgr (typically the `worker_env.device_mgr`). + DeviceMgr* device_mgr() { + return device_mgr_ ? device_mgr_.get() : borrowed_device_mgr_; + } + + DynamicDeviceMgr* remote_device_mgr() { return remote_device_mgr_.get(); } + + const string& session_name() const { return session_name_; } + const string& worker_name() const { return worker_name_; } + + WorkerCacheInterface* worker_cache() const { + tf_shared_lock l(worker_session_state_mu_); + return worker_cache_.get(); + } + GraphMgr* graph_mgr() const { return graph_mgr_.get(); } + + DistributedFunctionLibraryRuntime* cluster_flr() const { + return cluster_flr_.get(); + } + + WorkerSession(const string& session_name, const string& worker_name, + std::unique_ptr worker_cache, + std::unique_ptr device_mgr, + std::unique_ptr graph_mgr, + std::unique_ptr remote_device_mgr, + DistributedFunctionLibraryRuntimeCreator cluster_flr_creator); + + static std::shared_ptr CreateWithBorrowedDeviceMgr( + const string& session_name, const string& worker_name, + std::unique_ptr worker_cache, + DeviceMgr* borrowed_device_mgr, std::unique_ptr graph_mgr, + std::unique_ptr remote_device_mgr, + DistributedFunctionLibraryRuntimeCreator cluster_flr_creator); + + // In the eager runtime we allow WorkerSession to be updated, where the + // worker cache will be recreated. If WorkerSession upate is expected and a + // worker in the cache is used in RPCs, the caller should hold a shared + // pointer to avoid the workers getting deleted. + std::shared_ptr GetSharedWorkerCache() { + tf_shared_lock l(worker_session_state_mu_); + return worker_cache_; + } + + // Update an existing worker session with new set of remote workers and + // devices. Added devices will be owned by the worker session, and removed + // devices will be freed by their names. + Status UpdateWorkerCacheAndDevices( + std::unique_ptr new_worker_cache, + std::vector> added_remote_devices, + const std::vector& removed_remote_devices); + + ~WorkerSession(); + + private: + WorkerSession(const string& session_name, const string& worker_name, + std::unique_ptr worker_cache, + DeviceMgr* borrowed_device_mgr, + std::unique_ptr graph_mgr, + std::unique_ptr remote_device_mgr, + DistributedFunctionLibraryRuntimeCreator cluster_flr_creator); + + // The name of the session. + const string session_name_; + + // The name of the worker. E.g., /job:mnist/replica:0/task:1. + const string worker_name_; + + mutable mutex worker_session_state_mu_; + // Object from which WorkerInterface instances can be obtained. + std::shared_ptr worker_cache_ + TF_GUARDED_BY(worker_session_state_mu_); + + // graph_mgr keeps track of the registered graphs of this session. + // + // Note: graph_mgr must be deleted before rendezvous_mgr! + // Note: graph_mgr must be deleted before device_mgr! + const std::unique_ptr graph_mgr_; + + std::unique_ptr cluster_flr_; + + const std::unique_ptr device_mgr_; + DeviceMgr* const borrowed_device_mgr_; // Not owned. + std::unique_ptr remote_device_mgr_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_SESSION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..f673e27ee05554399e18dd7ae59b71d5a9b8336b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example.pb.h @@ -0,0 +1,679 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/example/example.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fexample_2fexample_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fexample_2fexample_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/example/feature.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2fexample_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_2fexample_2fexample_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fexample_2fexample_2eproto; +namespace tensorflow { +class Example; +struct ExampleDefaultTypeInternal; +extern ExampleDefaultTypeInternal _Example_default_instance_; +class SequenceExample; +struct SequenceExampleDefaultTypeInternal; +extern SequenceExampleDefaultTypeInternal _SequenceExample_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::Example* Arena::CreateMaybeMessage<::tensorflow::Example>(Arena*); +template<> ::tensorflow::SequenceExample* Arena::CreateMaybeMessage<::tensorflow::SequenceExample>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class Example final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.Example) */ { + public: + inline Example() : Example(nullptr) {} + ~Example() override; + explicit PROTOBUF_CONSTEXPR Example(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Example(const Example& from); + Example(Example&& from) noexcept + : Example() { + *this = ::std::move(from); + } + + inline Example& operator=(const Example& from) { + CopyFrom(from); + return *this; + } + inline Example& operator=(Example&& 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 Example& default_instance() { + return *internal_default_instance(); + } + static inline const Example* internal_default_instance() { + return reinterpret_cast( + &_Example_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(Example& a, Example& b) { + a.Swap(&b); + } + inline void Swap(Example* 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(Example* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Example* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Example& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const Example& from) { + Example::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(Example* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.Example"; + } + protected: + explicit Example(::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 { + kFeaturesFieldNumber = 1, + }; + // .tensorflow.Features features = 1; + bool has_features() const; + private: + bool _internal_has_features() const; + public: + void clear_features(); + const ::tensorflow::Features& features() const; + PROTOBUF_NODISCARD ::tensorflow::Features* release_features(); + ::tensorflow::Features* mutable_features(); + void set_allocated_features(::tensorflow::Features* features); + private: + const ::tensorflow::Features& _internal_features() const; + ::tensorflow::Features* _internal_mutable_features(); + public: + void unsafe_arena_set_allocated_features( + ::tensorflow::Features* features); + ::tensorflow::Features* unsafe_arena_release_features(); + + // @@protoc_insertion_point(class_scope:tensorflow.Example) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::Features* features_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_2eproto; +}; +// ------------------------------------------------------------------- + +class SequenceExample final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.SequenceExample) */ { + public: + inline SequenceExample() : SequenceExample(nullptr) {} + ~SequenceExample() override; + explicit PROTOBUF_CONSTEXPR SequenceExample(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + SequenceExample(const SequenceExample& from); + SequenceExample(SequenceExample&& from) noexcept + : SequenceExample() { + *this = ::std::move(from); + } + + inline SequenceExample& operator=(const SequenceExample& from) { + CopyFrom(from); + return *this; + } + inline SequenceExample& operator=(SequenceExample&& 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 SequenceExample& default_instance() { + return *internal_default_instance(); + } + static inline const SequenceExample* internal_default_instance() { + return reinterpret_cast( + &_SequenceExample_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(SequenceExample& a, SequenceExample& b) { + a.Swap(&b); + } + inline void Swap(SequenceExample* 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(SequenceExample* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + SequenceExample* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const SequenceExample& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const SequenceExample& from) { + SequenceExample::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(SequenceExample* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.SequenceExample"; + } + protected: + explicit SequenceExample(::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 { + kContextFieldNumber = 1, + kFeatureListsFieldNumber = 2, + }; + // .tensorflow.Features context = 1; + bool has_context() const; + private: + bool _internal_has_context() const; + public: + void clear_context(); + const ::tensorflow::Features& context() const; + PROTOBUF_NODISCARD ::tensorflow::Features* release_context(); + ::tensorflow::Features* mutable_context(); + void set_allocated_context(::tensorflow::Features* context); + private: + const ::tensorflow::Features& _internal_context() const; + ::tensorflow::Features* _internal_mutable_context(); + public: + void unsafe_arena_set_allocated_context( + ::tensorflow::Features* context); + ::tensorflow::Features* unsafe_arena_release_context(); + + // .tensorflow.FeatureLists feature_lists = 2; + bool has_feature_lists() const; + private: + bool _internal_has_feature_lists() const; + public: + void clear_feature_lists(); + const ::tensorflow::FeatureLists& feature_lists() const; + PROTOBUF_NODISCARD ::tensorflow::FeatureLists* release_feature_lists(); + ::tensorflow::FeatureLists* mutable_feature_lists(); + void set_allocated_feature_lists(::tensorflow::FeatureLists* feature_lists); + private: + const ::tensorflow::FeatureLists& _internal_feature_lists() const; + ::tensorflow::FeatureLists* _internal_mutable_feature_lists(); + public: + void unsafe_arena_set_allocated_feature_lists( + ::tensorflow::FeatureLists* feature_lists); + ::tensorflow::FeatureLists* unsafe_arena_release_feature_lists(); + + // @@protoc_insertion_point(class_scope:tensorflow.SequenceExample) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::Features* context_; + ::tensorflow::FeatureLists* feature_lists_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// Example + +// .tensorflow.Features features = 1; +inline bool Example::_internal_has_features() const { + return this != internal_default_instance() && _impl_.features_ != nullptr; +} +inline bool Example::has_features() const { + return _internal_has_features(); +} +inline const ::tensorflow::Features& Example::_internal_features() const { + const ::tensorflow::Features* p = _impl_.features_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_Features_default_instance_); +} +inline const ::tensorflow::Features& Example::features() const { + // @@protoc_insertion_point(field_get:tensorflow.Example.features) + return _internal_features(); +} +inline void Example::unsafe_arena_set_allocated_features( + ::tensorflow::Features* features) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.features_); + } + _impl_.features_ = features; + if (features) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.Example.features) +} +inline ::tensorflow::Features* Example::release_features() { + + ::tensorflow::Features* temp = _impl_.features_; + _impl_.features_ = 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::Features* Example::unsafe_arena_release_features() { + // @@protoc_insertion_point(field_release:tensorflow.Example.features) + + ::tensorflow::Features* temp = _impl_.features_; + _impl_.features_ = nullptr; + return temp; +} +inline ::tensorflow::Features* Example::_internal_mutable_features() { + + if (_impl_.features_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::Features>(GetArenaForAllocation()); + _impl_.features_ = p; + } + return _impl_.features_; +} +inline ::tensorflow::Features* Example::mutable_features() { + ::tensorflow::Features* _msg = _internal_mutable_features(); + // @@protoc_insertion_point(field_mutable:tensorflow.Example.features) + return _msg; +} +inline void Example::set_allocated_features(::tensorflow::Features* features) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.features_); + } + if (features) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(features)); + if (message_arena != submessage_arena) { + features = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, features, submessage_arena); + } + + } else { + + } + _impl_.features_ = features; + // @@protoc_insertion_point(field_set_allocated:tensorflow.Example.features) +} + +// ------------------------------------------------------------------- + +// SequenceExample + +// .tensorflow.Features context = 1; +inline bool SequenceExample::_internal_has_context() const { + return this != internal_default_instance() && _impl_.context_ != nullptr; +} +inline bool SequenceExample::has_context() const { + return _internal_has_context(); +} +inline const ::tensorflow::Features& SequenceExample::_internal_context() const { + const ::tensorflow::Features* p = _impl_.context_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_Features_default_instance_); +} +inline const ::tensorflow::Features& SequenceExample::context() const { + // @@protoc_insertion_point(field_get:tensorflow.SequenceExample.context) + return _internal_context(); +} +inline void SequenceExample::unsafe_arena_set_allocated_context( + ::tensorflow::Features* context) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.context_); + } + _impl_.context_ = context; + if (context) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.SequenceExample.context) +} +inline ::tensorflow::Features* SequenceExample::release_context() { + + ::tensorflow::Features* temp = _impl_.context_; + _impl_.context_ = 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::Features* SequenceExample::unsafe_arena_release_context() { + // @@protoc_insertion_point(field_release:tensorflow.SequenceExample.context) + + ::tensorflow::Features* temp = _impl_.context_; + _impl_.context_ = nullptr; + return temp; +} +inline ::tensorflow::Features* SequenceExample::_internal_mutable_context() { + + if (_impl_.context_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::Features>(GetArenaForAllocation()); + _impl_.context_ = p; + } + return _impl_.context_; +} +inline ::tensorflow::Features* SequenceExample::mutable_context() { + ::tensorflow::Features* _msg = _internal_mutable_context(); + // @@protoc_insertion_point(field_mutable:tensorflow.SequenceExample.context) + return _msg; +} +inline void SequenceExample::set_allocated_context(::tensorflow::Features* context) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.context_); + } + if (context) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(context)); + if (message_arena != submessage_arena) { + context = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, context, submessage_arena); + } + + } else { + + } + _impl_.context_ = context; + // @@protoc_insertion_point(field_set_allocated:tensorflow.SequenceExample.context) +} + +// .tensorflow.FeatureLists feature_lists = 2; +inline bool SequenceExample::_internal_has_feature_lists() const { + return this != internal_default_instance() && _impl_.feature_lists_ != nullptr; +} +inline bool SequenceExample::has_feature_lists() const { + return _internal_has_feature_lists(); +} +inline const ::tensorflow::FeatureLists& SequenceExample::_internal_feature_lists() const { + const ::tensorflow::FeatureLists* p = _impl_.feature_lists_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_FeatureLists_default_instance_); +} +inline const ::tensorflow::FeatureLists& SequenceExample::feature_lists() const { + // @@protoc_insertion_point(field_get:tensorflow.SequenceExample.feature_lists) + return _internal_feature_lists(); +} +inline void SequenceExample::unsafe_arena_set_allocated_feature_lists( + ::tensorflow::FeatureLists* feature_lists) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.feature_lists_); + } + _impl_.feature_lists_ = feature_lists; + if (feature_lists) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.SequenceExample.feature_lists) +} +inline ::tensorflow::FeatureLists* SequenceExample::release_feature_lists() { + + ::tensorflow::FeatureLists* temp = _impl_.feature_lists_; + _impl_.feature_lists_ = 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::FeatureLists* SequenceExample::unsafe_arena_release_feature_lists() { + // @@protoc_insertion_point(field_release:tensorflow.SequenceExample.feature_lists) + + ::tensorflow::FeatureLists* temp = _impl_.feature_lists_; + _impl_.feature_lists_ = nullptr; + return temp; +} +inline ::tensorflow::FeatureLists* SequenceExample::_internal_mutable_feature_lists() { + + if (_impl_.feature_lists_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::FeatureLists>(GetArenaForAllocation()); + _impl_.feature_lists_ = p; + } + return _impl_.feature_lists_; +} +inline ::tensorflow::FeatureLists* SequenceExample::mutable_feature_lists() { + ::tensorflow::FeatureLists* _msg = _internal_mutable_feature_lists(); + // @@protoc_insertion_point(field_mutable:tensorflow.SequenceExample.feature_lists) + return _msg; +} +inline void SequenceExample::set_allocated_feature_lists(::tensorflow::FeatureLists* feature_lists) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.feature_lists_); + } + if (feature_lists) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(feature_lists)); + if (message_arena != submessage_arena) { + feature_lists = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, feature_lists, submessage_arena); + } + + } else { + + } + _impl_.feature_lists_ = feature_lists; + // @@protoc_insertion_point(field_set_allocated:tensorflow.SequenceExample.feature_lists) +} + +#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_2fexample_2fexample_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example.proto new file mode 100644 index 0000000000000000000000000000000000000000..9f762fb51136992a73a95de1fa08cd4b5676a624 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example.proto @@ -0,0 +1,301 @@ +// Protocol messages for describing input data Examples for machine learning +// model training or inference. +syntax = "proto3"; + +package tensorflow; + +import "tensorflow/core/example/feature.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "ExampleProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.example"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/example/example_protos_go_proto"; + +// An Example is a mostly-normalized data format for storing data for +// training and inference. It contains a key-value store (features); where +// each key (string) maps to a Feature message (which is oneof packed BytesList, +// FloatList, or Int64List). This flexible and compact format allows the +// storage of large amounts of typed data, but requires that the data shape +// and use be determined by the configuration files and parsers that are used to +// read and write this format. That is, the Example is mostly *not* a +// self-describing format. In TensorFlow, Examples are read in row-major +// format, so any configuration that describes data with rank-2 or above +// should keep this in mind. If you flatten a matrix into a FloatList it should +// be stored as [ row 0 ... row 1 ... row M-1 ] +// +// An Example for a movie recommendation application: +// features { +// feature { +// key: "age" +// value { float_list { +// value: 29.0 +// }} +// } +// feature { +// key: "movie" +// value { bytes_list { +// value: "The Shawshank Redemption" +// value: "Fight Club" +// }} +// } +// feature { +// key: "movie_ratings" +// value { float_list { +// value: 9.0 +// value: 9.7 +// }} +// } +// feature { +// key: "suggestion" +// value { bytes_list { +// value: "Inception" +// }} +// } +// # Note that this feature exists to be used as a label in training. +// # E.g., if training a logistic regression model to predict purchase +// # probability in our learning tool we would set the label feature to +// # "suggestion_purchased". +// feature { +// key: "suggestion_purchased" +// value { float_list { +// value: 1.0 +// }} +// } +// # Similar to "suggestion_purchased" above this feature exists to be used +// # as a label in training. +// # E.g., if training a linear regression model to predict purchase +// # price in our learning tool we would set the label feature to +// # "purchase_price". +// feature { +// key: "purchase_price" +// value { float_list { +// value: 9.99 +// }} +// } +// } +// +// A conformant Example data set obeys the following conventions: +// - If a Feature K exists in one example with data type T, it must be of +// type T in all other examples when present. It may be omitted. +// - The number of instances of Feature K list data may vary across examples, +// depending on the requirements of the model. +// - If a Feature K doesn't exist in an example, a K-specific default will be +// used, if configured. +// - If a Feature K exists in an example but contains no items, the intent +// is considered to be an empty tensor and no default will be used. + +message Example { + Features features = 1; +} + +// A SequenceExample is an Example representing one or more sequences, and +// some context. The context contains features which apply to the entire +// example. The feature_lists contain a key, value map where each key is +// associated with a repeated set of Features (a FeatureList). +// A FeatureList thus represents the values of a feature identified by its key +// over time / frames. +// +// Below is a SequenceExample for a movie recommendation application recording a +// sequence of ratings by a user. The time-independent features ("locale", +// "age", "favorites") describing the user are part of the context. The sequence +// of movies the user rated are part of the feature_lists. For each movie in the +// sequence we have information on its name and actors and the user's rating. +// This information is recorded in three separate feature_list(s). +// In the example below there are only two movies. All three feature_list(s), +// namely "movie_ratings", "movie_names", and "actors" have a feature value for +// both movies. Note, that "actors" is itself a bytes_list with multiple +// strings per movie. +// +// context: { +// feature: { +// key : "locale" +// value: { +// bytes_list: { +// value: [ "pt_BR" ] +// } +// } +// } +// feature: { +// key : "age" +// value: { +// float_list: { +// value: [ 19.0 ] +// } +// } +// } +// feature: { +// key : "favorites" +// value: { +// bytes_list: { +// value: [ "Majesty Rose", "Savannah Outen", "One Direction" ] +// } +// } +// } +// } +// feature_lists: { +// feature_list: { +// key : "movie_ratings" +// value: { +// feature: { +// float_list: { +// value: [ 4.5 ] +// } +// } +// feature: { +// float_list: { +// value: [ 5.0 ] +// } +// } +// } +// } +// feature_list: { +// key : "movie_names" +// value: { +// feature: { +// bytes_list: { +// value: [ "The Shawshank Redemption" ] +// } +// } +// feature: { +// bytes_list: { +// value: [ "Fight Club" ] +// } +// } +// } +// } +// feature_list: { +// key : "actors" +// value: { +// feature: { +// bytes_list: { +// value: [ "Tim Robbins", "Morgan Freeman" ] +// } +// } +// feature: { +// bytes_list: { +// value: [ "Brad Pitt", "Edward Norton", "Helena Bonham Carter" ] +// } +// } +// } +// } +// } +// +// A conformant SequenceExample data set obeys the following conventions: +// +// Context: +// - All conformant context features K must obey the same conventions as +// a conformant Example's features (see above). +// Feature lists: +// - A FeatureList L may be missing in an example; it is up to the +// parser configuration to determine if this is allowed or considered +// an empty list (zero length). +// - If a FeatureList L exists, it may be empty (zero length). +// - If a FeatureList L is non-empty, all features within the FeatureList +// must have the same data type T. Even across SequenceExamples, the type T +// of the FeatureList identified by the same key must be the same. An entry +// without any values may serve as an empty feature. +// - If a FeatureList L is non-empty, it is up to the parser configuration +// to determine if all features within the FeatureList must +// have the same size. The same holds for this FeatureList across multiple +// examples. +// - For sequence modeling, e.g.: +// http://colah.github.io/posts/2015-08-Understanding-LSTMs/ +// https://github.com/tensorflow/nmt +// the feature lists represent a sequence of frames. +// In this scenario, all FeatureLists in a SequenceExample have the same +// number of Feature messages, so that the ith element in each FeatureList +// is part of the ith frame (or time step). +// Examples of conformant and non-conformant examples' FeatureLists: +// +// Conformant FeatureLists: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } } +// } } +// +// Non-conformant FeatureLists (mismatched types): +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { int64_list: { value: [ 5 ] } } } +// } } +// +// Conditionally conformant FeatureLists, the parser configuration determines +// if the feature sizes must match: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0, 6.0 ] } } } +// } } +// +// Conformant pair of SequenceExample +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } } +// } } +// and: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } +// feature: { float_list: { value: [ 2.0 ] } } } +// } } +// +// Conformant pair of SequenceExample +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } } +// } } +// and: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { } +// } } +// +// Conditionally conformant pair of SequenceExample, the parser configuration +// determines if the second feature_lists is consistent (zero-length) or +// invalid (missing "movie_ratings"): +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } } +// } } +// and: +// feature_lists: { } +// +// Non-conformant pair of SequenceExample (mismatched types) +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } } +// } } +// and: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { int64_list: { value: [ 4 ] } } +// feature: { int64_list: { value: [ 5 ] } } +// feature: { int64_list: { value: [ 2 ] } } } +// } } +// +// Conditionally conformant pair of SequenceExample; the parser configuration +// determines if the feature sizes must match: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.5 ] } } +// feature: { float_list: { value: [ 5.0 ] } } } +// } } +// and: +// feature_lists: { feature_list: { +// key: "movie_ratings" +// value: { feature: { float_list: { value: [ 4.0 ] } } +// feature: { float_list: { value: [ 5.0, 3.0 ] } } +// } } + +message SequenceExample { + Features context = 1; + FeatureLists feature_lists = 2; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.h new file mode 100644 index 0000000000000000000000000000000000000000..8bbed28471d5a7123a7a5840a99665bd9cb530f3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.h @@ -0,0 +1,56 @@ +/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_EXAMPLE_EXAMPLE_PARSER_CONFIGURATION_H_ +#define TENSORFLOW_CORE_EXAMPLE_EXAMPLE_PARSER_CONFIGURATION_H_ + +#include +#include + +#include "tensorflow/core/example/example.pb.h" +#include "tensorflow/core/example/example_parser_configuration.pb.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session.h" +#include "tensorflow/core/util/example_proto_helper.h" +#include "tensorflow/core/util/sparse/sparse_tensor.h" + +// This is a set of helper methods that will make it possible to share +// tensorflow::Example proto Tensor conversion code inside the ExampleParserOp +// OpKernel as well as in external code. +namespace tensorflow { + +// Given a graph and the node_name of a ParseExample op, +// extract the FixedLenFeature/VarLenFeature configurations. +Status ExtractExampleParserConfiguration( + const tensorflow::GraphDef& graph, const string& node_name, + tensorflow::Session* session, + std::vector* fixed_len_features, + std::vector* var_len_features); + +// Given a config proto, ostensibly extracted via python, +// fill a vector of C++ structs suitable for calling +// the tensorflow.Example -> Tensor conversion code. +Status ExampleParserConfigurationProtoToFeatureVectors( + const ExampleParserConfiguration& config_proto, + std::vector* fixed_len_features, + std::vector* var_len_features); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_EXAMPLE_EXAMPLE_PARSER_CONFIGURATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..f321972e5684e6c05c7ceb561b8930c1a584f59a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.pb.h @@ -0,0 +1,1504 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/example/example_parser_configuration.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include "tensorflow/core/framework/tensor.pb.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_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_2fexample_2fexample_5fparser_5fconfiguration_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto; +namespace tensorflow { +class ExampleParserConfiguration; +struct ExampleParserConfigurationDefaultTypeInternal; +extern ExampleParserConfigurationDefaultTypeInternal _ExampleParserConfiguration_default_instance_; +class ExampleParserConfiguration_FeatureMapEntry_DoNotUse; +struct ExampleParserConfiguration_FeatureMapEntry_DoNotUseDefaultTypeInternal; +extern ExampleParserConfiguration_FeatureMapEntry_DoNotUseDefaultTypeInternal _ExampleParserConfiguration_FeatureMapEntry_DoNotUse_default_instance_; +class FeatureConfiguration; +struct FeatureConfigurationDefaultTypeInternal; +extern FeatureConfigurationDefaultTypeInternal _FeatureConfiguration_default_instance_; +class FixedLenFeatureProto; +struct FixedLenFeatureProtoDefaultTypeInternal; +extern FixedLenFeatureProtoDefaultTypeInternal _FixedLenFeatureProto_default_instance_; +class VarLenFeatureProto; +struct VarLenFeatureProtoDefaultTypeInternal; +extern VarLenFeatureProtoDefaultTypeInternal _VarLenFeatureProto_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::ExampleParserConfiguration* Arena::CreateMaybeMessage<::tensorflow::ExampleParserConfiguration>(Arena*); +template<> ::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::ExampleParserConfiguration_FeatureMapEntry_DoNotUse>(Arena*); +template<> ::tensorflow::FeatureConfiguration* Arena::CreateMaybeMessage<::tensorflow::FeatureConfiguration>(Arena*); +template<> ::tensorflow::FixedLenFeatureProto* Arena::CreateMaybeMessage<::tensorflow::FixedLenFeatureProto>(Arena*); +template<> ::tensorflow::VarLenFeatureProto* Arena::CreateMaybeMessage<::tensorflow::VarLenFeatureProto>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class VarLenFeatureProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.VarLenFeatureProto) */ { + public: + inline VarLenFeatureProto() : VarLenFeatureProto(nullptr) {} + ~VarLenFeatureProto() override; + explicit PROTOBUF_CONSTEXPR VarLenFeatureProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + VarLenFeatureProto(const VarLenFeatureProto& from); + VarLenFeatureProto(VarLenFeatureProto&& from) noexcept + : VarLenFeatureProto() { + *this = ::std::move(from); + } + + inline VarLenFeatureProto& operator=(const VarLenFeatureProto& from) { + CopyFrom(from); + return *this; + } + inline VarLenFeatureProto& operator=(VarLenFeatureProto&& 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 VarLenFeatureProto& default_instance() { + return *internal_default_instance(); + } + static inline const VarLenFeatureProto* internal_default_instance() { + return reinterpret_cast( + &_VarLenFeatureProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(VarLenFeatureProto& a, VarLenFeatureProto& b) { + a.Swap(&b); + } + inline void Swap(VarLenFeatureProto* 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(VarLenFeatureProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + VarLenFeatureProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const VarLenFeatureProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const VarLenFeatureProto& from) { + VarLenFeatureProto::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(VarLenFeatureProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.VarLenFeatureProto"; + } + protected: + explicit VarLenFeatureProto(::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 { + kValuesOutputTensorNameFieldNumber = 2, + kIndicesOutputTensorNameFieldNumber = 3, + kShapesOutputTensorNameFieldNumber = 4, + kDtypeFieldNumber = 1, + }; + // string values_output_tensor_name = 2; + void clear_values_output_tensor_name(); + const std::string& values_output_tensor_name() const; + template + void set_values_output_tensor_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_values_output_tensor_name(); + PROTOBUF_NODISCARD std::string* release_values_output_tensor_name(); + void set_allocated_values_output_tensor_name(std::string* values_output_tensor_name); + private: + const std::string& _internal_values_output_tensor_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_values_output_tensor_name(const std::string& value); + std::string* _internal_mutable_values_output_tensor_name(); + public: + + // string indices_output_tensor_name = 3; + void clear_indices_output_tensor_name(); + const std::string& indices_output_tensor_name() const; + template + void set_indices_output_tensor_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_indices_output_tensor_name(); + PROTOBUF_NODISCARD std::string* release_indices_output_tensor_name(); + void set_allocated_indices_output_tensor_name(std::string* indices_output_tensor_name); + private: + const std::string& _internal_indices_output_tensor_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_indices_output_tensor_name(const std::string& value); + std::string* _internal_mutable_indices_output_tensor_name(); + public: + + // string shapes_output_tensor_name = 4; + void clear_shapes_output_tensor_name(); + const std::string& shapes_output_tensor_name() const; + template + void set_shapes_output_tensor_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_shapes_output_tensor_name(); + PROTOBUF_NODISCARD std::string* release_shapes_output_tensor_name(); + void set_allocated_shapes_output_tensor_name(std::string* shapes_output_tensor_name); + private: + const std::string& _internal_shapes_output_tensor_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_shapes_output_tensor_name(const std::string& value); + std::string* _internal_mutable_shapes_output_tensor_name(); + public: + + // .tensorflow.DataType dtype = 1; + 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: + + // @@protoc_insertion_point(class_scope:tensorflow.VarLenFeatureProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr values_output_tensor_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr indices_output_tensor_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr shapes_output_tensor_name_; + int dtype_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto; +}; +// ------------------------------------------------------------------- + +class FixedLenFeatureProto final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.FixedLenFeatureProto) */ { + public: + inline FixedLenFeatureProto() : FixedLenFeatureProto(nullptr) {} + ~FixedLenFeatureProto() override; + explicit PROTOBUF_CONSTEXPR FixedLenFeatureProto(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FixedLenFeatureProto(const FixedLenFeatureProto& from); + FixedLenFeatureProto(FixedLenFeatureProto&& from) noexcept + : FixedLenFeatureProto() { + *this = ::std::move(from); + } + + inline FixedLenFeatureProto& operator=(const FixedLenFeatureProto& from) { + CopyFrom(from); + return *this; + } + inline FixedLenFeatureProto& operator=(FixedLenFeatureProto&& 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 FixedLenFeatureProto& default_instance() { + return *internal_default_instance(); + } + static inline const FixedLenFeatureProto* internal_default_instance() { + return reinterpret_cast( + &_FixedLenFeatureProto_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(FixedLenFeatureProto& a, FixedLenFeatureProto& b) { + a.Swap(&b); + } + inline void Swap(FixedLenFeatureProto* 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(FixedLenFeatureProto* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FixedLenFeatureProto* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FixedLenFeatureProto& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FixedLenFeatureProto& from) { + FixedLenFeatureProto::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(FixedLenFeatureProto* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.FixedLenFeatureProto"; + } + protected: + explicit FixedLenFeatureProto(::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 { + kValuesOutputTensorNameFieldNumber = 4, + kShapeFieldNumber = 2, + kDefaultValueFieldNumber = 3, + kDtypeFieldNumber = 1, + }; + // string values_output_tensor_name = 4; + void clear_values_output_tensor_name(); + const std::string& values_output_tensor_name() const; + template + void set_values_output_tensor_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_values_output_tensor_name(); + PROTOBUF_NODISCARD std::string* release_values_output_tensor_name(); + void set_allocated_values_output_tensor_name(std::string* values_output_tensor_name); + private: + const std::string& _internal_values_output_tensor_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_values_output_tensor_name(const std::string& value); + std::string* _internal_mutable_values_output_tensor_name(); + public: + + // .tensorflow.TensorShapeProto shape = 2; + bool has_shape() const; + private: + bool _internal_has_shape() const; + public: + void clear_shape(); + const ::tensorflow::TensorShapeProto& shape() const; + PROTOBUF_NODISCARD ::tensorflow::TensorShapeProto* release_shape(); + ::tensorflow::TensorShapeProto* mutable_shape(); + void set_allocated_shape(::tensorflow::TensorShapeProto* shape); + private: + const ::tensorflow::TensorShapeProto& _internal_shape() const; + ::tensorflow::TensorShapeProto* _internal_mutable_shape(); + public: + void unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape); + ::tensorflow::TensorShapeProto* unsafe_arena_release_shape(); + + // .tensorflow.TensorProto default_value = 3; + bool has_default_value() const; + private: + bool _internal_has_default_value() const; + public: + void clear_default_value(); + const ::tensorflow::TensorProto& default_value() const; + PROTOBUF_NODISCARD ::tensorflow::TensorProto* release_default_value(); + ::tensorflow::TensorProto* mutable_default_value(); + void set_allocated_default_value(::tensorflow::TensorProto* default_value); + private: + const ::tensorflow::TensorProto& _internal_default_value() const; + ::tensorflow::TensorProto* _internal_mutable_default_value(); + public: + void unsafe_arena_set_allocated_default_value( + ::tensorflow::TensorProto* default_value); + ::tensorflow::TensorProto* unsafe_arena_release_default_value(); + + // .tensorflow.DataType dtype = 1; + 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: + + // @@protoc_insertion_point(class_scope:tensorflow.FixedLenFeatureProto) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr values_output_tensor_name_; + ::tensorflow::TensorShapeProto* shape_; + ::tensorflow::TensorProto* default_value_; + int dtype_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto; +}; +// ------------------------------------------------------------------- + +class FeatureConfiguration final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.FeatureConfiguration) */ { + public: + inline FeatureConfiguration() : FeatureConfiguration(nullptr) {} + ~FeatureConfiguration() override; + explicit PROTOBUF_CONSTEXPR FeatureConfiguration(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FeatureConfiguration(const FeatureConfiguration& from); + FeatureConfiguration(FeatureConfiguration&& from) noexcept + : FeatureConfiguration() { + *this = ::std::move(from); + } + + inline FeatureConfiguration& operator=(const FeatureConfiguration& from) { + CopyFrom(from); + return *this; + } + inline FeatureConfiguration& operator=(FeatureConfiguration&& 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 FeatureConfiguration& default_instance() { + return *internal_default_instance(); + } + enum ConfigCase { + kFixedLenFeature = 1, + kVarLenFeature = 2, + CONFIG_NOT_SET = 0, + }; + + static inline const FeatureConfiguration* internal_default_instance() { + return reinterpret_cast( + &_FeatureConfiguration_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(FeatureConfiguration& a, FeatureConfiguration& b) { + a.Swap(&b); + } + inline void Swap(FeatureConfiguration* 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(FeatureConfiguration* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FeatureConfiguration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FeatureConfiguration& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FeatureConfiguration& from) { + FeatureConfiguration::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(FeatureConfiguration* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.FeatureConfiguration"; + } + protected: + explicit FeatureConfiguration(::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 { + kFixedLenFeatureFieldNumber = 1, + kVarLenFeatureFieldNumber = 2, + }; + // .tensorflow.FixedLenFeatureProto fixed_len_feature = 1; + bool has_fixed_len_feature() const; + private: + bool _internal_has_fixed_len_feature() const; + public: + void clear_fixed_len_feature(); + const ::tensorflow::FixedLenFeatureProto& fixed_len_feature() const; + PROTOBUF_NODISCARD ::tensorflow::FixedLenFeatureProto* release_fixed_len_feature(); + ::tensorflow::FixedLenFeatureProto* mutable_fixed_len_feature(); + void set_allocated_fixed_len_feature(::tensorflow::FixedLenFeatureProto* fixed_len_feature); + private: + const ::tensorflow::FixedLenFeatureProto& _internal_fixed_len_feature() const; + ::tensorflow::FixedLenFeatureProto* _internal_mutable_fixed_len_feature(); + public: + void unsafe_arena_set_allocated_fixed_len_feature( + ::tensorflow::FixedLenFeatureProto* fixed_len_feature); + ::tensorflow::FixedLenFeatureProto* unsafe_arena_release_fixed_len_feature(); + + // .tensorflow.VarLenFeatureProto var_len_feature = 2; + bool has_var_len_feature() const; + private: + bool _internal_has_var_len_feature() const; + public: + void clear_var_len_feature(); + const ::tensorflow::VarLenFeatureProto& var_len_feature() const; + PROTOBUF_NODISCARD ::tensorflow::VarLenFeatureProto* release_var_len_feature(); + ::tensorflow::VarLenFeatureProto* mutable_var_len_feature(); + void set_allocated_var_len_feature(::tensorflow::VarLenFeatureProto* var_len_feature); + private: + const ::tensorflow::VarLenFeatureProto& _internal_var_len_feature() const; + ::tensorflow::VarLenFeatureProto* _internal_mutable_var_len_feature(); + public: + void unsafe_arena_set_allocated_var_len_feature( + ::tensorflow::VarLenFeatureProto* var_len_feature); + ::tensorflow::VarLenFeatureProto* unsafe_arena_release_var_len_feature(); + + void clear_config(); + ConfigCase config_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.FeatureConfiguration) + private: + class _Internal; + void set_has_fixed_len_feature(); + void set_has_var_len_feature(); + + inline bool has_config() const; + inline void clear_has_config(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union ConfigUnion { + constexpr ConfigUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::tensorflow::FixedLenFeatureProto* fixed_len_feature_; + ::tensorflow::VarLenFeatureProto* var_len_feature_; + } config_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto; +}; +// ------------------------------------------------------------------- + +class ExampleParserConfiguration_FeatureMapEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + ExampleParserConfiguration_FeatureMapEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR ExampleParserConfiguration_FeatureMapEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit ExampleParserConfiguration_FeatureMapEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const ExampleParserConfiguration_FeatureMapEntry_DoNotUse& other); + static const ExampleParserConfiguration_FeatureMapEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_ExampleParserConfiguration_FeatureMapEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.ExampleParserConfiguration.FeatureMapEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto; +}; + +// ------------------------------------------------------------------- + +class ExampleParserConfiguration final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ExampleParserConfiguration) */ { + public: + inline ExampleParserConfiguration() : ExampleParserConfiguration(nullptr) {} + ~ExampleParserConfiguration() override; + explicit PROTOBUF_CONSTEXPR ExampleParserConfiguration(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ExampleParserConfiguration(const ExampleParserConfiguration& from); + ExampleParserConfiguration(ExampleParserConfiguration&& from) noexcept + : ExampleParserConfiguration() { + *this = ::std::move(from); + } + + inline ExampleParserConfiguration& operator=(const ExampleParserConfiguration& from) { + CopyFrom(from); + return *this; + } + inline ExampleParserConfiguration& operator=(ExampleParserConfiguration&& 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 ExampleParserConfiguration& default_instance() { + return *internal_default_instance(); + } + static inline const ExampleParserConfiguration* internal_default_instance() { + return reinterpret_cast( + &_ExampleParserConfiguration_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(ExampleParserConfiguration& a, ExampleParserConfiguration& b) { + a.Swap(&b); + } + inline void Swap(ExampleParserConfiguration* 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(ExampleParserConfiguration* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ExampleParserConfiguration* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ExampleParserConfiguration& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ExampleParserConfiguration& from) { + ExampleParserConfiguration::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(ExampleParserConfiguration* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ExampleParserConfiguration"; + } + protected: + explicit ExampleParserConfiguration(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kFeatureMapFieldNumber = 1, + }; + // map feature_map = 1; + int feature_map_size() const; + private: + int _internal_feature_map_size() const; + public: + void clear_feature_map(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >& + _internal_feature_map() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >* + _internal_mutable_feature_map(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >& + feature_map() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >* + mutable_feature_map(); + + // @@protoc_insertion_point(class_scope:tensorflow.ExampleParserConfiguration) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + ExampleParserConfiguration_FeatureMapEntry_DoNotUse, + std::string, ::tensorflow::FeatureConfiguration, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> feature_map_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2fexample_5fparser_5fconfiguration_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// VarLenFeatureProto + +// .tensorflow.DataType dtype = 1; +inline void VarLenFeatureProto::clear_dtype() { + _impl_.dtype_ = 0; +} +inline ::tensorflow::DataType VarLenFeatureProto::_internal_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.dtype_); +} +inline ::tensorflow::DataType VarLenFeatureProto::dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.VarLenFeatureProto.dtype) + return _internal_dtype(); +} +inline void VarLenFeatureProto::_internal_set_dtype(::tensorflow::DataType value) { + + _impl_.dtype_ = value; +} +inline void VarLenFeatureProto::set_dtype(::tensorflow::DataType value) { + _internal_set_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.VarLenFeatureProto.dtype) +} + +// string values_output_tensor_name = 2; +inline void VarLenFeatureProto::clear_values_output_tensor_name() { + _impl_.values_output_tensor_name_.ClearToEmpty(); +} +inline const std::string& VarLenFeatureProto::values_output_tensor_name() const { + // @@protoc_insertion_point(field_get:tensorflow.VarLenFeatureProto.values_output_tensor_name) + return _internal_values_output_tensor_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void VarLenFeatureProto::set_values_output_tensor_name(ArgT0&& arg0, ArgT... args) { + + _impl_.values_output_tensor_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.VarLenFeatureProto.values_output_tensor_name) +} +inline std::string* VarLenFeatureProto::mutable_values_output_tensor_name() { + std::string* _s = _internal_mutable_values_output_tensor_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.VarLenFeatureProto.values_output_tensor_name) + return _s; +} +inline const std::string& VarLenFeatureProto::_internal_values_output_tensor_name() const { + return _impl_.values_output_tensor_name_.Get(); +} +inline void VarLenFeatureProto::_internal_set_values_output_tensor_name(const std::string& value) { + + _impl_.values_output_tensor_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* VarLenFeatureProto::_internal_mutable_values_output_tensor_name() { + + return _impl_.values_output_tensor_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* VarLenFeatureProto::release_values_output_tensor_name() { + // @@protoc_insertion_point(field_release:tensorflow.VarLenFeatureProto.values_output_tensor_name) + return _impl_.values_output_tensor_name_.Release(); +} +inline void VarLenFeatureProto::set_allocated_values_output_tensor_name(std::string* values_output_tensor_name) { + if (values_output_tensor_name != nullptr) { + + } else { + + } + _impl_.values_output_tensor_name_.SetAllocated(values_output_tensor_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.values_output_tensor_name_.IsDefault()) { + _impl_.values_output_tensor_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.VarLenFeatureProto.values_output_tensor_name) +} + +// string indices_output_tensor_name = 3; +inline void VarLenFeatureProto::clear_indices_output_tensor_name() { + _impl_.indices_output_tensor_name_.ClearToEmpty(); +} +inline const std::string& VarLenFeatureProto::indices_output_tensor_name() const { + // @@protoc_insertion_point(field_get:tensorflow.VarLenFeatureProto.indices_output_tensor_name) + return _internal_indices_output_tensor_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void VarLenFeatureProto::set_indices_output_tensor_name(ArgT0&& arg0, ArgT... args) { + + _impl_.indices_output_tensor_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.VarLenFeatureProto.indices_output_tensor_name) +} +inline std::string* VarLenFeatureProto::mutable_indices_output_tensor_name() { + std::string* _s = _internal_mutable_indices_output_tensor_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.VarLenFeatureProto.indices_output_tensor_name) + return _s; +} +inline const std::string& VarLenFeatureProto::_internal_indices_output_tensor_name() const { + return _impl_.indices_output_tensor_name_.Get(); +} +inline void VarLenFeatureProto::_internal_set_indices_output_tensor_name(const std::string& value) { + + _impl_.indices_output_tensor_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* VarLenFeatureProto::_internal_mutable_indices_output_tensor_name() { + + return _impl_.indices_output_tensor_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* VarLenFeatureProto::release_indices_output_tensor_name() { + // @@protoc_insertion_point(field_release:tensorflow.VarLenFeatureProto.indices_output_tensor_name) + return _impl_.indices_output_tensor_name_.Release(); +} +inline void VarLenFeatureProto::set_allocated_indices_output_tensor_name(std::string* indices_output_tensor_name) { + if (indices_output_tensor_name != nullptr) { + + } else { + + } + _impl_.indices_output_tensor_name_.SetAllocated(indices_output_tensor_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.indices_output_tensor_name_.IsDefault()) { + _impl_.indices_output_tensor_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.VarLenFeatureProto.indices_output_tensor_name) +} + +// string shapes_output_tensor_name = 4; +inline void VarLenFeatureProto::clear_shapes_output_tensor_name() { + _impl_.shapes_output_tensor_name_.ClearToEmpty(); +} +inline const std::string& VarLenFeatureProto::shapes_output_tensor_name() const { + // @@protoc_insertion_point(field_get:tensorflow.VarLenFeatureProto.shapes_output_tensor_name) + return _internal_shapes_output_tensor_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void VarLenFeatureProto::set_shapes_output_tensor_name(ArgT0&& arg0, ArgT... args) { + + _impl_.shapes_output_tensor_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.VarLenFeatureProto.shapes_output_tensor_name) +} +inline std::string* VarLenFeatureProto::mutable_shapes_output_tensor_name() { + std::string* _s = _internal_mutable_shapes_output_tensor_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.VarLenFeatureProto.shapes_output_tensor_name) + return _s; +} +inline const std::string& VarLenFeatureProto::_internal_shapes_output_tensor_name() const { + return _impl_.shapes_output_tensor_name_.Get(); +} +inline void VarLenFeatureProto::_internal_set_shapes_output_tensor_name(const std::string& value) { + + _impl_.shapes_output_tensor_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* VarLenFeatureProto::_internal_mutable_shapes_output_tensor_name() { + + return _impl_.shapes_output_tensor_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* VarLenFeatureProto::release_shapes_output_tensor_name() { + // @@protoc_insertion_point(field_release:tensorflow.VarLenFeatureProto.shapes_output_tensor_name) + return _impl_.shapes_output_tensor_name_.Release(); +} +inline void VarLenFeatureProto::set_allocated_shapes_output_tensor_name(std::string* shapes_output_tensor_name) { + if (shapes_output_tensor_name != nullptr) { + + } else { + + } + _impl_.shapes_output_tensor_name_.SetAllocated(shapes_output_tensor_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.shapes_output_tensor_name_.IsDefault()) { + _impl_.shapes_output_tensor_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.VarLenFeatureProto.shapes_output_tensor_name) +} + +// ------------------------------------------------------------------- + +// FixedLenFeatureProto + +// .tensorflow.DataType dtype = 1; +inline void FixedLenFeatureProto::clear_dtype() { + _impl_.dtype_ = 0; +} +inline ::tensorflow::DataType FixedLenFeatureProto::_internal_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.dtype_); +} +inline ::tensorflow::DataType FixedLenFeatureProto::dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.FixedLenFeatureProto.dtype) + return _internal_dtype(); +} +inline void FixedLenFeatureProto::_internal_set_dtype(::tensorflow::DataType value) { + + _impl_.dtype_ = value; +} +inline void FixedLenFeatureProto::set_dtype(::tensorflow::DataType value) { + _internal_set_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.FixedLenFeatureProto.dtype) +} + +// .tensorflow.TensorShapeProto shape = 2; +inline bool FixedLenFeatureProto::_internal_has_shape() const { + return this != internal_default_instance() && _impl_.shape_ != nullptr; +} +inline bool FixedLenFeatureProto::has_shape() const { + return _internal_has_shape(); +} +inline const ::tensorflow::TensorShapeProto& FixedLenFeatureProto::_internal_shape() const { + const ::tensorflow::TensorShapeProto* p = _impl_.shape_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorShapeProto_default_instance_); +} +inline const ::tensorflow::TensorShapeProto& FixedLenFeatureProto::shape() const { + // @@protoc_insertion_point(field_get:tensorflow.FixedLenFeatureProto.shape) + return _internal_shape(); +} +inline void FixedLenFeatureProto::unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + _impl_.shape_ = shape; + if (shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.FixedLenFeatureProto.shape) +} +inline ::tensorflow::TensorShapeProto* FixedLenFeatureProto::release_shape() { + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::TensorShapeProto* FixedLenFeatureProto::unsafe_arena_release_shape() { + // @@protoc_insertion_point(field_release:tensorflow.FixedLenFeatureProto.shape) + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; + return temp; +} +inline ::tensorflow::TensorShapeProto* FixedLenFeatureProto::_internal_mutable_shape() { + + if (_impl_.shape_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorShapeProto>(GetArenaForAllocation()); + _impl_.shape_ = p; + } + return _impl_.shape_; +} +inline ::tensorflow::TensorShapeProto* FixedLenFeatureProto::mutable_shape() { + ::tensorflow::TensorShapeProto* _msg = _internal_mutable_shape(); + // @@protoc_insertion_point(field_mutable:tensorflow.FixedLenFeatureProto.shape) + return _msg; +} +inline void FixedLenFeatureProto::set_allocated_shape(::tensorflow::TensorShapeProto* shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + if (shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(shape)); + if (message_arena != submessage_arena) { + shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, shape, submessage_arena); + } + + } else { + + } + _impl_.shape_ = shape; + // @@protoc_insertion_point(field_set_allocated:tensorflow.FixedLenFeatureProto.shape) +} + +// .tensorflow.TensorProto default_value = 3; +inline bool FixedLenFeatureProto::_internal_has_default_value() const { + return this != internal_default_instance() && _impl_.default_value_ != nullptr; +} +inline bool FixedLenFeatureProto::has_default_value() const { + return _internal_has_default_value(); +} +inline const ::tensorflow::TensorProto& FixedLenFeatureProto::_internal_default_value() const { + const ::tensorflow::TensorProto* p = _impl_.default_value_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorProto_default_instance_); +} +inline const ::tensorflow::TensorProto& FixedLenFeatureProto::default_value() const { + // @@protoc_insertion_point(field_get:tensorflow.FixedLenFeatureProto.default_value) + return _internal_default_value(); +} +inline void FixedLenFeatureProto::unsafe_arena_set_allocated_default_value( + ::tensorflow::TensorProto* default_value) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.default_value_); + } + _impl_.default_value_ = default_value; + if (default_value) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.FixedLenFeatureProto.default_value) +} +inline ::tensorflow::TensorProto* FixedLenFeatureProto::release_default_value() { + + ::tensorflow::TensorProto* temp = _impl_.default_value_; + _impl_.default_value_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::TensorProto* FixedLenFeatureProto::unsafe_arena_release_default_value() { + // @@protoc_insertion_point(field_release:tensorflow.FixedLenFeatureProto.default_value) + + ::tensorflow::TensorProto* temp = _impl_.default_value_; + _impl_.default_value_ = nullptr; + return temp; +} +inline ::tensorflow::TensorProto* FixedLenFeatureProto::_internal_mutable_default_value() { + + if (_impl_.default_value_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorProto>(GetArenaForAllocation()); + _impl_.default_value_ = p; + } + return _impl_.default_value_; +} +inline ::tensorflow::TensorProto* FixedLenFeatureProto::mutable_default_value() { + ::tensorflow::TensorProto* _msg = _internal_mutable_default_value(); + // @@protoc_insertion_point(field_mutable:tensorflow.FixedLenFeatureProto.default_value) + return _msg; +} +inline void FixedLenFeatureProto::set_allocated_default_value(::tensorflow::TensorProto* default_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.default_value_); + } + if (default_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(default_value)); + if (message_arena != submessage_arena) { + default_value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, default_value, submessage_arena); + } + + } else { + + } + _impl_.default_value_ = default_value; + // @@protoc_insertion_point(field_set_allocated:tensorflow.FixedLenFeatureProto.default_value) +} + +// string values_output_tensor_name = 4; +inline void FixedLenFeatureProto::clear_values_output_tensor_name() { + _impl_.values_output_tensor_name_.ClearToEmpty(); +} +inline const std::string& FixedLenFeatureProto::values_output_tensor_name() const { + // @@protoc_insertion_point(field_get:tensorflow.FixedLenFeatureProto.values_output_tensor_name) + return _internal_values_output_tensor_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void FixedLenFeatureProto::set_values_output_tensor_name(ArgT0&& arg0, ArgT... args) { + + _impl_.values_output_tensor_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.FixedLenFeatureProto.values_output_tensor_name) +} +inline std::string* FixedLenFeatureProto::mutable_values_output_tensor_name() { + std::string* _s = _internal_mutable_values_output_tensor_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.FixedLenFeatureProto.values_output_tensor_name) + return _s; +} +inline const std::string& FixedLenFeatureProto::_internal_values_output_tensor_name() const { + return _impl_.values_output_tensor_name_.Get(); +} +inline void FixedLenFeatureProto::_internal_set_values_output_tensor_name(const std::string& value) { + + _impl_.values_output_tensor_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* FixedLenFeatureProto::_internal_mutable_values_output_tensor_name() { + + return _impl_.values_output_tensor_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* FixedLenFeatureProto::release_values_output_tensor_name() { + // @@protoc_insertion_point(field_release:tensorflow.FixedLenFeatureProto.values_output_tensor_name) + return _impl_.values_output_tensor_name_.Release(); +} +inline void FixedLenFeatureProto::set_allocated_values_output_tensor_name(std::string* values_output_tensor_name) { + if (values_output_tensor_name != nullptr) { + + } else { + + } + _impl_.values_output_tensor_name_.SetAllocated(values_output_tensor_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.values_output_tensor_name_.IsDefault()) { + _impl_.values_output_tensor_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.FixedLenFeatureProto.values_output_tensor_name) +} + +// ------------------------------------------------------------------- + +// FeatureConfiguration + +// .tensorflow.FixedLenFeatureProto fixed_len_feature = 1; +inline bool FeatureConfiguration::_internal_has_fixed_len_feature() const { + return config_case() == kFixedLenFeature; +} +inline bool FeatureConfiguration::has_fixed_len_feature() const { + return _internal_has_fixed_len_feature(); +} +inline void FeatureConfiguration::set_has_fixed_len_feature() { + _impl_._oneof_case_[0] = kFixedLenFeature; +} +inline void FeatureConfiguration::clear_fixed_len_feature() { + if (_internal_has_fixed_len_feature()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.config_.fixed_len_feature_; + } + clear_has_config(); + } +} +inline ::tensorflow::FixedLenFeatureProto* FeatureConfiguration::release_fixed_len_feature() { + // @@protoc_insertion_point(field_release:tensorflow.FeatureConfiguration.fixed_len_feature) + if (_internal_has_fixed_len_feature()) { + clear_has_config(); + ::tensorflow::FixedLenFeatureProto* temp = _impl_.config_.fixed_len_feature_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.config_.fixed_len_feature_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::FixedLenFeatureProto& FeatureConfiguration::_internal_fixed_len_feature() const { + return _internal_has_fixed_len_feature() + ? *_impl_.config_.fixed_len_feature_ + : reinterpret_cast< ::tensorflow::FixedLenFeatureProto&>(::tensorflow::_FixedLenFeatureProto_default_instance_); +} +inline const ::tensorflow::FixedLenFeatureProto& FeatureConfiguration::fixed_len_feature() const { + // @@protoc_insertion_point(field_get:tensorflow.FeatureConfiguration.fixed_len_feature) + return _internal_fixed_len_feature(); +} +inline ::tensorflow::FixedLenFeatureProto* FeatureConfiguration::unsafe_arena_release_fixed_len_feature() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.FeatureConfiguration.fixed_len_feature) + if (_internal_has_fixed_len_feature()) { + clear_has_config(); + ::tensorflow::FixedLenFeatureProto* temp = _impl_.config_.fixed_len_feature_; + _impl_.config_.fixed_len_feature_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void FeatureConfiguration::unsafe_arena_set_allocated_fixed_len_feature(::tensorflow::FixedLenFeatureProto* fixed_len_feature) { + clear_config(); + if (fixed_len_feature) { + set_has_fixed_len_feature(); + _impl_.config_.fixed_len_feature_ = fixed_len_feature; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.FeatureConfiguration.fixed_len_feature) +} +inline ::tensorflow::FixedLenFeatureProto* FeatureConfiguration::_internal_mutable_fixed_len_feature() { + if (!_internal_has_fixed_len_feature()) { + clear_config(); + set_has_fixed_len_feature(); + _impl_.config_.fixed_len_feature_ = CreateMaybeMessage< ::tensorflow::FixedLenFeatureProto >(GetArenaForAllocation()); + } + return _impl_.config_.fixed_len_feature_; +} +inline ::tensorflow::FixedLenFeatureProto* FeatureConfiguration::mutable_fixed_len_feature() { + ::tensorflow::FixedLenFeatureProto* _msg = _internal_mutable_fixed_len_feature(); + // @@protoc_insertion_point(field_mutable:tensorflow.FeatureConfiguration.fixed_len_feature) + return _msg; +} + +// .tensorflow.VarLenFeatureProto var_len_feature = 2; +inline bool FeatureConfiguration::_internal_has_var_len_feature() const { + return config_case() == kVarLenFeature; +} +inline bool FeatureConfiguration::has_var_len_feature() const { + return _internal_has_var_len_feature(); +} +inline void FeatureConfiguration::set_has_var_len_feature() { + _impl_._oneof_case_[0] = kVarLenFeature; +} +inline void FeatureConfiguration::clear_var_len_feature() { + if (_internal_has_var_len_feature()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.config_.var_len_feature_; + } + clear_has_config(); + } +} +inline ::tensorflow::VarLenFeatureProto* FeatureConfiguration::release_var_len_feature() { + // @@protoc_insertion_point(field_release:tensorflow.FeatureConfiguration.var_len_feature) + if (_internal_has_var_len_feature()) { + clear_has_config(); + ::tensorflow::VarLenFeatureProto* temp = _impl_.config_.var_len_feature_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.config_.var_len_feature_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::VarLenFeatureProto& FeatureConfiguration::_internal_var_len_feature() const { + return _internal_has_var_len_feature() + ? *_impl_.config_.var_len_feature_ + : reinterpret_cast< ::tensorflow::VarLenFeatureProto&>(::tensorflow::_VarLenFeatureProto_default_instance_); +} +inline const ::tensorflow::VarLenFeatureProto& FeatureConfiguration::var_len_feature() const { + // @@protoc_insertion_point(field_get:tensorflow.FeatureConfiguration.var_len_feature) + return _internal_var_len_feature(); +} +inline ::tensorflow::VarLenFeatureProto* FeatureConfiguration::unsafe_arena_release_var_len_feature() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.FeatureConfiguration.var_len_feature) + if (_internal_has_var_len_feature()) { + clear_has_config(); + ::tensorflow::VarLenFeatureProto* temp = _impl_.config_.var_len_feature_; + _impl_.config_.var_len_feature_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void FeatureConfiguration::unsafe_arena_set_allocated_var_len_feature(::tensorflow::VarLenFeatureProto* var_len_feature) { + clear_config(); + if (var_len_feature) { + set_has_var_len_feature(); + _impl_.config_.var_len_feature_ = var_len_feature; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.FeatureConfiguration.var_len_feature) +} +inline ::tensorflow::VarLenFeatureProto* FeatureConfiguration::_internal_mutable_var_len_feature() { + if (!_internal_has_var_len_feature()) { + clear_config(); + set_has_var_len_feature(); + _impl_.config_.var_len_feature_ = CreateMaybeMessage< ::tensorflow::VarLenFeatureProto >(GetArenaForAllocation()); + } + return _impl_.config_.var_len_feature_; +} +inline ::tensorflow::VarLenFeatureProto* FeatureConfiguration::mutable_var_len_feature() { + ::tensorflow::VarLenFeatureProto* _msg = _internal_mutable_var_len_feature(); + // @@protoc_insertion_point(field_mutable:tensorflow.FeatureConfiguration.var_len_feature) + return _msg; +} + +inline bool FeatureConfiguration::has_config() const { + return config_case() != CONFIG_NOT_SET; +} +inline void FeatureConfiguration::clear_has_config() { + _impl_._oneof_case_[0] = CONFIG_NOT_SET; +} +inline FeatureConfiguration::ConfigCase FeatureConfiguration::config_case() const { + return FeatureConfiguration::ConfigCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ExampleParserConfiguration + +// map feature_map = 1; +inline int ExampleParserConfiguration::_internal_feature_map_size() const { + return _impl_.feature_map_.size(); +} +inline int ExampleParserConfiguration::feature_map_size() const { + return _internal_feature_map_size(); +} +inline void ExampleParserConfiguration::clear_feature_map() { + _impl_.feature_map_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >& +ExampleParserConfiguration::_internal_feature_map() const { + return _impl_.feature_map_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >& +ExampleParserConfiguration::feature_map() const { + // @@protoc_insertion_point(field_map:tensorflow.ExampleParserConfiguration.feature_map) + return _internal_feature_map(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >* +ExampleParserConfiguration::_internal_mutable_feature_map() { + return _impl_.feature_map_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureConfiguration >* +ExampleParserConfiguration::mutable_feature_map() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.ExampleParserConfiguration.feature_map) + return _internal_mutable_feature_map(); +} + +#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_2fexample_2fexample_5fparser_5fconfiguration_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.proto new file mode 100644 index 0000000000000000000000000000000000000000..0af0f4b44ca968dca5f82e62abfc95e69f0eac84 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/example_parser_configuration.proto @@ -0,0 +1,40 @@ +// Protocol messages for describing the configuration of the ExampleParserOp. + +syntax = "proto3"; + +package tensorflow; + +import "tensorflow/core/framework/tensor.proto"; +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "ExampleParserConfigurationProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.example"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/example/example_parser_configuration_go_proto"; + +message VarLenFeatureProto { + tensorflow.DataType dtype = 1; + string values_output_tensor_name = 2; + string indices_output_tensor_name = 3; + string shapes_output_tensor_name = 4; +} + +message FixedLenFeatureProto { + tensorflow.DataType dtype = 1; + tensorflow.TensorShapeProto shape = 2; + tensorflow.TensorProto default_value = 3; + string values_output_tensor_name = 4; +} + +message FeatureConfiguration { + oneof config { + FixedLenFeatureProto fixed_len_feature = 1; + VarLenFeatureProto var_len_feature = 2; + } +} + +message ExampleParserConfiguration { + map feature_map = 1; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..55ac3a4c3e3b0f68085ae4745c926b668462b7f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature.pb.h @@ -0,0 +1,1895 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/example/feature.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fexample_2ffeature_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fexample_2ffeature_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fexample_2ffeature_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_2fexample_2ffeature_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fexample_2ffeature_2eproto; +namespace tensorflow { +class BytesList; +struct BytesListDefaultTypeInternal; +extern BytesListDefaultTypeInternal _BytesList_default_instance_; +class Feature; +struct FeatureDefaultTypeInternal; +extern FeatureDefaultTypeInternal _Feature_default_instance_; +class FeatureList; +struct FeatureListDefaultTypeInternal; +extern FeatureListDefaultTypeInternal _FeatureList_default_instance_; +class FeatureLists; +struct FeatureListsDefaultTypeInternal; +extern FeatureListsDefaultTypeInternal _FeatureLists_default_instance_; +class FeatureLists_FeatureListEntry_DoNotUse; +struct FeatureLists_FeatureListEntry_DoNotUseDefaultTypeInternal; +extern FeatureLists_FeatureListEntry_DoNotUseDefaultTypeInternal _FeatureLists_FeatureListEntry_DoNotUse_default_instance_; +class Features; +struct FeaturesDefaultTypeInternal; +extern FeaturesDefaultTypeInternal _Features_default_instance_; +class Features_FeatureEntry_DoNotUse; +struct Features_FeatureEntry_DoNotUseDefaultTypeInternal; +extern Features_FeatureEntry_DoNotUseDefaultTypeInternal _Features_FeatureEntry_DoNotUse_default_instance_; +class FloatList; +struct FloatListDefaultTypeInternal; +extern FloatListDefaultTypeInternal _FloatList_default_instance_; +class Int64List; +struct Int64ListDefaultTypeInternal; +extern Int64ListDefaultTypeInternal _Int64List_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::BytesList* Arena::CreateMaybeMessage<::tensorflow::BytesList>(Arena*); +template<> ::tensorflow::Feature* Arena::CreateMaybeMessage<::tensorflow::Feature>(Arena*); +template<> ::tensorflow::FeatureList* Arena::CreateMaybeMessage<::tensorflow::FeatureList>(Arena*); +template<> ::tensorflow::FeatureLists* Arena::CreateMaybeMessage<::tensorflow::FeatureLists>(Arena*); +template<> ::tensorflow::FeatureLists_FeatureListEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::FeatureLists_FeatureListEntry_DoNotUse>(Arena*); +template<> ::tensorflow::Features* Arena::CreateMaybeMessage<::tensorflow::Features>(Arena*); +template<> ::tensorflow::Features_FeatureEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::Features_FeatureEntry_DoNotUse>(Arena*); +template<> ::tensorflow::FloatList* Arena::CreateMaybeMessage<::tensorflow::FloatList>(Arena*); +template<> ::tensorflow::Int64List* Arena::CreateMaybeMessage<::tensorflow::Int64List>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class BytesList final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.BytesList) */ { + public: + inline BytesList() : BytesList(nullptr) {} + ~BytesList() override; + explicit PROTOBUF_CONSTEXPR BytesList(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + BytesList(const BytesList& from); + BytesList(BytesList&& from) noexcept + : BytesList() { + *this = ::std::move(from); + } + + inline BytesList& operator=(const BytesList& from) { + CopyFrom(from); + return *this; + } + inline BytesList& operator=(BytesList&& 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 BytesList& default_instance() { + return *internal_default_instance(); + } + static inline const BytesList* internal_default_instance() { + return reinterpret_cast( + &_BytesList_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(BytesList& a, BytesList& b) { + a.Swap(&b); + } + inline void Swap(BytesList* 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(BytesList* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + BytesList* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const BytesList& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const BytesList& from) { + BytesList::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(BytesList* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.BytesList"; + } + protected: + explicit BytesList(::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 { + kValueFieldNumber = 1, + }; + // repeated bytes value = 1; + int value_size() const; + private: + int _internal_value_size() const; + public: + void clear_value(); + const std::string& value(int index) const; + std::string* mutable_value(int index); + void set_value(int index, const std::string& value); + void set_value(int index, std::string&& value); + void set_value(int index, const char* value); + void set_value(int index, const void* value, size_t size); + std::string* add_value(); + void add_value(const std::string& value); + void add_value(std::string&& value); + void add_value(const char* value); + void add_value(const void* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& value() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_value(); + private: + const std::string& _internal_value(int index) const; + std::string* _internal_add_value(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.BytesList) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// ------------------------------------------------------------------- + +class FloatList final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.FloatList) */ { + public: + inline FloatList() : FloatList(nullptr) {} + ~FloatList() override; + explicit PROTOBUF_CONSTEXPR FloatList(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FloatList(const FloatList& from); + FloatList(FloatList&& from) noexcept + : FloatList() { + *this = ::std::move(from); + } + + inline FloatList& operator=(const FloatList& from) { + CopyFrom(from); + return *this; + } + inline FloatList& operator=(FloatList&& 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 FloatList& default_instance() { + return *internal_default_instance(); + } + static inline const FloatList* internal_default_instance() { + return reinterpret_cast( + &_FloatList_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(FloatList& a, FloatList& b) { + a.Swap(&b); + } + inline void Swap(FloatList* 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(FloatList* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FloatList* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FloatList& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FloatList& from) { + FloatList::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(FloatList* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.FloatList"; + } + protected: + explicit FloatList(::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 { + kValueFieldNumber = 1, + }; + // repeated float value = 1 [packed = true]; + int value_size() const; + private: + int _internal_value_size() const; + public: + void clear_value(); + private: + float _internal_value(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& + _internal_value() const; + void _internal_add_value(float value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* + _internal_mutable_value(); + public: + float value(int index) const; + void set_value(int index, float value); + void add_value(float value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& + value() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* + mutable_value(); + + // @@protoc_insertion_point(class_scope:tensorflow.FloatList) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< float > value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// ------------------------------------------------------------------- + +class Int64List final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.Int64List) */ { + public: + inline Int64List() : Int64List(nullptr) {} + ~Int64List() override; + explicit PROTOBUF_CONSTEXPR Int64List(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Int64List(const Int64List& from); + Int64List(Int64List&& from) noexcept + : Int64List() { + *this = ::std::move(from); + } + + inline Int64List& operator=(const Int64List& from) { + CopyFrom(from); + return *this; + } + inline Int64List& operator=(Int64List&& 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 Int64List& default_instance() { + return *internal_default_instance(); + } + static inline const Int64List* internal_default_instance() { + return reinterpret_cast( + &_Int64List_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(Int64List& a, Int64List& b) { + a.Swap(&b); + } + inline void Swap(Int64List* 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(Int64List* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Int64List* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Int64List& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const Int64List& from) { + Int64List::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(Int64List* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.Int64List"; + } + protected: + explicit Int64List(::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 { + kValueFieldNumber = 1, + }; + // repeated int64 value = 1 [packed = true]; + int value_size() const; + private: + int _internal_value_size() const; + public: + void clear_value(); + private: + int64_t _internal_value(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_value() const; + void _internal_add_value(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_value(); + public: + int64_t value(int index) const; + void set_value(int index, int64_t value); + void add_value(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + value() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_value(); + + // @@protoc_insertion_point(class_scope:tensorflow.Int64List) + 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 > value_; + mutable std::atomic _value_cached_byte_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// ------------------------------------------------------------------- + +class Feature final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.Feature) */ { + public: + inline Feature() : Feature(nullptr) {} + ~Feature() override; + explicit PROTOBUF_CONSTEXPR Feature(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Feature(const Feature& from); + Feature(Feature&& from) noexcept + : Feature() { + *this = ::std::move(from); + } + + inline Feature& operator=(const Feature& from) { + CopyFrom(from); + return *this; + } + inline Feature& operator=(Feature&& 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 Feature& default_instance() { + return *internal_default_instance(); + } + enum KindCase { + kBytesList = 1, + kFloatList = 2, + kInt64List = 3, + KIND_NOT_SET = 0, + }; + + static inline const Feature* internal_default_instance() { + return reinterpret_cast( + &_Feature_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(Feature& a, Feature& b) { + a.Swap(&b); + } + inline void Swap(Feature* 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(Feature* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Feature* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Feature& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const Feature& from) { + Feature::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(Feature* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.Feature"; + } + protected: + explicit Feature(::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 { + kBytesListFieldNumber = 1, + kFloatListFieldNumber = 2, + kInt64ListFieldNumber = 3, + }; + // .tensorflow.BytesList bytes_list = 1; + bool has_bytes_list() const; + private: + bool _internal_has_bytes_list() const; + public: + void clear_bytes_list(); + const ::tensorflow::BytesList& bytes_list() const; + PROTOBUF_NODISCARD ::tensorflow::BytesList* release_bytes_list(); + ::tensorflow::BytesList* mutable_bytes_list(); + void set_allocated_bytes_list(::tensorflow::BytesList* bytes_list); + private: + const ::tensorflow::BytesList& _internal_bytes_list() const; + ::tensorflow::BytesList* _internal_mutable_bytes_list(); + public: + void unsafe_arena_set_allocated_bytes_list( + ::tensorflow::BytesList* bytes_list); + ::tensorflow::BytesList* unsafe_arena_release_bytes_list(); + + // .tensorflow.FloatList float_list = 2; + bool has_float_list() const; + private: + bool _internal_has_float_list() const; + public: + void clear_float_list(); + const ::tensorflow::FloatList& float_list() const; + PROTOBUF_NODISCARD ::tensorflow::FloatList* release_float_list(); + ::tensorflow::FloatList* mutable_float_list(); + void set_allocated_float_list(::tensorflow::FloatList* float_list); + private: + const ::tensorflow::FloatList& _internal_float_list() const; + ::tensorflow::FloatList* _internal_mutable_float_list(); + public: + void unsafe_arena_set_allocated_float_list( + ::tensorflow::FloatList* float_list); + ::tensorflow::FloatList* unsafe_arena_release_float_list(); + + // .tensorflow.Int64List int64_list = 3; + bool has_int64_list() const; + private: + bool _internal_has_int64_list() const; + public: + void clear_int64_list(); + const ::tensorflow::Int64List& int64_list() const; + PROTOBUF_NODISCARD ::tensorflow::Int64List* release_int64_list(); + ::tensorflow::Int64List* mutable_int64_list(); + void set_allocated_int64_list(::tensorflow::Int64List* int64_list); + private: + const ::tensorflow::Int64List& _internal_int64_list() const; + ::tensorflow::Int64List* _internal_mutable_int64_list(); + public: + void unsafe_arena_set_allocated_int64_list( + ::tensorflow::Int64List* int64_list); + ::tensorflow::Int64List* unsafe_arena_release_int64_list(); + + void clear_kind(); + KindCase kind_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.Feature) + private: + class _Internal; + void set_has_bytes_list(); + void set_has_float_list(); + void set_has_int64_list(); + + inline bool has_kind() const; + inline void clear_has_kind(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union KindUnion { + constexpr KindUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::tensorflow::BytesList* bytes_list_; + ::tensorflow::FloatList* float_list_; + ::tensorflow::Int64List* int64_list_; + } kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// ------------------------------------------------------------------- + +class Features_FeatureEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + Features_FeatureEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR Features_FeatureEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit Features_FeatureEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const Features_FeatureEntry_DoNotUse& other); + static const Features_FeatureEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_Features_FeatureEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.Features.FeatureEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; + +// ------------------------------------------------------------------- + +class Features final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.Features) */ { + public: + inline Features() : Features(nullptr) {} + ~Features() override; + explicit PROTOBUF_CONSTEXPR Features(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Features(const Features& from); + Features(Features&& from) noexcept + : Features() { + *this = ::std::move(from); + } + + inline Features& operator=(const Features& from) { + CopyFrom(from); + return *this; + } + inline Features& operator=(Features&& 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 Features& default_instance() { + return *internal_default_instance(); + } + static inline const Features* internal_default_instance() { + return reinterpret_cast( + &_Features_default_instance_); + } + static constexpr int kIndexInFileMessages = + 5; + + friend void swap(Features& a, Features& b) { + a.Swap(&b); + } + inline void Swap(Features* 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(Features* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Features* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Features& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const Features& from) { + Features::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(Features* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.Features"; + } + protected: + explicit Features(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kFeatureFieldNumber = 1, + }; + // map feature = 1; + int feature_size() const; + private: + int _internal_feature_size() const; + public: + void clear_feature(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >& + _internal_feature() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >* + _internal_mutable_feature(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >& + feature() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >* + mutable_feature(); + + // @@protoc_insertion_point(class_scope:tensorflow.Features) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + Features_FeatureEntry_DoNotUse, + std::string, ::tensorflow::Feature, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> feature_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// ------------------------------------------------------------------- + +class FeatureList final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.FeatureList) */ { + public: + inline FeatureList() : FeatureList(nullptr) {} + ~FeatureList() override; + explicit PROTOBUF_CONSTEXPR FeatureList(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FeatureList(const FeatureList& from); + FeatureList(FeatureList&& from) noexcept + : FeatureList() { + *this = ::std::move(from); + } + + inline FeatureList& operator=(const FeatureList& from) { + CopyFrom(from); + return *this; + } + inline FeatureList& operator=(FeatureList&& 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 FeatureList& default_instance() { + return *internal_default_instance(); + } + static inline const FeatureList* internal_default_instance() { + return reinterpret_cast( + &_FeatureList_default_instance_); + } + static constexpr int kIndexInFileMessages = + 6; + + friend void swap(FeatureList& a, FeatureList& b) { + a.Swap(&b); + } + inline void Swap(FeatureList* 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(FeatureList* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FeatureList* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FeatureList& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FeatureList& from) { + FeatureList::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(FeatureList* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.FeatureList"; + } + protected: + explicit FeatureList(::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 { + kFeatureFieldNumber = 1, + }; + // repeated .tensorflow.Feature feature = 1; + int feature_size() const; + private: + int _internal_feature_size() const; + public: + void clear_feature(); + ::tensorflow::Feature* mutable_feature(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::Feature >* + mutable_feature(); + private: + const ::tensorflow::Feature& _internal_feature(int index) const; + ::tensorflow::Feature* _internal_add_feature(); + public: + const ::tensorflow::Feature& feature(int index) const; + ::tensorflow::Feature* add_feature(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::Feature >& + feature() const; + + // @@protoc_insertion_point(class_scope:tensorflow.FeatureList) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::Feature > feature_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// ------------------------------------------------------------------- + +class FeatureLists_FeatureListEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + FeatureLists_FeatureListEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR FeatureLists_FeatureListEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit FeatureLists_FeatureListEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const FeatureLists_FeatureListEntry_DoNotUse& other); + static const FeatureLists_FeatureListEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_FeatureLists_FeatureListEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.FeatureLists.FeatureListEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; + +// ------------------------------------------------------------------- + +class FeatureLists final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.FeatureLists) */ { + public: + inline FeatureLists() : FeatureLists(nullptr) {} + ~FeatureLists() override; + explicit PROTOBUF_CONSTEXPR FeatureLists(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FeatureLists(const FeatureLists& from); + FeatureLists(FeatureLists&& from) noexcept + : FeatureLists() { + *this = ::std::move(from); + } + + inline FeatureLists& operator=(const FeatureLists& from) { + CopyFrom(from); + return *this; + } + inline FeatureLists& operator=(FeatureLists&& 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 FeatureLists& default_instance() { + return *internal_default_instance(); + } + static inline const FeatureLists* internal_default_instance() { + return reinterpret_cast( + &_FeatureLists_default_instance_); + } + static constexpr int kIndexInFileMessages = + 8; + + friend void swap(FeatureLists& a, FeatureLists& b) { + a.Swap(&b); + } + inline void Swap(FeatureLists* 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(FeatureLists* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FeatureLists* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FeatureLists& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FeatureLists& from) { + FeatureLists::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(FeatureLists* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.FeatureLists"; + } + protected: + explicit FeatureLists(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kFeatureListFieldNumber = 1, + }; + // map feature_list = 1; + int feature_list_size() const; + private: + int _internal_feature_list_size() const; + public: + void clear_feature_list(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >& + _internal_feature_list() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >* + _internal_mutable_feature_list(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >& + feature_list() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >* + mutable_feature_list(); + + // @@protoc_insertion_point(class_scope:tensorflow.FeatureLists) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + FeatureLists_FeatureListEntry_DoNotUse, + std::string, ::tensorflow::FeatureList, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> feature_list_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fexample_2ffeature_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// BytesList + +// repeated bytes value = 1; +inline int BytesList::_internal_value_size() const { + return _impl_.value_.size(); +} +inline int BytesList::value_size() const { + return _internal_value_size(); +} +inline void BytesList::clear_value() { + _impl_.value_.Clear(); +} +inline std::string* BytesList::add_value() { + std::string* _s = _internal_add_value(); + // @@protoc_insertion_point(field_add_mutable:tensorflow.BytesList.value) + return _s; +} +inline const std::string& BytesList::_internal_value(int index) const { + return _impl_.value_.Get(index); +} +inline const std::string& BytesList::value(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.BytesList.value) + return _internal_value(index); +} +inline std::string* BytesList::mutable_value(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.BytesList.value) + return _impl_.value_.Mutable(index); +} +inline void BytesList::set_value(int index, const std::string& value) { + _impl_.value_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:tensorflow.BytesList.value) +} +inline void BytesList::set_value(int index, std::string&& value) { + _impl_.value_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:tensorflow.BytesList.value) +} +inline void BytesList::set_value(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.value_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:tensorflow.BytesList.value) +} +inline void BytesList::set_value(int index, const void* value, size_t size) { + _impl_.value_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:tensorflow.BytesList.value) +} +inline std::string* BytesList::_internal_add_value() { + return _impl_.value_.Add(); +} +inline void BytesList::add_value(const std::string& value) { + _impl_.value_.Add()->assign(value); + // @@protoc_insertion_point(field_add:tensorflow.BytesList.value) +} +inline void BytesList::add_value(std::string&& value) { + _impl_.value_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:tensorflow.BytesList.value) +} +inline void BytesList::add_value(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.value_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:tensorflow.BytesList.value) +} +inline void BytesList::add_value(const void* value, size_t size) { + _impl_.value_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:tensorflow.BytesList.value) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +BytesList::value() const { + // @@protoc_insertion_point(field_list:tensorflow.BytesList.value) + return _impl_.value_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +BytesList::mutable_value() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.BytesList.value) + return &_impl_.value_; +} + +// ------------------------------------------------------------------- + +// FloatList + +// repeated float value = 1 [packed = true]; +inline int FloatList::_internal_value_size() const { + return _impl_.value_.size(); +} +inline int FloatList::value_size() const { + return _internal_value_size(); +} +inline void FloatList::clear_value() { + _impl_.value_.Clear(); +} +inline float FloatList::_internal_value(int index) const { + return _impl_.value_.Get(index); +} +inline float FloatList::value(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.FloatList.value) + return _internal_value(index); +} +inline void FloatList::set_value(int index, float value) { + _impl_.value_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.FloatList.value) +} +inline void FloatList::_internal_add_value(float value) { + _impl_.value_.Add(value); +} +inline void FloatList::add_value(float value) { + _internal_add_value(value); + // @@protoc_insertion_point(field_add:tensorflow.FloatList.value) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& +FloatList::_internal_value() const { + return _impl_.value_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& +FloatList::value() const { + // @@protoc_insertion_point(field_list:tensorflow.FloatList.value) + return _internal_value(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* +FloatList::_internal_mutable_value() { + return &_impl_.value_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* +FloatList::mutable_value() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.FloatList.value) + return _internal_mutable_value(); +} + +// ------------------------------------------------------------------- + +// Int64List + +// repeated int64 value = 1 [packed = true]; +inline int Int64List::_internal_value_size() const { + return _impl_.value_.size(); +} +inline int Int64List::value_size() const { + return _internal_value_size(); +} +inline void Int64List::clear_value() { + _impl_.value_.Clear(); +} +inline int64_t Int64List::_internal_value(int index) const { + return _impl_.value_.Get(index); +} +inline int64_t Int64List::value(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.Int64List.value) + return _internal_value(index); +} +inline void Int64List::set_value(int index, int64_t value) { + _impl_.value_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.Int64List.value) +} +inline void Int64List::_internal_add_value(int64_t value) { + _impl_.value_.Add(value); +} +inline void Int64List::add_value(int64_t value) { + _internal_add_value(value); + // @@protoc_insertion_point(field_add:tensorflow.Int64List.value) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +Int64List::_internal_value() const { + return _impl_.value_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +Int64List::value() const { + // @@protoc_insertion_point(field_list:tensorflow.Int64List.value) + return _internal_value(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +Int64List::_internal_mutable_value() { + return &_impl_.value_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +Int64List::mutable_value() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.Int64List.value) + return _internal_mutable_value(); +} + +// ------------------------------------------------------------------- + +// Feature + +// .tensorflow.BytesList bytes_list = 1; +inline bool Feature::_internal_has_bytes_list() const { + return kind_case() == kBytesList; +} +inline bool Feature::has_bytes_list() const { + return _internal_has_bytes_list(); +} +inline void Feature::set_has_bytes_list() { + _impl_._oneof_case_[0] = kBytesList; +} +inline void Feature::clear_bytes_list() { + if (_internal_has_bytes_list()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.kind_.bytes_list_; + } + clear_has_kind(); + } +} +inline ::tensorflow::BytesList* Feature::release_bytes_list() { + // @@protoc_insertion_point(field_release:tensorflow.Feature.bytes_list) + if (_internal_has_bytes_list()) { + clear_has_kind(); + ::tensorflow::BytesList* temp = _impl_.kind_.bytes_list_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.kind_.bytes_list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::BytesList& Feature::_internal_bytes_list() const { + return _internal_has_bytes_list() + ? *_impl_.kind_.bytes_list_ + : reinterpret_cast< ::tensorflow::BytesList&>(::tensorflow::_BytesList_default_instance_); +} +inline const ::tensorflow::BytesList& Feature::bytes_list() const { + // @@protoc_insertion_point(field_get:tensorflow.Feature.bytes_list) + return _internal_bytes_list(); +} +inline ::tensorflow::BytesList* Feature::unsafe_arena_release_bytes_list() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.Feature.bytes_list) + if (_internal_has_bytes_list()) { + clear_has_kind(); + ::tensorflow::BytesList* temp = _impl_.kind_.bytes_list_; + _impl_.kind_.bytes_list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void Feature::unsafe_arena_set_allocated_bytes_list(::tensorflow::BytesList* bytes_list) { + clear_kind(); + if (bytes_list) { + set_has_bytes_list(); + _impl_.kind_.bytes_list_ = bytes_list; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.Feature.bytes_list) +} +inline ::tensorflow::BytesList* Feature::_internal_mutable_bytes_list() { + if (!_internal_has_bytes_list()) { + clear_kind(); + set_has_bytes_list(); + _impl_.kind_.bytes_list_ = CreateMaybeMessage< ::tensorflow::BytesList >(GetArenaForAllocation()); + } + return _impl_.kind_.bytes_list_; +} +inline ::tensorflow::BytesList* Feature::mutable_bytes_list() { + ::tensorflow::BytesList* _msg = _internal_mutable_bytes_list(); + // @@protoc_insertion_point(field_mutable:tensorflow.Feature.bytes_list) + return _msg; +} + +// .tensorflow.FloatList float_list = 2; +inline bool Feature::_internal_has_float_list() const { + return kind_case() == kFloatList; +} +inline bool Feature::has_float_list() const { + return _internal_has_float_list(); +} +inline void Feature::set_has_float_list() { + _impl_._oneof_case_[0] = kFloatList; +} +inline void Feature::clear_float_list() { + if (_internal_has_float_list()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.kind_.float_list_; + } + clear_has_kind(); + } +} +inline ::tensorflow::FloatList* Feature::release_float_list() { + // @@protoc_insertion_point(field_release:tensorflow.Feature.float_list) + if (_internal_has_float_list()) { + clear_has_kind(); + ::tensorflow::FloatList* temp = _impl_.kind_.float_list_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.kind_.float_list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::FloatList& Feature::_internal_float_list() const { + return _internal_has_float_list() + ? *_impl_.kind_.float_list_ + : reinterpret_cast< ::tensorflow::FloatList&>(::tensorflow::_FloatList_default_instance_); +} +inline const ::tensorflow::FloatList& Feature::float_list() const { + // @@protoc_insertion_point(field_get:tensorflow.Feature.float_list) + return _internal_float_list(); +} +inline ::tensorflow::FloatList* Feature::unsafe_arena_release_float_list() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.Feature.float_list) + if (_internal_has_float_list()) { + clear_has_kind(); + ::tensorflow::FloatList* temp = _impl_.kind_.float_list_; + _impl_.kind_.float_list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void Feature::unsafe_arena_set_allocated_float_list(::tensorflow::FloatList* float_list) { + clear_kind(); + if (float_list) { + set_has_float_list(); + _impl_.kind_.float_list_ = float_list; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.Feature.float_list) +} +inline ::tensorflow::FloatList* Feature::_internal_mutable_float_list() { + if (!_internal_has_float_list()) { + clear_kind(); + set_has_float_list(); + _impl_.kind_.float_list_ = CreateMaybeMessage< ::tensorflow::FloatList >(GetArenaForAllocation()); + } + return _impl_.kind_.float_list_; +} +inline ::tensorflow::FloatList* Feature::mutable_float_list() { + ::tensorflow::FloatList* _msg = _internal_mutable_float_list(); + // @@protoc_insertion_point(field_mutable:tensorflow.Feature.float_list) + return _msg; +} + +// .tensorflow.Int64List int64_list = 3; +inline bool Feature::_internal_has_int64_list() const { + return kind_case() == kInt64List; +} +inline bool Feature::has_int64_list() const { + return _internal_has_int64_list(); +} +inline void Feature::set_has_int64_list() { + _impl_._oneof_case_[0] = kInt64List; +} +inline void Feature::clear_int64_list() { + if (_internal_has_int64_list()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.kind_.int64_list_; + } + clear_has_kind(); + } +} +inline ::tensorflow::Int64List* Feature::release_int64_list() { + // @@protoc_insertion_point(field_release:tensorflow.Feature.int64_list) + if (_internal_has_int64_list()) { + clear_has_kind(); + ::tensorflow::Int64List* temp = _impl_.kind_.int64_list_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.kind_.int64_list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::Int64List& Feature::_internal_int64_list() const { + return _internal_has_int64_list() + ? *_impl_.kind_.int64_list_ + : reinterpret_cast< ::tensorflow::Int64List&>(::tensorflow::_Int64List_default_instance_); +} +inline const ::tensorflow::Int64List& Feature::int64_list() const { + // @@protoc_insertion_point(field_get:tensorflow.Feature.int64_list) + return _internal_int64_list(); +} +inline ::tensorflow::Int64List* Feature::unsafe_arena_release_int64_list() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.Feature.int64_list) + if (_internal_has_int64_list()) { + clear_has_kind(); + ::tensorflow::Int64List* temp = _impl_.kind_.int64_list_; + _impl_.kind_.int64_list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void Feature::unsafe_arena_set_allocated_int64_list(::tensorflow::Int64List* int64_list) { + clear_kind(); + if (int64_list) { + set_has_int64_list(); + _impl_.kind_.int64_list_ = int64_list; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.Feature.int64_list) +} +inline ::tensorflow::Int64List* Feature::_internal_mutable_int64_list() { + if (!_internal_has_int64_list()) { + clear_kind(); + set_has_int64_list(); + _impl_.kind_.int64_list_ = CreateMaybeMessage< ::tensorflow::Int64List >(GetArenaForAllocation()); + } + return _impl_.kind_.int64_list_; +} +inline ::tensorflow::Int64List* Feature::mutable_int64_list() { + ::tensorflow::Int64List* _msg = _internal_mutable_int64_list(); + // @@protoc_insertion_point(field_mutable:tensorflow.Feature.int64_list) + return _msg; +} + +inline bool Feature::has_kind() const { + return kind_case() != KIND_NOT_SET; +} +inline void Feature::clear_has_kind() { + _impl_._oneof_case_[0] = KIND_NOT_SET; +} +inline Feature::KindCase Feature::kind_case() const { + return Feature::KindCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// Features + +// map feature = 1; +inline int Features::_internal_feature_size() const { + return _impl_.feature_.size(); +} +inline int Features::feature_size() const { + return _internal_feature_size(); +} +inline void Features::clear_feature() { + _impl_.feature_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >& +Features::_internal_feature() const { + return _impl_.feature_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >& +Features::feature() const { + // @@protoc_insertion_point(field_map:tensorflow.Features.feature) + return _internal_feature(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >* +Features::_internal_mutable_feature() { + return _impl_.feature_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::Feature >* +Features::mutable_feature() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.Features.feature) + return _internal_mutable_feature(); +} + +// ------------------------------------------------------------------- + +// FeatureList + +// repeated .tensorflow.Feature feature = 1; +inline int FeatureList::_internal_feature_size() const { + return _impl_.feature_.size(); +} +inline int FeatureList::feature_size() const { + return _internal_feature_size(); +} +inline void FeatureList::clear_feature() { + _impl_.feature_.Clear(); +} +inline ::tensorflow::Feature* FeatureList::mutable_feature(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.FeatureList.feature) + return _impl_.feature_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::Feature >* +FeatureList::mutable_feature() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.FeatureList.feature) + return &_impl_.feature_; +} +inline const ::tensorflow::Feature& FeatureList::_internal_feature(int index) const { + return _impl_.feature_.Get(index); +} +inline const ::tensorflow::Feature& FeatureList::feature(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.FeatureList.feature) + return _internal_feature(index); +} +inline ::tensorflow::Feature* FeatureList::_internal_add_feature() { + return _impl_.feature_.Add(); +} +inline ::tensorflow::Feature* FeatureList::add_feature() { + ::tensorflow::Feature* _add = _internal_add_feature(); + // @@protoc_insertion_point(field_add:tensorflow.FeatureList.feature) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::Feature >& +FeatureList::feature() const { + // @@protoc_insertion_point(field_list:tensorflow.FeatureList.feature) + return _impl_.feature_; +} + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// FeatureLists + +// map feature_list = 1; +inline int FeatureLists::_internal_feature_list_size() const { + return _impl_.feature_list_.size(); +} +inline int FeatureLists::feature_list_size() const { + return _internal_feature_list_size(); +} +inline void FeatureLists::clear_feature_list() { + _impl_.feature_list_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >& +FeatureLists::_internal_feature_list() const { + return _impl_.feature_list_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >& +FeatureLists::feature_list() const { + // @@protoc_insertion_point(field_map:tensorflow.FeatureLists.feature_list) + return _internal_feature_list(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >* +FeatureLists::_internal_mutable_feature_list() { + return _impl_.feature_list_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::FeatureList >* +FeatureLists::mutable_feature_list() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.FeatureLists.feature_list) + return _internal_mutable_feature_list(); +} + +#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_2fexample_2ffeature_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature.proto new file mode 100644 index 0000000000000000000000000000000000000000..7f9fad982348d238ac2ac8fd12ae19bba147de52 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature.proto @@ -0,0 +1,110 @@ +// Protocol messages for describing features for machine learning model +// training or inference. +// +// There are three base Feature types: +// - bytes +// - float +// - int64 +// +// A Feature contains Lists which may hold zero or more values. These +// lists are the base values BytesList, FloatList, Int64List. +// +// Features are organized into categories by name. The Features message +// contains the mapping from name to Feature. +// +// Example Features for a movie recommendation application: +// feature { +// key: "age" +// value { float_list { +// value: 29.0 +// }} +// } +// feature { +// key: "movie" +// value { bytes_list { +// value: "The Shawshank Redemption" +// value: "Fight Club" +// }} +// } +// feature { +// key: "movie_ratings" +// value { float_list { +// value: 9.0 +// value: 9.7 +// }} +// } +// feature { +// key: "suggestion" +// value { bytes_list { +// value: "Inception" +// }} +// } +// feature { +// key: "suggestion_purchased" +// value { int64_list { +// value: 1 +// }} +// } +// feature { +// key: "purchase_price" +// value { float_list { +// value: 9.99 +// }} +// } +// + +syntax = "proto3"; + +package tensorflow; + +option cc_enable_arenas = true; +option java_outer_classname = "FeatureProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.example"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/example/example_protos_go_proto"; + +// LINT.IfChange +// Containers to hold repeated fundamental values. +message BytesList { + repeated bytes value = 1; +} +message FloatList { + repeated float value = 1 [packed = true]; +} +message Int64List { + repeated int64 value = 1 [packed = true]; +} + +// Containers for non-sequential data. +message Feature { + // Each feature can be exactly one kind. + oneof kind { + BytesList bytes_list = 1; + FloatList float_list = 2; + Int64List int64_list = 3; + } +} + +message Features { + // Map from feature name to feature. + map feature = 1; +} + +// Containers for sequential data. +// +// A FeatureList contains lists of Features. These may hold zero or more +// Feature values. +// +// FeatureLists are organized into categories by name. The FeatureLists message +// contains the mapping from name to FeatureList. +// +message FeatureList { + repeated Feature feature = 1; +} + +message FeatureLists { + // Map from feature name to feature list. + map feature_list = 1; +} +// LINT.ThenChange( +// https://www.tensorflow.org/code/tensorflow/python/training/training.py) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature_util.h new file mode 100644 index 0000000000000000000000000000000000000000..5f55138a94f4b055c14bd7b8cfe842bb45df6459 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/example/feature_util.h @@ -0,0 +1,638 @@ +/* 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 set of lightweight wrappers which simplify access to Feature protos. +// +// TensorFlow Example proto uses associative maps on top of oneof fields. +// SequenceExample proto uses associative map of FeatureList. +// So accessing feature values is not very convenient. +// +// For example, to read a first value of integer feature "tag": +// int id = example.features().feature().at("tag").int64_list().value(0); +// +// to add a value: +// auto features = example->mutable_features(); +// (*features->mutable_feature())["tag"].mutable_int64_list()->add_value(id); +// +// For float features you have to use float_list, for string - bytes_list. +// +// To do the same with this library: +// int id = GetFeatureValues("tag", example).Get(0); +// GetFeatureValues("tag", &example)->Add(id); +// +// Modification of bytes features is slightly different: +// auto tag = GetFeatureValues("tag", &example); +// *tag->Add() = "lorem ipsum"; +// +// To copy multiple values into a feature: +// AppendFeatureValues({1,2,3}, "tag", &example); +// +// GetFeatureValues gives you access to underlying data - RepeatedField object +// (RepeatedPtrField for byte list). So refer to its documentation of +// RepeatedField for full list of supported methods. +// +// NOTE: Due to the nature of oneof proto fields setting a feature of one type +// automatically clears all values stored as another type with the same feature +// key. +// +// This library also has tools to work with SequenceExample protos. +// +// To get a value from SequenceExample.context: +// int id = GetFeatureValues("tag", se.context()).Get(0); +// To add a value to the context: +// GetFeatureValues("tag", se.mutable_context())->Add(42); +// +// To add values to feature_lists: +// AppendFeatureValues({4.0}, +// GetFeatureList("images", &se)->Add()); +// AppendFeatureValues({5.0, 3.0}, +// GetFeatureList("images", &se)->Add()); +// This will create a feature list keyed as "images" with two features: +// feature_lists { +// feature_list { +// key: "images" +// value { +// feature { float_list { value: [4.0] } } +// feature { float_list { value: [5.0, 3.0] } } +// } +// } +// } +// For string-valued features, note that the Append... and Set... functions +// support absl::string_view containers. This allows you to copy existing +// buffers into a Feature with only one copy: +// std::vector image; +// image.push_back(image_buffer); // No copy. +// SetFeatureValues(image, "image", &example); // Copy. +// +// Functions exposed by this library: +// HasFeature<[FeatureType]>(key, proto) -> bool +// Returns true if a feature with the specified key, and optionally +// FeatureType, belongs to the Features or Example proto. +// HasFeatureList(key, sequence_example) -> bool +// Returns true if SequenceExample has a feature_list with the key. +// +// GetFeatureValues(key, proto) -> RepeatedField +// Returns values for the specified key and the FeatureType. +// Supported types for the proto: Example, Features. +// GetFeatureList(key, sequence_example) -> RepeatedPtrField +// Returns Feature protos associated with a key. +// +// AppendFeatureValues(begin, end, feature) +// AppendFeatureValues(container or initializer_list, feature) +// Copies values into a Feature. +// AppendFeatureValues(begin, end, key, proto) +// AppendFeatureValues(container or initializer_list, key, proto) +// Copies values into Features and Example protos with the specified key. +// +// ClearFeatureValues(feature) +// Clears the feature's repeated field of the given type. +// +// SetFeatureValues(begin, end, feature) +// SetFeatureValues(container or initializer_list, feature) +// Clears a Feature, then copies values into it. +// SetFeatureValues(begin, end, key, proto) +// SetFeatureValues(container or initializer_list, key, proto) +// Clears Features or Example protos with the specified key, +// then copies values into them. +// +// Auxiliary functions, it is unlikely you'll need to use them directly: +// GetFeatures(proto) -> Features +// A convenience function to get Features proto. +// Supported types for the proto: Example, Features. +// GetFeature(key, proto) -> Feature +// Returns a Feature proto for the specified key. +// Supported types for the proto: Example, Features. +// GetFeatureValues(feature) -> RepeatedField +// Returns values of the feature for the FeatureType. + +#ifndef TENSORFLOW_CORE_EXAMPLE_FEATURE_UTIL_H_ +#define TENSORFLOW_CORE_EXAMPLE_FEATURE_UTIL_H_ + +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "tensorflow/core/example/example.pb.h" +#include "tensorflow/core/example/feature.pb.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/stringpiece.h" + +// Must come after the import for absl::string_view. +#ifdef ABSL_HAVE_STD_STRING_VIEW +#include +#endif + +namespace tensorflow { +namespace internal { + +// TODO(gorban): Update all clients in a followup CL. +// Returns a reference to a feature corresponding to the name. +// Note: it will create a new Feature if it is missing in the example. +ABSL_DEPRECATED("Use GetFeature instead.") +Feature& ExampleFeature(absl::string_view name, Example* example); + +// Specializations of RepeatedFieldTrait define a type of RepeatedField +// corresponding to a selected feature type. +template +struct RepeatedFieldTrait; + +template <> +struct RepeatedFieldTrait { + using Type = protobuf::RepeatedField; +}; + +template <> +struct RepeatedFieldTrait { + using Type = protobuf::RepeatedField; +}; + +template <> +struct RepeatedFieldTrait { + using Type = protobuf::RepeatedPtrField; +}; + +template <> +struct RepeatedFieldTrait { + using Type = protobuf::RepeatedPtrField; +}; + +// Specializations of FeatureTrait define a type of feature corresponding to a +// selected value type. +template +struct FeatureTrait; + +template +struct FeatureTrait::value>::type> { + using Type = protobuf_int64; +}; + +template +struct FeatureTrait< + ValueType, + typename std::enable_if::value>::type> { + using Type = float; +}; + +template +struct is_string + : public std::integral_constant< + bool, + std::is_same::type>::value || + std::is_same::type>::value> { +}; + +template <> +struct is_string : std::true_type {}; + +template <> +struct is_string<::tensorflow::StringPiece> : std::true_type {}; + +template <> +struct is_string : std::true_type {}; + +template +struct FeatureTrait< + ValueType, typename std::enable_if::value>::type> { + using Type = std::string; +}; + +// Port of the C++20 `requires` expressions. +template +constexpr bool Requires(F) { + return std::is_invocable::value; +} + +struct NoneSuch {}; + +// True if the Feature map in a tf.Example supports heterogenous lookup. +// See https://abseil.io/tips/144. +inline constexpr bool kFeatureMapHasHeterogeneousLookup = + Requires( + [](auto&& c) -> decltype(c.find(NoneSuch{})) {}); + +// Converts an `absl::string_view` into a string-type compatible for use in the +// protobuf library (e.g. as lookup keys in `proto2::Map` or as elements addable +// to a `proto2::RepeatedPtrField`) depending on the BUILD mode. +// +// NOTE: While the newest versions of `proto2::Map` support heterogenous lookup, +// it does so through `std::string_view`. If the type is just an alias (as noted +// by `ABSL_USES_STD_STRING_VIEW`) then nothing more needs to be done; however, +// when the type is not an alias an explicit conversion to is necessary. +// +// NOTE: This conversion is only necessary until the migration for protobuf to +// take a dependency on ABSL is complete. +inline auto ProtoMapKey(absl::string_view str) { + if constexpr (kFeatureMapHasHeterogeneousLookup) { +#ifdef ABSL_USES_STD_STRING_VIEW + return str; +#else +#ifdef ABSL_HAVE_STD_STRING_VIEW + return std::string_view(str.data(), str.size()); +#else + return std::string(str); +#endif +#endif + } else { + return std::string(str); + } +} + +} // namespace internal + +// Returns true if sequence_example has a feature_list with the specified key. +bool HasFeatureList(absl::string_view key, + const SequenceExample& sequence_example); + +template +struct TypeHasFeatures : std::false_type {}; + +template <> +struct TypeHasFeatures : std::true_type {}; + +template <> +struct TypeHasFeatures : std::true_type {}; + +template <> +struct TypeHasFeatures : std::true_type {}; + +// A family of template functions to return mutable Features proto from a +// container proto. Supported ProtoTypes: SequenceExample, Example, Features. +template +typename std::enable_if::value, Features*>::type +GetFeatures(ProtoType* proto); + +template <> +Features* GetFeatures(Features* proto); +template <> +Features* GetFeatures(Example* proto); +template <> +Features* GetFeatures(SequenceExample* proto); + +template +typename std::enable_if::value, + const Features&>::type +GetFeatures(const ProtoType& proto); + +template <> +const Features& GetFeatures(const Features& proto); +template <> +const Features& GetFeatures(const Example& proto); +template <> +const Features& GetFeatures(const SequenceExample& proto); + +// Base declaration of a family of template functions to return a read only +// repeated field of feature values. +template +const typename internal::RepeatedFieldTrait::Type& +GetFeatureValues(const Feature& feature); + +template <> +const protobuf::RepeatedField& GetFeatureValues( + const Feature& feature); +template <> +const protobuf::RepeatedField& GetFeatureValues( + const Feature& feature); +template <> +const protobuf::RepeatedPtrField& GetFeatureValues( + const Feature& feature); +template <> +const protobuf::RepeatedPtrField& GetFeatureValues( + const Feature& feature); + +// Returns a read only repeated field corresponding to a feature with the +// specified name and FeatureType. Supported ProtoTypes: SequenceExample, +// Example, Features. +template +const typename internal::RepeatedFieldTrait::Type& +GetFeatureValues(absl::string_view key, const ProtoType& proto) { + return GetFeatureValues( + GetFeatures(proto).feature().at(internal::ProtoMapKey(key))); +} + +// Returns a mutable repeated field of a feature values. +template +typename internal::RepeatedFieldTrait::Type* GetFeatureValues( + Feature* feature); + +template <> +protobuf::RepeatedField* GetFeatureValues( + Feature* feature); +template <> +protobuf::RepeatedField* GetFeatureValues(Feature* feature); +template <> +protobuf::RepeatedPtrField* GetFeatureValues( + Feature* feature); +template <> +protobuf::RepeatedPtrField* GetFeatureValues( + Feature* feature); + +// Returns a mutable repeated field corresponding to a feature with the +// specified name and FeatureType. Supported ProtoTypes: SequenceExample, +// Example, Features. +template +typename internal::RepeatedFieldTrait::Type* GetFeatureValues( + absl::string_view key, ProtoType* proto) { + ::tensorflow::Feature& feature = + (*GetFeatures(proto)->mutable_feature())[internal::ProtoMapKey(key)]; + return GetFeatureValues(&feature); +} + +// Returns a read-only Feature proto for the specified key, throws +// std::out_of_range if the key is not found. Supported types for the proto: +// SequenceExample, Example, Features. +template +const Feature& GetFeature(absl::string_view key, const ProtoType& proto) { + return GetFeatures(proto).feature().at(internal::ProtoMapKey(key)); +} + +// Returns a read-only Feature proto for the specified key, returns nullptr +// if the key is not found. Supported types for the proto: SequenceExample, +// Example, Features. +template +const Feature* MaybeGetFeature(absl::string_view key, const ProtoType& proto) { + const protobuf::Map& feature_map = + GetFeatures(proto).feature(); + auto it = feature_map.find(internal::ProtoMapKey(key)); + + if (it == feature_map.end()) { + return nullptr; + } + + return &it->second; +} + +// Base declaration of a family of template functions to return a read only +// repeated field of feature values or nullptr. +template +const typename internal::RepeatedFieldTrait::Type* +MaybeGetFeatureValues(const Feature& feature); + +template <> +const protobuf::RepeatedField* +MaybeGetFeatureValues(const Feature& feature); +template <> +const protobuf::RepeatedField* MaybeGetFeatureValues( + const Feature& feature); +template <> +const protobuf::RepeatedPtrField* MaybeGetFeatureValues( + const Feature& feature); +template <> +const protobuf::RepeatedPtrField* +MaybeGetFeatureValues(const Feature& feature); + +// Returns a read only repeated field corresponding to a feature with the +// specified name and FeatureType. Supported ProtoTypes: SequenceExample, +// Example, Features. +template +const typename internal::RepeatedFieldTrait::Type* +MaybeGetFeatureValues(absl::string_view key, const ProtoType& proto) { + const Feature* feature = MaybeGetFeature(key, proto); + if (feature == nullptr) { + return nullptr; + } + return &GetFeatureValues(*feature); +} + +// Returns a mutable Feature proto for the specified key, creates a new if +// necessary. Supported types for the proto: SequenceExample, Example, Features. +template +Feature* GetFeature(absl::string_view key, ProtoType* proto) { + return &(*GetFeatures(proto)->mutable_feature())[internal::ProtoMapKey(key)]; +} + +// Returns a repeated field with features corresponding to a feature_list key. +const protobuf::RepeatedPtrField& GetFeatureList( + absl::string_view key, const SequenceExample& sequence_example); + +// Returns a mutable repeated field with features corresponding to a +// feature_list key. It will create a new FeatureList if necessary. +protobuf::RepeatedPtrField* GetFeatureList( + absl::string_view feature_list_key, SequenceExample* sequence_example); + +template +void AppendFeatureValues(IteratorType first, IteratorType last, + Feature* feature) { + using FeatureType = typename internal::FeatureTrait< + typename std::iterator_traits::value_type>::Type; + auto& values = *GetFeatureValues(feature); + values.Reserve(std::distance(first, last)); + for (auto it = first; it != last; ++it) { + *values.Add() = *it; + } +} + +template +void AppendFeatureValues(std::initializer_list container, + Feature* feature) { + using FeatureType = typename internal::FeatureTrait::Type; + auto& values = *GetFeatureValues(feature); + values.Reserve(container.size()); + for (auto& elt : container) { + *values.Add() = std::move(elt); + } +} + +namespace internal { + +// HasSize::value is true_type if T has a size() member. +template +struct HasSize : std::false_type {}; + +template +struct HasSize().size())>> + : std::true_type {}; + +// Reserves the container's size, if a container.size() method exists. +template +auto ReserveIfSizeAvailable(const ContainerType& container, + RepeatedFieldType& values) -> + typename std::enable_if_t::value, void> { + values.Reserve(container.size()); +} + +template +auto ReserveIfSizeAvailable(const ContainerType& container, + RepeatedFieldType& values) -> + typename std::enable_if_t::value, void> {} + +} // namespace internal + +template +void AppendFeatureValues(const ContainerType& container, Feature* feature) { + using IteratorType = typename ContainerType::const_iterator; + using FeatureType = typename internal::FeatureTrait< + typename std::iterator_traits::value_type>::Type; + auto* values = GetFeatureValues(feature); + internal::ReserveIfSizeAvailable(container, *values); + // This is equivalent to std::copy into `values` with a + // RepeatedFieldBackInserter, the difference is RFBI isn't compatible with + // types that we want to convert (e.g. absl::string_view -> std::string). + for (const auto& elt : container) { + if constexpr (internal::is_string::value) { + *values->Add() = std::string(elt); + } else { + *values->Add() = elt; + } + } +} + +// Copies elements from the range, defined by [first, last) into the feature +// obtainable from the (proto, key) combination. +template +void AppendFeatureValues(IteratorType first, IteratorType last, + absl::string_view key, ProtoType* proto) { + AppendFeatureValues(first, last, GetFeature(key, GetFeatures(proto))); +} + +// Copies all elements from the container into a feature. +template +void AppendFeatureValues(const ContainerType& container, absl::string_view key, + ProtoType* proto) { + AppendFeatureValues(container, + GetFeature(key, GetFeatures(proto))); +} + +// Copies all elements from the initializer list into a Feature contained by +// Features or Example proto. +template +void AppendFeatureValues(std::initializer_list container, + absl::string_view key, ProtoType* proto) { + AppendFeatureValues(container, + GetFeature(key, GetFeatures(proto))); +} + +// Clears the feature's repeated field (int64, float, or string). +template +void ClearFeatureValues(Feature* feature); + +template <> +void ClearFeatureValues(Feature* feature); +template <> +void ClearFeatureValues(Feature* feature); +template <> +void ClearFeatureValues(Feature* feature); +template <> +void ClearFeatureValues(Feature* feature); + +// Clears the feature's repeated field (int64, float, or string). Copies +// elements from the range, defined by [first, last) into the feature's repeated +// field. +template +void SetFeatureValues(IteratorType first, IteratorType last, Feature* feature) { + using FeatureType = typename internal::FeatureTrait< + typename std::iterator_traits::value_type>::Type; + ClearFeatureValues(feature); + AppendFeatureValues(first, last, feature); +} + +// Clears the feature's repeated field (int64, float, or string). Copies all +// elements from the initializer list into the feature's repeated field. +template +void SetFeatureValues(std::initializer_list container, + Feature* feature) { + using FeatureType = typename internal::FeatureTrait::Type; + ClearFeatureValues(feature); + AppendFeatureValues(container, feature); +} + +// Clears the feature's repeated field (int64, float, or string). Copies all +// elements from the container into the feature's repeated field. +template +void SetFeatureValues(const ContainerType& container, Feature* feature) { + using IteratorType = typename ContainerType::const_iterator; + using FeatureType = typename internal::FeatureTrait< + typename std::iterator_traits::value_type>::Type; + ClearFeatureValues(feature); + AppendFeatureValues(container, feature); +} + +// Clears the feature's repeated field (int64, float, or string). Copies +// elements from the range, defined by [first, last) into the feature's repeated +// field. +template +void SetFeatureValues(IteratorType first, IteratorType last, + absl::string_view key, ProtoType* proto) { + SetFeatureValues(first, last, GetFeature(key, GetFeatures(proto))); +} + +// Clears the feature's repeated field (int64, float, or string). Copies all +// elements from the container into the feature's repeated field. +template +void SetFeatureValues(const ContainerType& container, absl::string_view key, + ProtoType* proto) { + SetFeatureValues(container, + GetFeature(key, GetFeatures(proto))); +} + +// Clears the feature's repeated field (int64, float, or string). Copies all +// elements from the initializer list into the feature's repeated field. +template +void SetFeatureValues(std::initializer_list container, + absl::string_view key, ProtoType* proto) { + SetFeatureValues(container, GetFeature(key, GetFeatures(proto))); +} + +// Returns true if a feature with the specified key belongs to the Features. +// The template parameter pack accepts zero or one template argument - which +// is FeatureType. If the FeatureType not specified (zero template arguments) +// the function will not check the feature type. Otherwise it will return false +// if the feature has a wrong type. +template +bool HasFeature(absl::string_view key, const Features& features); + +template <> +bool HasFeature<>(absl::string_view key, const Features& features); +template <> +bool HasFeature(absl::string_view key, + const Features& features); +template <> +bool HasFeature(absl::string_view key, const Features& features); +template <> +bool HasFeature(absl::string_view key, const Features& features); +template <> +bool HasFeature(absl::string_view key, const Features& features); + +// Returns true if a feature with the specified key belongs to the Example. +// Doesn't check feature type if used without FeatureType, otherwise the +// specialized versions return false if the feature has a wrong type. +template +bool HasFeature(absl::string_view key, const Example& example) { + return HasFeature(key, GetFeatures(example)); +} + +// Returns true if a feature with the specified key belongs to the +// SequenceExample. Doesn't check feature type if used without FeatureType, +// otherwise the specialized versions return false if the feature has a wrong +// type. +template +bool HasFeature(absl::string_view key, + const SequenceExample& sequence_example) { + return HasFeature(key, GetFeatures(sequence_example)); +} + +// TODO(gorban): update all clients in a followup CL. +template +ABSL_DEPRECATED("Use HasFeature instead.") +bool ExampleHasFeature(absl::string_view key, const Example& example) { + return HasFeature(key, example); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_EXAMPLE_FEATURE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocation_description.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocation_description.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..e645c180df12d0b0e38c91de6048a0db91b3914e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocation_description.pb.h @@ -0,0 +1,437 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/allocation_description.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fallocation_5fdescription_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fallocation_5fdescription_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fallocation_5fdescription_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_2fframework_2fallocation_5fdescription_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fallocation_5fdescription_2eproto; +namespace tensorflow { +class AllocationDescription; +struct AllocationDescriptionDefaultTypeInternal; +extern AllocationDescriptionDefaultTypeInternal _AllocationDescription_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::AllocationDescription* Arena::CreateMaybeMessage<::tensorflow::AllocationDescription>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class AllocationDescription final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.AllocationDescription) */ { + public: + inline AllocationDescription() : AllocationDescription(nullptr) {} + ~AllocationDescription() override; + explicit PROTOBUF_CONSTEXPR AllocationDescription(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AllocationDescription(const AllocationDescription& from); + AllocationDescription(AllocationDescription&& from) noexcept + : AllocationDescription() { + *this = ::std::move(from); + } + + inline AllocationDescription& operator=(const AllocationDescription& from) { + CopyFrom(from); + return *this; + } + inline AllocationDescription& operator=(AllocationDescription&& 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 AllocationDescription& default_instance() { + return *internal_default_instance(); + } + static inline const AllocationDescription* internal_default_instance() { + return reinterpret_cast( + &_AllocationDescription_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(AllocationDescription& a, AllocationDescription& b) { + a.Swap(&b); + } + inline void Swap(AllocationDescription* 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(AllocationDescription* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AllocationDescription* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AllocationDescription& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AllocationDescription& from) { + AllocationDescription::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(AllocationDescription* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.AllocationDescription"; + } + protected: + explicit AllocationDescription(::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 { + kAllocatorNameFieldNumber = 3, + kRequestedBytesFieldNumber = 1, + kAllocatedBytesFieldNumber = 2, + kAllocationIdFieldNumber = 4, + kPtrFieldNumber = 6, + kHasSingleReferenceFieldNumber = 5, + }; + // string allocator_name = 3; + void clear_allocator_name(); + const std::string& allocator_name() const; + template + void set_allocator_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_allocator_name(); + PROTOBUF_NODISCARD std::string* release_allocator_name(); + void set_allocated_allocator_name(std::string* allocator_name); + private: + const std::string& _internal_allocator_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_allocator_name(const std::string& value); + std::string* _internal_mutable_allocator_name(); + public: + + // int64 requested_bytes = 1; + void clear_requested_bytes(); + int64_t requested_bytes() const; + void set_requested_bytes(int64_t value); + private: + int64_t _internal_requested_bytes() const; + void _internal_set_requested_bytes(int64_t value); + public: + + // int64 allocated_bytes = 2; + void clear_allocated_bytes(); + int64_t allocated_bytes() const; + void set_allocated_bytes(int64_t value); + private: + int64_t _internal_allocated_bytes() const; + void _internal_set_allocated_bytes(int64_t value); + public: + + // int64 allocation_id = 4; + void clear_allocation_id(); + int64_t allocation_id() const; + void set_allocation_id(int64_t value); + private: + int64_t _internal_allocation_id() const; + void _internal_set_allocation_id(int64_t value); + public: + + // uint64 ptr = 6; + void clear_ptr(); + uint64_t ptr() const; + void set_ptr(uint64_t value); + private: + uint64_t _internal_ptr() const; + void _internal_set_ptr(uint64_t value); + public: + + // bool has_single_reference = 5; + void clear_has_single_reference(); + bool has_single_reference() const; + void set_has_single_reference(bool value); + private: + bool _internal_has_single_reference() const; + void _internal_set_has_single_reference(bool value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.AllocationDescription) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr allocator_name_; + int64_t requested_bytes_; + int64_t allocated_bytes_; + int64_t allocation_id_; + uint64_t ptr_; + bool has_single_reference_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fallocation_5fdescription_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// AllocationDescription + +// int64 requested_bytes = 1; +inline void AllocationDescription::clear_requested_bytes() { + _impl_.requested_bytes_ = int64_t{0}; +} +inline int64_t AllocationDescription::_internal_requested_bytes() const { + return _impl_.requested_bytes_; +} +inline int64_t AllocationDescription::requested_bytes() const { + // @@protoc_insertion_point(field_get:tensorflow.AllocationDescription.requested_bytes) + return _internal_requested_bytes(); +} +inline void AllocationDescription::_internal_set_requested_bytes(int64_t value) { + + _impl_.requested_bytes_ = value; +} +inline void AllocationDescription::set_requested_bytes(int64_t value) { + _internal_set_requested_bytes(value); + // @@protoc_insertion_point(field_set:tensorflow.AllocationDescription.requested_bytes) +} + +// int64 allocated_bytes = 2; +inline void AllocationDescription::clear_allocated_bytes() { + _impl_.allocated_bytes_ = int64_t{0}; +} +inline int64_t AllocationDescription::_internal_allocated_bytes() const { + return _impl_.allocated_bytes_; +} +inline int64_t AllocationDescription::allocated_bytes() const { + // @@protoc_insertion_point(field_get:tensorflow.AllocationDescription.allocated_bytes) + return _internal_allocated_bytes(); +} +inline void AllocationDescription::_internal_set_allocated_bytes(int64_t value) { + + _impl_.allocated_bytes_ = value; +} +inline void AllocationDescription::set_allocated_bytes(int64_t value) { + _internal_set_allocated_bytes(value); + // @@protoc_insertion_point(field_set:tensorflow.AllocationDescription.allocated_bytes) +} + +// string allocator_name = 3; +inline void AllocationDescription::clear_allocator_name() { + _impl_.allocator_name_.ClearToEmpty(); +} +inline const std::string& AllocationDescription::allocator_name() const { + // @@protoc_insertion_point(field_get:tensorflow.AllocationDescription.allocator_name) + return _internal_allocator_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void AllocationDescription::set_allocator_name(ArgT0&& arg0, ArgT... args) { + + _impl_.allocator_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.AllocationDescription.allocator_name) +} +inline std::string* AllocationDescription::mutable_allocator_name() { + std::string* _s = _internal_mutable_allocator_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.AllocationDescription.allocator_name) + return _s; +} +inline const std::string& AllocationDescription::_internal_allocator_name() const { + return _impl_.allocator_name_.Get(); +} +inline void AllocationDescription::_internal_set_allocator_name(const std::string& value) { + + _impl_.allocator_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* AllocationDescription::_internal_mutable_allocator_name() { + + return _impl_.allocator_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* AllocationDescription::release_allocator_name() { + // @@protoc_insertion_point(field_release:tensorflow.AllocationDescription.allocator_name) + return _impl_.allocator_name_.Release(); +} +inline void AllocationDescription::set_allocated_allocator_name(std::string* allocator_name) { + if (allocator_name != nullptr) { + + } else { + + } + _impl_.allocator_name_.SetAllocated(allocator_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.allocator_name_.IsDefault()) { + _impl_.allocator_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.AllocationDescription.allocator_name) +} + +// int64 allocation_id = 4; +inline void AllocationDescription::clear_allocation_id() { + _impl_.allocation_id_ = int64_t{0}; +} +inline int64_t AllocationDescription::_internal_allocation_id() const { + return _impl_.allocation_id_; +} +inline int64_t AllocationDescription::allocation_id() const { + // @@protoc_insertion_point(field_get:tensorflow.AllocationDescription.allocation_id) + return _internal_allocation_id(); +} +inline void AllocationDescription::_internal_set_allocation_id(int64_t value) { + + _impl_.allocation_id_ = value; +} +inline void AllocationDescription::set_allocation_id(int64_t value) { + _internal_set_allocation_id(value); + // @@protoc_insertion_point(field_set:tensorflow.AllocationDescription.allocation_id) +} + +// bool has_single_reference = 5; +inline void AllocationDescription::clear_has_single_reference() { + _impl_.has_single_reference_ = false; +} +inline bool AllocationDescription::_internal_has_single_reference() const { + return _impl_.has_single_reference_; +} +inline bool AllocationDescription::has_single_reference() const { + // @@protoc_insertion_point(field_get:tensorflow.AllocationDescription.has_single_reference) + return _internal_has_single_reference(); +} +inline void AllocationDescription::_internal_set_has_single_reference(bool value) { + + _impl_.has_single_reference_ = value; +} +inline void AllocationDescription::set_has_single_reference(bool value) { + _internal_set_has_single_reference(value); + // @@protoc_insertion_point(field_set:tensorflow.AllocationDescription.has_single_reference) +} + +// uint64 ptr = 6; +inline void AllocationDescription::clear_ptr() { + _impl_.ptr_ = uint64_t{0u}; +} +inline uint64_t AllocationDescription::_internal_ptr() const { + return _impl_.ptr_; +} +inline uint64_t AllocationDescription::ptr() const { + // @@protoc_insertion_point(field_get:tensorflow.AllocationDescription.ptr) + return _internal_ptr(); +} +inline void AllocationDescription::_internal_set_ptr(uint64_t value) { + + _impl_.ptr_ = value; +} +inline void AllocationDescription::set_ptr(uint64_t value) { + _internal_set_ptr(value); + // @@protoc_insertion_point(field_set:tensorflow.AllocationDescription.ptr) +} + +#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_2fframework_2fallocation_5fdescription_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocation_description.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocation_description.proto new file mode 100644 index 0000000000000000000000000000000000000000..f18caa40b2bde7cbb3a51b676cfdbfad18caa740 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocation_description.proto @@ -0,0 +1,29 @@ +syntax = "proto3"; + +package tensorflow; + +option cc_enable_arenas = true; +option java_outer_classname = "AllocationDescriptionProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/allocation_description_go_proto"; + +message AllocationDescription { + // Total number of bytes requested + int64 requested_bytes = 1; + + // Total number of bytes allocated if known + int64 allocated_bytes = 2; + + // Name of the allocator used + string allocator_name = 3; + + // Identifier of the allocated buffer if known + int64 allocation_id = 4; + + // Set if this tensor only has one remaining reference + bool has_single_reference = 5; + + // Address of the allocation. + uint64 ptr = 6; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocator.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..9e6fdc8f0c9369479815153f9b76c670b325026f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocator.h @@ -0,0 +1,55 @@ +/* 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_FRAMEWORK_ALLOCATOR_H_ +#define TENSORFLOW_CORE_FRAMEWORK_ALLOCATOR_H_ + +#include + +#include +#include + +#include "absl/strings/string_view.h" +#include "absl/types/optional.h" +#include "tensorflow/core/framework/numeric_types.h" +#include "tensorflow/core/framework/type_traits.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/numa.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/framework/allocator.h" + +namespace tensorflow { + +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::AllocationAttributes; +using tsl::Allocator; +using tsl::AllocatorAttributes; +using tsl::AllocatorMemoryType; +using tsl::AllocatorStats; +using tsl::AllocatorWrapper; +using tsl::cpu_allocator; +using tsl::cpu_allocator_base; +using tsl::CPUAllocatorFullStatsEnabled; +using tsl::CPUAllocatorStatsEnabled; +using tsl::DisableCPUAllocatorStats; +using tsl::EnableCPUAllocatorFullStats; +using tsl::EnableCPUAllocatorStats; +using tsl::SubAllocator; +// NOLINTEND(misc-unused-using-decls) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_ALLOCATOR_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocator_registry.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocator_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..1bc537554c76c117b3449fa2d2e84a672281f8f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/allocator_registry.h @@ -0,0 +1,40 @@ +/* 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. +==============================================================================*/ + +// Classes to maintain a static registry of memory allocator factories. +#ifndef TENSORFLOW_CORE_FRAMEWORK_ALLOCATOR_REGISTRY_H_ +#define TENSORFLOW_CORE_FRAMEWORK_ALLOCATOR_REGISTRY_H_ + +#include +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/numa.h" +#include "tsl/framework/allocator_registry.h" + +namespace tensorflow { + +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::AllocatorFactory; +using tsl::AllocatorFactoryRegistration; +using tsl::AllocatorFactoryRegistry; +using tsl::ProcessStateInterface; +// NOLINTEND(misc-unused-using-decls) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_ALLOCATOR_REGISTRY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/api_def.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/api_def.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..f61281b12652f0c6f7b0e417853b1c3454309b03 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/api_def.pb.h @@ -0,0 +1,2369 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/api_def.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include "tensorflow/core/framework/attr_value.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fapi_5fdef_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_2fframework_2fapi_5fdef_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto; +namespace tensorflow { +class ApiDef; +struct ApiDefDefaultTypeInternal; +extern ApiDefDefaultTypeInternal _ApiDef_default_instance_; +class ApiDef_Arg; +struct ApiDef_ArgDefaultTypeInternal; +extern ApiDef_ArgDefaultTypeInternal _ApiDef_Arg_default_instance_; +class ApiDef_Attr; +struct ApiDef_AttrDefaultTypeInternal; +extern ApiDef_AttrDefaultTypeInternal _ApiDef_Attr_default_instance_; +class ApiDef_Endpoint; +struct ApiDef_EndpointDefaultTypeInternal; +extern ApiDef_EndpointDefaultTypeInternal _ApiDef_Endpoint_default_instance_; +class ApiDefs; +struct ApiDefsDefaultTypeInternal; +extern ApiDefsDefaultTypeInternal _ApiDefs_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::ApiDef* Arena::CreateMaybeMessage<::tensorflow::ApiDef>(Arena*); +template<> ::tensorflow::ApiDef_Arg* Arena::CreateMaybeMessage<::tensorflow::ApiDef_Arg>(Arena*); +template<> ::tensorflow::ApiDef_Attr* Arena::CreateMaybeMessage<::tensorflow::ApiDef_Attr>(Arena*); +template<> ::tensorflow::ApiDef_Endpoint* Arena::CreateMaybeMessage<::tensorflow::ApiDef_Endpoint>(Arena*); +template<> ::tensorflow::ApiDefs* Arena::CreateMaybeMessage<::tensorflow::ApiDefs>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +enum ApiDef_Visibility : int { + ApiDef_Visibility_DEFAULT_VISIBILITY = 0, + ApiDef_Visibility_VISIBLE = 1, + ApiDef_Visibility_SKIP = 2, + ApiDef_Visibility_HIDDEN = 3, + ApiDef_Visibility_ApiDef_Visibility_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + ApiDef_Visibility_ApiDef_Visibility_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool ApiDef_Visibility_IsValid(int value); +constexpr ApiDef_Visibility ApiDef_Visibility_Visibility_MIN = ApiDef_Visibility_DEFAULT_VISIBILITY; +constexpr ApiDef_Visibility ApiDef_Visibility_Visibility_MAX = ApiDef_Visibility_HIDDEN; +constexpr int ApiDef_Visibility_Visibility_ARRAYSIZE = ApiDef_Visibility_Visibility_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* ApiDef_Visibility_descriptor(); +template +inline const std::string& ApiDef_Visibility_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function ApiDef_Visibility_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + ApiDef_Visibility_descriptor(), enum_t_value); +} +inline bool ApiDef_Visibility_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ApiDef_Visibility* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + ApiDef_Visibility_descriptor(), name, value); +} +// =================================================================== + +class ApiDef_Endpoint final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ApiDef.Endpoint) */ { + public: + inline ApiDef_Endpoint() : ApiDef_Endpoint(nullptr) {} + ~ApiDef_Endpoint() override; + explicit PROTOBUF_CONSTEXPR ApiDef_Endpoint(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ApiDef_Endpoint(const ApiDef_Endpoint& from); + ApiDef_Endpoint(ApiDef_Endpoint&& from) noexcept + : ApiDef_Endpoint() { + *this = ::std::move(from); + } + + inline ApiDef_Endpoint& operator=(const ApiDef_Endpoint& from) { + CopyFrom(from); + return *this; + } + inline ApiDef_Endpoint& operator=(ApiDef_Endpoint&& 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 ApiDef_Endpoint& default_instance() { + return *internal_default_instance(); + } + static inline const ApiDef_Endpoint* internal_default_instance() { + return reinterpret_cast( + &_ApiDef_Endpoint_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(ApiDef_Endpoint& a, ApiDef_Endpoint& b) { + a.Swap(&b); + } + inline void Swap(ApiDef_Endpoint* 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(ApiDef_Endpoint* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ApiDef_Endpoint* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ApiDef_Endpoint& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ApiDef_Endpoint& from) { + ApiDef_Endpoint::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(ApiDef_Endpoint* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ApiDef.Endpoint"; + } + protected: + explicit ApiDef_Endpoint(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + kDeprecatedFieldNumber = 3, + kDeprecationVersionFieldNumber = 4, + }; + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // bool deprecated = 3; + void clear_deprecated(); + bool deprecated() const; + void set_deprecated(bool value); + private: + bool _internal_deprecated() const; + void _internal_set_deprecated(bool value); + public: + + // int32 deprecation_version = 4; + void clear_deprecation_version(); + int32_t deprecation_version() const; + void set_deprecation_version(int32_t value); + private: + int32_t _internal_deprecation_version() const; + void _internal_set_deprecation_version(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.ApiDef.Endpoint) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + bool deprecated_; + int32_t deprecation_version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto; +}; +// ------------------------------------------------------------------- + +class ApiDef_Arg final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ApiDef.Arg) */ { + public: + inline ApiDef_Arg() : ApiDef_Arg(nullptr) {} + ~ApiDef_Arg() override; + explicit PROTOBUF_CONSTEXPR ApiDef_Arg(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ApiDef_Arg(const ApiDef_Arg& from); + ApiDef_Arg(ApiDef_Arg&& from) noexcept + : ApiDef_Arg() { + *this = ::std::move(from); + } + + inline ApiDef_Arg& operator=(const ApiDef_Arg& from) { + CopyFrom(from); + return *this; + } + inline ApiDef_Arg& operator=(ApiDef_Arg&& 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 ApiDef_Arg& default_instance() { + return *internal_default_instance(); + } + static inline const ApiDef_Arg* internal_default_instance() { + return reinterpret_cast( + &_ApiDef_Arg_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(ApiDef_Arg& a, ApiDef_Arg& b) { + a.Swap(&b); + } + inline void Swap(ApiDef_Arg* 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(ApiDef_Arg* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ApiDef_Arg* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ApiDef_Arg& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ApiDef_Arg& from) { + ApiDef_Arg::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(ApiDef_Arg* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ApiDef.Arg"; + } + protected: + explicit ApiDef_Arg(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + kRenameToFieldNumber = 2, + kDescriptionFieldNumber = 3, + }; + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string rename_to = 2; + void clear_rename_to(); + const std::string& rename_to() const; + template + void set_rename_to(ArgT0&& arg0, ArgT... args); + std::string* mutable_rename_to(); + PROTOBUF_NODISCARD std::string* release_rename_to(); + void set_allocated_rename_to(std::string* rename_to); + private: + const std::string& _internal_rename_to() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_rename_to(const std::string& value); + std::string* _internal_mutable_rename_to(); + public: + + // string description = 3; + void clear_description(); + const std::string& description() const; + template + void set_description(ArgT0&& arg0, ArgT... args); + std::string* mutable_description(); + PROTOBUF_NODISCARD std::string* release_description(); + void set_allocated_description(std::string* description); + private: + const std::string& _internal_description() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_description(const std::string& value); + std::string* _internal_mutable_description(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.ApiDef.Arg) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr rename_to_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr description_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto; +}; +// ------------------------------------------------------------------- + +class ApiDef_Attr final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ApiDef.Attr) */ { + public: + inline ApiDef_Attr() : ApiDef_Attr(nullptr) {} + ~ApiDef_Attr() override; + explicit PROTOBUF_CONSTEXPR ApiDef_Attr(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ApiDef_Attr(const ApiDef_Attr& from); + ApiDef_Attr(ApiDef_Attr&& from) noexcept + : ApiDef_Attr() { + *this = ::std::move(from); + } + + inline ApiDef_Attr& operator=(const ApiDef_Attr& from) { + CopyFrom(from); + return *this; + } + inline ApiDef_Attr& operator=(ApiDef_Attr&& 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 ApiDef_Attr& default_instance() { + return *internal_default_instance(); + } + static inline const ApiDef_Attr* internal_default_instance() { + return reinterpret_cast( + &_ApiDef_Attr_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(ApiDef_Attr& a, ApiDef_Attr& b) { + a.Swap(&b); + } + inline void Swap(ApiDef_Attr* 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(ApiDef_Attr* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ApiDef_Attr* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ApiDef_Attr& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ApiDef_Attr& from) { + ApiDef_Attr::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(ApiDef_Attr* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ApiDef.Attr"; + } + protected: + explicit ApiDef_Attr(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + kRenameToFieldNumber = 2, + kDescriptionFieldNumber = 4, + kDefaultValueFieldNumber = 3, + }; + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string rename_to = 2; + void clear_rename_to(); + const std::string& rename_to() const; + template + void set_rename_to(ArgT0&& arg0, ArgT... args); + std::string* mutable_rename_to(); + PROTOBUF_NODISCARD std::string* release_rename_to(); + void set_allocated_rename_to(std::string* rename_to); + private: + const std::string& _internal_rename_to() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_rename_to(const std::string& value); + std::string* _internal_mutable_rename_to(); + public: + + // string description = 4; + void clear_description(); + const std::string& description() const; + template + void set_description(ArgT0&& arg0, ArgT... args); + std::string* mutable_description(); + PROTOBUF_NODISCARD std::string* release_description(); + void set_allocated_description(std::string* description); + private: + const std::string& _internal_description() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_description(const std::string& value); + std::string* _internal_mutable_description(); + public: + + // .tensorflow.AttrValue default_value = 3; + bool has_default_value() const; + private: + bool _internal_has_default_value() const; + public: + void clear_default_value(); + const ::tensorflow::AttrValue& default_value() const; + PROTOBUF_NODISCARD ::tensorflow::AttrValue* release_default_value(); + ::tensorflow::AttrValue* mutable_default_value(); + void set_allocated_default_value(::tensorflow::AttrValue* default_value); + private: + const ::tensorflow::AttrValue& _internal_default_value() const; + ::tensorflow::AttrValue* _internal_mutable_default_value(); + public: + void unsafe_arena_set_allocated_default_value( + ::tensorflow::AttrValue* default_value); + ::tensorflow::AttrValue* unsafe_arena_release_default_value(); + + // @@protoc_insertion_point(class_scope:tensorflow.ApiDef.Attr) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr rename_to_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr description_; + ::tensorflow::AttrValue* default_value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto; +}; +// ------------------------------------------------------------------- + +class ApiDef final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ApiDef) */ { + public: + inline ApiDef() : ApiDef(nullptr) {} + ~ApiDef() override; + explicit PROTOBUF_CONSTEXPR ApiDef(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ApiDef(const ApiDef& from); + ApiDef(ApiDef&& from) noexcept + : ApiDef() { + *this = ::std::move(from); + } + + inline ApiDef& operator=(const ApiDef& from) { + CopyFrom(from); + return *this; + } + inline ApiDef& operator=(ApiDef&& 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 ApiDef& default_instance() { + return *internal_default_instance(); + } + static inline const ApiDef* internal_default_instance() { + return reinterpret_cast( + &_ApiDef_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(ApiDef& a, ApiDef& b) { + a.Swap(&b); + } + inline void Swap(ApiDef* 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(ApiDef* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ApiDef* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ApiDef& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ApiDef& from) { + ApiDef::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(ApiDef* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ApiDef"; + } + protected: + explicit ApiDef(::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 ApiDef_Endpoint Endpoint; + typedef ApiDef_Arg Arg; + typedef ApiDef_Attr Attr; + + typedef ApiDef_Visibility Visibility; + static constexpr Visibility DEFAULT_VISIBILITY = + ApiDef_Visibility_DEFAULT_VISIBILITY; + static constexpr Visibility VISIBLE = + ApiDef_Visibility_VISIBLE; + static constexpr Visibility SKIP = + ApiDef_Visibility_SKIP; + static constexpr Visibility HIDDEN = + ApiDef_Visibility_HIDDEN; + static inline bool Visibility_IsValid(int value) { + return ApiDef_Visibility_IsValid(value); + } + static constexpr Visibility Visibility_MIN = + ApiDef_Visibility_Visibility_MIN; + static constexpr Visibility Visibility_MAX = + ApiDef_Visibility_Visibility_MAX; + static constexpr int Visibility_ARRAYSIZE = + ApiDef_Visibility_Visibility_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + Visibility_descriptor() { + return ApiDef_Visibility_descriptor(); + } + template + static inline const std::string& Visibility_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Visibility_Name."); + return ApiDef_Visibility_Name(enum_t_value); + } + static inline bool Visibility_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + Visibility* value) { + return ApiDef_Visibility_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kEndpointFieldNumber = 3, + kInArgFieldNumber = 4, + kOutArgFieldNumber = 5, + kAttrFieldNumber = 6, + kArgOrderFieldNumber = 11, + kGraphOpNameFieldNumber = 1, + kSummaryFieldNumber = 7, + kDescriptionFieldNumber = 8, + kDescriptionPrefixFieldNumber = 9, + kDescriptionSuffixFieldNumber = 10, + kDeprecationMessageFieldNumber = 12, + kVisibilityFieldNumber = 2, + kDeprecationVersionFieldNumber = 13, + }; + // repeated .tensorflow.ApiDef.Endpoint endpoint = 3; + int endpoint_size() const; + private: + int _internal_endpoint_size() const; + public: + void clear_endpoint(); + ::tensorflow::ApiDef_Endpoint* mutable_endpoint(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Endpoint >* + mutable_endpoint(); + private: + const ::tensorflow::ApiDef_Endpoint& _internal_endpoint(int index) const; + ::tensorflow::ApiDef_Endpoint* _internal_add_endpoint(); + public: + const ::tensorflow::ApiDef_Endpoint& endpoint(int index) const; + ::tensorflow::ApiDef_Endpoint* add_endpoint(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Endpoint >& + endpoint() const; + + // repeated .tensorflow.ApiDef.Arg in_arg = 4; + int in_arg_size() const; + private: + int _internal_in_arg_size() const; + public: + void clear_in_arg(); + ::tensorflow::ApiDef_Arg* mutable_in_arg(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >* + mutable_in_arg(); + private: + const ::tensorflow::ApiDef_Arg& _internal_in_arg(int index) const; + ::tensorflow::ApiDef_Arg* _internal_add_in_arg(); + public: + const ::tensorflow::ApiDef_Arg& in_arg(int index) const; + ::tensorflow::ApiDef_Arg* add_in_arg(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >& + in_arg() const; + + // repeated .tensorflow.ApiDef.Arg out_arg = 5; + int out_arg_size() const; + private: + int _internal_out_arg_size() const; + public: + void clear_out_arg(); + ::tensorflow::ApiDef_Arg* mutable_out_arg(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >* + mutable_out_arg(); + private: + const ::tensorflow::ApiDef_Arg& _internal_out_arg(int index) const; + ::tensorflow::ApiDef_Arg* _internal_add_out_arg(); + public: + const ::tensorflow::ApiDef_Arg& out_arg(int index) const; + ::tensorflow::ApiDef_Arg* add_out_arg(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >& + out_arg() const; + + // repeated .tensorflow.ApiDef.Attr attr = 6; + int attr_size() const; + private: + int _internal_attr_size() const; + public: + void clear_attr(); + ::tensorflow::ApiDef_Attr* mutable_attr(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Attr >* + mutable_attr(); + private: + const ::tensorflow::ApiDef_Attr& _internal_attr(int index) const; + ::tensorflow::ApiDef_Attr* _internal_add_attr(); + public: + const ::tensorflow::ApiDef_Attr& attr(int index) const; + ::tensorflow::ApiDef_Attr* add_attr(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Attr >& + attr() const; + + // repeated string arg_order = 11; + int arg_order_size() const; + private: + int _internal_arg_order_size() const; + public: + void clear_arg_order(); + const std::string& arg_order(int index) const; + std::string* mutable_arg_order(int index); + void set_arg_order(int index, const std::string& value); + void set_arg_order(int index, std::string&& value); + void set_arg_order(int index, const char* value); + void set_arg_order(int index, const char* value, size_t size); + std::string* add_arg_order(); + void add_arg_order(const std::string& value); + void add_arg_order(std::string&& value); + void add_arg_order(const char* value); + void add_arg_order(const char* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& arg_order() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_arg_order(); + private: + const std::string& _internal_arg_order(int index) const; + std::string* _internal_add_arg_order(); + public: + + // string graph_op_name = 1; + void clear_graph_op_name(); + const std::string& graph_op_name() const; + template + void set_graph_op_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_graph_op_name(); + PROTOBUF_NODISCARD std::string* release_graph_op_name(); + void set_allocated_graph_op_name(std::string* graph_op_name); + private: + const std::string& _internal_graph_op_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_graph_op_name(const std::string& value); + std::string* _internal_mutable_graph_op_name(); + public: + + // string summary = 7; + void clear_summary(); + const std::string& summary() const; + template + void set_summary(ArgT0&& arg0, ArgT... args); + std::string* mutable_summary(); + PROTOBUF_NODISCARD std::string* release_summary(); + void set_allocated_summary(std::string* summary); + private: + const std::string& _internal_summary() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_summary(const std::string& value); + std::string* _internal_mutable_summary(); + public: + + // string description = 8; + void clear_description(); + const std::string& description() const; + template + void set_description(ArgT0&& arg0, ArgT... args); + std::string* mutable_description(); + PROTOBUF_NODISCARD std::string* release_description(); + void set_allocated_description(std::string* description); + private: + const std::string& _internal_description() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_description(const std::string& value); + std::string* _internal_mutable_description(); + public: + + // string description_prefix = 9; + void clear_description_prefix(); + const std::string& description_prefix() const; + template + void set_description_prefix(ArgT0&& arg0, ArgT... args); + std::string* mutable_description_prefix(); + PROTOBUF_NODISCARD std::string* release_description_prefix(); + void set_allocated_description_prefix(std::string* description_prefix); + private: + const std::string& _internal_description_prefix() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_description_prefix(const std::string& value); + std::string* _internal_mutable_description_prefix(); + public: + + // string description_suffix = 10; + void clear_description_suffix(); + const std::string& description_suffix() const; + template + void set_description_suffix(ArgT0&& arg0, ArgT... args); + std::string* mutable_description_suffix(); + PROTOBUF_NODISCARD std::string* release_description_suffix(); + void set_allocated_description_suffix(std::string* description_suffix); + private: + const std::string& _internal_description_suffix() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_description_suffix(const std::string& value); + std::string* _internal_mutable_description_suffix(); + public: + + // string deprecation_message = 12; + void clear_deprecation_message(); + const std::string& deprecation_message() const; + template + void set_deprecation_message(ArgT0&& arg0, ArgT... args); + std::string* mutable_deprecation_message(); + PROTOBUF_NODISCARD std::string* release_deprecation_message(); + void set_allocated_deprecation_message(std::string* deprecation_message); + private: + const std::string& _internal_deprecation_message() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_deprecation_message(const std::string& value); + std::string* _internal_mutable_deprecation_message(); + public: + + // .tensorflow.ApiDef.Visibility visibility = 2; + void clear_visibility(); + ::tensorflow::ApiDef_Visibility visibility() const; + void set_visibility(::tensorflow::ApiDef_Visibility value); + private: + ::tensorflow::ApiDef_Visibility _internal_visibility() const; + void _internal_set_visibility(::tensorflow::ApiDef_Visibility value); + public: + + // int32 deprecation_version = 13; + void clear_deprecation_version(); + int32_t deprecation_version() const; + void set_deprecation_version(int32_t value); + private: + int32_t _internal_deprecation_version() const; + void _internal_set_deprecation_version(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.ApiDef) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Endpoint > endpoint_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg > in_arg_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg > out_arg_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Attr > attr_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField arg_order_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr graph_op_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr summary_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr description_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr description_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr description_suffix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr deprecation_message_; + int visibility_; + int32_t deprecation_version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto; +}; +// ------------------------------------------------------------------- + +class ApiDefs final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.ApiDefs) */ { + public: + inline ApiDefs() : ApiDefs(nullptr) {} + ~ApiDefs() override; + explicit PROTOBUF_CONSTEXPR ApiDefs(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ApiDefs(const ApiDefs& from); + ApiDefs(ApiDefs&& from) noexcept + : ApiDefs() { + *this = ::std::move(from); + } + + inline ApiDefs& operator=(const ApiDefs& from) { + CopyFrom(from); + return *this; + } + inline ApiDefs& operator=(ApiDefs&& 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 ApiDefs& default_instance() { + return *internal_default_instance(); + } + static inline const ApiDefs* internal_default_instance() { + return reinterpret_cast( + &_ApiDefs_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(ApiDefs& a, ApiDefs& b) { + a.Swap(&b); + } + inline void Swap(ApiDefs* 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(ApiDefs* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ApiDefs* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ApiDefs& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ApiDefs& from) { + ApiDefs::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(ApiDefs* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.ApiDefs"; + } + protected: + explicit ApiDefs(::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 { + kOpFieldNumber = 1, + }; + // repeated .tensorflow.ApiDef op = 1; + int op_size() const; + private: + int _internal_op_size() const; + public: + void clear_op(); + ::tensorflow::ApiDef* mutable_op(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef >* + mutable_op(); + private: + const ::tensorflow::ApiDef& _internal_op(int index) const; + ::tensorflow::ApiDef* _internal_add_op(); + public: + const ::tensorflow::ApiDef& op(int index) const; + ::tensorflow::ApiDef* add_op(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef >& + op() const; + + // @@protoc_insertion_point(class_scope:tensorflow.ApiDefs) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef > op_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// ApiDef_Endpoint + +// string name = 1; +inline void ApiDef_Endpoint::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& ApiDef_Endpoint::name() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Endpoint.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Endpoint::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Endpoint.name) +} +inline std::string* ApiDef_Endpoint::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Endpoint.name) + return _s; +} +inline const std::string& ApiDef_Endpoint::_internal_name() const { + return _impl_.name_.Get(); +} +inline void ApiDef_Endpoint::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Endpoint::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Endpoint::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Endpoint.name) + return _impl_.name_.Release(); +} +inline void ApiDef_Endpoint::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Endpoint.name) +} + +// bool deprecated = 3; +inline void ApiDef_Endpoint::clear_deprecated() { + _impl_.deprecated_ = false; +} +inline bool ApiDef_Endpoint::_internal_deprecated() const { + return _impl_.deprecated_; +} +inline bool ApiDef_Endpoint::deprecated() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Endpoint.deprecated) + return _internal_deprecated(); +} +inline void ApiDef_Endpoint::_internal_set_deprecated(bool value) { + + _impl_.deprecated_ = value; +} +inline void ApiDef_Endpoint::set_deprecated(bool value) { + _internal_set_deprecated(value); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Endpoint.deprecated) +} + +// int32 deprecation_version = 4; +inline void ApiDef_Endpoint::clear_deprecation_version() { + _impl_.deprecation_version_ = 0; +} +inline int32_t ApiDef_Endpoint::_internal_deprecation_version() const { + return _impl_.deprecation_version_; +} +inline int32_t ApiDef_Endpoint::deprecation_version() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Endpoint.deprecation_version) + return _internal_deprecation_version(); +} +inline void ApiDef_Endpoint::_internal_set_deprecation_version(int32_t value) { + + _impl_.deprecation_version_ = value; +} +inline void ApiDef_Endpoint::set_deprecation_version(int32_t value) { + _internal_set_deprecation_version(value); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Endpoint.deprecation_version) +} + +// ------------------------------------------------------------------- + +// ApiDef_Arg + +// string name = 1; +inline void ApiDef_Arg::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& ApiDef_Arg::name() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Arg.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Arg::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Arg.name) +} +inline std::string* ApiDef_Arg::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Arg.name) + return _s; +} +inline const std::string& ApiDef_Arg::_internal_name() const { + return _impl_.name_.Get(); +} +inline void ApiDef_Arg::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Arg::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Arg::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Arg.name) + return _impl_.name_.Release(); +} +inline void ApiDef_Arg::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Arg.name) +} + +// string rename_to = 2; +inline void ApiDef_Arg::clear_rename_to() { + _impl_.rename_to_.ClearToEmpty(); +} +inline const std::string& ApiDef_Arg::rename_to() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Arg.rename_to) + return _internal_rename_to(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Arg::set_rename_to(ArgT0&& arg0, ArgT... args) { + + _impl_.rename_to_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Arg.rename_to) +} +inline std::string* ApiDef_Arg::mutable_rename_to() { + std::string* _s = _internal_mutable_rename_to(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Arg.rename_to) + return _s; +} +inline const std::string& ApiDef_Arg::_internal_rename_to() const { + return _impl_.rename_to_.Get(); +} +inline void ApiDef_Arg::_internal_set_rename_to(const std::string& value) { + + _impl_.rename_to_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Arg::_internal_mutable_rename_to() { + + return _impl_.rename_to_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Arg::release_rename_to() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Arg.rename_to) + return _impl_.rename_to_.Release(); +} +inline void ApiDef_Arg::set_allocated_rename_to(std::string* rename_to) { + if (rename_to != nullptr) { + + } else { + + } + _impl_.rename_to_.SetAllocated(rename_to, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.rename_to_.IsDefault()) { + _impl_.rename_to_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Arg.rename_to) +} + +// string description = 3; +inline void ApiDef_Arg::clear_description() { + _impl_.description_.ClearToEmpty(); +} +inline const std::string& ApiDef_Arg::description() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Arg.description) + return _internal_description(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Arg::set_description(ArgT0&& arg0, ArgT... args) { + + _impl_.description_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Arg.description) +} +inline std::string* ApiDef_Arg::mutable_description() { + std::string* _s = _internal_mutable_description(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Arg.description) + return _s; +} +inline const std::string& ApiDef_Arg::_internal_description() const { + return _impl_.description_.Get(); +} +inline void ApiDef_Arg::_internal_set_description(const std::string& value) { + + _impl_.description_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Arg::_internal_mutable_description() { + + return _impl_.description_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Arg::release_description() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Arg.description) + return _impl_.description_.Release(); +} +inline void ApiDef_Arg::set_allocated_description(std::string* description) { + if (description != nullptr) { + + } else { + + } + _impl_.description_.SetAllocated(description, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.description_.IsDefault()) { + _impl_.description_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Arg.description) +} + +// ------------------------------------------------------------------- + +// ApiDef_Attr + +// string name = 1; +inline void ApiDef_Attr::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& ApiDef_Attr::name() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Attr.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Attr::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Attr.name) +} +inline std::string* ApiDef_Attr::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Attr.name) + return _s; +} +inline const std::string& ApiDef_Attr::_internal_name() const { + return _impl_.name_.Get(); +} +inline void ApiDef_Attr::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Attr::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Attr::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Attr.name) + return _impl_.name_.Release(); +} +inline void ApiDef_Attr::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Attr.name) +} + +// string rename_to = 2; +inline void ApiDef_Attr::clear_rename_to() { + _impl_.rename_to_.ClearToEmpty(); +} +inline const std::string& ApiDef_Attr::rename_to() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Attr.rename_to) + return _internal_rename_to(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Attr::set_rename_to(ArgT0&& arg0, ArgT... args) { + + _impl_.rename_to_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Attr.rename_to) +} +inline std::string* ApiDef_Attr::mutable_rename_to() { + std::string* _s = _internal_mutable_rename_to(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Attr.rename_to) + return _s; +} +inline const std::string& ApiDef_Attr::_internal_rename_to() const { + return _impl_.rename_to_.Get(); +} +inline void ApiDef_Attr::_internal_set_rename_to(const std::string& value) { + + _impl_.rename_to_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Attr::_internal_mutable_rename_to() { + + return _impl_.rename_to_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Attr::release_rename_to() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Attr.rename_to) + return _impl_.rename_to_.Release(); +} +inline void ApiDef_Attr::set_allocated_rename_to(std::string* rename_to) { + if (rename_to != nullptr) { + + } else { + + } + _impl_.rename_to_.SetAllocated(rename_to, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.rename_to_.IsDefault()) { + _impl_.rename_to_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Attr.rename_to) +} + +// .tensorflow.AttrValue default_value = 3; +inline bool ApiDef_Attr::_internal_has_default_value() const { + return this != internal_default_instance() && _impl_.default_value_ != nullptr; +} +inline bool ApiDef_Attr::has_default_value() const { + return _internal_has_default_value(); +} +inline const ::tensorflow::AttrValue& ApiDef_Attr::_internal_default_value() const { + const ::tensorflow::AttrValue* p = _impl_.default_value_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_AttrValue_default_instance_); +} +inline const ::tensorflow::AttrValue& ApiDef_Attr::default_value() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Attr.default_value) + return _internal_default_value(); +} +inline void ApiDef_Attr::unsafe_arena_set_allocated_default_value( + ::tensorflow::AttrValue* default_value) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.default_value_); + } + _impl_.default_value_ = default_value; + if (default_value) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.ApiDef.Attr.default_value) +} +inline ::tensorflow::AttrValue* ApiDef_Attr::release_default_value() { + + ::tensorflow::AttrValue* temp = _impl_.default_value_; + _impl_.default_value_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::AttrValue* ApiDef_Attr::unsafe_arena_release_default_value() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Attr.default_value) + + ::tensorflow::AttrValue* temp = _impl_.default_value_; + _impl_.default_value_ = nullptr; + return temp; +} +inline ::tensorflow::AttrValue* ApiDef_Attr::_internal_mutable_default_value() { + + if (_impl_.default_value_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::AttrValue>(GetArenaForAllocation()); + _impl_.default_value_ = p; + } + return _impl_.default_value_; +} +inline ::tensorflow::AttrValue* ApiDef_Attr::mutable_default_value() { + ::tensorflow::AttrValue* _msg = _internal_mutable_default_value(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Attr.default_value) + return _msg; +} +inline void ApiDef_Attr::set_allocated_default_value(::tensorflow::AttrValue* default_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.default_value_); + } + if (default_value) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(default_value)); + if (message_arena != submessage_arena) { + default_value = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, default_value, submessage_arena); + } + + } else { + + } + _impl_.default_value_ = default_value; + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Attr.default_value) +} + +// string description = 4; +inline void ApiDef_Attr::clear_description() { + _impl_.description_.ClearToEmpty(); +} +inline const std::string& ApiDef_Attr::description() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.Attr.description) + return _internal_description(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef_Attr::set_description(ArgT0&& arg0, ArgT... args) { + + _impl_.description_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.Attr.description) +} +inline std::string* ApiDef_Attr::mutable_description() { + std::string* _s = _internal_mutable_description(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.Attr.description) + return _s; +} +inline const std::string& ApiDef_Attr::_internal_description() const { + return _impl_.description_.Get(); +} +inline void ApiDef_Attr::_internal_set_description(const std::string& value) { + + _impl_.description_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef_Attr::_internal_mutable_description() { + + return _impl_.description_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef_Attr::release_description() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.Attr.description) + return _impl_.description_.Release(); +} +inline void ApiDef_Attr::set_allocated_description(std::string* description) { + if (description != nullptr) { + + } else { + + } + _impl_.description_.SetAllocated(description, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.description_.IsDefault()) { + _impl_.description_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.Attr.description) +} + +// ------------------------------------------------------------------- + +// ApiDef + +// string graph_op_name = 1; +inline void ApiDef::clear_graph_op_name() { + _impl_.graph_op_name_.ClearToEmpty(); +} +inline const std::string& ApiDef::graph_op_name() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.graph_op_name) + return _internal_graph_op_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef::set_graph_op_name(ArgT0&& arg0, ArgT... args) { + + _impl_.graph_op_name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.graph_op_name) +} +inline std::string* ApiDef::mutable_graph_op_name() { + std::string* _s = _internal_mutable_graph_op_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.graph_op_name) + return _s; +} +inline const std::string& ApiDef::_internal_graph_op_name() const { + return _impl_.graph_op_name_.Get(); +} +inline void ApiDef::_internal_set_graph_op_name(const std::string& value) { + + _impl_.graph_op_name_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef::_internal_mutable_graph_op_name() { + + return _impl_.graph_op_name_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef::release_graph_op_name() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.graph_op_name) + return _impl_.graph_op_name_.Release(); +} +inline void ApiDef::set_allocated_graph_op_name(std::string* graph_op_name) { + if (graph_op_name != nullptr) { + + } else { + + } + _impl_.graph_op_name_.SetAllocated(graph_op_name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.graph_op_name_.IsDefault()) { + _impl_.graph_op_name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.graph_op_name) +} + +// string deprecation_message = 12; +inline void ApiDef::clear_deprecation_message() { + _impl_.deprecation_message_.ClearToEmpty(); +} +inline const std::string& ApiDef::deprecation_message() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.deprecation_message) + return _internal_deprecation_message(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef::set_deprecation_message(ArgT0&& arg0, ArgT... args) { + + _impl_.deprecation_message_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.deprecation_message) +} +inline std::string* ApiDef::mutable_deprecation_message() { + std::string* _s = _internal_mutable_deprecation_message(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.deprecation_message) + return _s; +} +inline const std::string& ApiDef::_internal_deprecation_message() const { + return _impl_.deprecation_message_.Get(); +} +inline void ApiDef::_internal_set_deprecation_message(const std::string& value) { + + _impl_.deprecation_message_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef::_internal_mutable_deprecation_message() { + + return _impl_.deprecation_message_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef::release_deprecation_message() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.deprecation_message) + return _impl_.deprecation_message_.Release(); +} +inline void ApiDef::set_allocated_deprecation_message(std::string* deprecation_message) { + if (deprecation_message != nullptr) { + + } else { + + } + _impl_.deprecation_message_.SetAllocated(deprecation_message, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.deprecation_message_.IsDefault()) { + _impl_.deprecation_message_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.deprecation_message) +} + +// int32 deprecation_version = 13; +inline void ApiDef::clear_deprecation_version() { + _impl_.deprecation_version_ = 0; +} +inline int32_t ApiDef::_internal_deprecation_version() const { + return _impl_.deprecation_version_; +} +inline int32_t ApiDef::deprecation_version() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.deprecation_version) + return _internal_deprecation_version(); +} +inline void ApiDef::_internal_set_deprecation_version(int32_t value) { + + _impl_.deprecation_version_ = value; +} +inline void ApiDef::set_deprecation_version(int32_t value) { + _internal_set_deprecation_version(value); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.deprecation_version) +} + +// .tensorflow.ApiDef.Visibility visibility = 2; +inline void ApiDef::clear_visibility() { + _impl_.visibility_ = 0; +} +inline ::tensorflow::ApiDef_Visibility ApiDef::_internal_visibility() const { + return static_cast< ::tensorflow::ApiDef_Visibility >(_impl_.visibility_); +} +inline ::tensorflow::ApiDef_Visibility ApiDef::visibility() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.visibility) + return _internal_visibility(); +} +inline void ApiDef::_internal_set_visibility(::tensorflow::ApiDef_Visibility value) { + + _impl_.visibility_ = value; +} +inline void ApiDef::set_visibility(::tensorflow::ApiDef_Visibility value) { + _internal_set_visibility(value); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.visibility) +} + +// repeated .tensorflow.ApiDef.Endpoint endpoint = 3; +inline int ApiDef::_internal_endpoint_size() const { + return _impl_.endpoint_.size(); +} +inline int ApiDef::endpoint_size() const { + return _internal_endpoint_size(); +} +inline void ApiDef::clear_endpoint() { + _impl_.endpoint_.Clear(); +} +inline ::tensorflow::ApiDef_Endpoint* ApiDef::mutable_endpoint(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.endpoint) + return _impl_.endpoint_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Endpoint >* +ApiDef::mutable_endpoint() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ApiDef.endpoint) + return &_impl_.endpoint_; +} +inline const ::tensorflow::ApiDef_Endpoint& ApiDef::_internal_endpoint(int index) const { + return _impl_.endpoint_.Get(index); +} +inline const ::tensorflow::ApiDef_Endpoint& ApiDef::endpoint(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.endpoint) + return _internal_endpoint(index); +} +inline ::tensorflow::ApiDef_Endpoint* ApiDef::_internal_add_endpoint() { + return _impl_.endpoint_.Add(); +} +inline ::tensorflow::ApiDef_Endpoint* ApiDef::add_endpoint() { + ::tensorflow::ApiDef_Endpoint* _add = _internal_add_endpoint(); + // @@protoc_insertion_point(field_add:tensorflow.ApiDef.endpoint) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Endpoint >& +ApiDef::endpoint() const { + // @@protoc_insertion_point(field_list:tensorflow.ApiDef.endpoint) + return _impl_.endpoint_; +} + +// repeated .tensorflow.ApiDef.Arg in_arg = 4; +inline int ApiDef::_internal_in_arg_size() const { + return _impl_.in_arg_.size(); +} +inline int ApiDef::in_arg_size() const { + return _internal_in_arg_size(); +} +inline void ApiDef::clear_in_arg() { + _impl_.in_arg_.Clear(); +} +inline ::tensorflow::ApiDef_Arg* ApiDef::mutable_in_arg(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.in_arg) + return _impl_.in_arg_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >* +ApiDef::mutable_in_arg() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ApiDef.in_arg) + return &_impl_.in_arg_; +} +inline const ::tensorflow::ApiDef_Arg& ApiDef::_internal_in_arg(int index) const { + return _impl_.in_arg_.Get(index); +} +inline const ::tensorflow::ApiDef_Arg& ApiDef::in_arg(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.in_arg) + return _internal_in_arg(index); +} +inline ::tensorflow::ApiDef_Arg* ApiDef::_internal_add_in_arg() { + return _impl_.in_arg_.Add(); +} +inline ::tensorflow::ApiDef_Arg* ApiDef::add_in_arg() { + ::tensorflow::ApiDef_Arg* _add = _internal_add_in_arg(); + // @@protoc_insertion_point(field_add:tensorflow.ApiDef.in_arg) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >& +ApiDef::in_arg() const { + // @@protoc_insertion_point(field_list:tensorflow.ApiDef.in_arg) + return _impl_.in_arg_; +} + +// repeated .tensorflow.ApiDef.Arg out_arg = 5; +inline int ApiDef::_internal_out_arg_size() const { + return _impl_.out_arg_.size(); +} +inline int ApiDef::out_arg_size() const { + return _internal_out_arg_size(); +} +inline void ApiDef::clear_out_arg() { + _impl_.out_arg_.Clear(); +} +inline ::tensorflow::ApiDef_Arg* ApiDef::mutable_out_arg(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.out_arg) + return _impl_.out_arg_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >* +ApiDef::mutable_out_arg() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ApiDef.out_arg) + return &_impl_.out_arg_; +} +inline const ::tensorflow::ApiDef_Arg& ApiDef::_internal_out_arg(int index) const { + return _impl_.out_arg_.Get(index); +} +inline const ::tensorflow::ApiDef_Arg& ApiDef::out_arg(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.out_arg) + return _internal_out_arg(index); +} +inline ::tensorflow::ApiDef_Arg* ApiDef::_internal_add_out_arg() { + return _impl_.out_arg_.Add(); +} +inline ::tensorflow::ApiDef_Arg* ApiDef::add_out_arg() { + ::tensorflow::ApiDef_Arg* _add = _internal_add_out_arg(); + // @@protoc_insertion_point(field_add:tensorflow.ApiDef.out_arg) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Arg >& +ApiDef::out_arg() const { + // @@protoc_insertion_point(field_list:tensorflow.ApiDef.out_arg) + return _impl_.out_arg_; +} + +// repeated string arg_order = 11; +inline int ApiDef::_internal_arg_order_size() const { + return _impl_.arg_order_.size(); +} +inline int ApiDef::arg_order_size() const { + return _internal_arg_order_size(); +} +inline void ApiDef::clear_arg_order() { + _impl_.arg_order_.Clear(); +} +inline std::string* ApiDef::add_arg_order() { + std::string* _s = _internal_add_arg_order(); + // @@protoc_insertion_point(field_add_mutable:tensorflow.ApiDef.arg_order) + return _s; +} +inline const std::string& ApiDef::_internal_arg_order(int index) const { + return _impl_.arg_order_.Get(index); +} +inline const std::string& ApiDef::arg_order(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.arg_order) + return _internal_arg_order(index); +} +inline std::string* ApiDef::mutable_arg_order(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.arg_order) + return _impl_.arg_order_.Mutable(index); +} +inline void ApiDef::set_arg_order(int index, const std::string& value) { + _impl_.arg_order_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.arg_order) +} +inline void ApiDef::set_arg_order(int index, std::string&& value) { + _impl_.arg_order_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.arg_order) +} +inline void ApiDef::set_arg_order(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.arg_order_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:tensorflow.ApiDef.arg_order) +} +inline void ApiDef::set_arg_order(int index, const char* value, size_t size) { + _impl_.arg_order_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:tensorflow.ApiDef.arg_order) +} +inline std::string* ApiDef::_internal_add_arg_order() { + return _impl_.arg_order_.Add(); +} +inline void ApiDef::add_arg_order(const std::string& value) { + _impl_.arg_order_.Add()->assign(value); + // @@protoc_insertion_point(field_add:tensorflow.ApiDef.arg_order) +} +inline void ApiDef::add_arg_order(std::string&& value) { + _impl_.arg_order_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:tensorflow.ApiDef.arg_order) +} +inline void ApiDef::add_arg_order(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.arg_order_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:tensorflow.ApiDef.arg_order) +} +inline void ApiDef::add_arg_order(const char* value, size_t size) { + _impl_.arg_order_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:tensorflow.ApiDef.arg_order) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +ApiDef::arg_order() const { + // @@protoc_insertion_point(field_list:tensorflow.ApiDef.arg_order) + return _impl_.arg_order_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +ApiDef::mutable_arg_order() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ApiDef.arg_order) + return &_impl_.arg_order_; +} + +// repeated .tensorflow.ApiDef.Attr attr = 6; +inline int ApiDef::_internal_attr_size() const { + return _impl_.attr_.size(); +} +inline int ApiDef::attr_size() const { + return _internal_attr_size(); +} +inline void ApiDef::clear_attr() { + _impl_.attr_.Clear(); +} +inline ::tensorflow::ApiDef_Attr* ApiDef::mutable_attr(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.attr) + return _impl_.attr_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Attr >* +ApiDef::mutable_attr() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ApiDef.attr) + return &_impl_.attr_; +} +inline const ::tensorflow::ApiDef_Attr& ApiDef::_internal_attr(int index) const { + return _impl_.attr_.Get(index); +} +inline const ::tensorflow::ApiDef_Attr& ApiDef::attr(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.attr) + return _internal_attr(index); +} +inline ::tensorflow::ApiDef_Attr* ApiDef::_internal_add_attr() { + return _impl_.attr_.Add(); +} +inline ::tensorflow::ApiDef_Attr* ApiDef::add_attr() { + ::tensorflow::ApiDef_Attr* _add = _internal_add_attr(); + // @@protoc_insertion_point(field_add:tensorflow.ApiDef.attr) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef_Attr >& +ApiDef::attr() const { + // @@protoc_insertion_point(field_list:tensorflow.ApiDef.attr) + return _impl_.attr_; +} + +// string summary = 7; +inline void ApiDef::clear_summary() { + _impl_.summary_.ClearToEmpty(); +} +inline const std::string& ApiDef::summary() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.summary) + return _internal_summary(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef::set_summary(ArgT0&& arg0, ArgT... args) { + + _impl_.summary_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.summary) +} +inline std::string* ApiDef::mutable_summary() { + std::string* _s = _internal_mutable_summary(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.summary) + return _s; +} +inline const std::string& ApiDef::_internal_summary() const { + return _impl_.summary_.Get(); +} +inline void ApiDef::_internal_set_summary(const std::string& value) { + + _impl_.summary_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef::_internal_mutable_summary() { + + return _impl_.summary_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef::release_summary() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.summary) + return _impl_.summary_.Release(); +} +inline void ApiDef::set_allocated_summary(std::string* summary) { + if (summary != nullptr) { + + } else { + + } + _impl_.summary_.SetAllocated(summary, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.summary_.IsDefault()) { + _impl_.summary_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.summary) +} + +// string description = 8; +inline void ApiDef::clear_description() { + _impl_.description_.ClearToEmpty(); +} +inline const std::string& ApiDef::description() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.description) + return _internal_description(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef::set_description(ArgT0&& arg0, ArgT... args) { + + _impl_.description_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.description) +} +inline std::string* ApiDef::mutable_description() { + std::string* _s = _internal_mutable_description(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.description) + return _s; +} +inline const std::string& ApiDef::_internal_description() const { + return _impl_.description_.Get(); +} +inline void ApiDef::_internal_set_description(const std::string& value) { + + _impl_.description_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef::_internal_mutable_description() { + + return _impl_.description_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef::release_description() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.description) + return _impl_.description_.Release(); +} +inline void ApiDef::set_allocated_description(std::string* description) { + if (description != nullptr) { + + } else { + + } + _impl_.description_.SetAllocated(description, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.description_.IsDefault()) { + _impl_.description_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.description) +} + +// string description_prefix = 9; +inline void ApiDef::clear_description_prefix() { + _impl_.description_prefix_.ClearToEmpty(); +} +inline const std::string& ApiDef::description_prefix() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.description_prefix) + return _internal_description_prefix(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef::set_description_prefix(ArgT0&& arg0, ArgT... args) { + + _impl_.description_prefix_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.description_prefix) +} +inline std::string* ApiDef::mutable_description_prefix() { + std::string* _s = _internal_mutable_description_prefix(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.description_prefix) + return _s; +} +inline const std::string& ApiDef::_internal_description_prefix() const { + return _impl_.description_prefix_.Get(); +} +inline void ApiDef::_internal_set_description_prefix(const std::string& value) { + + _impl_.description_prefix_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef::_internal_mutable_description_prefix() { + + return _impl_.description_prefix_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef::release_description_prefix() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.description_prefix) + return _impl_.description_prefix_.Release(); +} +inline void ApiDef::set_allocated_description_prefix(std::string* description_prefix) { + if (description_prefix != nullptr) { + + } else { + + } + _impl_.description_prefix_.SetAllocated(description_prefix, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.description_prefix_.IsDefault()) { + _impl_.description_prefix_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.description_prefix) +} + +// string description_suffix = 10; +inline void ApiDef::clear_description_suffix() { + _impl_.description_suffix_.ClearToEmpty(); +} +inline const std::string& ApiDef::description_suffix() const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDef.description_suffix) + return _internal_description_suffix(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void ApiDef::set_description_suffix(ArgT0&& arg0, ArgT... args) { + + _impl_.description_suffix_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.ApiDef.description_suffix) +} +inline std::string* ApiDef::mutable_description_suffix() { + std::string* _s = _internal_mutable_description_suffix(); + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDef.description_suffix) + return _s; +} +inline const std::string& ApiDef::_internal_description_suffix() const { + return _impl_.description_suffix_.Get(); +} +inline void ApiDef::_internal_set_description_suffix(const std::string& value) { + + _impl_.description_suffix_.Set(value, GetArenaForAllocation()); +} +inline std::string* ApiDef::_internal_mutable_description_suffix() { + + return _impl_.description_suffix_.Mutable(GetArenaForAllocation()); +} +inline std::string* ApiDef::release_description_suffix() { + // @@protoc_insertion_point(field_release:tensorflow.ApiDef.description_suffix) + return _impl_.description_suffix_.Release(); +} +inline void ApiDef::set_allocated_description_suffix(std::string* description_suffix) { + if (description_suffix != nullptr) { + + } else { + + } + _impl_.description_suffix_.SetAllocated(description_suffix, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.description_suffix_.IsDefault()) { + _impl_.description_suffix_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.ApiDef.description_suffix) +} + +// ------------------------------------------------------------------- + +// ApiDefs + +// repeated .tensorflow.ApiDef op = 1; +inline int ApiDefs::_internal_op_size() const { + return _impl_.op_.size(); +} +inline int ApiDefs::op_size() const { + return _internal_op_size(); +} +inline void ApiDefs::clear_op() { + _impl_.op_.Clear(); +} +inline ::tensorflow::ApiDef* ApiDefs::mutable_op(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.ApiDefs.op) + return _impl_.op_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef >* +ApiDefs::mutable_op() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.ApiDefs.op) + return &_impl_.op_; +} +inline const ::tensorflow::ApiDef& ApiDefs::_internal_op(int index) const { + return _impl_.op_.Get(index); +} +inline const ::tensorflow::ApiDef& ApiDefs::op(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.ApiDefs.op) + return _internal_op(index); +} +inline ::tensorflow::ApiDef* ApiDefs::_internal_add_op() { + return _impl_.op_.Add(); +} +inline ::tensorflow::ApiDef* ApiDefs::add_op() { + ::tensorflow::ApiDef* _add = _internal_add_op(); + // @@protoc_insertion_point(field_add:tensorflow.ApiDefs.op) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::ApiDef >& +ApiDefs::op() const { + // @@protoc_insertion_point(field_list:tensorflow.ApiDefs.op) + return _impl_.op_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::tensorflow::ApiDef_Visibility> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::ApiDef_Visibility>() { + return ::tensorflow::ApiDef_Visibility_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fapi_5fdef_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/api_def.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/api_def.proto new file mode 100644 index 0000000000000000000000000000000000000000..1823ce64f2f64bd9987d510c35b4e7ac933ec0bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/api_def.proto @@ -0,0 +1,138 @@ +// Defines the text format for including per-op API definition and +// overrides for client language op code generators. + +syntax = "proto3"; + +package tensorflow; + +import "tensorflow/core/framework/attr_value.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "ApiDefProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/api_def_go_proto"; + +// Used to specify and override the default API & behavior in the +// generated code for client languages, from what you would get from +// the OpDef alone. There will be a set of ApiDefs that are common +// to all client languages, and another set per client language. +// The per-client-language ApiDefs will inherit values from the +// common ApiDefs which it can either replace or modify. +// +// We separate the API definition from the OpDef so we can evolve the +// API while remaining backwards compatible when interpreting old +// graphs. Overrides go in an "api_def.pbtxt" file with a text-format +// ApiDefs message. +// +// WARNING: Be *very* careful changing the API for any existing op -- +// you can change the semantics of existing code. These changes may +// need to wait until a major release of TensorFlow to avoid breaking +// our compatibility promises. +message ApiDef { + // Name of the op (in the OpDef) to specify the API for. + string graph_op_name = 1; + // If this op is deprecated, set deprecation message to the message + // that should be logged when this op is used. + // The message should indicate alternative op to use, if any. + string deprecation_message = 12; + // Major version when the op will be deleted. For e.g. set this + // value to 2 if op API should be removed in TensorFlow 2.0 and + // deprecated in versions before that. + int32 deprecation_version = 13; + + enum Visibility { + // Normally this is "VISIBLE" unless you are inheriting a + // different value from another ApiDef. + DEFAULT_VISIBILITY = 0; + // Publicly visible in the API. + VISIBLE = 1; + // Do not include this op in the generated API. If visibility is + // set to 'SKIP', other fields are ignored for this op. + SKIP = 2; + // Hide this op by putting it into an internal namespace (or whatever + // is appropriate in the target language). + HIDDEN = 3; + } + Visibility visibility = 2; + + // If you specify any endpoint, this will replace all of the + // inherited endpoints. The first endpoint should be the + // "canonical" endpoint, and should not be deprecated (unless all + // endpoints are deprecated). + message Endpoint { + // Name should be either like "CamelCaseName" or + // "Package.CamelCaseName". Client-language-specific ApiDefs may + // use a snake_case convention instead of CamelCase. + string name = 1; + + // Set if this endpoint is deprecated. If set to true, a message suggesting + // to use a non-deprecated endpoint instead will be printed. If all + // endpoints are deprecated, set deprecation_message in ApiDef instead. + bool deprecated = 3; + + // Major version when an endpoint will be deleted. For e.g. set this + // value to 2 if endpoint should be removed in TensorFlow 2.0 and + // deprecated in versions before that. + int32 deprecation_version = 4; + } + repeated Endpoint endpoint = 3; + + message Arg { + string name = 1; + + // Change the name used to access this arg in the API from what + // is used in the GraphDef. Note that these names in `backticks` + // will also be replaced in the summary & description fields. + string rename_to = 2; + + // Note: this will replace any inherited arg doc. There is no + // current way of modifying arg descriptions (other than replacing + // them entirely) as can be done with op descriptions. + string description = 3; + } + repeated Arg in_arg = 4; + repeated Arg out_arg = 5; + // List of original in_arg names to specify new argument order. + // Length of arg_order should be either empty to keep current order + // or match size of in_arg. + repeated string arg_order = 11; + + // Description of the graph-construction-time configuration of this + // Op. That is to say, this describes the attr fields that will + // be specified in the NodeDef. + message Attr { + string name = 1; + + // Change the name used to access this attr in the API from what + // is used in the GraphDef. Note that these names in `backticks` + // will also be replaced in the summary & description fields. + string rename_to = 2; + + // Specify a new default value to use for this attr. This default + // will be used when creating new graphs, as opposed to the + // default in the OpDef, which will be used when interpreting old + // GraphDefs. + AttrValue default_value = 3; + + // Note: this will replace any inherited attr doc, there is no current + // way of modifying attr descriptions as can be done with op descriptions. + string description = 4; + } + repeated Attr attr = 6; + + // One-line human-readable description of what the Op does. + string summary = 7; + + // Additional, longer human-readable description of what the Op does. + string description = 8; + + // Modify an existing/inherited description by adding text to the beginning + // or end. + string description_prefix = 9; + string description_suffix = 10; +} + +message ApiDefs { + repeated ApiDef op = 1; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..39c52721826fec27e20d1d76454be34acaadcbb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value.pb.h @@ -0,0 +1,2035 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/attr_value.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include +#include "tensorflow/core/framework/tensor.pb.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fattr_5fvalue_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_2fframework_2fattr_5fvalue_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto; +namespace tensorflow { +class AttrValue; +struct AttrValueDefaultTypeInternal; +extern AttrValueDefaultTypeInternal _AttrValue_default_instance_; +class AttrValue_ListValue; +struct AttrValue_ListValueDefaultTypeInternal; +extern AttrValue_ListValueDefaultTypeInternal _AttrValue_ListValue_default_instance_; +class NameAttrList; +struct NameAttrListDefaultTypeInternal; +extern NameAttrListDefaultTypeInternal _NameAttrList_default_instance_; +class NameAttrList_AttrEntry_DoNotUse; +struct NameAttrList_AttrEntry_DoNotUseDefaultTypeInternal; +extern NameAttrList_AttrEntry_DoNotUseDefaultTypeInternal _NameAttrList_AttrEntry_DoNotUse_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::AttrValue* Arena::CreateMaybeMessage<::tensorflow::AttrValue>(Arena*); +template<> ::tensorflow::AttrValue_ListValue* Arena::CreateMaybeMessage<::tensorflow::AttrValue_ListValue>(Arena*); +template<> ::tensorflow::NameAttrList* Arena::CreateMaybeMessage<::tensorflow::NameAttrList>(Arena*); +template<> ::tensorflow::NameAttrList_AttrEntry_DoNotUse* Arena::CreateMaybeMessage<::tensorflow::NameAttrList_AttrEntry_DoNotUse>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class AttrValue_ListValue final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.AttrValue.ListValue) */ { + public: + inline AttrValue_ListValue() : AttrValue_ListValue(nullptr) {} + ~AttrValue_ListValue() override; + explicit PROTOBUF_CONSTEXPR AttrValue_ListValue(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AttrValue_ListValue(const AttrValue_ListValue& from); + AttrValue_ListValue(AttrValue_ListValue&& from) noexcept + : AttrValue_ListValue() { + *this = ::std::move(from); + } + + inline AttrValue_ListValue& operator=(const AttrValue_ListValue& from) { + CopyFrom(from); + return *this; + } + inline AttrValue_ListValue& operator=(AttrValue_ListValue&& 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 AttrValue_ListValue& default_instance() { + return *internal_default_instance(); + } + static inline const AttrValue_ListValue* internal_default_instance() { + return reinterpret_cast( + &_AttrValue_ListValue_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(AttrValue_ListValue& a, AttrValue_ListValue& b) { + a.Swap(&b); + } + inline void Swap(AttrValue_ListValue* 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(AttrValue_ListValue* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AttrValue_ListValue* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AttrValue_ListValue& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AttrValue_ListValue& from) { + AttrValue_ListValue::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(AttrValue_ListValue* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.AttrValue.ListValue"; + } + protected: + explicit AttrValue_ListValue(::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 { + kSFieldNumber = 2, + kIFieldNumber = 3, + kFFieldNumber = 4, + kBFieldNumber = 5, + kTypeFieldNumber = 6, + kShapeFieldNumber = 7, + kTensorFieldNumber = 8, + kFuncFieldNumber = 9, + }; + // repeated bytes s = 2; + int s_size() const; + private: + int _internal_s_size() const; + public: + void clear_s(); + const std::string& s(int index) const; + std::string* mutable_s(int index); + void set_s(int index, const std::string& value); + void set_s(int index, std::string&& value); + void set_s(int index, const char* value); + void set_s(int index, const void* value, size_t size); + std::string* add_s(); + void add_s(const std::string& value); + void add_s(std::string&& value); + void add_s(const char* value); + void add_s(const void* value, size_t size); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& s() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_s(); + private: + const std::string& _internal_s(int index) const; + std::string* _internal_add_s(); + public: + + // repeated int64 i = 3 [packed = true]; + int i_size() const; + private: + int _internal_i_size() const; + public: + void clear_i(); + private: + int64_t _internal_i(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + _internal_i() const; + void _internal_add_i(int64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + _internal_mutable_i(); + public: + int64_t i(int index) const; + void set_i(int index, int64_t value); + void add_i(int64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& + i() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* + mutable_i(); + + // repeated float f = 4 [packed = true]; + int f_size() const; + private: + int _internal_f_size() const; + public: + void clear_f(); + private: + float _internal_f(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& + _internal_f() const; + void _internal_add_f(float value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* + _internal_mutable_f(); + public: + float f(int index) const; + void set_f(int index, float value); + void add_f(float value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& + f() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* + mutable_f(); + + // repeated bool b = 5 [packed = true]; + int b_size() const; + private: + int _internal_b_size() const; + public: + void clear_b(); + private: + bool _internal_b(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >& + _internal_b() const; + void _internal_add_b(bool value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >* + _internal_mutable_b(); + public: + bool b(int index) const; + void set_b(int index, bool value); + void add_b(bool value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >& + b() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >* + mutable_b(); + + // repeated .tensorflow.DataType type = 6 [packed = true]; + int type_size() const; + private: + int _internal_type_size() const; + public: + void clear_type(); + private: + ::tensorflow::DataType _internal_type(int index) const; + void _internal_add_type(::tensorflow::DataType value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField* _internal_mutable_type(); + public: + ::tensorflow::DataType type(int index) const; + void set_type(int index, ::tensorflow::DataType value); + void add_type(::tensorflow::DataType value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField& type() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField* mutable_type(); + + // repeated .tensorflow.TensorShapeProto shape = 7; + int shape_size() const; + private: + int _internal_shape_size() const; + public: + void clear_shape(); + ::tensorflow::TensorShapeProto* mutable_shape(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorShapeProto >* + mutable_shape(); + private: + const ::tensorflow::TensorShapeProto& _internal_shape(int index) const; + ::tensorflow::TensorShapeProto* _internal_add_shape(); + public: + const ::tensorflow::TensorShapeProto& shape(int index) const; + ::tensorflow::TensorShapeProto* add_shape(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorShapeProto >& + shape() const; + + // repeated .tensorflow.TensorProto tensor = 8; + int tensor_size() const; + private: + int _internal_tensor_size() const; + public: + void clear_tensor(); + ::tensorflow::TensorProto* mutable_tensor(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >* + mutable_tensor(); + private: + const ::tensorflow::TensorProto& _internal_tensor(int index) const; + ::tensorflow::TensorProto* _internal_add_tensor(); + public: + const ::tensorflow::TensorProto& tensor(int index) const; + ::tensorflow::TensorProto* add_tensor(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >& + tensor() const; + + // repeated .tensorflow.NameAttrList func = 9; + int func_size() const; + private: + int _internal_func_size() const; + public: + void clear_func(); + ::tensorflow::NameAttrList* mutable_func(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::NameAttrList >* + mutable_func(); + private: + const ::tensorflow::NameAttrList& _internal_func(int index) const; + ::tensorflow::NameAttrList* _internal_add_func(); + public: + const ::tensorflow::NameAttrList& func(int index) const; + ::tensorflow::NameAttrList* add_func(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::NameAttrList >& + func() const; + + // @@protoc_insertion_point(class_scope:tensorflow.AttrValue.ListValue) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField s_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > i_; + mutable std::atomic _i_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< float > f_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool > b_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField type_; + mutable std::atomic _type_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorShapeProto > shape_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto > tensor_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::NameAttrList > func_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto; +}; +// ------------------------------------------------------------------- + +class AttrValue final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.AttrValue) */ { + public: + inline AttrValue() : AttrValue(nullptr) {} + ~AttrValue() override; + explicit PROTOBUF_CONSTEXPR AttrValue(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AttrValue(const AttrValue& from); + AttrValue(AttrValue&& from) noexcept + : AttrValue() { + *this = ::std::move(from); + } + + inline AttrValue& operator=(const AttrValue& from) { + CopyFrom(from); + return *this; + } + inline AttrValue& operator=(AttrValue&& 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 AttrValue& default_instance() { + return *internal_default_instance(); + } + enum ValueCase { + kS = 2, + kI = 3, + kF = 4, + kB = 5, + kType = 6, + kShape = 7, + kTensor = 8, + kList = 1, + kFunc = 10, + kPlaceholder = 9, + VALUE_NOT_SET = 0, + }; + + static inline const AttrValue* internal_default_instance() { + return reinterpret_cast( + &_AttrValue_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(AttrValue& a, AttrValue& b) { + a.Swap(&b); + } + inline void Swap(AttrValue* 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(AttrValue* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AttrValue* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AttrValue& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AttrValue& from) { + AttrValue::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(AttrValue* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.AttrValue"; + } + protected: + explicit AttrValue(::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 AttrValue_ListValue ListValue; + + // accessors ------------------------------------------------------- + + enum : int { + kSFieldNumber = 2, + kIFieldNumber = 3, + kFFieldNumber = 4, + kBFieldNumber = 5, + kTypeFieldNumber = 6, + kShapeFieldNumber = 7, + kTensorFieldNumber = 8, + kListFieldNumber = 1, + kFuncFieldNumber = 10, + kPlaceholderFieldNumber = 9, + }; + // bytes s = 2; + bool has_s() const; + private: + bool _internal_has_s() const; + public: + void clear_s(); + const std::string& s() const; + template + void set_s(ArgT0&& arg0, ArgT... args); + std::string* mutable_s(); + PROTOBUF_NODISCARD std::string* release_s(); + void set_allocated_s(std::string* s); + private: + const std::string& _internal_s() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_s(const std::string& value); + std::string* _internal_mutable_s(); + public: + + // int64 i = 3; + bool has_i() const; + private: + bool _internal_has_i() const; + public: + void clear_i(); + int64_t i() const; + void set_i(int64_t value); + private: + int64_t _internal_i() const; + void _internal_set_i(int64_t value); + public: + + // float f = 4; + bool has_f() const; + private: + bool _internal_has_f() const; + public: + void clear_f(); + float f() const; + void set_f(float value); + private: + float _internal_f() const; + void _internal_set_f(float value); + public: + + // bool b = 5; + bool has_b() const; + private: + bool _internal_has_b() const; + public: + void clear_b(); + bool b() const; + void set_b(bool value); + private: + bool _internal_b() const; + void _internal_set_b(bool value); + public: + + // .tensorflow.DataType type = 6; + bool has_type() const; + private: + bool _internal_has_type() const; + public: + void clear_type(); + ::tensorflow::DataType type() const; + void set_type(::tensorflow::DataType value); + private: + ::tensorflow::DataType _internal_type() const; + void _internal_set_type(::tensorflow::DataType value); + public: + + // .tensorflow.TensorShapeProto shape = 7; + bool has_shape() const; + private: + bool _internal_has_shape() const; + public: + void clear_shape(); + const ::tensorflow::TensorShapeProto& shape() const; + PROTOBUF_NODISCARD ::tensorflow::TensorShapeProto* release_shape(); + ::tensorflow::TensorShapeProto* mutable_shape(); + void set_allocated_shape(::tensorflow::TensorShapeProto* shape); + private: + const ::tensorflow::TensorShapeProto& _internal_shape() const; + ::tensorflow::TensorShapeProto* _internal_mutable_shape(); + public: + void unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape); + ::tensorflow::TensorShapeProto* unsafe_arena_release_shape(); + + // .tensorflow.TensorProto tensor = 8; + bool has_tensor() const; + private: + bool _internal_has_tensor() const; + public: + void clear_tensor(); + const ::tensorflow::TensorProto& tensor() const; + PROTOBUF_NODISCARD ::tensorflow::TensorProto* release_tensor(); + ::tensorflow::TensorProto* mutable_tensor(); + void set_allocated_tensor(::tensorflow::TensorProto* tensor); + private: + const ::tensorflow::TensorProto& _internal_tensor() const; + ::tensorflow::TensorProto* _internal_mutable_tensor(); + public: + void unsafe_arena_set_allocated_tensor( + ::tensorflow::TensorProto* tensor); + ::tensorflow::TensorProto* unsafe_arena_release_tensor(); + + // .tensorflow.AttrValue.ListValue list = 1; + bool has_list() const; + private: + bool _internal_has_list() const; + public: + void clear_list(); + const ::tensorflow::AttrValue_ListValue& list() const; + PROTOBUF_NODISCARD ::tensorflow::AttrValue_ListValue* release_list(); + ::tensorflow::AttrValue_ListValue* mutable_list(); + void set_allocated_list(::tensorflow::AttrValue_ListValue* list); + private: + const ::tensorflow::AttrValue_ListValue& _internal_list() const; + ::tensorflow::AttrValue_ListValue* _internal_mutable_list(); + public: + void unsafe_arena_set_allocated_list( + ::tensorflow::AttrValue_ListValue* list); + ::tensorflow::AttrValue_ListValue* unsafe_arena_release_list(); + + // .tensorflow.NameAttrList func = 10; + bool has_func() const; + private: + bool _internal_has_func() const; + public: + void clear_func(); + const ::tensorflow::NameAttrList& func() const; + PROTOBUF_NODISCARD ::tensorflow::NameAttrList* release_func(); + ::tensorflow::NameAttrList* mutable_func(); + void set_allocated_func(::tensorflow::NameAttrList* func); + private: + const ::tensorflow::NameAttrList& _internal_func() const; + ::tensorflow::NameAttrList* _internal_mutable_func(); + public: + void unsafe_arena_set_allocated_func( + ::tensorflow::NameAttrList* func); + ::tensorflow::NameAttrList* unsafe_arena_release_func(); + + // string placeholder = 9; + bool has_placeholder() const; + private: + bool _internal_has_placeholder() const; + public: + void clear_placeholder(); + const std::string& placeholder() const; + template + void set_placeholder(ArgT0&& arg0, ArgT... args); + std::string* mutable_placeholder(); + PROTOBUF_NODISCARD std::string* release_placeholder(); + void set_allocated_placeholder(std::string* placeholder); + private: + const std::string& _internal_placeholder() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_placeholder(const std::string& value); + std::string* _internal_mutable_placeholder(); + public: + + void clear_value(); + ValueCase value_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.AttrValue) + private: + class _Internal; + void set_has_s(); + void set_has_i(); + void set_has_f(); + void set_has_b(); + void set_has_type(); + void set_has_shape(); + void set_has_tensor(); + void set_has_list(); + void set_has_func(); + void set_has_placeholder(); + + inline bool has_value() const; + inline void clear_has_value(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union ValueUnion { + constexpr ValueUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr s_; + int64_t i_; + float f_; + bool b_; + int type_; + ::tensorflow::TensorShapeProto* shape_; + ::tensorflow::TensorProto* tensor_; + ::tensorflow::AttrValue_ListValue* list_; + ::tensorflow::NameAttrList* func_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr placeholder_; + } value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto; +}; +// ------------------------------------------------------------------- + +class NameAttrList_AttrEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry { +public: + typedef ::PROTOBUF_NAMESPACE_ID::internal::MapEntry SuperType; + NameAttrList_AttrEntry_DoNotUse(); + explicit PROTOBUF_CONSTEXPR NameAttrList_AttrEntry_DoNotUse( + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + explicit NameAttrList_AttrEntry_DoNotUse(::PROTOBUF_NAMESPACE_ID::Arena* arena); + void MergeFrom(const NameAttrList_AttrEntry_DoNotUse& other); + static const NameAttrList_AttrEntry_DoNotUse* internal_default_instance() { return reinterpret_cast(&_NameAttrList_AttrEntry_DoNotUse_default_instance_); } + static bool ValidateKey(std::string* s) { + return ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String(s->data(), static_cast(s->size()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::PARSE, "tensorflow.NameAttrList.AttrEntry.key"); + } + static bool ValidateValue(void*) { return true; } + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto; +}; + +// ------------------------------------------------------------------- + +class NameAttrList final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.NameAttrList) */ { + public: + inline NameAttrList() : NameAttrList(nullptr) {} + ~NameAttrList() override; + explicit PROTOBUF_CONSTEXPR NameAttrList(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + NameAttrList(const NameAttrList& from); + NameAttrList(NameAttrList&& from) noexcept + : NameAttrList() { + *this = ::std::move(from); + } + + inline NameAttrList& operator=(const NameAttrList& from) { + CopyFrom(from); + return *this; + } + inline NameAttrList& operator=(NameAttrList&& 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 NameAttrList& default_instance() { + return *internal_default_instance(); + } + static inline const NameAttrList* internal_default_instance() { + return reinterpret_cast( + &_NameAttrList_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(NameAttrList& a, NameAttrList& b) { + a.Swap(&b); + } + inline void Swap(NameAttrList* 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(NameAttrList* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + NameAttrList* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const NameAttrList& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const NameAttrList& from) { + NameAttrList::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(NameAttrList* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.NameAttrList"; + } + protected: + explicit NameAttrList(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + + // accessors ------------------------------------------------------- + + enum : int { + kAttrFieldNumber = 2, + kNameFieldNumber = 1, + }; + // map attr = 2; + int attr_size() const; + private: + int _internal_attr_size() const; + public: + void clear_attr(); + private: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >& + _internal_attr() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >* + _internal_mutable_attr(); + public: + const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >& + attr() const; + ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >* + mutable_attr(); + + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.NameAttrList) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + NameAttrList_AttrEntry_DoNotUse, + std::string, ::tensorflow::AttrValue, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> attr_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fattr_5fvalue_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// AttrValue_ListValue + +// repeated bytes s = 2; +inline int AttrValue_ListValue::_internal_s_size() const { + return _impl_.s_.size(); +} +inline int AttrValue_ListValue::s_size() const { + return _internal_s_size(); +} +inline void AttrValue_ListValue::clear_s() { + _impl_.s_.Clear(); +} +inline std::string* AttrValue_ListValue::add_s() { + std::string* _s = _internal_add_s(); + // @@protoc_insertion_point(field_add_mutable:tensorflow.AttrValue.ListValue.s) + return _s; +} +inline const std::string& AttrValue_ListValue::_internal_s(int index) const { + return _impl_.s_.Get(index); +} +inline const std::string& AttrValue_ListValue::s(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.s) + return _internal_s(index); +} +inline std::string* AttrValue_ListValue::mutable_s(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.ListValue.s) + return _impl_.s_.Mutable(index); +} +inline void AttrValue_ListValue::set_s(int index, const std::string& value) { + _impl_.s_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.ListValue.s) +} +inline void AttrValue_ListValue::set_s(int index, std::string&& value) { + _impl_.s_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.ListValue.s) +} +inline void AttrValue_ListValue::set_s(int index, const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.s_.Mutable(index)->assign(value); + // @@protoc_insertion_point(field_set_char:tensorflow.AttrValue.ListValue.s) +} +inline void AttrValue_ListValue::set_s(int index, const void* value, size_t size) { + _impl_.s_.Mutable(index)->assign( + reinterpret_cast(value), size); + // @@protoc_insertion_point(field_set_pointer:tensorflow.AttrValue.ListValue.s) +} +inline std::string* AttrValue_ListValue::_internal_add_s() { + return _impl_.s_.Add(); +} +inline void AttrValue_ListValue::add_s(const std::string& value) { + _impl_.s_.Add()->assign(value); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.s) +} +inline void AttrValue_ListValue::add_s(std::string&& value) { + _impl_.s_.Add(std::move(value)); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.s) +} +inline void AttrValue_ListValue::add_s(const char* value) { + GOOGLE_DCHECK(value != nullptr); + _impl_.s_.Add()->assign(value); + // @@protoc_insertion_point(field_add_char:tensorflow.AttrValue.ListValue.s) +} +inline void AttrValue_ListValue::add_s(const void* value, size_t size) { + _impl_.s_.Add()->assign(reinterpret_cast(value), size); + // @@protoc_insertion_point(field_add_pointer:tensorflow.AttrValue.ListValue.s) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& +AttrValue_ListValue::s() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.s) + return _impl_.s_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* +AttrValue_ListValue::mutable_s() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.s) + return &_impl_.s_; +} + +// repeated int64 i = 3 [packed = true]; +inline int AttrValue_ListValue::_internal_i_size() const { + return _impl_.i_.size(); +} +inline int AttrValue_ListValue::i_size() const { + return _internal_i_size(); +} +inline void AttrValue_ListValue::clear_i() { + _impl_.i_.Clear(); +} +inline int64_t AttrValue_ListValue::_internal_i(int index) const { + return _impl_.i_.Get(index); +} +inline int64_t AttrValue_ListValue::i(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.i) + return _internal_i(index); +} +inline void AttrValue_ListValue::set_i(int index, int64_t value) { + _impl_.i_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.ListValue.i) +} +inline void AttrValue_ListValue::_internal_add_i(int64_t value) { + _impl_.i_.Add(value); +} +inline void AttrValue_ListValue::add_i(int64_t value) { + _internal_add_i(value); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.i) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +AttrValue_ListValue::_internal_i() const { + return _impl_.i_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >& +AttrValue_ListValue::i() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.i) + return _internal_i(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +AttrValue_ListValue::_internal_mutable_i() { + return &_impl_.i_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t >* +AttrValue_ListValue::mutable_i() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.i) + return _internal_mutable_i(); +} + +// repeated float f = 4 [packed = true]; +inline int AttrValue_ListValue::_internal_f_size() const { + return _impl_.f_.size(); +} +inline int AttrValue_ListValue::f_size() const { + return _internal_f_size(); +} +inline void AttrValue_ListValue::clear_f() { + _impl_.f_.Clear(); +} +inline float AttrValue_ListValue::_internal_f(int index) const { + return _impl_.f_.Get(index); +} +inline float AttrValue_ListValue::f(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.f) + return _internal_f(index); +} +inline void AttrValue_ListValue::set_f(int index, float value) { + _impl_.f_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.ListValue.f) +} +inline void AttrValue_ListValue::_internal_add_f(float value) { + _impl_.f_.Add(value); +} +inline void AttrValue_ListValue::add_f(float value) { + _internal_add_f(value); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.f) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& +AttrValue_ListValue::_internal_f() const { + return _impl_.f_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >& +AttrValue_ListValue::f() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.f) + return _internal_f(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* +AttrValue_ListValue::_internal_mutable_f() { + return &_impl_.f_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< float >* +AttrValue_ListValue::mutable_f() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.f) + return _internal_mutable_f(); +} + +// repeated bool b = 5 [packed = true]; +inline int AttrValue_ListValue::_internal_b_size() const { + return _impl_.b_.size(); +} +inline int AttrValue_ListValue::b_size() const { + return _internal_b_size(); +} +inline void AttrValue_ListValue::clear_b() { + _impl_.b_.Clear(); +} +inline bool AttrValue_ListValue::_internal_b(int index) const { + return _impl_.b_.Get(index); +} +inline bool AttrValue_ListValue::b(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.b) + return _internal_b(index); +} +inline void AttrValue_ListValue::set_b(int index, bool value) { + _impl_.b_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.ListValue.b) +} +inline void AttrValue_ListValue::_internal_add_b(bool value) { + _impl_.b_.Add(value); +} +inline void AttrValue_ListValue::add_b(bool value) { + _internal_add_b(value); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.b) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >& +AttrValue_ListValue::_internal_b() const { + return _impl_.b_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >& +AttrValue_ListValue::b() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.b) + return _internal_b(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >* +AttrValue_ListValue::_internal_mutable_b() { + return &_impl_.b_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< bool >* +AttrValue_ListValue::mutable_b() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.b) + return _internal_mutable_b(); +} + +// repeated .tensorflow.DataType type = 6 [packed = true]; +inline int AttrValue_ListValue::_internal_type_size() const { + return _impl_.type_.size(); +} +inline int AttrValue_ListValue::type_size() const { + return _internal_type_size(); +} +inline void AttrValue_ListValue::clear_type() { + _impl_.type_.Clear(); +} +inline ::tensorflow::DataType AttrValue_ListValue::_internal_type(int index) const { + return static_cast< ::tensorflow::DataType >(_impl_.type_.Get(index)); +} +inline ::tensorflow::DataType AttrValue_ListValue::type(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.type) + return _internal_type(index); +} +inline void AttrValue_ListValue::set_type(int index, ::tensorflow::DataType value) { + _impl_.type_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.ListValue.type) +} +inline void AttrValue_ListValue::_internal_add_type(::tensorflow::DataType value) { + _impl_.type_.Add(value); +} +inline void AttrValue_ListValue::add_type(::tensorflow::DataType value) { + _internal_add_type(value); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.type) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField& +AttrValue_ListValue::type() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.type) + return _impl_.type_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField* +AttrValue_ListValue::_internal_mutable_type() { + return &_impl_.type_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField* +AttrValue_ListValue::mutable_type() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.type) + return _internal_mutable_type(); +} + +// repeated .tensorflow.TensorShapeProto shape = 7; +inline int AttrValue_ListValue::_internal_shape_size() const { + return _impl_.shape_.size(); +} +inline int AttrValue_ListValue::shape_size() const { + return _internal_shape_size(); +} +inline ::tensorflow::TensorShapeProto* AttrValue_ListValue::mutable_shape(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.ListValue.shape) + return _impl_.shape_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorShapeProto >* +AttrValue_ListValue::mutable_shape() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.shape) + return &_impl_.shape_; +} +inline const ::tensorflow::TensorShapeProto& AttrValue_ListValue::_internal_shape(int index) const { + return _impl_.shape_.Get(index); +} +inline const ::tensorflow::TensorShapeProto& AttrValue_ListValue::shape(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.shape) + return _internal_shape(index); +} +inline ::tensorflow::TensorShapeProto* AttrValue_ListValue::_internal_add_shape() { + return _impl_.shape_.Add(); +} +inline ::tensorflow::TensorShapeProto* AttrValue_ListValue::add_shape() { + ::tensorflow::TensorShapeProto* _add = _internal_add_shape(); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.shape) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorShapeProto >& +AttrValue_ListValue::shape() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.shape) + return _impl_.shape_; +} + +// repeated .tensorflow.TensorProto tensor = 8; +inline int AttrValue_ListValue::_internal_tensor_size() const { + return _impl_.tensor_.size(); +} +inline int AttrValue_ListValue::tensor_size() const { + return _internal_tensor_size(); +} +inline ::tensorflow::TensorProto* AttrValue_ListValue::mutable_tensor(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.ListValue.tensor) + return _impl_.tensor_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >* +AttrValue_ListValue::mutable_tensor() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.tensor) + return &_impl_.tensor_; +} +inline const ::tensorflow::TensorProto& AttrValue_ListValue::_internal_tensor(int index) const { + return _impl_.tensor_.Get(index); +} +inline const ::tensorflow::TensorProto& AttrValue_ListValue::tensor(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.tensor) + return _internal_tensor(index); +} +inline ::tensorflow::TensorProto* AttrValue_ListValue::_internal_add_tensor() { + return _impl_.tensor_.Add(); +} +inline ::tensorflow::TensorProto* AttrValue_ListValue::add_tensor() { + ::tensorflow::TensorProto* _add = _internal_add_tensor(); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.tensor) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >& +AttrValue_ListValue::tensor() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.tensor) + return _impl_.tensor_; +} + +// repeated .tensorflow.NameAttrList func = 9; +inline int AttrValue_ListValue::_internal_func_size() const { + return _impl_.func_.size(); +} +inline int AttrValue_ListValue::func_size() const { + return _internal_func_size(); +} +inline void AttrValue_ListValue::clear_func() { + _impl_.func_.Clear(); +} +inline ::tensorflow::NameAttrList* AttrValue_ListValue::mutable_func(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.ListValue.func) + return _impl_.func_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::NameAttrList >* +AttrValue_ListValue::mutable_func() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.AttrValue.ListValue.func) + return &_impl_.func_; +} +inline const ::tensorflow::NameAttrList& AttrValue_ListValue::_internal_func(int index) const { + return _impl_.func_.Get(index); +} +inline const ::tensorflow::NameAttrList& AttrValue_ListValue::func(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.ListValue.func) + return _internal_func(index); +} +inline ::tensorflow::NameAttrList* AttrValue_ListValue::_internal_add_func() { + return _impl_.func_.Add(); +} +inline ::tensorflow::NameAttrList* AttrValue_ListValue::add_func() { + ::tensorflow::NameAttrList* _add = _internal_add_func(); + // @@protoc_insertion_point(field_add:tensorflow.AttrValue.ListValue.func) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::NameAttrList >& +AttrValue_ListValue::func() const { + // @@protoc_insertion_point(field_list:tensorflow.AttrValue.ListValue.func) + return _impl_.func_; +} + +// ------------------------------------------------------------------- + +// AttrValue + +// bytes s = 2; +inline bool AttrValue::_internal_has_s() const { + return value_case() == kS; +} +inline bool AttrValue::has_s() const { + return _internal_has_s(); +} +inline void AttrValue::set_has_s() { + _impl_._oneof_case_[0] = kS; +} +inline void AttrValue::clear_s() { + if (_internal_has_s()) { + _impl_.value_.s_.Destroy(); + clear_has_value(); + } +} +inline const std::string& AttrValue::s() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.s) + return _internal_s(); +} +template +inline void AttrValue::set_s(ArgT0&& arg0, ArgT... args) { + if (!_internal_has_s()) { + clear_value(); + set_has_s(); + _impl_.value_.s_.InitDefault(); + } + _impl_.value_.s_.SetBytes( static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.s) +} +inline std::string* AttrValue::mutable_s() { + std::string* _s = _internal_mutable_s(); + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.s) + return _s; +} +inline const std::string& AttrValue::_internal_s() const { + if (_internal_has_s()) { + return _impl_.value_.s_.Get(); + } + return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); +} +inline void AttrValue::_internal_set_s(const std::string& value) { + if (!_internal_has_s()) { + clear_value(); + set_has_s(); + _impl_.value_.s_.InitDefault(); + } + _impl_.value_.s_.Set(value, GetArenaForAllocation()); +} +inline std::string* AttrValue::_internal_mutable_s() { + if (!_internal_has_s()) { + clear_value(); + set_has_s(); + _impl_.value_.s_.InitDefault(); + } + return _impl_.value_.s_.Mutable( GetArenaForAllocation()); +} +inline std::string* AttrValue::release_s() { + // @@protoc_insertion_point(field_release:tensorflow.AttrValue.s) + if (_internal_has_s()) { + clear_has_value(); + return _impl_.value_.s_.Release(); + } else { + return nullptr; + } +} +inline void AttrValue::set_allocated_s(std::string* s) { + if (has_value()) { + clear_value(); + } + if (s != nullptr) { + set_has_s(); + _impl_.value_.s_.InitAllocated(s, GetArenaForAllocation()); + } + // @@protoc_insertion_point(field_set_allocated:tensorflow.AttrValue.s) +} + +// int64 i = 3; +inline bool AttrValue::_internal_has_i() const { + return value_case() == kI; +} +inline bool AttrValue::has_i() const { + return _internal_has_i(); +} +inline void AttrValue::set_has_i() { + _impl_._oneof_case_[0] = kI; +} +inline void AttrValue::clear_i() { + if (_internal_has_i()) { + _impl_.value_.i_ = int64_t{0}; + clear_has_value(); + } +} +inline int64_t AttrValue::_internal_i() const { + if (_internal_has_i()) { + return _impl_.value_.i_; + } + return int64_t{0}; +} +inline void AttrValue::_internal_set_i(int64_t value) { + if (!_internal_has_i()) { + clear_value(); + set_has_i(); + } + _impl_.value_.i_ = value; +} +inline int64_t AttrValue::i() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.i) + return _internal_i(); +} +inline void AttrValue::set_i(int64_t value) { + _internal_set_i(value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.i) +} + +// float f = 4; +inline bool AttrValue::_internal_has_f() const { + return value_case() == kF; +} +inline bool AttrValue::has_f() const { + return _internal_has_f(); +} +inline void AttrValue::set_has_f() { + _impl_._oneof_case_[0] = kF; +} +inline void AttrValue::clear_f() { + if (_internal_has_f()) { + _impl_.value_.f_ = 0; + clear_has_value(); + } +} +inline float AttrValue::_internal_f() const { + if (_internal_has_f()) { + return _impl_.value_.f_; + } + return 0; +} +inline void AttrValue::_internal_set_f(float value) { + if (!_internal_has_f()) { + clear_value(); + set_has_f(); + } + _impl_.value_.f_ = value; +} +inline float AttrValue::f() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.f) + return _internal_f(); +} +inline void AttrValue::set_f(float value) { + _internal_set_f(value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.f) +} + +// bool b = 5; +inline bool AttrValue::_internal_has_b() const { + return value_case() == kB; +} +inline bool AttrValue::has_b() const { + return _internal_has_b(); +} +inline void AttrValue::set_has_b() { + _impl_._oneof_case_[0] = kB; +} +inline void AttrValue::clear_b() { + if (_internal_has_b()) { + _impl_.value_.b_ = false; + clear_has_value(); + } +} +inline bool AttrValue::_internal_b() const { + if (_internal_has_b()) { + return _impl_.value_.b_; + } + return false; +} +inline void AttrValue::_internal_set_b(bool value) { + if (!_internal_has_b()) { + clear_value(); + set_has_b(); + } + _impl_.value_.b_ = value; +} +inline bool AttrValue::b() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.b) + return _internal_b(); +} +inline void AttrValue::set_b(bool value) { + _internal_set_b(value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.b) +} + +// .tensorflow.DataType type = 6; +inline bool AttrValue::_internal_has_type() const { + return value_case() == kType; +} +inline bool AttrValue::has_type() const { + return _internal_has_type(); +} +inline void AttrValue::set_has_type() { + _impl_._oneof_case_[0] = kType; +} +inline void AttrValue::clear_type() { + if (_internal_has_type()) { + _impl_.value_.type_ = 0; + clear_has_value(); + } +} +inline ::tensorflow::DataType AttrValue::_internal_type() const { + if (_internal_has_type()) { + return static_cast< ::tensorflow::DataType >(_impl_.value_.type_); + } + return static_cast< ::tensorflow::DataType >(0); +} +inline ::tensorflow::DataType AttrValue::type() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.type) + return _internal_type(); +} +inline void AttrValue::_internal_set_type(::tensorflow::DataType value) { + if (!_internal_has_type()) { + clear_value(); + set_has_type(); + } + _impl_.value_.type_ = value; +} +inline void AttrValue::set_type(::tensorflow::DataType value) { + _internal_set_type(value); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.type) +} + +// .tensorflow.TensorShapeProto shape = 7; +inline bool AttrValue::_internal_has_shape() const { + return value_case() == kShape; +} +inline bool AttrValue::has_shape() const { + return _internal_has_shape(); +} +inline void AttrValue::set_has_shape() { + _impl_._oneof_case_[0] = kShape; +} +inline ::tensorflow::TensorShapeProto* AttrValue::release_shape() { + // @@protoc_insertion_point(field_release:tensorflow.AttrValue.shape) + if (_internal_has_shape()) { + clear_has_value(); + ::tensorflow::TensorShapeProto* temp = _impl_.value_.shape_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.value_.shape_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::TensorShapeProto& AttrValue::_internal_shape() const { + return _internal_has_shape() + ? *_impl_.value_.shape_ + : reinterpret_cast< ::tensorflow::TensorShapeProto&>(::tensorflow::_TensorShapeProto_default_instance_); +} +inline const ::tensorflow::TensorShapeProto& AttrValue::shape() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.shape) + return _internal_shape(); +} +inline ::tensorflow::TensorShapeProto* AttrValue::unsafe_arena_release_shape() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.AttrValue.shape) + if (_internal_has_shape()) { + clear_has_value(); + ::tensorflow::TensorShapeProto* temp = _impl_.value_.shape_; + _impl_.value_.shape_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AttrValue::unsafe_arena_set_allocated_shape(::tensorflow::TensorShapeProto* shape) { + clear_value(); + if (shape) { + set_has_shape(); + _impl_.value_.shape_ = shape; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.AttrValue.shape) +} +inline ::tensorflow::TensorShapeProto* AttrValue::_internal_mutable_shape() { + if (!_internal_has_shape()) { + clear_value(); + set_has_shape(); + _impl_.value_.shape_ = CreateMaybeMessage< ::tensorflow::TensorShapeProto >(GetArenaForAllocation()); + } + return _impl_.value_.shape_; +} +inline ::tensorflow::TensorShapeProto* AttrValue::mutable_shape() { + ::tensorflow::TensorShapeProto* _msg = _internal_mutable_shape(); + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.shape) + return _msg; +} + +// .tensorflow.TensorProto tensor = 8; +inline bool AttrValue::_internal_has_tensor() const { + return value_case() == kTensor; +} +inline bool AttrValue::has_tensor() const { + return _internal_has_tensor(); +} +inline void AttrValue::set_has_tensor() { + _impl_._oneof_case_[0] = kTensor; +} +inline ::tensorflow::TensorProto* AttrValue::release_tensor() { + // @@protoc_insertion_point(field_release:tensorflow.AttrValue.tensor) + if (_internal_has_tensor()) { + clear_has_value(); + ::tensorflow::TensorProto* temp = _impl_.value_.tensor_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.value_.tensor_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::TensorProto& AttrValue::_internal_tensor() const { + return _internal_has_tensor() + ? *_impl_.value_.tensor_ + : reinterpret_cast< ::tensorflow::TensorProto&>(::tensorflow::_TensorProto_default_instance_); +} +inline const ::tensorflow::TensorProto& AttrValue::tensor() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.tensor) + return _internal_tensor(); +} +inline ::tensorflow::TensorProto* AttrValue::unsafe_arena_release_tensor() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.AttrValue.tensor) + if (_internal_has_tensor()) { + clear_has_value(); + ::tensorflow::TensorProto* temp = _impl_.value_.tensor_; + _impl_.value_.tensor_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AttrValue::unsafe_arena_set_allocated_tensor(::tensorflow::TensorProto* tensor) { + clear_value(); + if (tensor) { + set_has_tensor(); + _impl_.value_.tensor_ = tensor; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.AttrValue.tensor) +} +inline ::tensorflow::TensorProto* AttrValue::_internal_mutable_tensor() { + if (!_internal_has_tensor()) { + clear_value(); + set_has_tensor(); + _impl_.value_.tensor_ = CreateMaybeMessage< ::tensorflow::TensorProto >(GetArenaForAllocation()); + } + return _impl_.value_.tensor_; +} +inline ::tensorflow::TensorProto* AttrValue::mutable_tensor() { + ::tensorflow::TensorProto* _msg = _internal_mutable_tensor(); + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.tensor) + return _msg; +} + +// .tensorflow.AttrValue.ListValue list = 1; +inline bool AttrValue::_internal_has_list() const { + return value_case() == kList; +} +inline bool AttrValue::has_list() const { + return _internal_has_list(); +} +inline void AttrValue::set_has_list() { + _impl_._oneof_case_[0] = kList; +} +inline void AttrValue::clear_list() { + if (_internal_has_list()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.value_.list_; + } + clear_has_value(); + } +} +inline ::tensorflow::AttrValue_ListValue* AttrValue::release_list() { + // @@protoc_insertion_point(field_release:tensorflow.AttrValue.list) + if (_internal_has_list()) { + clear_has_value(); + ::tensorflow::AttrValue_ListValue* temp = _impl_.value_.list_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.value_.list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::AttrValue_ListValue& AttrValue::_internal_list() const { + return _internal_has_list() + ? *_impl_.value_.list_ + : reinterpret_cast< ::tensorflow::AttrValue_ListValue&>(::tensorflow::_AttrValue_ListValue_default_instance_); +} +inline const ::tensorflow::AttrValue_ListValue& AttrValue::list() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.list) + return _internal_list(); +} +inline ::tensorflow::AttrValue_ListValue* AttrValue::unsafe_arena_release_list() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.AttrValue.list) + if (_internal_has_list()) { + clear_has_value(); + ::tensorflow::AttrValue_ListValue* temp = _impl_.value_.list_; + _impl_.value_.list_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AttrValue::unsafe_arena_set_allocated_list(::tensorflow::AttrValue_ListValue* list) { + clear_value(); + if (list) { + set_has_list(); + _impl_.value_.list_ = list; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.AttrValue.list) +} +inline ::tensorflow::AttrValue_ListValue* AttrValue::_internal_mutable_list() { + if (!_internal_has_list()) { + clear_value(); + set_has_list(); + _impl_.value_.list_ = CreateMaybeMessage< ::tensorflow::AttrValue_ListValue >(GetArenaForAllocation()); + } + return _impl_.value_.list_; +} +inline ::tensorflow::AttrValue_ListValue* AttrValue::mutable_list() { + ::tensorflow::AttrValue_ListValue* _msg = _internal_mutable_list(); + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.list) + return _msg; +} + +// .tensorflow.NameAttrList func = 10; +inline bool AttrValue::_internal_has_func() const { + return value_case() == kFunc; +} +inline bool AttrValue::has_func() const { + return _internal_has_func(); +} +inline void AttrValue::set_has_func() { + _impl_._oneof_case_[0] = kFunc; +} +inline void AttrValue::clear_func() { + if (_internal_has_func()) { + if (GetArenaForAllocation() == nullptr) { + delete _impl_.value_.func_; + } + clear_has_value(); + } +} +inline ::tensorflow::NameAttrList* AttrValue::release_func() { + // @@protoc_insertion_point(field_release:tensorflow.AttrValue.func) + if (_internal_has_func()) { + clear_has_value(); + ::tensorflow::NameAttrList* temp = _impl_.value_.func_; + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } + _impl_.value_.func_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline const ::tensorflow::NameAttrList& AttrValue::_internal_func() const { + return _internal_has_func() + ? *_impl_.value_.func_ + : reinterpret_cast< ::tensorflow::NameAttrList&>(::tensorflow::_NameAttrList_default_instance_); +} +inline const ::tensorflow::NameAttrList& AttrValue::func() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.func) + return _internal_func(); +} +inline ::tensorflow::NameAttrList* AttrValue::unsafe_arena_release_func() { + // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.AttrValue.func) + if (_internal_has_func()) { + clear_has_value(); + ::tensorflow::NameAttrList* temp = _impl_.value_.func_; + _impl_.value_.func_ = nullptr; + return temp; + } else { + return nullptr; + } +} +inline void AttrValue::unsafe_arena_set_allocated_func(::tensorflow::NameAttrList* func) { + clear_value(); + if (func) { + set_has_func(); + _impl_.value_.func_ = func; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.AttrValue.func) +} +inline ::tensorflow::NameAttrList* AttrValue::_internal_mutable_func() { + if (!_internal_has_func()) { + clear_value(); + set_has_func(); + _impl_.value_.func_ = CreateMaybeMessage< ::tensorflow::NameAttrList >(GetArenaForAllocation()); + } + return _impl_.value_.func_; +} +inline ::tensorflow::NameAttrList* AttrValue::mutable_func() { + ::tensorflow::NameAttrList* _msg = _internal_mutable_func(); + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.func) + return _msg; +} + +// string placeholder = 9; +inline bool AttrValue::_internal_has_placeholder() const { + return value_case() == kPlaceholder; +} +inline bool AttrValue::has_placeholder() const { + return _internal_has_placeholder(); +} +inline void AttrValue::set_has_placeholder() { + _impl_._oneof_case_[0] = kPlaceholder; +} +inline void AttrValue::clear_placeholder() { + if (_internal_has_placeholder()) { + _impl_.value_.placeholder_.Destroy(); + clear_has_value(); + } +} +inline const std::string& AttrValue::placeholder() const { + // @@protoc_insertion_point(field_get:tensorflow.AttrValue.placeholder) + return _internal_placeholder(); +} +template +inline void AttrValue::set_placeholder(ArgT0&& arg0, ArgT... args) { + if (!_internal_has_placeholder()) { + clear_value(); + set_has_placeholder(); + _impl_.value_.placeholder_.InitDefault(); + } + _impl_.value_.placeholder_.Set( static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.AttrValue.placeholder) +} +inline std::string* AttrValue::mutable_placeholder() { + std::string* _s = _internal_mutable_placeholder(); + // @@protoc_insertion_point(field_mutable:tensorflow.AttrValue.placeholder) + return _s; +} +inline const std::string& AttrValue::_internal_placeholder() const { + if (_internal_has_placeholder()) { + return _impl_.value_.placeholder_.Get(); + } + return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); +} +inline void AttrValue::_internal_set_placeholder(const std::string& value) { + if (!_internal_has_placeholder()) { + clear_value(); + set_has_placeholder(); + _impl_.value_.placeholder_.InitDefault(); + } + _impl_.value_.placeholder_.Set(value, GetArenaForAllocation()); +} +inline std::string* AttrValue::_internal_mutable_placeholder() { + if (!_internal_has_placeholder()) { + clear_value(); + set_has_placeholder(); + _impl_.value_.placeholder_.InitDefault(); + } + return _impl_.value_.placeholder_.Mutable( GetArenaForAllocation()); +} +inline std::string* AttrValue::release_placeholder() { + // @@protoc_insertion_point(field_release:tensorflow.AttrValue.placeholder) + if (_internal_has_placeholder()) { + clear_has_value(); + return _impl_.value_.placeholder_.Release(); + } else { + return nullptr; + } +} +inline void AttrValue::set_allocated_placeholder(std::string* placeholder) { + if (has_value()) { + clear_value(); + } + if (placeholder != nullptr) { + set_has_placeholder(); + _impl_.value_.placeholder_.InitAllocated(placeholder, GetArenaForAllocation()); + } + // @@protoc_insertion_point(field_set_allocated:tensorflow.AttrValue.placeholder) +} + +inline bool AttrValue::has_value() const { + return value_case() != VALUE_NOT_SET; +} +inline void AttrValue::clear_has_value() { + _impl_._oneof_case_[0] = VALUE_NOT_SET; +} +inline AttrValue::ValueCase AttrValue::value_case() const { + return AttrValue::ValueCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// NameAttrList + +// string name = 1; +inline void NameAttrList::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& NameAttrList::name() const { + // @@protoc_insertion_point(field_get:tensorflow.NameAttrList.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void NameAttrList::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.NameAttrList.name) +} +inline std::string* NameAttrList::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.NameAttrList.name) + return _s; +} +inline const std::string& NameAttrList::_internal_name() const { + return _impl_.name_.Get(); +} +inline void NameAttrList::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* NameAttrList::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* NameAttrList::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.NameAttrList.name) + return _impl_.name_.Release(); +} +inline void NameAttrList::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.NameAttrList.name) +} + +// map attr = 2; +inline int NameAttrList::_internal_attr_size() const { + return _impl_.attr_.size(); +} +inline int NameAttrList::attr_size() const { + return _internal_attr_size(); +} +inline void NameAttrList::clear_attr() { + _impl_.attr_.Clear(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >& +NameAttrList::_internal_attr() const { + return _impl_.attr_.GetMap(); +} +inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >& +NameAttrList::attr() const { + // @@protoc_insertion_point(field_map:tensorflow.NameAttrList.attr) + return _internal_attr(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >* +NameAttrList::_internal_mutable_attr() { + return _impl_.attr_.MutableMap(); +} +inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::tensorflow::AttrValue >* +NameAttrList::mutable_attr() { + // @@protoc_insertion_point(field_mutable_map:tensorflow.NameAttrList.attr) + return _internal_mutable_attr(); +} + +#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_2fframework_2fattr_5fvalue_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value.proto new file mode 100644 index 0000000000000000000000000000000000000000..2bd5b552a3614ae0cc8cb316dfc4ae8482c5e3e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value.proto @@ -0,0 +1,64 @@ +syntax = "proto3"; + +package tensorflow; + +import "tensorflow/core/framework/tensor.proto"; +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "AttrValueProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/attr_value_go_proto"; + +// Protocol buffer representing the value for an attr used to configure an Op. +// Comment indicates the corresponding attr type. Only the field matching the +// attr type may be filled. +message AttrValue { + // LINT.IfChange + message ListValue { + repeated bytes s = 2; // "list(string)" + repeated int64 i = 3 [packed = true]; // "list(int)" + repeated float f = 4 [packed = true]; // "list(float)" + repeated bool b = 5 [packed = true]; // "list(bool)" + repeated DataType type = 6 [packed = true]; // "list(type)" + repeated TensorShapeProto shape = 7; // "list(shape)" + repeated TensorProto tensor = 8; // "list(tensor)" + repeated NameAttrList func = 9; // "list(attr)" + } + // LINT.ThenChange(//tensorflow/c/c_api.cc) + + oneof value { + bytes s = 2; // "string" + int64 i = 3; // "int" + float f = 4; // "float" + bool b = 5; // "bool" + DataType type = 6; // "type" + TensorShapeProto shape = 7; // "shape" + TensorProto tensor = 8; // "tensor" + ListValue list = 1; // any "list(...)" + + // "func" represents a function. func.name is a function's name or + // a primitive op's name. func.attr.first is the name of an attr + // defined for that function. func.attr.second is the value for + // that attr in the instantiation. + NameAttrList func = 10; + + // This is a placeholder only used in nodes defined inside a + // function. It indicates the attr value will be supplied when + // the function is instantiated. For example, let us suppose a + // node "N" in function "FN". "N" has an attr "A" with value + // placeholder = "foo". When FN is instantiated with attr "foo" + // set to "bar", the instantiated node N's attr A will have been + // given the value "bar". + string placeholder = 9; + } +} + +// A list of attr names and their values. The whole list is attached +// with a string name. E.g., MatMul[T=float]. +message NameAttrList { + string name = 1; + map attr = 2; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value_util.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value_util.h new file mode 100644 index 0000000000000000000000000000000000000000..0717e2cc3307c80e8e4b55c208c6314e5c491b3a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/attr_value_util.h @@ -0,0 +1,140 @@ +/* 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_FRAMEWORK_ATTR_VALUE_UTIL_H_ +#define TENSORFLOW_CORE_FRAMEWORK_ATTR_VALUE_UTIL_H_ + +#include +#include +#include + +#include "tensorflow/core/framework/partial_tensor_shape.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/lib/gtl/array_slice.h" + +namespace tensorflow { + +namespace attr_value_util_internal { +// Return the size of the tensor represented by this TensorProto. If shape is +// not fully defined return -1. +int64_t TensorByteSize(const TensorProto& t); +} // namespace attr_value_util_internal + +// Forward declare protos so their symbols can be removed from .so exports +class AttrValue; +class NameAttrList; + +// A human-readable rendering of attr_value, that is more concise than a +// text-format proto. +std::string SummarizeAttrValue(const AttrValue& attr_value); + +// Generates an error if attr_value doesn't have the indicated attr type. +Status AttrValueHasType(const AttrValue& attr_value, StringPiece type); + +// Converts a text proto value from "text" into the field of *out +// indicated by "type" (e.g. from the type field of an AttrDef). +// Examples: +// * If type:"int" and text:"-14", then *out is set to "i: -14" +// * If type:"list(string)" and text:"['foo', 'bar']", +// then *out is set to "list { s: ['foo', 'bar'] }" +// Returns true on success. +bool ParseAttrValue(StringPiece type, StringPiece text, AttrValue* out); + +// Sets *out based on the type of value. +void SetAttrValue(const std::string& value, AttrValue* out); +void SetAttrValue(const tstring& value, AttrValue* out); +void SetAttrValue(const char* value, AttrValue* out); +void SetAttrValue(StringPiece value, AttrValue* out); +void SetAttrValue(int64_t value, AttrValue* out); +void SetAttrValue(int32_t value, AttrValue* out); +void SetAttrValue(float value, AttrValue* out); +void SetAttrValue(double value, AttrValue* out); +void SetAttrValue(bool value, AttrValue* out); +void SetAttrValue(DataType value, AttrValue* out); +void SetAttrValue(const TensorShape& value, AttrValue* out); +void SetAttrValue(const TensorShapeProto& value, AttrValue* out); +void SetAttrValue(const PartialTensorShape& value, AttrValue* out); +void SetAttrValue(const Tensor& value, AttrValue* out); +void SetAttrValue(const TensorProto& value, AttrValue* out); +void SetAttrValue(const NameAttrList& value, AttrValue* out); + +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(const std::vector& value, AttrValue* out); +void SetAttrValue(std::initializer_list value, AttrValue* out); +void SetAttrValue(DataTypeSlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); +void SetAttrValue(gtl::ArraySlice value, AttrValue* out); + +void SetAttrValue(const AttrValue& value, AttrValue* out); + +void MoveAttrValue(std::vector&& value, AttrValue* out); + +// Returns a hash of `a` that is consistent with AreAttrValuesEqual. In other +// words, if two AttrValues compare equal according to AreAttrValuesEqual, +// they will have the same hash value. +// Similarly to protobuf deterministic serialization, hash value is +// guaranteed to be stable only for a given binary. In particular, one should +// probably not persist the returned value. +uint64 AttrValueHash(const AttrValue& a); + +// WARNING: Equality check might return false-negative for large (> 32mb) +// tensors defined with different TensorProto representations. +// +// A pair of consistent hash and equals functions that are guaranteed to be fast +// with AttrValues that potentially can have very large Tensors (larger than +// 32mb) defined by TensorProto. If large identical Tensors are defined using +// different representations (e.g. one with tensor content, and second with +// bool_val), they will have different hash code and equals will return false. +// Small (less than 32mb) tensors with different TensorProto representations +// hashed/compared by their tensor content. +uint64 FastAttrValueHash(const AttrValue& a); +// Returns true if a and b have the same value. If false negatives are allowed, +// then compares proto representation to avoid construction of large (> 32mb) +// tensors. +bool AreAttrValuesEqual(const AttrValue& a, const AttrValue& b, + bool allow_false_negatives = false); + +// Returns true if "val" has a placeholder. +bool HasPlaceHolder(const AttrValue& val); + +// SubstitutePlaceholders recursively replaces placeholders in 'value' +// with an attr value by calling SubstituteFunc. Returns true iff all +// placeholders in "value" are replaced with a value. +// +// SubstituteFunc is given a placeholder string. If the placeholder is +// unknown, SubstituteFunc returns false. Otherwise, overwrites the +// attr value and returns true. +using SubstituteFunc = std::function; +bool SubstitutePlaceholders(const SubstituteFunc& substitute, AttrValue* value); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_ATTR_VALUE_UTIL_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/bfloat16.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/bfloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..4f13039daa39426a05657ae039734ddfa727cfec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/bfloat16.h @@ -0,0 +1,61 @@ +/* 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_FRAMEWORK_BFLOAT16_H_ +#define TENSORFLOW_CORE_FRAMEWORK_BFLOAT16_H_ + +#include "tensorflow/core/framework/numeric_types.h" +#include "tensorflow/core/platform/types.h" + +// Compact 16-bit encoding of floating point numbers. This representation uses +// 1 bit for the sign, 8 bits for the exponent and 7 bits for the mantissa. It +// is assumed that floats are in IEEE 754 format so the representation is just +// bits 16-31 of a single precision float. +// +// NOTE: The IEEE floating point standard defines a float16 format that +// is different than this format (it has fewer bits of exponent and more +// bits of mantissa). We don't use that format here because conversion +// to/from 32-bit floats is more complex for that format, and the +// conversion for this format is very simple. +// +// Because of the existing IEEE float16 type, we do not name our representation +// "float16" but just use "uint16". +// +// <-----our 16bits float-------> +// s e e e e e e e e f f f f f f f f f f f f f f f f f f f f f f f +// <------------------------------float--------------------------> +// 3 3 2 2 1 1 0 +// 1 0 3 2 5 4 0 +// +// +// This type only supports conversion back and forth with float. +// +// This file must be compilable by nvcc. +// +// The type is defined in framework/numeric_types.h. + +namespace tensorflow { + +// Convert from float to bfloat16 with rounding-to-nearest-even. +void RoundFloatToBFloat16(const float* src, bfloat16* dst, int64_t size); +// Convert from float to bfloat16 with truncation. Notice this conversion is +// lossy since it truncates the float to 7 mantissa bits without rounding. +void FloatToBFloat16(const float* src, bfloat16* dst, int64_t size); +// Convert from bfloat16 to float. This conversion is lossless. +void BFloat16ToFloat(const bfloat16* src, float* dst, int64_t size); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_BFLOAT16_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/bounds_check.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/bounds_check.h new file mode 100644 index 0000000000000000000000000000000000000000..76e6e6dd05877708cc8c3c600c60115979047259 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/bounds_check.h @@ -0,0 +1,54 @@ +/* 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_FRAMEWORK_BOUNDS_CHECK_H_ +#define TENSORFLOW_CORE_FRAMEWORK_BOUNDS_CHECK_H_ + +#include + +#include "Eigen/Core" // from @eigen_archive +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +// Check that 0 <= index < limit using a single comparison, assuming +// that 0 <= limit if Index is signed. Intended for use in performance +// critical contexts where 0 <= index < limit is almost always true. +template +EIGEN_ALWAYS_INLINE EIGEN_DEVICE_FUNC bool FastBoundsCheck(const Ta index, + const Tb limit) { + static_assert(std::is_integral::value && std::is_integral::value, + "FastBoundsCheck can only be used on integer types."); + typedef typename std::make_unsigned::type UIndex; + return TF_PREDICT_TRUE(static_cast(index) < + static_cast(limit)); +} + +namespace internal { +// Ensure that the compiler cannot elide a copy into a local, for +// bounds checking on source tensors that might be updated asynchronously. +// This function may only be used on primitive integral types (int32, int64, +// etc). It does not guarantee any atomicity or barriers. +template +EIGEN_ALWAYS_INLINE EIGEN_DEVICE_FUNC const T SubtleMustCopy(const T &x) { + static_assert(std::is_integral::value, + "SubtleMustCopy can only be used on integer types."); + auto *to_x = reinterpret_cast(&x); + return *to_x; +} +} // namespace internal +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_BOUNDS_CHECK_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cancellation.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cancellation.h new file mode 100644 index 0000000000000000000000000000000000000000..7961787e87ebbbd0a18e4d64c80458e53e74037c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cancellation.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. +==============================================================================*/ + +#ifndef TENSORFLOW_CORE_FRAMEWORK_CANCELLATION_H_ +#define TENSORFLOW_CORE_FRAMEWORK_CANCELLATION_H_ + +#include "tensorflow/core/lib/core/notification.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/gtl/flatmap.h" +#include "tensorflow/core/lib/hash/hash.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/stringpiece.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/framework/cancellation.h" + +namespace tensorflow { +// NOLINTBEGIN(misc-unused-using-decls) +using tsl::CancelCallback; +using tsl::CancellationManager; +using tsl::CancellationToken; +using tsl::RegisterCancellationCallback; +// NOLINTEND(misc-unused-using-decls) +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_CANCELLATION_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/collective.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/collective.h new file mode 100644 index 0000000000000000000000000000000000000000..4b43fb226af248c615caf34d07fc61b6085c0c9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/collective.h @@ -0,0 +1,516 @@ +/* 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_FRAMEWORK_COLLECTIVE_H_ +#define TENSORFLOW_CORE_FRAMEWORK_COLLECTIVE_H_ + +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/intrusive_ptr.h" + +namespace tensorflow { + +class BufRendezvous; +class CompleteGroupRequest; +class CompleteGroupResponse; +class CompleteInstanceRequest; +class CompleteInstanceResponse; +class Device; +class DeviceMgr; +class GetStepSequenceRequest; +class GetStepSequenceResponse; +class NcclManager; +class Tensor; + +// Types of supported collective operations. +enum CollectiveType { + REDUCTION_COLLECTIVE = 0, + BROADCAST_COLLECTIVE, + GATHER_COLLECTIVE, + PERMUTE_COLLECTIVE, + ALL_TO_ALL_COLLECTIVE, + REDUCE_SCATTER_COLLECTIVE, + UNDEFINED_COLLECTIVE, +}; + +// Some collective op implementations require runtime group configuration from +// the OpKernel. Currently, this struct is used to set communicator key for +// NCCL-based collective implementation. +struct CollGroupRuntimeDetails { + string communicator_key; // for communicator-based techniques e.g. NCCL + string ToString() const; +}; + +struct CollGroupMember { + DeviceAttributes device; + string task; + bool is_local; + // User provided rank + int32 rank = -1; +}; + +// Data common to all members of a device group. +// All members share the same device set but its order is +// particular to an instance so it is stored there. +struct CollGroupParams { + // Inputs from Collective ops: + int32 group_key; + int32 group_size; + DeviceType device_type; + int user_specified_rank = -1; // rank provided by the user. + // Generated from Collective Group Resolver: + // Members in this group, in default rank order. + std::vector members; + // True if every task has the same number of devices. + bool same_num_devices_per_task = false; + // Task -> number of devices on that task. + std::unordered_map num_devices_per_task; + int32 num_tasks; // number of distinct tasks in group + CollGroupRuntimeDetails runtime_details; + string ToString() const; + CollGroupParams() + : group_key(0), group_size(0), device_type(DEVICE_CPU), num_tasks(0) {} +}; + +// The best implementation of a collective op depends on many factors +// including the number of devices involved, the topology of +// interconnects between them and the sizes of inputs. This structure +// is used in generating and representing data movement choreography +// for each specific algorithm, hence it does not have a single, fixed +// interpretation. On first execution the runtime will update this +// structure with decisions that will guide all subsequent executions. +struct CollImplDetails { + string collective_name; + std::vector> subdiv_permutations; + // subdiv_offsets and max_subdivs_per_device are used together as follows: + // When subdiv_offsets is provided (non-empty) it is used as is. When + // subdiv_offsets is not provided subdivisons are generated dynamically + // constrained by max_subdivs_per_device. When subdiv_offsets is empty AND + // max_subdivs_per_device = 0 an internal default kMaxSubdivsPerDeviceDefault + // is used. When max_subdivs_per_device = -1, no subivision is done. + int max_subdivs_per_device = -1; // Upper bound on subdivisions per device. + std::vector subdiv_offsets; + std::vector subdiv_source_rank; // rank of source in each subdiv + std::vector + dependencies; // collective instances on which this node depends + string communication_hint; // user-supplied hint for implementation choice, + // e.g. ring or nccl + float timeout_seconds; // If non zero, set a completion timeout for the + // collective op to detect staleness. +}; + +// Data common to all members of a collective instance. +// TODO(b/163171014) Refactor this struct to not be a union of all fields. +struct CollInstanceParams { + // Identifies all participating graph nodes. + int32 instance_key = -1; + // The full identifier includes both instance_key and step_id. + int64_t step_id = 0; + CollectiveType type = UNDEFINED_COLLECTIVE; + DataType data_type = DT_FLOAT; + TensorShape shape = {0}; + CollImplDetails impl_details; + string ToString() const; + CollInstanceParams& operator=(const struct CollInstanceParams& other); + std::vector devices; // permuter only + + // For permuter only + // Each rank in the permutation is a receiver. + // Indices of each rank means a sender to that rank. + // Example: permutation = {2,0,1} means + // rank 0 sends to rank 2 + // rank 1 sends to rank 0 + // rank 2 sends to rank 1 + std::vector permutation; +}; + +// Unique to a single CollectiveOp node. +struct CollectiveParams : public core::RefCounted { + CollGroupParams group; + CollInstanceParams instance; + + string name = ""; // node name used only for log or error messages + int default_rank = -1; // index of this op within device_names + bool is_source = false; // broadcast only + int source_rank = -1; // broadcast only + // Rank of this device in each subdivision permutation. + std::vector subdiv_rank; + OpKernel* merge_op = nullptr; // reduction only + OpKernel* final_op = nullptr; // reduction only + string ToString() const; + bool run_group_initialization = true; + bool is_stateless = false; +}; + +class CollectiveExecutor; + +// Interface that provides resolution of device localities. +class DeviceResolverInterface { + public: + virtual ~DeviceResolverInterface() {} + + // Populates *attributes with the DeviceAttributes of the specified device. + virtual Status GetDeviceAttributes(const string& device, + DeviceAttributes* attributes) = 0; + + // Returns all device attributes of a task. + virtual Status GetAllDeviceAttributes( + const string& task, std::vector* attributes) = 0; + + // Updates device attributes. It returns error if any device already + // exists in the DeviceResolver and has a different incarnation. + virtual Status UpdateDeviceAttributes( + const std::vector& attributes) = 0; +}; + +// Interface that provides resolution of shared CollectiveParams fields. +class ParamResolverInterface { + public: + virtual ~ParamResolverInterface() {} + + // Called by each collective op at first execution in order to fill out + // the CollectiveParams structure with data gathered from the full + // (maybe distributed) collection of peer nodes. + virtual void CompleteParamsAsync(const DeviceAttributes& device, + CollectiveParams* cp, + CancellationManager* cancel_mgr, + const StatusCallback& done) = 0; + + // Completes group_params with data gathered from all devices in the group. + // This blocks until all devices are there. + virtual void CompleteGroupAsync(const DeviceAttributes& device, + CollGroupParams* group_params, + CancellationManager* cancel_mgr, + const StatusCallback& done) = 0; + + // Used within a distributed implementation to discover/verify data + // shared across an instance group. + // Note: this works differently from CompleteGroupAsync as a refactor is in + // progress. + virtual void CompleteInstanceAsync(const CompleteInstanceRequest* request, + CompleteInstanceResponse* response, + CancellationManager* cancel_mgr, + const StatusCallback& done) = 0; + + // Looks up a group. It returns an error if the group is not ready or not + // found. + virtual Status LookupGroup(int32_t group_key, CollGroupParams* group) = 0; + + // Aborts the resolver. After abortion the resolver can no longer be used. + virtual void StartAbort(const Status& s) = 0; +}; + +// Graphs which utilize Collective Ops in a common instance must +// execute with identical step_ids even if they are disjoint graphs +// run by otherwise independent tasks. This interface supplies +// coordinated step_ids to use in such cases. +class StepSequenceInterface { + public: + virtual ~StepSequenceInterface() {} + + // Used with a distributed implementation to coordinate step_id + // sequences across tasks. + virtual void GetStepSequenceAsync(const GetStepSequenceRequest* request, + GetStepSequenceResponse* response, + const StatusCallback& done) = 0; + + // Refresh the local per-graph_key step_id sequence from collective + // group leader, if applicable. + virtual void RefreshStepIdSequenceAsync(int64_t graph_key, + const StatusCallback& done) = 0; + + // Returns the step_id that should be used for initiating a new execution + // on the specified graph. May return the same step_id multiple times if + // RetireStepId or RefreshStepIdReservation is not called. + virtual int64_t NextStepId(int64_t graph_key) = 0; + + // Reports that execution of the given step has completed successfully. + // Should be called immediately after a step completes with OK status, + // prior to calling NextStepId(). If the step fails, don't call. + virtual void RetireStepId(int64_t graph_key, int64_t step_id) = 0; +}; + +class NcclCommunicatorInterface; + +// Interface that provides access to per-step CollectiveExecutor +// instances and various distributed resolution capabilities. +class CollectiveExecutorMgrInterface : public StepSequenceInterface { + public: + virtual ~CollectiveExecutorMgrInterface() {} + + // Returns the step-specific CollectiveExecutor, creating if one does not + // already exist. The caller assumes ownership of one Ref on the object. + virtual CollectiveExecutor* FindOrCreate(int64_t step_id) = 0; + + // If there is a CollectiveExecutor for step_id, remove it from the + // table. + virtual void Cleanup(int64_t step_id) = 0; + + virtual ParamResolverInterface* GetParamResolver() const = 0; + + virtual DeviceResolverInterface* GetDeviceResolver() const = 0; + + virtual NcclCommunicatorInterface* GetNcclCommunicator() const = 0; +}; + +// Interface that a Collective Op implementation uses to exchange data +// with peers. Note that data exchange is currently limited to types +// for which DMAHelper::CanUseDMA() returns true, i.e. dense numeric +// types. +class CollectiveRemoteAccess { + public: + virtual ~CollectiveRemoteAccess() {} + + virtual void RecvFromPeer(const string& peer_device, const string& peer_task, + bool peer_is_local, const string& key, + Device* to_device, DeviceContext* to_device_ctx, + const AllocatorAttributes& to_alloc_attr, + Tensor* to_tensor, + const DeviceLocality& client_locality, + int dev_to_dev_stream_index, + CancellationManager* cancellation_manager, + const StatusCallback& done) = 0; + + virtual void PostToPeer(const string& peer_device, const string& peer_task, + const string& key, Device* from_device, + DeviceContext* from_device_ctx, + const AllocatorAttributes& from_alloc_attr, + const Tensor* from_tensor, + const DeviceLocality& client_locality, + CancellationManager* cancellation_manager, + const StatusCallback& done) = 0; + + // Checks the health of a collective peer. It probes the peer to see if it is + // alive. Note that if a peer has restarted, it's considered a different one, + // so CheckPeerHealth fails. + virtual void CheckPeerHealth(const string& peer_task, int64_t timeout_in_ms, + const StatusCallback& done) = 0; + + virtual BufRendezvous* buf_rendezvous() = 0; + + virtual void StartAbort(const Status& s) = 0; +}; + +// A step-specific object that can execute a collective operation completely +// described by a CollectiveParams object. +class CollectiveExecutor : public core::RefCounted { + public: + virtual void StartAbort(const Status& s) {} + + virtual void ExecuteAsync(OpKernelContext* ctx, + const CollectiveParams* col_params, + const string& exec_key, StatusCallback done) { + done(errors::Internal( + "A collective Op has been called in a context in which " + "a CollectiveExecutor has not been provided.")); + } + + virtual void CompleteParamsAsync(const DeviceAttributes& device, + CollectiveParams* cp, + CancellationManager* cancel_mgr, + StatusCallback done) { + done(errors::Internal( + "A collective Op has been called in a context in which " + "a CollectiveExecutor has not been provided.")); + } + + virtual void CompleteGroupAsync(const DeviceAttributes& device, + CollGroupParams* group_params, + CancellationManager* cancel_mgr, + StatusCallback done) { + return cem_->GetParamResolver()->CompleteGroupAsync(device, group_params, + cancel_mgr, done); + } + + virtual Status LookupGroup(int32_t group_key, CollGroupParams* group) { + return cem_->GetParamResolver()->LookupGroup(group_key, group); + } + + // Runs the potentially-blocking closure/expensive callback. + virtual void RunClosure(std::function closure) = 0; + + virtual CollectiveRemoteAccess* remote_access() { return nullptr; } + + // `WaitForDependencies` and `Launched` are used for fine-grained control of + // execution order between collective instances. These functions are intended + // to be called in `Run` function of collective implementations, and may be + // used to make part, or whole, of the collective execution ordered with + // respect to other collective instances. + // + // `WaitForDependencies` will block until it is safe to continue the callee's + // execution, where safety is defined as: ordered with respect to the + // collective instances defined in the callee's `wait_for` attribute. + virtual void WaitForDependencies(const CollectiveParams& col_params) {} + // `UnblockDependencies` unblocks the dependent collective instances by + // recording that this caller's device has completed the critical portion of + // the collective execution. + virtual void UnblockDependencies(const CollectiveParams& col_params) {} + + // Used to designate an invalid group or instance key. + static int64_t kInvalidId; + + // Lexically scoped handle for Ref. + class Handle { + public: + explicit Handle(CollectiveExecutor* ce, bool inherit_ref) : ce_(ce) { + if (!inherit_ref) ce->Ref(); + } + ~Handle() { ce_->Unref(); } + CollectiveExecutor* get() const { return ce_; } + + private: + CollectiveExecutor* ce_; + }; + + protected: + explicit CollectiveExecutor(CollectiveExecutorMgrInterface* cem) + : cem_(cem) {} + + // For use only by derived classes + static OpKernelContext::Params* CtxParams(OpKernelContext* ctx); + CollectiveExecutorMgrInterface* cem_; + + CollectiveExecutor(const CollectiveExecutor&) = delete; + void operator=(const CollectiveExecutor&) = delete; +}; + +struct CollectiveContext { + CollectiveExecutor* col_exec; // Not owned + NcclCommunicatorInterface* nccl_communicator; // Not owned + const DeviceMgr* dev_mgr; // Not owned + OpKernelContext* op_ctx; // Not owned + OpKernelContext::Params* op_params; // Not owned + core::IntrusivePtr col_params; + const string exec_key; + const int64_t step_id; + const Tensor* input; // Not owned + Tensor* output; // Not owned + Device* device; // The device for which this instance labors + const string device_name; + DeviceLocality device_locality; + + CollectiveContext(CollectiveExecutor* col_exec, + NcclCommunicatorInterface* nccl_communicator, + const DeviceMgr* dev_mgr, OpKernelContext* ctx, + OpKernelContext::Params* op_params, + const CollectiveParams* col_params, const string& exec_key, + int64_t step_id, const Tensor* input, Tensor* output); +}; + +class NcclCommunicatorInterface { + public: + virtual ~NcclCommunicatorInterface() = default; + + virtual string GenerateCommunicatorKey() = 0; + + virtual void Enqueue(std::shared_ptr col_ctx, + StatusCallback done) = 0; + + virtual void StartAbort(const Status& s) = 0; +}; + +// Interface of a Collective Op implementation. Each specific CollectiveOp will +// implement this interface and register the implementation via the +// CollectiveRegistry detailed below. See common_runtime/ring_reducer and +// common_runtime/hierarchical_tree_broadcaster for examples. +class CollectiveImplementationInterface : public core::RefCounted { + public: + virtual ~CollectiveImplementationInterface() = default; + + // Initializes the portions of `col_params` specific to this + // implementation. Called exactly once for every Collective instance during + // the CollectiveParams resolution process when the graph is first executed, + // at the end of `CompleteInstanceLocal()`. + // NOTE(ayushd): This is effectively a static function because it modifies the + // `col_params` passed in and should not manipulate any data members. However + // because it is virtual and needs to be implemented by every derived class we + // do not mark it as static. + virtual Status InitializeCollectiveParams(CollectiveParams* col_params) = 0; + + // Prepares the CollectiveContext for executing this CollectiveImplementation. + // Called from CollectiveExecutor right before calling Run(). The + // CollectiveContext passed in must outlive the CollectiveImplementation + // object. + virtual Status InitializeCollectiveContext( + std::shared_ptr col_ctx) = 0; + + // Processes and moves data according to the logic of this Collective + // implementation. Relies on appropriate initialization of op-specific + // CollectiveParams in InitializeCollectiveParams(), as well as appropriate + // context initialization in InitializeCollectiveContext(). + virtual void Run(StatusCallback done) = 0; +}; + +// Static-methods only class for registering and looking up collective +// implementations. +class CollectiveRegistry { + public: + using Factory = std::function; + // Looks up a previously registered CollectiveImplementation under + // `collective_name`. If found, creates an instance of the implementation and + // assign to `implementation`. + static Status Lookup(const string& collective_name, + CollectiveImplementationInterface** implementation); + + // Looks up a previously registered CollectiveImplementation under + // `collective_name`. If found, returns the static instance of this + // implementation via `implementation`. This instance should only be used to + // call InitializateCollectiveParams. + static Status LookupParamResolverInstance( + const string& collective_name, + CollectiveImplementationInterface** implementation); + + // Returns all registered collective implementations. + static void GetAll( + std::vector* implementations); + + private: + friend class CollectiveRegistration; + // Registers a CollectiveImplementation with name `collective_name` and + // factory `factory`. The latter is a function used to create instances of + // the CollectiveImplementation. Also creates a static instance of the + // implementation - this instance is used during param resolution and should + // only be used to call InitializeCollectiveParams. + static Status Register(const string& collective_name, Factory factory); + + static Status LookupHelper(const string& collective_name, + CollectiveImplementationInterface** implementation, + bool param_resolver); +}; + +// Class used to call CollectiveRegistry::Register. This should only be used to +// create a global static object. +class CollectiveRegistration { + public: + CollectiveRegistration(const string& collective_name, + CollectiveRegistry::Factory factory) { + TF_CHECK_OK(CollectiveRegistry::Register(collective_name, factory)); + } +}; + +#define REGISTER_COLLECTIVE(name, implementation) \ + static CollectiveRegistration register_##name##_collective( \ + #name, []() { return new implementation; }); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_COLLECTIVE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/common_shape_fns.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/common_shape_fns.h new file mode 100644 index 0000000000000000000000000000000000000000..ce65aa99d13706323c923fe8beedc89c055ef002 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/common_shape_fns.h @@ -0,0 +1,304 @@ +/* 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_FRAMEWORK_COMMON_SHAPE_FNS_H_ +#define TENSORFLOW_CORE_FRAMEWORK_COMMON_SHAPE_FNS_H_ + +#include + +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { + +namespace shape_inference { + +// Like GetWindowedOutputSize, but deals with DimensionHandles. Does not support +// EXPLICIT padding. +Status GetWindowedOutputSizeFromDims(InferenceContext* c, + DimensionHandle input_size, + DimensionOrConstant filter_size, + int64_t stride, Padding padding_type, + DimensionHandle* output_size); + +// The V2 version computes the same outputs with arbitrary dilation_rate, and +// supports EXPLICIT padding. For detailed equations, refer to the comments +// for GetWindowedOutputSize(). The 'padding_before' and 'padding_after' +// parameters are only used if padding_type == EXPLICIT. +Status GetWindowedOutputSizeFromDimsV2( + InferenceContext* c, DimensionHandle input_size, + DimensionOrConstant filter_size, int64_t dilation_rate, int64_t stride, + Padding padding_type, int64_t padding_before, int64_t padding_after, + DimensionHandle* output_size); + +// Transfers shape of input(0) to output(0). +Status UnchangedShape(shape_inference::InferenceContext* c); + +// Transfers shape of input(0) to output(0), after asserting its rank is . +inline Status UnchangedShapeWithRank(shape_inference::InferenceContext* c, + int32_t rank) { + ShapeHandle out; + TF_RETURN_IF_ERROR(c->WithRank(c->input(0), rank, &out)); + c->set_output(0, out); + return OkStatus(); +} + +// Transfers shape of input(0) to output(0), after asserting its rank >= . +inline Status UnchangedShapeWithRankAtLeast( + shape_inference::InferenceContext* c, int32_t rank) { + ShapeHandle out; + TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), rank, &out)); + c->set_output(0, out); + return OkStatus(); +} + +// Transfers shape of input(0) to output(0), after asserting its rank <= . +inline Status UnchangedShapeWithRankAtMost(shape_inference::InferenceContext* c, + int32_t rank) { + ShapeHandle out; + TF_RETURN_IF_ERROR(c->WithRankAtMost(c->input(0), rank, &out)); + c->set_output(0, out); + return OkStatus(); +} + +// Shape function for use with ops no outputs. +inline Status NoOutputs(shape_inference::InferenceContext* c) { + return OkStatus(); +} + +// Shape function for ops that output a single scalar value. +inline Status ScalarShape(shape_inference::InferenceContext* c) { + c->set_output(0, c->Scalar()); + return OkStatus(); +} + +// Shape function for binary ops where both inputs and the output match. +inline Status MergeBothInputsShapeFn(InferenceContext* c) { + ShapeHandle out; + TF_RETURN_IF_ERROR(c->Merge(c->input(0), c->input(1), &out)); + c->set_output(0, out); + return OkStatus(); +} + +// Shape function for dataset iterators. +Status DatasetIteratorShape(shape_inference::InferenceContext* c); + +// Returns a new shape with the specified dims arranged in the specified +// format. The returned value is owned by this context. +// Note: if format = "FORMAT_NCHW_VECT_C" then C represents the outer_depth. +Status MakeShapeFromFormat(TensorFormat format, DimensionOrConstant N, + const std::vector& spatial, + DimensionOrConstant C, ShapeHandle* out, + shape_inference::InferenceContext* context); + +// Shape function for MatMul-like operations. +Status MatMulShape(shape_inference::InferenceContext* c); + +// Shape function for Batched MatMul-like operations with broadcasting across +// batch dimensions. +Status BatchMatMulV2Shape(shape_inference::InferenceContext* c); + +// Shape function for BatchMatMul-like operations +Status BatchMatMulShape(shape_inference::InferenceContext* c); + +// Shape function for Einsum. +Status EinsumShape(shape_inference::InferenceContext* c); + +// Shape function for BiasAdd-like operations. +Status BiasAddShape(shape_inference::InferenceContext* c); + +// Shape function for BiasAddGrad-like operations. +Status BiasAddGradShape(shape_inference::InferenceContext* c); + +// Shape function for general Convolution operation +Status ConvShape(shape_inference::InferenceContext* c); + +// Shape function for Conv2D-like operations that support explicit padding. +Status Conv2DShapeWithExplicitPadding(shape_inference::InferenceContext* c); + +// Shape function for Conv2D-like operations that do not support explicit +// padding. +Status Conv2DShape(shape_inference::InferenceContext* c); + +// Shape function for Conv3D-like operations. +Status Conv3DShape(shape_inference::InferenceContext* c); + +// Shape function for DepthwiseConv2D-like operations that support explicit +// padding. +Status DepthwiseConv2DNativeShapeWithExplicitPadding( + shape_inference::InferenceContext* c); + +// Shape function for DepthwiseConv2D-like operations that do not support +// explicit padding. +Status DepthwiseConv2DNativeShape(shape_inference::InferenceContext* c); + +// Shape function for Conv2DBackpropInput. +Status Conv2DBackpropInputShape(shape_inference::InferenceContext* c); + +// Shape function for Conv2DBackpropFilterWithBias. +Status Conv2DBackpropFilterWithBiasShape(shape_inference::InferenceContext* c); + +// Shape function for AvgPool-like operations. +Status AvgPoolShape(shape_inference::InferenceContext* c); + +// Shape function for AvgPoolGrad-like operations. +Status AvgPoolGradShape(shape_inference::InferenceContext* c); + +// Shape function for FusedBatchNorm and FusedBatchNormV2 operations. +Status FusedBatchNormShape(shape_inference::InferenceContext* c); + +// Shape function for FusedBatchNormV3 operations. +Status FusedBatchNormV3Shape(shape_inference::InferenceContext* c); + +// Shape function for _FusedBatchNormEx operations. +Status FusedBatchNormExShape(shape_inference::InferenceContext* c); + +// Shape function for FusedBatchNormGrad and FusedBatchNormGradV2 operations. +Status FusedBatchNormGradShape(shape_inference::InferenceContext* c); + +// Shape function for _FusedBatchNormGradEx operations. +Status FusedBatchNormGradExShape(shape_inference::InferenceContext* c); + +// Shape function for MatrixDiagPartV2 and MatrixDiagPartV3 operations. +Status MatrixDiagPartV2Shape(shape_inference::InferenceContext* c); + +// Shape function for MatrixDiagV2 and MatrixDiagV3 operations. +Status MatrixDiagV2Shape(shape_inference::InferenceContext* c); + +// Shape function for MatrixSetDiagV2 and MatrixSetDiagV3 operations. +Status MatrixSetDiagV2Shape(shape_inference::InferenceContext* c); + +// Shape function for MaxPool-like operations that support explicit padding. +Status MaxPoolShapeWithExplicitPadding(shape_inference::InferenceContext* c); + +// Shape function for MaxPool-like operations that do not support explicit +// padding. +Status MaxPoolShape(shape_inference::InferenceContext* c); + +// Shape function for MaxPoolV2-like operations. +Status MaxPoolV2Shape(shape_inference::InferenceContext* c, int num_inputs); + +// Shape function for MaxPoolGrad-like operations. +Status MaxPoolGradShape(shape_inference::InferenceContext* c); + +// Shape function for 3D Pooling operations. +Status Pool3DShape(shape_inference::InferenceContext* c); + +// Shape function for MaxPool3DGrad-like operations. +Status MaxPool3DGradShape(shape_inference::InferenceContext* c); + +// Shape function for AvgPool3DGrad-like operations. +Status AvgPool3DGradShape(shape_inference::InferenceContext* c); + +// Shape function for use with ops whose output shapes are unknown. +Status UnknownShape(shape_inference::InferenceContext* c); + +// Shape function for reduction operations. +Status ReductionShape(shape_inference::InferenceContext* c); + +// Shape function for unsorted segment operations. +Status SegmentReductionWithNumSegmentsShapeFn(InferenceContext* c); + +// Shape function for concat operations. +// is the number of inputs to concatenate and are taken +// from inputs +// [1,num_inputs_to_concat] of the op. Input 0 is the concat_dim input. +Status ConcatShape(shape_inference::InferenceContext* c, + int num_inputs_to_concat); + +// Shape function for concat operations. +Status ConcatV2Shape(shape_inference::InferenceContext* c); + +Status QuantizedConcatV2Shape(InferenceContext* c, int num_inputs_to_concat); + +// Shape function for binary operators that broadcast their inputs +// and with output to output_index. +// Note: out cannot be NULL. +Status BroadcastBinaryOpOutputShapeFnHelper(InferenceContext* c, + ShapeHandle shape_x, + ShapeHandle shape_y, + bool incompatible_shape_error, + ShapeHandle* out); + +// Shape function for binary operators that broadcast their inputs +// and with output to output_index. +inline Status BroadcastBinaryOpOutputShapeFn(InferenceContext* c, + int output_index) { + ShapeHandle out; + TF_RETURN_IF_ERROR(BroadcastBinaryOpOutputShapeFnHelper( + c, c->input(0), c->input(1), true, &out)); + c->set_output(output_index, out); + return OkStatus(); +} + +// Shape function for binary operators that broadcast their inputs. +// Tested by ops/math_ops_test.cc. +inline Status BroadcastBinaryOpShapeFn(InferenceContext* c) { + return BroadcastBinaryOpOutputShapeFn(c, 0); +} + +// Shape function for random operations. +Status RandomShape(shape_inference::InferenceContext* c); + +// Shape function for Slice operations. +Status SliceShape(shape_inference::InferenceContext* c); + +// Validates the 3 component tensors of a sparse tensor have the proper +// shapes. This mimics SparseTensor.__init__ in python/framework/ops.py. +Status ValidateSparseTensor(InferenceContext* c, ShapeHandle indices_shape, + ShapeHandle values_shape, ShapeHandle shape_shape); + +Status ValidateVariableResourceHandle( + InferenceContext* c, std::vector* shape_and_type); + +// Shape function for GatherNd operations. +Status GatherNdShape(InferenceContext* c); + +// Helper shape function for ScatterNd.../TensorScatter... operations. +Status ScatterNdShapeHelper(InferenceContext* c, ShapeHandle indices_shape, + ShapeHandle updates_shape, ShapeHandle input_shape); + +// Shape function for ops with an explicit "shape" attribute. +Status ExplicitShape(InferenceContext* c); + +// Shape function for multiple-output ops with an explicit "shapes" attribute. +Status ExplicitShapes(InferenceContext* c); + +// Shape function for SparseReduceMax and SparseReduceSum. +Status SparseReduceShapeFn(InferenceContext* c); + +// Shape function for QuantizedConv2D op. +Status QuantizedConv2DShape(InferenceContext* c); + +// Shape function for _QuantizedConv2D op/fusion. +Status FusedQuantizedConv2DShape(InferenceContext* c); + +// Shape function for _QuantizedDepthwiseConv2D op/fusion. +Status FusedQuantizedDepthwiseConv2D(InferenceContext* c); + +// Shape function for QuantizedAvgPool op +Status QuantizedAvgPoolShape(InferenceContext* c); + +// Shape function for QuantizeV2 op +Status QuantizeV2Shape(InferenceContext* c); + +// Shape function for ReduceScatter ops +Status ReduceScatterShape(shape_inference::InferenceContext* c); + +} // namespace shape_inference + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_COMMON_SHAPE_FNS_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/control_flow.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/control_flow.h new file mode 100644 index 0000000000000000000000000000000000000000..3cc270b323d92fc0ee01e3646db821e3cfff9429 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/control_flow.h @@ -0,0 +1,58 @@ +/* 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_FRAMEWORK_CONTROL_FLOW_H_ +#define TENSORFLOW_CORE_FRAMEWORK_CONTROL_FLOW_H_ + +#include "tensorflow/core/lib/hash/hash.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +const uint64 kIllegalFrameId = ~0uLL; +const int64_t kIllegalIterId = -1; + +// For the purpose of control flow, every tensor produced by TensorFlow is +// conceptually tagged by a 'FrameAndIter'. FrameAndIter consists of a +// 'frame_id' and an 'iter_id'. The tensor value it represents is produced +// in the frame with frame_id at the iteration of iter_id. +struct FrameAndIter { + uint64 frame_id = kIllegalFrameId; + int64_t iter_id = kIllegalIterId; + + FrameAndIter() {} + + FrameAndIter(uint64 frame, int64_t iter) { + frame_id = frame; + iter_id = iter; + } + + bool operator==(const FrameAndIter& other) const { + return (frame_id == other.frame_id && iter_id == other.iter_id); + } +}; + +struct FrameAndIterHash { + size_t operator()(const FrameAndIter& key) const { + // Make sure there are no padding bytes that we don't want + CHECK_EQ(sizeof(uint64) + sizeof(int64_t), sizeof(FrameAndIter)); + return Hash64(reinterpret_cast(&key), sizeof(FrameAndIter)); + } +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_CONTROL_FLOW_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cost_graph.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cost_graph.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..d2d836b0a1d5373bc37126a43bdbed08a87d0a9f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cost_graph.pb.h @@ -0,0 +1,1954 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/cost_graph.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fcost_5fgraph_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/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fcost_5fgraph_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_2fframework_2fcost_5fgraph_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto; +namespace tensorflow { +class CostGraphDef; +struct CostGraphDefDefaultTypeInternal; +extern CostGraphDefDefaultTypeInternal _CostGraphDef_default_instance_; +class CostGraphDef_AggregatedCost; +struct CostGraphDef_AggregatedCostDefaultTypeInternal; +extern CostGraphDef_AggregatedCostDefaultTypeInternal _CostGraphDef_AggregatedCost_default_instance_; +class CostGraphDef_Node; +struct CostGraphDef_NodeDefaultTypeInternal; +extern CostGraphDef_NodeDefaultTypeInternal _CostGraphDef_Node_default_instance_; +class CostGraphDef_Node_InputInfo; +struct CostGraphDef_Node_InputInfoDefaultTypeInternal; +extern CostGraphDef_Node_InputInfoDefaultTypeInternal _CostGraphDef_Node_InputInfo_default_instance_; +class CostGraphDef_Node_OutputInfo; +struct CostGraphDef_Node_OutputInfoDefaultTypeInternal; +extern CostGraphDef_Node_OutputInfoDefaultTypeInternal _CostGraphDef_Node_OutputInfo_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::CostGraphDef* Arena::CreateMaybeMessage<::tensorflow::CostGraphDef>(Arena*); +template<> ::tensorflow::CostGraphDef_AggregatedCost* Arena::CreateMaybeMessage<::tensorflow::CostGraphDef_AggregatedCost>(Arena*); +template<> ::tensorflow::CostGraphDef_Node* Arena::CreateMaybeMessage<::tensorflow::CostGraphDef_Node>(Arena*); +template<> ::tensorflow::CostGraphDef_Node_InputInfo* Arena::CreateMaybeMessage<::tensorflow::CostGraphDef_Node_InputInfo>(Arena*); +template<> ::tensorflow::CostGraphDef_Node_OutputInfo* Arena::CreateMaybeMessage<::tensorflow::CostGraphDef_Node_OutputInfo>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class CostGraphDef_Node_InputInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CostGraphDef.Node.InputInfo) */ { + public: + inline CostGraphDef_Node_InputInfo() : CostGraphDef_Node_InputInfo(nullptr) {} + ~CostGraphDef_Node_InputInfo() override; + explicit PROTOBUF_CONSTEXPR CostGraphDef_Node_InputInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CostGraphDef_Node_InputInfo(const CostGraphDef_Node_InputInfo& from); + CostGraphDef_Node_InputInfo(CostGraphDef_Node_InputInfo&& from) noexcept + : CostGraphDef_Node_InputInfo() { + *this = ::std::move(from); + } + + inline CostGraphDef_Node_InputInfo& operator=(const CostGraphDef_Node_InputInfo& from) { + CopyFrom(from); + return *this; + } + inline CostGraphDef_Node_InputInfo& operator=(CostGraphDef_Node_InputInfo&& 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 CostGraphDef_Node_InputInfo& default_instance() { + return *internal_default_instance(); + } + static inline const CostGraphDef_Node_InputInfo* internal_default_instance() { + return reinterpret_cast( + &_CostGraphDef_Node_InputInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CostGraphDef_Node_InputInfo& a, CostGraphDef_Node_InputInfo& b) { + a.Swap(&b); + } + inline void Swap(CostGraphDef_Node_InputInfo* 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(CostGraphDef_Node_InputInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CostGraphDef_Node_InputInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CostGraphDef_Node_InputInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CostGraphDef_Node_InputInfo& from) { + CostGraphDef_Node_InputInfo::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(CostGraphDef_Node_InputInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CostGraphDef.Node.InputInfo"; + } + protected: + explicit CostGraphDef_Node_InputInfo(::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 { + kPrecedingNodeFieldNumber = 1, + kPrecedingPortFieldNumber = 2, + }; + // int32 preceding_node = 1; + void clear_preceding_node(); + int32_t preceding_node() const; + void set_preceding_node(int32_t value); + private: + int32_t _internal_preceding_node() const; + void _internal_set_preceding_node(int32_t value); + public: + + // int32 preceding_port = 2; + void clear_preceding_port(); + int32_t preceding_port() const; + void set_preceding_port(int32_t value); + private: + int32_t _internal_preceding_port() const; + void _internal_set_preceding_port(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.CostGraphDef.Node.InputInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int32_t preceding_node_; + int32_t preceding_port_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto; +}; +// ------------------------------------------------------------------- + +class CostGraphDef_Node_OutputInfo final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CostGraphDef.Node.OutputInfo) */ { + public: + inline CostGraphDef_Node_OutputInfo() : CostGraphDef_Node_OutputInfo(nullptr) {} + ~CostGraphDef_Node_OutputInfo() override; + explicit PROTOBUF_CONSTEXPR CostGraphDef_Node_OutputInfo(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CostGraphDef_Node_OutputInfo(const CostGraphDef_Node_OutputInfo& from); + CostGraphDef_Node_OutputInfo(CostGraphDef_Node_OutputInfo&& from) noexcept + : CostGraphDef_Node_OutputInfo() { + *this = ::std::move(from); + } + + inline CostGraphDef_Node_OutputInfo& operator=(const CostGraphDef_Node_OutputInfo& from) { + CopyFrom(from); + return *this; + } + inline CostGraphDef_Node_OutputInfo& operator=(CostGraphDef_Node_OutputInfo&& 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 CostGraphDef_Node_OutputInfo& default_instance() { + return *internal_default_instance(); + } + static inline const CostGraphDef_Node_OutputInfo* internal_default_instance() { + return reinterpret_cast( + &_CostGraphDef_Node_OutputInfo_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(CostGraphDef_Node_OutputInfo& a, CostGraphDef_Node_OutputInfo& b) { + a.Swap(&b); + } + inline void Swap(CostGraphDef_Node_OutputInfo* 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(CostGraphDef_Node_OutputInfo* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CostGraphDef_Node_OutputInfo* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CostGraphDef_Node_OutputInfo& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CostGraphDef_Node_OutputInfo& from) { + CostGraphDef_Node_OutputInfo::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(CostGraphDef_Node_OutputInfo* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CostGraphDef.Node.OutputInfo"; + } + protected: + explicit CostGraphDef_Node_OutputInfo(::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 { + kShapeFieldNumber = 3, + kSizeFieldNumber = 1, + kAliasInputPortFieldNumber = 2, + kDtypeFieldNumber = 4, + }; + // .tensorflow.TensorShapeProto shape = 3; + bool has_shape() const; + private: + bool _internal_has_shape() const; + public: + void clear_shape(); + const ::tensorflow::TensorShapeProto& shape() const; + PROTOBUF_NODISCARD ::tensorflow::TensorShapeProto* release_shape(); + ::tensorflow::TensorShapeProto* mutable_shape(); + void set_allocated_shape(::tensorflow::TensorShapeProto* shape); + private: + const ::tensorflow::TensorShapeProto& _internal_shape() const; + ::tensorflow::TensorShapeProto* _internal_mutable_shape(); + public: + void unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape); + ::tensorflow::TensorShapeProto* unsafe_arena_release_shape(); + + // int64 size = 1; + void clear_size(); + int64_t size() const; + void set_size(int64_t value); + private: + int64_t _internal_size() const; + void _internal_set_size(int64_t value); + public: + + // int64 alias_input_port = 2; + void clear_alias_input_port(); + int64_t alias_input_port() const; + void set_alias_input_port(int64_t value); + private: + int64_t _internal_alias_input_port() const; + void _internal_set_alias_input_port(int64_t value); + public: + + // .tensorflow.DataType dtype = 4; + 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: + + // @@protoc_insertion_point(class_scope:tensorflow.CostGraphDef.Node.OutputInfo) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::TensorShapeProto* shape_; + int64_t size_; + int64_t alias_input_port_; + int dtype_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto; +}; +// ------------------------------------------------------------------- + +class CostGraphDef_Node final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CostGraphDef.Node) */ { + public: + inline CostGraphDef_Node() : CostGraphDef_Node(nullptr) {} + ~CostGraphDef_Node() override; + explicit PROTOBUF_CONSTEXPR CostGraphDef_Node(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CostGraphDef_Node(const CostGraphDef_Node& from); + CostGraphDef_Node(CostGraphDef_Node&& from) noexcept + : CostGraphDef_Node() { + *this = ::std::move(from); + } + + inline CostGraphDef_Node& operator=(const CostGraphDef_Node& from) { + CopyFrom(from); + return *this; + } + inline CostGraphDef_Node& operator=(CostGraphDef_Node&& 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 CostGraphDef_Node& default_instance() { + return *internal_default_instance(); + } + static inline const CostGraphDef_Node* internal_default_instance() { + return reinterpret_cast( + &_CostGraphDef_Node_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(CostGraphDef_Node& a, CostGraphDef_Node& b) { + a.Swap(&b); + } + inline void Swap(CostGraphDef_Node* 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(CostGraphDef_Node* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CostGraphDef_Node* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CostGraphDef_Node& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CostGraphDef_Node& from) { + CostGraphDef_Node::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(CostGraphDef_Node* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CostGraphDef.Node"; + } + protected: + explicit CostGraphDef_Node(::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 CostGraphDef_Node_InputInfo InputInfo; + typedef CostGraphDef_Node_OutputInfo OutputInfo; + + // accessors ------------------------------------------------------- + + enum : int { + kInputInfoFieldNumber = 4, + kOutputInfoFieldNumber = 5, + kControlInputFieldNumber = 8, + kNameFieldNumber = 1, + kDeviceFieldNumber = 2, + kTemporaryMemorySizeFieldNumber = 6, + kComputeCostFieldNumber = 9, + kIdFieldNumber = 3, + kIsFinalFieldNumber = 7, + kInaccurateFieldNumber = 17, + kHostTempMemorySizeFieldNumber = 10, + kDeviceTempMemorySizeFieldNumber = 11, + kPersistentMemorySizeFieldNumber = 12, + kComputeTimeFieldNumber = 14, + kMemoryTimeFieldNumber = 15, + kDevicePersistentMemorySizeFieldNumber = 16, + }; + // repeated .tensorflow.CostGraphDef.Node.InputInfo input_info = 4; + int input_info_size() const; + private: + int _internal_input_info_size() const; + public: + void clear_input_info(); + ::tensorflow::CostGraphDef_Node_InputInfo* mutable_input_info(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_InputInfo >* + mutable_input_info(); + private: + const ::tensorflow::CostGraphDef_Node_InputInfo& _internal_input_info(int index) const; + ::tensorflow::CostGraphDef_Node_InputInfo* _internal_add_input_info(); + public: + const ::tensorflow::CostGraphDef_Node_InputInfo& input_info(int index) const; + ::tensorflow::CostGraphDef_Node_InputInfo* add_input_info(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_InputInfo >& + input_info() const; + + // repeated .tensorflow.CostGraphDef.Node.OutputInfo output_info = 5; + int output_info_size() const; + private: + int _internal_output_info_size() const; + public: + void clear_output_info(); + ::tensorflow::CostGraphDef_Node_OutputInfo* mutable_output_info(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_OutputInfo >* + mutable_output_info(); + private: + const ::tensorflow::CostGraphDef_Node_OutputInfo& _internal_output_info(int index) const; + ::tensorflow::CostGraphDef_Node_OutputInfo* _internal_add_output_info(); + public: + const ::tensorflow::CostGraphDef_Node_OutputInfo& output_info(int index) const; + ::tensorflow::CostGraphDef_Node_OutputInfo* add_output_info(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_OutputInfo >& + output_info() const; + + // repeated int32 control_input = 8; + int control_input_size() const; + private: + int _internal_control_input_size() const; + public: + void clear_control_input(); + private: + int32_t _internal_control_input(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + _internal_control_input() const; + void _internal_add_control_input(int32_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + _internal_mutable_control_input(); + public: + int32_t control_input(int index) const; + void set_control_input(int index, int32_t value); + void add_control_input(int32_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + control_input() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + mutable_control_input(); + + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string device = 2; + void clear_device(); + const std::string& device() const; + template + void set_device(ArgT0&& arg0, ArgT... args); + std::string* mutable_device(); + PROTOBUF_NODISCARD std::string* release_device(); + void set_allocated_device(std::string* device); + private: + const std::string& _internal_device() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device(const std::string& value); + std::string* _internal_mutable_device(); + public: + + // int64 temporary_memory_size = 6; + void clear_temporary_memory_size(); + int64_t temporary_memory_size() const; + void set_temporary_memory_size(int64_t value); + private: + int64_t _internal_temporary_memory_size() const; + void _internal_set_temporary_memory_size(int64_t value); + public: + + // int64 compute_cost = 9; + void clear_compute_cost(); + int64_t compute_cost() const; + void set_compute_cost(int64_t value); + private: + int64_t _internal_compute_cost() const; + void _internal_set_compute_cost(int64_t value); + public: + + // int32 id = 3; + void clear_id(); + int32_t id() const; + void set_id(int32_t value); + private: + int32_t _internal_id() const; + void _internal_set_id(int32_t value); + public: + + // bool is_final = 7; + void clear_is_final(); + bool is_final() const; + void set_is_final(bool value); + private: + bool _internal_is_final() const; + void _internal_set_is_final(bool value); + public: + + // bool inaccurate = 17; + void clear_inaccurate(); + bool inaccurate() const; + void set_inaccurate(bool value); + private: + bool _internal_inaccurate() const; + void _internal_set_inaccurate(bool value); + public: + + // int64 host_temp_memory_size = 10 [deprecated = true]; + PROTOBUF_DEPRECATED void clear_host_temp_memory_size(); + PROTOBUF_DEPRECATED int64_t host_temp_memory_size() const; + PROTOBUF_DEPRECATED void set_host_temp_memory_size(int64_t value); + private: + int64_t _internal_host_temp_memory_size() const; + void _internal_set_host_temp_memory_size(int64_t value); + public: + + // int64 device_temp_memory_size = 11 [deprecated = true]; + PROTOBUF_DEPRECATED void clear_device_temp_memory_size(); + PROTOBUF_DEPRECATED int64_t device_temp_memory_size() const; + PROTOBUF_DEPRECATED void set_device_temp_memory_size(int64_t value); + private: + int64_t _internal_device_temp_memory_size() const; + void _internal_set_device_temp_memory_size(int64_t value); + public: + + // int64 persistent_memory_size = 12; + void clear_persistent_memory_size(); + int64_t persistent_memory_size() const; + void set_persistent_memory_size(int64_t value); + private: + int64_t _internal_persistent_memory_size() const; + void _internal_set_persistent_memory_size(int64_t value); + public: + + // int64 compute_time = 14; + void clear_compute_time(); + int64_t compute_time() const; + void set_compute_time(int64_t value); + private: + int64_t _internal_compute_time() const; + void _internal_set_compute_time(int64_t value); + public: + + // int64 memory_time = 15; + void clear_memory_time(); + int64_t memory_time() const; + void set_memory_time(int64_t value); + private: + int64_t _internal_memory_time() const; + void _internal_set_memory_time(int64_t value); + public: + + // int64 device_persistent_memory_size = 16 [deprecated = true]; + PROTOBUF_DEPRECATED void clear_device_persistent_memory_size(); + PROTOBUF_DEPRECATED int64_t device_persistent_memory_size() const; + PROTOBUF_DEPRECATED void set_device_persistent_memory_size(int64_t value); + private: + int64_t _internal_device_persistent_memory_size() const; + void _internal_set_device_persistent_memory_size(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.CostGraphDef.Node) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_InputInfo > input_info_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_OutputInfo > output_info_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > control_input_; + mutable std::atomic _control_input_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_; + int64_t temporary_memory_size_; + int64_t compute_cost_; + int32_t id_; + bool is_final_; + bool inaccurate_; + int64_t host_temp_memory_size_; + int64_t device_temp_memory_size_; + int64_t persistent_memory_size_; + int64_t compute_time_; + int64_t memory_time_; + int64_t device_persistent_memory_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto; +}; +// ------------------------------------------------------------------- + +class CostGraphDef_AggregatedCost final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CostGraphDef.AggregatedCost) */ { + public: + inline CostGraphDef_AggregatedCost() : CostGraphDef_AggregatedCost(nullptr) {} + ~CostGraphDef_AggregatedCost() override; + explicit PROTOBUF_CONSTEXPR CostGraphDef_AggregatedCost(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CostGraphDef_AggregatedCost(const CostGraphDef_AggregatedCost& from); + CostGraphDef_AggregatedCost(CostGraphDef_AggregatedCost&& from) noexcept + : CostGraphDef_AggregatedCost() { + *this = ::std::move(from); + } + + inline CostGraphDef_AggregatedCost& operator=(const CostGraphDef_AggregatedCost& from) { + CopyFrom(from); + return *this; + } + inline CostGraphDef_AggregatedCost& operator=(CostGraphDef_AggregatedCost&& 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 CostGraphDef_AggregatedCost& default_instance() { + return *internal_default_instance(); + } + static inline const CostGraphDef_AggregatedCost* internal_default_instance() { + return reinterpret_cast( + &_CostGraphDef_AggregatedCost_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(CostGraphDef_AggregatedCost& a, CostGraphDef_AggregatedCost& b) { + a.Swap(&b); + } + inline void Swap(CostGraphDef_AggregatedCost* 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(CostGraphDef_AggregatedCost* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CostGraphDef_AggregatedCost* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CostGraphDef_AggregatedCost& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CostGraphDef_AggregatedCost& from) { + CostGraphDef_AggregatedCost::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(CostGraphDef_AggregatedCost* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CostGraphDef.AggregatedCost"; + } + protected: + explicit CostGraphDef_AggregatedCost(::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 { + kDimensionFieldNumber = 2, + kCostFieldNumber = 1, + }; + // string dimension = 2; + void clear_dimension(); + const std::string& dimension() const; + template + void set_dimension(ArgT0&& arg0, ArgT... args); + std::string* mutable_dimension(); + PROTOBUF_NODISCARD std::string* release_dimension(); + void set_allocated_dimension(std::string* dimension); + private: + const std::string& _internal_dimension() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_dimension(const std::string& value); + std::string* _internal_mutable_dimension(); + public: + + // float cost = 1; + void clear_cost(); + float cost() const; + void set_cost(float value); + private: + float _internal_cost() const; + void _internal_set_cost(float value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.CostGraphDef.AggregatedCost) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr dimension_; + float cost_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto; +}; +// ------------------------------------------------------------------- + +class CostGraphDef final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.CostGraphDef) */ { + public: + inline CostGraphDef() : CostGraphDef(nullptr) {} + ~CostGraphDef() override; + explicit PROTOBUF_CONSTEXPR CostGraphDef(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CostGraphDef(const CostGraphDef& from); + CostGraphDef(CostGraphDef&& from) noexcept + : CostGraphDef() { + *this = ::std::move(from); + } + + inline CostGraphDef& operator=(const CostGraphDef& from) { + CopyFrom(from); + return *this; + } + inline CostGraphDef& operator=(CostGraphDef&& 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 CostGraphDef& default_instance() { + return *internal_default_instance(); + } + static inline const CostGraphDef* internal_default_instance() { + return reinterpret_cast( + &_CostGraphDef_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(CostGraphDef& a, CostGraphDef& b) { + a.Swap(&b); + } + inline void Swap(CostGraphDef* 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(CostGraphDef* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CostGraphDef* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CostGraphDef& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CostGraphDef& from) { + CostGraphDef::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(CostGraphDef* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.CostGraphDef"; + } + protected: + explicit CostGraphDef(::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 CostGraphDef_Node Node; + typedef CostGraphDef_AggregatedCost AggregatedCost; + + // accessors ------------------------------------------------------- + + enum : int { + kNodeFieldNumber = 1, + kCostFieldNumber = 2, + }; + // repeated .tensorflow.CostGraphDef.Node node = 1; + int node_size() const; + private: + int _internal_node_size() const; + public: + void clear_node(); + ::tensorflow::CostGraphDef_Node* mutable_node(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node >* + mutable_node(); + private: + const ::tensorflow::CostGraphDef_Node& _internal_node(int index) const; + ::tensorflow::CostGraphDef_Node* _internal_add_node(); + public: + const ::tensorflow::CostGraphDef_Node& node(int index) const; + ::tensorflow::CostGraphDef_Node* add_node(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node >& + node() const; + + // repeated .tensorflow.CostGraphDef.AggregatedCost cost = 2; + int cost_size() const; + private: + int _internal_cost_size() const; + public: + void clear_cost(); + ::tensorflow::CostGraphDef_AggregatedCost* mutable_cost(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_AggregatedCost >* + mutable_cost(); + private: + const ::tensorflow::CostGraphDef_AggregatedCost& _internal_cost(int index) const; + ::tensorflow::CostGraphDef_AggregatedCost* _internal_add_cost(); + public: + const ::tensorflow::CostGraphDef_AggregatedCost& cost(int index) const; + ::tensorflow::CostGraphDef_AggregatedCost* add_cost(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_AggregatedCost >& + cost() const; + + // @@protoc_insertion_point(class_scope:tensorflow.CostGraphDef) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node > node_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_AggregatedCost > cost_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcost_5fgraph_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CostGraphDef_Node_InputInfo + +// int32 preceding_node = 1; +inline void CostGraphDef_Node_InputInfo::clear_preceding_node() { + _impl_.preceding_node_ = 0; +} +inline int32_t CostGraphDef_Node_InputInfo::_internal_preceding_node() const { + return _impl_.preceding_node_; +} +inline int32_t CostGraphDef_Node_InputInfo::preceding_node() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.InputInfo.preceding_node) + return _internal_preceding_node(); +} +inline void CostGraphDef_Node_InputInfo::_internal_set_preceding_node(int32_t value) { + + _impl_.preceding_node_ = value; +} +inline void CostGraphDef_Node_InputInfo::set_preceding_node(int32_t value) { + _internal_set_preceding_node(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.InputInfo.preceding_node) +} + +// int32 preceding_port = 2; +inline void CostGraphDef_Node_InputInfo::clear_preceding_port() { + _impl_.preceding_port_ = 0; +} +inline int32_t CostGraphDef_Node_InputInfo::_internal_preceding_port() const { + return _impl_.preceding_port_; +} +inline int32_t CostGraphDef_Node_InputInfo::preceding_port() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.InputInfo.preceding_port) + return _internal_preceding_port(); +} +inline void CostGraphDef_Node_InputInfo::_internal_set_preceding_port(int32_t value) { + + _impl_.preceding_port_ = value; +} +inline void CostGraphDef_Node_InputInfo::set_preceding_port(int32_t value) { + _internal_set_preceding_port(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.InputInfo.preceding_port) +} + +// ------------------------------------------------------------------- + +// CostGraphDef_Node_OutputInfo + +// int64 size = 1; +inline void CostGraphDef_Node_OutputInfo::clear_size() { + _impl_.size_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node_OutputInfo::_internal_size() const { + return _impl_.size_; +} +inline int64_t CostGraphDef_Node_OutputInfo::size() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.OutputInfo.size) + return _internal_size(); +} +inline void CostGraphDef_Node_OutputInfo::_internal_set_size(int64_t value) { + + _impl_.size_ = value; +} +inline void CostGraphDef_Node_OutputInfo::set_size(int64_t value) { + _internal_set_size(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.OutputInfo.size) +} + +// int64 alias_input_port = 2; +inline void CostGraphDef_Node_OutputInfo::clear_alias_input_port() { + _impl_.alias_input_port_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node_OutputInfo::_internal_alias_input_port() const { + return _impl_.alias_input_port_; +} +inline int64_t CostGraphDef_Node_OutputInfo::alias_input_port() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.OutputInfo.alias_input_port) + return _internal_alias_input_port(); +} +inline void CostGraphDef_Node_OutputInfo::_internal_set_alias_input_port(int64_t value) { + + _impl_.alias_input_port_ = value; +} +inline void CostGraphDef_Node_OutputInfo::set_alias_input_port(int64_t value) { + _internal_set_alias_input_port(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.OutputInfo.alias_input_port) +} + +// .tensorflow.TensorShapeProto shape = 3; +inline bool CostGraphDef_Node_OutputInfo::_internal_has_shape() const { + return this != internal_default_instance() && _impl_.shape_ != nullptr; +} +inline bool CostGraphDef_Node_OutputInfo::has_shape() const { + return _internal_has_shape(); +} +inline const ::tensorflow::TensorShapeProto& CostGraphDef_Node_OutputInfo::_internal_shape() const { + const ::tensorflow::TensorShapeProto* p = _impl_.shape_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorShapeProto_default_instance_); +} +inline const ::tensorflow::TensorShapeProto& CostGraphDef_Node_OutputInfo::shape() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.OutputInfo.shape) + return _internal_shape(); +} +inline void CostGraphDef_Node_OutputInfo::unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + _impl_.shape_ = shape; + if (shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CostGraphDef.Node.OutputInfo.shape) +} +inline ::tensorflow::TensorShapeProto* CostGraphDef_Node_OutputInfo::release_shape() { + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::TensorShapeProto* CostGraphDef_Node_OutputInfo::unsafe_arena_release_shape() { + // @@protoc_insertion_point(field_release:tensorflow.CostGraphDef.Node.OutputInfo.shape) + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; + return temp; +} +inline ::tensorflow::TensorShapeProto* CostGraphDef_Node_OutputInfo::_internal_mutable_shape() { + + if (_impl_.shape_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorShapeProto>(GetArenaForAllocation()); + _impl_.shape_ = p; + } + return _impl_.shape_; +} +inline ::tensorflow::TensorShapeProto* CostGraphDef_Node_OutputInfo::mutable_shape() { + ::tensorflow::TensorShapeProto* _msg = _internal_mutable_shape(); + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.Node.OutputInfo.shape) + return _msg; +} +inline void CostGraphDef_Node_OutputInfo::set_allocated_shape(::tensorflow::TensorShapeProto* shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + if (shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(shape)); + if (message_arena != submessage_arena) { + shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, shape, submessage_arena); + } + + } else { + + } + _impl_.shape_ = shape; + // @@protoc_insertion_point(field_set_allocated:tensorflow.CostGraphDef.Node.OutputInfo.shape) +} + +// .tensorflow.DataType dtype = 4; +inline void CostGraphDef_Node_OutputInfo::clear_dtype() { + _impl_.dtype_ = 0; +} +inline ::tensorflow::DataType CostGraphDef_Node_OutputInfo::_internal_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.dtype_); +} +inline ::tensorflow::DataType CostGraphDef_Node_OutputInfo::dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.OutputInfo.dtype) + return _internal_dtype(); +} +inline void CostGraphDef_Node_OutputInfo::_internal_set_dtype(::tensorflow::DataType value) { + + _impl_.dtype_ = value; +} +inline void CostGraphDef_Node_OutputInfo::set_dtype(::tensorflow::DataType value) { + _internal_set_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.OutputInfo.dtype) +} + +// ------------------------------------------------------------------- + +// CostGraphDef_Node + +// string name = 1; +inline void CostGraphDef_Node::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& CostGraphDef_Node::name() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CostGraphDef_Node::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.name) +} +inline std::string* CostGraphDef_Node::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.Node.name) + return _s; +} +inline const std::string& CostGraphDef_Node::_internal_name() const { + return _impl_.name_.Get(); +} +inline void CostGraphDef_Node::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* CostGraphDef_Node::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* CostGraphDef_Node::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.CostGraphDef.Node.name) + return _impl_.name_.Release(); +} +inline void CostGraphDef_Node::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CostGraphDef.Node.name) +} + +// string device = 2; +inline void CostGraphDef_Node::clear_device() { + _impl_.device_.ClearToEmpty(); +} +inline const std::string& CostGraphDef_Node::device() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.device) + return _internal_device(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CostGraphDef_Node::set_device(ArgT0&& arg0, ArgT... args) { + + _impl_.device_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.device) +} +inline std::string* CostGraphDef_Node::mutable_device() { + std::string* _s = _internal_mutable_device(); + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.Node.device) + return _s; +} +inline const std::string& CostGraphDef_Node::_internal_device() const { + return _impl_.device_.Get(); +} +inline void CostGraphDef_Node::_internal_set_device(const std::string& value) { + + _impl_.device_.Set(value, GetArenaForAllocation()); +} +inline std::string* CostGraphDef_Node::_internal_mutable_device() { + + return _impl_.device_.Mutable(GetArenaForAllocation()); +} +inline std::string* CostGraphDef_Node::release_device() { + // @@protoc_insertion_point(field_release:tensorflow.CostGraphDef.Node.device) + return _impl_.device_.Release(); +} +inline void CostGraphDef_Node::set_allocated_device(std::string* device) { + if (device != nullptr) { + + } else { + + } + _impl_.device_.SetAllocated(device, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_.IsDefault()) { + _impl_.device_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CostGraphDef.Node.device) +} + +// int32 id = 3; +inline void CostGraphDef_Node::clear_id() { + _impl_.id_ = 0; +} +inline int32_t CostGraphDef_Node::_internal_id() const { + return _impl_.id_; +} +inline int32_t CostGraphDef_Node::id() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.id) + return _internal_id(); +} +inline void CostGraphDef_Node::_internal_set_id(int32_t value) { + + _impl_.id_ = value; +} +inline void CostGraphDef_Node::set_id(int32_t value) { + _internal_set_id(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.id) +} + +// repeated .tensorflow.CostGraphDef.Node.InputInfo input_info = 4; +inline int CostGraphDef_Node::_internal_input_info_size() const { + return _impl_.input_info_.size(); +} +inline int CostGraphDef_Node::input_info_size() const { + return _internal_input_info_size(); +} +inline void CostGraphDef_Node::clear_input_info() { + _impl_.input_info_.Clear(); +} +inline ::tensorflow::CostGraphDef_Node_InputInfo* CostGraphDef_Node::mutable_input_info(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.Node.input_info) + return _impl_.input_info_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_InputInfo >* +CostGraphDef_Node::mutable_input_info() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.CostGraphDef.Node.input_info) + return &_impl_.input_info_; +} +inline const ::tensorflow::CostGraphDef_Node_InputInfo& CostGraphDef_Node::_internal_input_info(int index) const { + return _impl_.input_info_.Get(index); +} +inline const ::tensorflow::CostGraphDef_Node_InputInfo& CostGraphDef_Node::input_info(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.input_info) + return _internal_input_info(index); +} +inline ::tensorflow::CostGraphDef_Node_InputInfo* CostGraphDef_Node::_internal_add_input_info() { + return _impl_.input_info_.Add(); +} +inline ::tensorflow::CostGraphDef_Node_InputInfo* CostGraphDef_Node::add_input_info() { + ::tensorflow::CostGraphDef_Node_InputInfo* _add = _internal_add_input_info(); + // @@protoc_insertion_point(field_add:tensorflow.CostGraphDef.Node.input_info) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_InputInfo >& +CostGraphDef_Node::input_info() const { + // @@protoc_insertion_point(field_list:tensorflow.CostGraphDef.Node.input_info) + return _impl_.input_info_; +} + +// repeated .tensorflow.CostGraphDef.Node.OutputInfo output_info = 5; +inline int CostGraphDef_Node::_internal_output_info_size() const { + return _impl_.output_info_.size(); +} +inline int CostGraphDef_Node::output_info_size() const { + return _internal_output_info_size(); +} +inline void CostGraphDef_Node::clear_output_info() { + _impl_.output_info_.Clear(); +} +inline ::tensorflow::CostGraphDef_Node_OutputInfo* CostGraphDef_Node::mutable_output_info(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.Node.output_info) + return _impl_.output_info_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_OutputInfo >* +CostGraphDef_Node::mutable_output_info() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.CostGraphDef.Node.output_info) + return &_impl_.output_info_; +} +inline const ::tensorflow::CostGraphDef_Node_OutputInfo& CostGraphDef_Node::_internal_output_info(int index) const { + return _impl_.output_info_.Get(index); +} +inline const ::tensorflow::CostGraphDef_Node_OutputInfo& CostGraphDef_Node::output_info(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.output_info) + return _internal_output_info(index); +} +inline ::tensorflow::CostGraphDef_Node_OutputInfo* CostGraphDef_Node::_internal_add_output_info() { + return _impl_.output_info_.Add(); +} +inline ::tensorflow::CostGraphDef_Node_OutputInfo* CostGraphDef_Node::add_output_info() { + ::tensorflow::CostGraphDef_Node_OutputInfo* _add = _internal_add_output_info(); + // @@protoc_insertion_point(field_add:tensorflow.CostGraphDef.Node.output_info) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node_OutputInfo >& +CostGraphDef_Node::output_info() const { + // @@protoc_insertion_point(field_list:tensorflow.CostGraphDef.Node.output_info) + return _impl_.output_info_; +} + +// int64 temporary_memory_size = 6; +inline void CostGraphDef_Node::clear_temporary_memory_size() { + _impl_.temporary_memory_size_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_temporary_memory_size() const { + return _impl_.temporary_memory_size_; +} +inline int64_t CostGraphDef_Node::temporary_memory_size() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.temporary_memory_size) + return _internal_temporary_memory_size(); +} +inline void CostGraphDef_Node::_internal_set_temporary_memory_size(int64_t value) { + + _impl_.temporary_memory_size_ = value; +} +inline void CostGraphDef_Node::set_temporary_memory_size(int64_t value) { + _internal_set_temporary_memory_size(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.temporary_memory_size) +} + +// int64 persistent_memory_size = 12; +inline void CostGraphDef_Node::clear_persistent_memory_size() { + _impl_.persistent_memory_size_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_persistent_memory_size() const { + return _impl_.persistent_memory_size_; +} +inline int64_t CostGraphDef_Node::persistent_memory_size() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.persistent_memory_size) + return _internal_persistent_memory_size(); +} +inline void CostGraphDef_Node::_internal_set_persistent_memory_size(int64_t value) { + + _impl_.persistent_memory_size_ = value; +} +inline void CostGraphDef_Node::set_persistent_memory_size(int64_t value) { + _internal_set_persistent_memory_size(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.persistent_memory_size) +} + +// int64 host_temp_memory_size = 10 [deprecated = true]; +inline void CostGraphDef_Node::clear_host_temp_memory_size() { + _impl_.host_temp_memory_size_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_host_temp_memory_size() const { + return _impl_.host_temp_memory_size_; +} +inline int64_t CostGraphDef_Node::host_temp_memory_size() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.host_temp_memory_size) + return _internal_host_temp_memory_size(); +} +inline void CostGraphDef_Node::_internal_set_host_temp_memory_size(int64_t value) { + + _impl_.host_temp_memory_size_ = value; +} +inline void CostGraphDef_Node::set_host_temp_memory_size(int64_t value) { + _internal_set_host_temp_memory_size(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.host_temp_memory_size) +} + +// int64 device_temp_memory_size = 11 [deprecated = true]; +inline void CostGraphDef_Node::clear_device_temp_memory_size() { + _impl_.device_temp_memory_size_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_device_temp_memory_size() const { + return _impl_.device_temp_memory_size_; +} +inline int64_t CostGraphDef_Node::device_temp_memory_size() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.device_temp_memory_size) + return _internal_device_temp_memory_size(); +} +inline void CostGraphDef_Node::_internal_set_device_temp_memory_size(int64_t value) { + + _impl_.device_temp_memory_size_ = value; +} +inline void CostGraphDef_Node::set_device_temp_memory_size(int64_t value) { + _internal_set_device_temp_memory_size(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.device_temp_memory_size) +} + +// int64 device_persistent_memory_size = 16 [deprecated = true]; +inline void CostGraphDef_Node::clear_device_persistent_memory_size() { + _impl_.device_persistent_memory_size_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_device_persistent_memory_size() const { + return _impl_.device_persistent_memory_size_; +} +inline int64_t CostGraphDef_Node::device_persistent_memory_size() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.device_persistent_memory_size) + return _internal_device_persistent_memory_size(); +} +inline void CostGraphDef_Node::_internal_set_device_persistent_memory_size(int64_t value) { + + _impl_.device_persistent_memory_size_ = value; +} +inline void CostGraphDef_Node::set_device_persistent_memory_size(int64_t value) { + _internal_set_device_persistent_memory_size(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.device_persistent_memory_size) +} + +// int64 compute_cost = 9; +inline void CostGraphDef_Node::clear_compute_cost() { + _impl_.compute_cost_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_compute_cost() const { + return _impl_.compute_cost_; +} +inline int64_t CostGraphDef_Node::compute_cost() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.compute_cost) + return _internal_compute_cost(); +} +inline void CostGraphDef_Node::_internal_set_compute_cost(int64_t value) { + + _impl_.compute_cost_ = value; +} +inline void CostGraphDef_Node::set_compute_cost(int64_t value) { + _internal_set_compute_cost(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.compute_cost) +} + +// int64 compute_time = 14; +inline void CostGraphDef_Node::clear_compute_time() { + _impl_.compute_time_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_compute_time() const { + return _impl_.compute_time_; +} +inline int64_t CostGraphDef_Node::compute_time() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.compute_time) + return _internal_compute_time(); +} +inline void CostGraphDef_Node::_internal_set_compute_time(int64_t value) { + + _impl_.compute_time_ = value; +} +inline void CostGraphDef_Node::set_compute_time(int64_t value) { + _internal_set_compute_time(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.compute_time) +} + +// int64 memory_time = 15; +inline void CostGraphDef_Node::clear_memory_time() { + _impl_.memory_time_ = int64_t{0}; +} +inline int64_t CostGraphDef_Node::_internal_memory_time() const { + return _impl_.memory_time_; +} +inline int64_t CostGraphDef_Node::memory_time() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.memory_time) + return _internal_memory_time(); +} +inline void CostGraphDef_Node::_internal_set_memory_time(int64_t value) { + + _impl_.memory_time_ = value; +} +inline void CostGraphDef_Node::set_memory_time(int64_t value) { + _internal_set_memory_time(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.memory_time) +} + +// bool is_final = 7; +inline void CostGraphDef_Node::clear_is_final() { + _impl_.is_final_ = false; +} +inline bool CostGraphDef_Node::_internal_is_final() const { + return _impl_.is_final_; +} +inline bool CostGraphDef_Node::is_final() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.is_final) + return _internal_is_final(); +} +inline void CostGraphDef_Node::_internal_set_is_final(bool value) { + + _impl_.is_final_ = value; +} +inline void CostGraphDef_Node::set_is_final(bool value) { + _internal_set_is_final(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.is_final) +} + +// repeated int32 control_input = 8; +inline int CostGraphDef_Node::_internal_control_input_size() const { + return _impl_.control_input_.size(); +} +inline int CostGraphDef_Node::control_input_size() const { + return _internal_control_input_size(); +} +inline void CostGraphDef_Node::clear_control_input() { + _impl_.control_input_.Clear(); +} +inline int32_t CostGraphDef_Node::_internal_control_input(int index) const { + return _impl_.control_input_.Get(index); +} +inline int32_t CostGraphDef_Node::control_input(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.control_input) + return _internal_control_input(index); +} +inline void CostGraphDef_Node::set_control_input(int index, int32_t value) { + _impl_.control_input_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.control_input) +} +inline void CostGraphDef_Node::_internal_add_control_input(int32_t value) { + _impl_.control_input_.Add(value); +} +inline void CostGraphDef_Node::add_control_input(int32_t value) { + _internal_add_control_input(value); + // @@protoc_insertion_point(field_add:tensorflow.CostGraphDef.Node.control_input) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +CostGraphDef_Node::_internal_control_input() const { + return _impl_.control_input_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +CostGraphDef_Node::control_input() const { + // @@protoc_insertion_point(field_list:tensorflow.CostGraphDef.Node.control_input) + return _internal_control_input(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +CostGraphDef_Node::_internal_mutable_control_input() { + return &_impl_.control_input_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +CostGraphDef_Node::mutable_control_input() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.CostGraphDef.Node.control_input) + return _internal_mutable_control_input(); +} + +// bool inaccurate = 17; +inline void CostGraphDef_Node::clear_inaccurate() { + _impl_.inaccurate_ = false; +} +inline bool CostGraphDef_Node::_internal_inaccurate() const { + return _impl_.inaccurate_; +} +inline bool CostGraphDef_Node::inaccurate() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.Node.inaccurate) + return _internal_inaccurate(); +} +inline void CostGraphDef_Node::_internal_set_inaccurate(bool value) { + + _impl_.inaccurate_ = value; +} +inline void CostGraphDef_Node::set_inaccurate(bool value) { + _internal_set_inaccurate(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.Node.inaccurate) +} + +// ------------------------------------------------------------------- + +// CostGraphDef_AggregatedCost + +// float cost = 1; +inline void CostGraphDef_AggregatedCost::clear_cost() { + _impl_.cost_ = 0; +} +inline float CostGraphDef_AggregatedCost::_internal_cost() const { + return _impl_.cost_; +} +inline float CostGraphDef_AggregatedCost::cost() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.AggregatedCost.cost) + return _internal_cost(); +} +inline void CostGraphDef_AggregatedCost::_internal_set_cost(float value) { + + _impl_.cost_ = value; +} +inline void CostGraphDef_AggregatedCost::set_cost(float value) { + _internal_set_cost(value); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.AggregatedCost.cost) +} + +// string dimension = 2; +inline void CostGraphDef_AggregatedCost::clear_dimension() { + _impl_.dimension_.ClearToEmpty(); +} +inline const std::string& CostGraphDef_AggregatedCost::dimension() const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.AggregatedCost.dimension) + return _internal_dimension(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CostGraphDef_AggregatedCost::set_dimension(ArgT0&& arg0, ArgT... args) { + + _impl_.dimension_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.CostGraphDef.AggregatedCost.dimension) +} +inline std::string* CostGraphDef_AggregatedCost::mutable_dimension() { + std::string* _s = _internal_mutable_dimension(); + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.AggregatedCost.dimension) + return _s; +} +inline const std::string& CostGraphDef_AggregatedCost::_internal_dimension() const { + return _impl_.dimension_.Get(); +} +inline void CostGraphDef_AggregatedCost::_internal_set_dimension(const std::string& value) { + + _impl_.dimension_.Set(value, GetArenaForAllocation()); +} +inline std::string* CostGraphDef_AggregatedCost::_internal_mutable_dimension() { + + return _impl_.dimension_.Mutable(GetArenaForAllocation()); +} +inline std::string* CostGraphDef_AggregatedCost::release_dimension() { + // @@protoc_insertion_point(field_release:tensorflow.CostGraphDef.AggregatedCost.dimension) + return _impl_.dimension_.Release(); +} +inline void CostGraphDef_AggregatedCost::set_allocated_dimension(std::string* dimension) { + if (dimension != nullptr) { + + } else { + + } + _impl_.dimension_.SetAllocated(dimension, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.dimension_.IsDefault()) { + _impl_.dimension_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.CostGraphDef.AggregatedCost.dimension) +} + +// ------------------------------------------------------------------- + +// CostGraphDef + +// repeated .tensorflow.CostGraphDef.Node node = 1; +inline int CostGraphDef::_internal_node_size() const { + return _impl_.node_.size(); +} +inline int CostGraphDef::node_size() const { + return _internal_node_size(); +} +inline void CostGraphDef::clear_node() { + _impl_.node_.Clear(); +} +inline ::tensorflow::CostGraphDef_Node* CostGraphDef::mutable_node(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.node) + return _impl_.node_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node >* +CostGraphDef::mutable_node() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.CostGraphDef.node) + return &_impl_.node_; +} +inline const ::tensorflow::CostGraphDef_Node& CostGraphDef::_internal_node(int index) const { + return _impl_.node_.Get(index); +} +inline const ::tensorflow::CostGraphDef_Node& CostGraphDef::node(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.node) + return _internal_node(index); +} +inline ::tensorflow::CostGraphDef_Node* CostGraphDef::_internal_add_node() { + return _impl_.node_.Add(); +} +inline ::tensorflow::CostGraphDef_Node* CostGraphDef::add_node() { + ::tensorflow::CostGraphDef_Node* _add = _internal_add_node(); + // @@protoc_insertion_point(field_add:tensorflow.CostGraphDef.node) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_Node >& +CostGraphDef::node() const { + // @@protoc_insertion_point(field_list:tensorflow.CostGraphDef.node) + return _impl_.node_; +} + +// repeated .tensorflow.CostGraphDef.AggregatedCost cost = 2; +inline int CostGraphDef::_internal_cost_size() const { + return _impl_.cost_.size(); +} +inline int CostGraphDef::cost_size() const { + return _internal_cost_size(); +} +inline void CostGraphDef::clear_cost() { + _impl_.cost_.Clear(); +} +inline ::tensorflow::CostGraphDef_AggregatedCost* CostGraphDef::mutable_cost(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.CostGraphDef.cost) + return _impl_.cost_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_AggregatedCost >* +CostGraphDef::mutable_cost() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.CostGraphDef.cost) + return &_impl_.cost_; +} +inline const ::tensorflow::CostGraphDef_AggregatedCost& CostGraphDef::_internal_cost(int index) const { + return _impl_.cost_.Get(index); +} +inline const ::tensorflow::CostGraphDef_AggregatedCost& CostGraphDef::cost(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.CostGraphDef.cost) + return _internal_cost(index); +} +inline ::tensorflow::CostGraphDef_AggregatedCost* CostGraphDef::_internal_add_cost() { + return _impl_.cost_.Add(); +} +inline ::tensorflow::CostGraphDef_AggregatedCost* CostGraphDef::add_cost() { + ::tensorflow::CostGraphDef_AggregatedCost* _add = _internal_add_cost(); + // @@protoc_insertion_point(field_add:tensorflow.CostGraphDef.cost) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::CostGraphDef_AggregatedCost >& +CostGraphDef::cost() const { + // @@protoc_insertion_point(field_list:tensorflow.CostGraphDef.cost) + return _impl_.cost_; +} + +#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_2fframework_2fcost_5fgraph_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cost_graph.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cost_graph.proto new file mode 100644 index 0000000000000000000000000000000000000000..42c9e23cfab4c2e76df8ffe50f1f420f3c0ae13f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cost_graph.proto @@ -0,0 +1,89 @@ +syntax = "proto3"; + +package tensorflow; + +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "CostGraphProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/cost_graph_go_proto"; + +message CostGraphDef { + message Node { + // The name of the node. Names are globally unique. + string name = 1; + + // The device of the node. Can be empty if the node is mapped to the + // default partition or partitioning hasn't been run yet. + string device = 2; + + // The id of the node. Node ids are only unique inside a partition. + int32 id = 3; + + // Inputs of this node. They must be executed before this node can be + // executed. An input is a particular output of another node, specified + // by the node id and the output index. + message InputInfo { + int32 preceding_node = 1; + int32 preceding_port = 2; + } + repeated InputInfo input_info = 4; + + // Outputs of this node. + message OutputInfo { + int64 size = 1; + // If >= 0, the output is an alias of an input. Note that an alias input + // may itself be an alias. The algorithm will therefore need to follow + // those pointers. + int64 alias_input_port = 2; + TensorShapeProto shape = 3; + DataType dtype = 4; + } + repeated OutputInfo output_info = 5; + + // Temporary memory used by this node. + int64 temporary_memory_size = 6; + + // Persistent memory used by this node. + int64 persistent_memory_size = 12; + + int64 host_temp_memory_size = 10 [deprecated = true]; + int64 device_temp_memory_size = 11 [deprecated = true]; + int64 device_persistent_memory_size = 16 [deprecated = true]; + + // Estimate of the computational cost of this node, in microseconds. + int64 compute_cost = 9; + + // Analytical estimate of the computational cost of this node, in + // microseconds. + int64 compute_time = 14; + + // Analytical estimate of the memory access cost of this node, in + // microseconds. + int64 memory_time = 15; + + // If true, the output is permanent: it can't be discarded, because this + // node is part of the "final output". Nodes may depend on final nodes. + bool is_final = 7; + + // Ids of the control inputs for this node. + repeated int32 control_input = 8; + + // Are the costs inaccurate? + bool inaccurate = 17; + } + repeated Node node = 1; + + // Total cost of this graph, typically used for balancing decisions. + message AggregatedCost { + // Aggregated cost value. + float cost = 1; + + // Aggregated cost dimension (e.g. 'memory', 'compute', 'network'). + string dimension = 2; + } + repeated AggregatedCost cost = 2; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cpp_shape_inference.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cpp_shape_inference.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..5e40b3c02bbd7d0b75273d041fcd77a7ab7d5511 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cpp_shape_inference.pb.h @@ -0,0 +1,1358 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/cpp_shape_inference.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_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/full_type.pb.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_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_2fframework_2fcpp_5fshape_5finference_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto; +namespace tensorflow { +namespace core { +class CppShapeInferenceInputsNeeded; +struct CppShapeInferenceInputsNeededDefaultTypeInternal; +extern CppShapeInferenceInputsNeededDefaultTypeInternal _CppShapeInferenceInputsNeeded_default_instance_; +class CppShapeInferenceResult; +struct CppShapeInferenceResultDefaultTypeInternal; +extern CppShapeInferenceResultDefaultTypeInternal _CppShapeInferenceResult_default_instance_; +class CppShapeInferenceResult_HandleData; +struct CppShapeInferenceResult_HandleDataDefaultTypeInternal; +extern CppShapeInferenceResult_HandleDataDefaultTypeInternal _CppShapeInferenceResult_HandleData_default_instance_; +class CppShapeInferenceResult_HandleShapeAndType; +struct CppShapeInferenceResult_HandleShapeAndTypeDefaultTypeInternal; +extern CppShapeInferenceResult_HandleShapeAndTypeDefaultTypeInternal _CppShapeInferenceResult_HandleShapeAndType_default_instance_; +} // namespace core +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::core::CppShapeInferenceInputsNeeded* Arena::CreateMaybeMessage<::tensorflow::core::CppShapeInferenceInputsNeeded>(Arena*); +template<> ::tensorflow::core::CppShapeInferenceResult* Arena::CreateMaybeMessage<::tensorflow::core::CppShapeInferenceResult>(Arena*); +template<> ::tensorflow::core::CppShapeInferenceResult_HandleData* Arena::CreateMaybeMessage<::tensorflow::core::CppShapeInferenceResult_HandleData>(Arena*); +template<> ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* Arena::CreateMaybeMessage<::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { +namespace core { + +// =================================================================== + +class CppShapeInferenceResult_HandleShapeAndType final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType) */ { + public: + inline CppShapeInferenceResult_HandleShapeAndType() : CppShapeInferenceResult_HandleShapeAndType(nullptr) {} + ~CppShapeInferenceResult_HandleShapeAndType() override; + explicit PROTOBUF_CONSTEXPR CppShapeInferenceResult_HandleShapeAndType(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CppShapeInferenceResult_HandleShapeAndType(const CppShapeInferenceResult_HandleShapeAndType& from); + CppShapeInferenceResult_HandleShapeAndType(CppShapeInferenceResult_HandleShapeAndType&& from) noexcept + : CppShapeInferenceResult_HandleShapeAndType() { + *this = ::std::move(from); + } + + inline CppShapeInferenceResult_HandleShapeAndType& operator=(const CppShapeInferenceResult_HandleShapeAndType& from) { + CopyFrom(from); + return *this; + } + inline CppShapeInferenceResult_HandleShapeAndType& operator=(CppShapeInferenceResult_HandleShapeAndType&& 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 CppShapeInferenceResult_HandleShapeAndType& default_instance() { + return *internal_default_instance(); + } + static inline const CppShapeInferenceResult_HandleShapeAndType* internal_default_instance() { + return reinterpret_cast( + &_CppShapeInferenceResult_HandleShapeAndType_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CppShapeInferenceResult_HandleShapeAndType& a, CppShapeInferenceResult_HandleShapeAndType& b) { + a.Swap(&b); + } + inline void Swap(CppShapeInferenceResult_HandleShapeAndType* 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(CppShapeInferenceResult_HandleShapeAndType* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CppShapeInferenceResult_HandleShapeAndType* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CppShapeInferenceResult_HandleShapeAndType& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CppShapeInferenceResult_HandleShapeAndType& from) { + CppShapeInferenceResult_HandleShapeAndType::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(CppShapeInferenceResult_HandleShapeAndType* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.core.CppShapeInferenceResult.HandleShapeAndType"; + } + protected: + explicit CppShapeInferenceResult_HandleShapeAndType(::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 { + kShapeFieldNumber = 1, + kTypeFieldNumber = 4, + kDtypeFieldNumber = 2, + }; + // .tensorflow.TensorShapeProto shape = 1; + bool has_shape() const; + private: + bool _internal_has_shape() const; + public: + void clear_shape(); + const ::tensorflow::TensorShapeProto& shape() const; + PROTOBUF_NODISCARD ::tensorflow::TensorShapeProto* release_shape(); + ::tensorflow::TensorShapeProto* mutable_shape(); + void set_allocated_shape(::tensorflow::TensorShapeProto* shape); + private: + const ::tensorflow::TensorShapeProto& _internal_shape() const; + ::tensorflow::TensorShapeProto* _internal_mutable_shape(); + public: + void unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape); + ::tensorflow::TensorShapeProto* unsafe_arena_release_shape(); + + // .tensorflow.FullTypeDef type = 4; + bool has_type() const; + private: + bool _internal_has_type() const; + public: + void clear_type(); + const ::tensorflow::FullTypeDef& type() const; + PROTOBUF_NODISCARD ::tensorflow::FullTypeDef* release_type(); + ::tensorflow::FullTypeDef* mutable_type(); + void set_allocated_type(::tensorflow::FullTypeDef* type); + private: + const ::tensorflow::FullTypeDef& _internal_type() const; + ::tensorflow::FullTypeDef* _internal_mutable_type(); + public: + void unsafe_arena_set_allocated_type( + ::tensorflow::FullTypeDef* type); + ::tensorflow::FullTypeDef* unsafe_arena_release_type(); + + // .tensorflow.DataType dtype = 2; + 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: + + // @@protoc_insertion_point(class_scope:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::TensorShapeProto* shape_; + ::tensorflow::FullTypeDef* type_; + int dtype_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto; +}; +// ------------------------------------------------------------------- + +class CppShapeInferenceResult_HandleData final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.core.CppShapeInferenceResult.HandleData) */ { + public: + inline CppShapeInferenceResult_HandleData() : CppShapeInferenceResult_HandleData(nullptr) {} + ~CppShapeInferenceResult_HandleData() override; + explicit PROTOBUF_CONSTEXPR CppShapeInferenceResult_HandleData(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CppShapeInferenceResult_HandleData(const CppShapeInferenceResult_HandleData& from); + CppShapeInferenceResult_HandleData(CppShapeInferenceResult_HandleData&& from) noexcept + : CppShapeInferenceResult_HandleData() { + *this = ::std::move(from); + } + + inline CppShapeInferenceResult_HandleData& operator=(const CppShapeInferenceResult_HandleData& from) { + CopyFrom(from); + return *this; + } + inline CppShapeInferenceResult_HandleData& operator=(CppShapeInferenceResult_HandleData&& 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 CppShapeInferenceResult_HandleData& default_instance() { + return *internal_default_instance(); + } + static inline const CppShapeInferenceResult_HandleData* internal_default_instance() { + return reinterpret_cast( + &_CppShapeInferenceResult_HandleData_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(CppShapeInferenceResult_HandleData& a, CppShapeInferenceResult_HandleData& b) { + a.Swap(&b); + } + inline void Swap(CppShapeInferenceResult_HandleData* 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(CppShapeInferenceResult_HandleData* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CppShapeInferenceResult_HandleData* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CppShapeInferenceResult_HandleData& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CppShapeInferenceResult_HandleData& from) { + CppShapeInferenceResult_HandleData::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(CppShapeInferenceResult_HandleData* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.core.CppShapeInferenceResult.HandleData"; + } + protected: + explicit CppShapeInferenceResult_HandleData(::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 { + kShapeAndTypeFieldNumber = 2, + kIsSetFieldNumber = 1, + }; + // repeated .tensorflow.core.CppShapeInferenceResult.HandleShapeAndType shape_and_type = 2; + int shape_and_type_size() const; + private: + int _internal_shape_and_type_size() const; + public: + void clear_shape_and_type(); + ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* mutable_shape_and_type(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType >* + mutable_shape_and_type(); + private: + const ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType& _internal_shape_and_type(int index) const; + ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* _internal_add_shape_and_type(); + public: + const ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType& shape_and_type(int index) const; + ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* add_shape_and_type(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType >& + shape_and_type() const; + + // bool is_set = 1; + void clear_is_set(); + bool is_set() const; + void set_is_set(bool value); + private: + bool _internal_is_set() const; + void _internal_set_is_set(bool value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.core.CppShapeInferenceResult.HandleData) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType > shape_and_type_; + bool is_set_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto; +}; +// ------------------------------------------------------------------- + +class CppShapeInferenceResult final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.core.CppShapeInferenceResult) */ { + public: + inline CppShapeInferenceResult() : CppShapeInferenceResult(nullptr) {} + ~CppShapeInferenceResult() override; + explicit PROTOBUF_CONSTEXPR CppShapeInferenceResult(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CppShapeInferenceResult(const CppShapeInferenceResult& from); + CppShapeInferenceResult(CppShapeInferenceResult&& from) noexcept + : CppShapeInferenceResult() { + *this = ::std::move(from); + } + + inline CppShapeInferenceResult& operator=(const CppShapeInferenceResult& from) { + CopyFrom(from); + return *this; + } + inline CppShapeInferenceResult& operator=(CppShapeInferenceResult&& 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 CppShapeInferenceResult& default_instance() { + return *internal_default_instance(); + } + static inline const CppShapeInferenceResult* internal_default_instance() { + return reinterpret_cast( + &_CppShapeInferenceResult_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(CppShapeInferenceResult& a, CppShapeInferenceResult& b) { + a.Swap(&b); + } + inline void Swap(CppShapeInferenceResult* 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(CppShapeInferenceResult* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CppShapeInferenceResult* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CppShapeInferenceResult& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CppShapeInferenceResult& from) { + CppShapeInferenceResult::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(CppShapeInferenceResult* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.core.CppShapeInferenceResult"; + } + protected: + explicit CppShapeInferenceResult(::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 CppShapeInferenceResult_HandleShapeAndType HandleShapeAndType; + typedef CppShapeInferenceResult_HandleData HandleData; + + // accessors ------------------------------------------------------- + + enum : int { + kShapeFieldNumber = 1, + kHandleDataFieldNumber = 4, + }; + // .tensorflow.TensorShapeProto shape = 1; + bool has_shape() const; + private: + bool _internal_has_shape() const; + public: + void clear_shape(); + const ::tensorflow::TensorShapeProto& shape() const; + PROTOBUF_NODISCARD ::tensorflow::TensorShapeProto* release_shape(); + ::tensorflow::TensorShapeProto* mutable_shape(); + void set_allocated_shape(::tensorflow::TensorShapeProto* shape); + private: + const ::tensorflow::TensorShapeProto& _internal_shape() const; + ::tensorflow::TensorShapeProto* _internal_mutable_shape(); + public: + void unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape); + ::tensorflow::TensorShapeProto* unsafe_arena_release_shape(); + + // .tensorflow.core.CppShapeInferenceResult.HandleData handle_data = 4; + bool has_handle_data() const; + private: + bool _internal_has_handle_data() const; + public: + void clear_handle_data(); + const ::tensorflow::core::CppShapeInferenceResult_HandleData& handle_data() const; + PROTOBUF_NODISCARD ::tensorflow::core::CppShapeInferenceResult_HandleData* release_handle_data(); + ::tensorflow::core::CppShapeInferenceResult_HandleData* mutable_handle_data(); + void set_allocated_handle_data(::tensorflow::core::CppShapeInferenceResult_HandleData* handle_data); + private: + const ::tensorflow::core::CppShapeInferenceResult_HandleData& _internal_handle_data() const; + ::tensorflow::core::CppShapeInferenceResult_HandleData* _internal_mutable_handle_data(); + public: + void unsafe_arena_set_allocated_handle_data( + ::tensorflow::core::CppShapeInferenceResult_HandleData* handle_data); + ::tensorflow::core::CppShapeInferenceResult_HandleData* unsafe_arena_release_handle_data(); + + // @@protoc_insertion_point(class_scope:tensorflow.core.CppShapeInferenceResult) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::TensorShapeProto* shape_; + ::tensorflow::core::CppShapeInferenceResult_HandleData* handle_data_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto; +}; +// ------------------------------------------------------------------- + +class CppShapeInferenceInputsNeeded final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.core.CppShapeInferenceInputsNeeded) */ { + public: + inline CppShapeInferenceInputsNeeded() : CppShapeInferenceInputsNeeded(nullptr) {} + ~CppShapeInferenceInputsNeeded() override; + explicit PROTOBUF_CONSTEXPR CppShapeInferenceInputsNeeded(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CppShapeInferenceInputsNeeded(const CppShapeInferenceInputsNeeded& from); + CppShapeInferenceInputsNeeded(CppShapeInferenceInputsNeeded&& from) noexcept + : CppShapeInferenceInputsNeeded() { + *this = ::std::move(from); + } + + inline CppShapeInferenceInputsNeeded& operator=(const CppShapeInferenceInputsNeeded& from) { + CopyFrom(from); + return *this; + } + inline CppShapeInferenceInputsNeeded& operator=(CppShapeInferenceInputsNeeded&& 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 CppShapeInferenceInputsNeeded& default_instance() { + return *internal_default_instance(); + } + static inline const CppShapeInferenceInputsNeeded* internal_default_instance() { + return reinterpret_cast( + &_CppShapeInferenceInputsNeeded_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(CppShapeInferenceInputsNeeded& a, CppShapeInferenceInputsNeeded& b) { + a.Swap(&b); + } + inline void Swap(CppShapeInferenceInputsNeeded* 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(CppShapeInferenceInputsNeeded* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CppShapeInferenceInputsNeeded* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CppShapeInferenceInputsNeeded& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CppShapeInferenceInputsNeeded& from) { + CppShapeInferenceInputsNeeded::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(CppShapeInferenceInputsNeeded* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.core.CppShapeInferenceInputsNeeded"; + } + protected: + explicit CppShapeInferenceInputsNeeded(::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 { + kInputTensorsNeededFieldNumber = 1, + kInputTensorsAsShapesNeededFieldNumber = 2, + }; + // repeated int32 input_tensors_needed = 1; + int input_tensors_needed_size() const; + private: + int _internal_input_tensors_needed_size() const; + public: + void clear_input_tensors_needed(); + private: + int32_t _internal_input_tensors_needed(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + _internal_input_tensors_needed() const; + void _internal_add_input_tensors_needed(int32_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + _internal_mutable_input_tensors_needed(); + public: + int32_t input_tensors_needed(int index) const; + void set_input_tensors_needed(int index, int32_t value); + void add_input_tensors_needed(int32_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + input_tensors_needed() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + mutable_input_tensors_needed(); + + // repeated int32 input_tensors_as_shapes_needed = 2; + int input_tensors_as_shapes_needed_size() const; + private: + int _internal_input_tensors_as_shapes_needed_size() const; + public: + void clear_input_tensors_as_shapes_needed(); + private: + int32_t _internal_input_tensors_as_shapes_needed(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + _internal_input_tensors_as_shapes_needed() const; + void _internal_add_input_tensors_as_shapes_needed(int32_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + _internal_mutable_input_tensors_as_shapes_needed(); + public: + int32_t input_tensors_as_shapes_needed(int index) const; + void set_input_tensors_as_shapes_needed(int index, int32_t value); + void add_input_tensors_as_shapes_needed(int32_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& + input_tensors_as_shapes_needed() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* + mutable_input_tensors_as_shapes_needed(); + + // @@protoc_insertion_point(class_scope:tensorflow.core.CppShapeInferenceInputsNeeded) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > input_tensors_needed_; + mutable std::atomic _input_tensors_needed_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > input_tensors_as_shapes_needed_; + mutable std::atomic _input_tensors_as_shapes_needed_cached_byte_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CppShapeInferenceResult_HandleShapeAndType + +// .tensorflow.TensorShapeProto shape = 1; +inline bool CppShapeInferenceResult_HandleShapeAndType::_internal_has_shape() const { + return this != internal_default_instance() && _impl_.shape_ != nullptr; +} +inline bool CppShapeInferenceResult_HandleShapeAndType::has_shape() const { + return _internal_has_shape(); +} +inline const ::tensorflow::TensorShapeProto& CppShapeInferenceResult_HandleShapeAndType::_internal_shape() const { + const ::tensorflow::TensorShapeProto* p = _impl_.shape_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorShapeProto_default_instance_); +} +inline const ::tensorflow::TensorShapeProto& CppShapeInferenceResult_HandleShapeAndType::shape() const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.shape) + return _internal_shape(); +} +inline void CppShapeInferenceResult_HandleShapeAndType::unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + _impl_.shape_ = shape; + if (shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.shape) +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult_HandleShapeAndType::release_shape() { + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult_HandleShapeAndType::unsafe_arena_release_shape() { + // @@protoc_insertion_point(field_release:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.shape) + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; + return temp; +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult_HandleShapeAndType::_internal_mutable_shape() { + + if (_impl_.shape_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorShapeProto>(GetArenaForAllocation()); + _impl_.shape_ = p; + } + return _impl_.shape_; +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult_HandleShapeAndType::mutable_shape() { + ::tensorflow::TensorShapeProto* _msg = _internal_mutable_shape(); + // @@protoc_insertion_point(field_mutable:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.shape) + return _msg; +} +inline void CppShapeInferenceResult_HandleShapeAndType::set_allocated_shape(::tensorflow::TensorShapeProto* shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + if (shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(shape)); + if (message_arena != submessage_arena) { + shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, shape, submessage_arena); + } + + } else { + + } + _impl_.shape_ = shape; + // @@protoc_insertion_point(field_set_allocated:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.shape) +} + +// .tensorflow.DataType dtype = 2; +inline void CppShapeInferenceResult_HandleShapeAndType::clear_dtype() { + _impl_.dtype_ = 0; +} +inline ::tensorflow::DataType CppShapeInferenceResult_HandleShapeAndType::_internal_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.dtype_); +} +inline ::tensorflow::DataType CppShapeInferenceResult_HandleShapeAndType::dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.dtype) + return _internal_dtype(); +} +inline void CppShapeInferenceResult_HandleShapeAndType::_internal_set_dtype(::tensorflow::DataType value) { + + _impl_.dtype_ = value; +} +inline void CppShapeInferenceResult_HandleShapeAndType::set_dtype(::tensorflow::DataType value) { + _internal_set_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.dtype) +} + +// .tensorflow.FullTypeDef type = 4; +inline bool CppShapeInferenceResult_HandleShapeAndType::_internal_has_type() const { + return this != internal_default_instance() && _impl_.type_ != nullptr; +} +inline bool CppShapeInferenceResult_HandleShapeAndType::has_type() const { + return _internal_has_type(); +} +inline const ::tensorflow::FullTypeDef& CppShapeInferenceResult_HandleShapeAndType::_internal_type() const { + const ::tensorflow::FullTypeDef* p = _impl_.type_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_FullTypeDef_default_instance_); +} +inline const ::tensorflow::FullTypeDef& CppShapeInferenceResult_HandleShapeAndType::type() const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.type) + return _internal_type(); +} +inline void CppShapeInferenceResult_HandleShapeAndType::unsafe_arena_set_allocated_type( + ::tensorflow::FullTypeDef* type) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.type_); + } + _impl_.type_ = type; + if (type) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.type) +} +inline ::tensorflow::FullTypeDef* CppShapeInferenceResult_HandleShapeAndType::release_type() { + + ::tensorflow::FullTypeDef* temp = _impl_.type_; + _impl_.type_ = 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::FullTypeDef* CppShapeInferenceResult_HandleShapeAndType::unsafe_arena_release_type() { + // @@protoc_insertion_point(field_release:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.type) + + ::tensorflow::FullTypeDef* temp = _impl_.type_; + _impl_.type_ = nullptr; + return temp; +} +inline ::tensorflow::FullTypeDef* CppShapeInferenceResult_HandleShapeAndType::_internal_mutable_type() { + + if (_impl_.type_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::FullTypeDef>(GetArenaForAllocation()); + _impl_.type_ = p; + } + return _impl_.type_; +} +inline ::tensorflow::FullTypeDef* CppShapeInferenceResult_HandleShapeAndType::mutable_type() { + ::tensorflow::FullTypeDef* _msg = _internal_mutable_type(); + // @@protoc_insertion_point(field_mutable:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.type) + return _msg; +} +inline void CppShapeInferenceResult_HandleShapeAndType::set_allocated_type(::tensorflow::FullTypeDef* type) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.type_); + } + if (type) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(type)); + if (message_arena != submessage_arena) { + type = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, type, submessage_arena); + } + + } else { + + } + _impl_.type_ = type; + // @@protoc_insertion_point(field_set_allocated:tensorflow.core.CppShapeInferenceResult.HandleShapeAndType.type) +} + +// ------------------------------------------------------------------- + +// CppShapeInferenceResult_HandleData + +// bool is_set = 1; +inline void CppShapeInferenceResult_HandleData::clear_is_set() { + _impl_.is_set_ = false; +} +inline bool CppShapeInferenceResult_HandleData::_internal_is_set() const { + return _impl_.is_set_; +} +inline bool CppShapeInferenceResult_HandleData::is_set() const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.HandleData.is_set) + return _internal_is_set(); +} +inline void CppShapeInferenceResult_HandleData::_internal_set_is_set(bool value) { + + _impl_.is_set_ = value; +} +inline void CppShapeInferenceResult_HandleData::set_is_set(bool value) { + _internal_set_is_set(value); + // @@protoc_insertion_point(field_set:tensorflow.core.CppShapeInferenceResult.HandleData.is_set) +} + +// repeated .tensorflow.core.CppShapeInferenceResult.HandleShapeAndType shape_and_type = 2; +inline int CppShapeInferenceResult_HandleData::_internal_shape_and_type_size() const { + return _impl_.shape_and_type_.size(); +} +inline int CppShapeInferenceResult_HandleData::shape_and_type_size() const { + return _internal_shape_and_type_size(); +} +inline void CppShapeInferenceResult_HandleData::clear_shape_and_type() { + _impl_.shape_and_type_.Clear(); +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* CppShapeInferenceResult_HandleData::mutable_shape_and_type(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.core.CppShapeInferenceResult.HandleData.shape_and_type) + return _impl_.shape_and_type_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType >* +CppShapeInferenceResult_HandleData::mutable_shape_and_type() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.core.CppShapeInferenceResult.HandleData.shape_and_type) + return &_impl_.shape_and_type_; +} +inline const ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType& CppShapeInferenceResult_HandleData::_internal_shape_and_type(int index) const { + return _impl_.shape_and_type_.Get(index); +} +inline const ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType& CppShapeInferenceResult_HandleData::shape_and_type(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.HandleData.shape_and_type) + return _internal_shape_and_type(index); +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* CppShapeInferenceResult_HandleData::_internal_add_shape_and_type() { + return _impl_.shape_and_type_.Add(); +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* CppShapeInferenceResult_HandleData::add_shape_and_type() { + ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType* _add = _internal_add_shape_and_type(); + // @@protoc_insertion_point(field_add:tensorflow.core.CppShapeInferenceResult.HandleData.shape_and_type) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::core::CppShapeInferenceResult_HandleShapeAndType >& +CppShapeInferenceResult_HandleData::shape_and_type() const { + // @@protoc_insertion_point(field_list:tensorflow.core.CppShapeInferenceResult.HandleData.shape_and_type) + return _impl_.shape_and_type_; +} + +// ------------------------------------------------------------------- + +// CppShapeInferenceResult + +// .tensorflow.TensorShapeProto shape = 1; +inline bool CppShapeInferenceResult::_internal_has_shape() const { + return this != internal_default_instance() && _impl_.shape_ != nullptr; +} +inline bool CppShapeInferenceResult::has_shape() const { + return _internal_has_shape(); +} +inline const ::tensorflow::TensorShapeProto& CppShapeInferenceResult::_internal_shape() const { + const ::tensorflow::TensorShapeProto* p = _impl_.shape_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorShapeProto_default_instance_); +} +inline const ::tensorflow::TensorShapeProto& CppShapeInferenceResult::shape() const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.shape) + return _internal_shape(); +} +inline void CppShapeInferenceResult::unsafe_arena_set_allocated_shape( + ::tensorflow::TensorShapeProto* shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + _impl_.shape_ = shape; + if (shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.core.CppShapeInferenceResult.shape) +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult::release_shape() { + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult::unsafe_arena_release_shape() { + // @@protoc_insertion_point(field_release:tensorflow.core.CppShapeInferenceResult.shape) + + ::tensorflow::TensorShapeProto* temp = _impl_.shape_; + _impl_.shape_ = nullptr; + return temp; +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult::_internal_mutable_shape() { + + if (_impl_.shape_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorShapeProto>(GetArenaForAllocation()); + _impl_.shape_ = p; + } + return _impl_.shape_; +} +inline ::tensorflow::TensorShapeProto* CppShapeInferenceResult::mutable_shape() { + ::tensorflow::TensorShapeProto* _msg = _internal_mutable_shape(); + // @@protoc_insertion_point(field_mutable:tensorflow.core.CppShapeInferenceResult.shape) + return _msg; +} +inline void CppShapeInferenceResult::set_allocated_shape(::tensorflow::TensorShapeProto* shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.shape_); + } + if (shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(shape)); + if (message_arena != submessage_arena) { + shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, shape, submessage_arena); + } + + } else { + + } + _impl_.shape_ = shape; + // @@protoc_insertion_point(field_set_allocated:tensorflow.core.CppShapeInferenceResult.shape) +} + +// .tensorflow.core.CppShapeInferenceResult.HandleData handle_data = 4; +inline bool CppShapeInferenceResult::_internal_has_handle_data() const { + return this != internal_default_instance() && _impl_.handle_data_ != nullptr; +} +inline bool CppShapeInferenceResult::has_handle_data() const { + return _internal_has_handle_data(); +} +inline void CppShapeInferenceResult::clear_handle_data() { + if (GetArenaForAllocation() == nullptr && _impl_.handle_data_ != nullptr) { + delete _impl_.handle_data_; + } + _impl_.handle_data_ = nullptr; +} +inline const ::tensorflow::core::CppShapeInferenceResult_HandleData& CppShapeInferenceResult::_internal_handle_data() const { + const ::tensorflow::core::CppShapeInferenceResult_HandleData* p = _impl_.handle_data_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::core::_CppShapeInferenceResult_HandleData_default_instance_); +} +inline const ::tensorflow::core::CppShapeInferenceResult_HandleData& CppShapeInferenceResult::handle_data() const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceResult.handle_data) + return _internal_handle_data(); +} +inline void CppShapeInferenceResult::unsafe_arena_set_allocated_handle_data( + ::tensorflow::core::CppShapeInferenceResult_HandleData* handle_data) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.handle_data_); + } + _impl_.handle_data_ = handle_data; + if (handle_data) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.core.CppShapeInferenceResult.handle_data) +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleData* CppShapeInferenceResult::release_handle_data() { + + ::tensorflow::core::CppShapeInferenceResult_HandleData* temp = _impl_.handle_data_; + _impl_.handle_data_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleData* CppShapeInferenceResult::unsafe_arena_release_handle_data() { + // @@protoc_insertion_point(field_release:tensorflow.core.CppShapeInferenceResult.handle_data) + + ::tensorflow::core::CppShapeInferenceResult_HandleData* temp = _impl_.handle_data_; + _impl_.handle_data_ = nullptr; + return temp; +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleData* CppShapeInferenceResult::_internal_mutable_handle_data() { + + if (_impl_.handle_data_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::core::CppShapeInferenceResult_HandleData>(GetArenaForAllocation()); + _impl_.handle_data_ = p; + } + return _impl_.handle_data_; +} +inline ::tensorflow::core::CppShapeInferenceResult_HandleData* CppShapeInferenceResult::mutable_handle_data() { + ::tensorflow::core::CppShapeInferenceResult_HandleData* _msg = _internal_mutable_handle_data(); + // @@protoc_insertion_point(field_mutable:tensorflow.core.CppShapeInferenceResult.handle_data) + return _msg; +} +inline void CppShapeInferenceResult::set_allocated_handle_data(::tensorflow::core::CppShapeInferenceResult_HandleData* handle_data) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.handle_data_; + } + if (handle_data) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(handle_data); + if (message_arena != submessage_arena) { + handle_data = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, handle_data, submessage_arena); + } + + } else { + + } + _impl_.handle_data_ = handle_data; + // @@protoc_insertion_point(field_set_allocated:tensorflow.core.CppShapeInferenceResult.handle_data) +} + +// ------------------------------------------------------------------- + +// CppShapeInferenceInputsNeeded + +// repeated int32 input_tensors_needed = 1; +inline int CppShapeInferenceInputsNeeded::_internal_input_tensors_needed_size() const { + return _impl_.input_tensors_needed_.size(); +} +inline int CppShapeInferenceInputsNeeded::input_tensors_needed_size() const { + return _internal_input_tensors_needed_size(); +} +inline void CppShapeInferenceInputsNeeded::clear_input_tensors_needed() { + _impl_.input_tensors_needed_.Clear(); +} +inline int32_t CppShapeInferenceInputsNeeded::_internal_input_tensors_needed(int index) const { + return _impl_.input_tensors_needed_.Get(index); +} +inline int32_t CppShapeInferenceInputsNeeded::input_tensors_needed(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_needed) + return _internal_input_tensors_needed(index); +} +inline void CppShapeInferenceInputsNeeded::set_input_tensors_needed(int index, int32_t value) { + _impl_.input_tensors_needed_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_needed) +} +inline void CppShapeInferenceInputsNeeded::_internal_add_input_tensors_needed(int32_t value) { + _impl_.input_tensors_needed_.Add(value); +} +inline void CppShapeInferenceInputsNeeded::add_input_tensors_needed(int32_t value) { + _internal_add_input_tensors_needed(value); + // @@protoc_insertion_point(field_add:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_needed) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +CppShapeInferenceInputsNeeded::_internal_input_tensors_needed() const { + return _impl_.input_tensors_needed_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +CppShapeInferenceInputsNeeded::input_tensors_needed() const { + // @@protoc_insertion_point(field_list:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_needed) + return _internal_input_tensors_needed(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +CppShapeInferenceInputsNeeded::_internal_mutable_input_tensors_needed() { + return &_impl_.input_tensors_needed_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +CppShapeInferenceInputsNeeded::mutable_input_tensors_needed() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_needed) + return _internal_mutable_input_tensors_needed(); +} + +// repeated int32 input_tensors_as_shapes_needed = 2; +inline int CppShapeInferenceInputsNeeded::_internal_input_tensors_as_shapes_needed_size() const { + return _impl_.input_tensors_as_shapes_needed_.size(); +} +inline int CppShapeInferenceInputsNeeded::input_tensors_as_shapes_needed_size() const { + return _internal_input_tensors_as_shapes_needed_size(); +} +inline void CppShapeInferenceInputsNeeded::clear_input_tensors_as_shapes_needed() { + _impl_.input_tensors_as_shapes_needed_.Clear(); +} +inline int32_t CppShapeInferenceInputsNeeded::_internal_input_tensors_as_shapes_needed(int index) const { + return _impl_.input_tensors_as_shapes_needed_.Get(index); +} +inline int32_t CppShapeInferenceInputsNeeded::input_tensors_as_shapes_needed(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_as_shapes_needed) + return _internal_input_tensors_as_shapes_needed(index); +} +inline void CppShapeInferenceInputsNeeded::set_input_tensors_as_shapes_needed(int index, int32_t value) { + _impl_.input_tensors_as_shapes_needed_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_as_shapes_needed) +} +inline void CppShapeInferenceInputsNeeded::_internal_add_input_tensors_as_shapes_needed(int32_t value) { + _impl_.input_tensors_as_shapes_needed_.Add(value); +} +inline void CppShapeInferenceInputsNeeded::add_input_tensors_as_shapes_needed(int32_t value) { + _internal_add_input_tensors_as_shapes_needed(value); + // @@protoc_insertion_point(field_add:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_as_shapes_needed) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +CppShapeInferenceInputsNeeded::_internal_input_tensors_as_shapes_needed() const { + return _impl_.input_tensors_as_shapes_needed_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& +CppShapeInferenceInputsNeeded::input_tensors_as_shapes_needed() const { + // @@protoc_insertion_point(field_list:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_as_shapes_needed) + return _internal_input_tensors_as_shapes_needed(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +CppShapeInferenceInputsNeeded::_internal_mutable_input_tensors_as_shapes_needed() { + return &_impl_.input_tensors_as_shapes_needed_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* +CppShapeInferenceInputsNeeded::mutable_input_tensors_as_shapes_needed() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.core.CppShapeInferenceInputsNeeded.input_tensors_as_shapes_needed) + return _internal_mutable_input_tensors_as_shapes_needed(); +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace core +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fcpp_5fshape_5finference_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cpp_shape_inference.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cpp_shape_inference.proto new file mode 100644 index 0000000000000000000000000000000000000000..4cdbf5dd5c80cab7e093669a12a6c0829c2cb83c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/cpp_shape_inference.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package tensorflow.core; + +import "tensorflow/core/framework/full_type.proto"; +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/python/framework/cpp_shape_inference_go_proto"; + +message CppShapeInferenceResult { + message HandleShapeAndType { + reserved 3; + + TensorShapeProto shape = 1; + DataType dtype = 2; + FullTypeDef type = 4; + } + message HandleData { + bool is_set = 1; + + // Only valid if . + repeated HandleShapeAndType shape_and_type = 2; + } + TensorShapeProto shape = 1; + + reserved 2; // was handle_shape + reserved 3; // was handle_dtype + HandleData handle_data = 4; +} + +message CppShapeInferenceInputsNeeded { + repeated int32 input_tensors_needed = 1; + repeated int32 input_tensors_as_shapes_needed = 2; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.h new file mode 100644 index 0000000000000000000000000000000000000000..a174234a86e483ed81412fc258ecc28233f82d4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.h @@ -0,0 +1,1690 @@ +/* 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_FRAMEWORK_DATASET_H_ +#define TENSORFLOW_CORE_FRAMEWORK_DATASET_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/memory/memory.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/attr_value_util.h" +#include "tensorflow/core/framework/cancellation.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/dataset_metadata.pb.h" +#include "tensorflow/core/framework/dataset_options.pb.h" +#include "tensorflow/core/framework/dataset_stateful_op_allowlist.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/function_handle_cache.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/model.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/thread_factory.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/framework/variant_encode_decode.h" +#include "tensorflow/core/framework/variant_tensor_data.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/threadpool.h" +#include "tensorflow/core/lib/core/threadpool_interface.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/cpu_info.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/tracing.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/thread_annotations.h" + +// Polymorphic datasets should support all primitive TensorFlow +// types. Use this macro to expand `m(T)` once for each primitive type +// `T`, e.g. to build a `switch` statement. +#define TF_CALL_DATASET_TYPES(m) TF_CALL_ALL_TYPES(m) TF_CALL_QUANTIZED_TYPES(m) + +namespace tensorflow { + +// Forward declarations to avoid introducing a dependency on headers in +// "tensorflow/core/graph/...". +class GraphDefBuilder; +class Node; + +namespace data { + +namespace internal { +// Merges Options from source to destination. If there is a conflict on a field, +// the field value from the source takes precedence. +void MergeOptions(const protobuf::Message& source, + protobuf::Message* destination); +void MergeOptions(const protobuf::MessageLite& source, + protobuf::MessageLite* destination); +} // namespace internal + +using TraceMeMetadata = std::vector>; + +constexpr char kTFDataFunction[] = "_tf_data_function"; + +constexpr int kInfiniteCardinality = -1; +constexpr int kUnknownCardinality = -2; + +// This constant is a magic number that is used (as a prefix) to identify keys +// used for serialization of iterator state. +constexpr char kFullNameRandomHex[] = "60d899aa0d8ce4351e7c3b419e92d25b"; +constexpr int kFullNameRandomHexLen = std::size(kFullNameRandomHex) - 1; +constexpr char kPipe[] = "|"; +constexpr char kColon[] = ":"; + +constexpr char kTFDataResourceTag[] = "tfdata"; +constexpr char kTraceInfoUnavailable[] = "unavailable"; +constexpr char kMetadata[] = "metadata"; + +constexpr char kCardinalityAttrForRewrite[] = "_cardinality"; + +class DatasetBase; +class IteratorContext; +class SerializationContext; + +inline bool IsTFDataFunction(const FunctionDef& func) { + auto iter = func.attr().find(data::kTFDataFunction); + return (iter != func.attr().end() && iter->second.b()); +} + +// Interface for reading values from a key-value store. +// Used for restoring iterator state. This class is thread safe. +// Please see comment on IteratorStateWriter for guidance around using the +// Read*(key, val) vs Read*(name, key, val). +class IteratorStateReader { + public: + // Determines whether the iterator state contains the given key. + virtual bool Contains(StringPiece key) const = 0; + virtual bool Contains(StringPiece name, StringPiece key) const = 0; + + // Reads an integer for the given key. + virtual Status ReadScalar(StringPiece key, int64_t* val) const = 0; + virtual Status ReadScalar(StringPiece name, StringPiece key, + int64_t* val) const = 0; + + // Reads a string for the given key. + virtual Status ReadScalar(StringPiece key, tstring* val) const = 0; + virtual Status ReadScalar(StringPiece name, StringPiece key, + tstring* val) const = 0; + + // Reads a tensor for the given key. + // TODO(jsimsa): Remove non-FLR overrides once all callers are updated. + virtual Status ReadTensor(StringPiece key, Tensor* val) const = 0; + virtual Status ReadTensor(FunctionLibraryRuntime* flr, StringPiece key, + Tensor* val) const = 0; + virtual Status ReadTensor(StringPiece name, StringPiece key, + Tensor* val) const = 0; + virtual Status ReadTensor(FunctionLibraryRuntime* flr, StringPiece name, + StringPiece key, Tensor* val) const = 0; + + virtual ~IteratorStateReader() {} +}; + +// Interface for writing values to a key-value store. +// Used for saving iterator state. Not thread safe. +// The IteratorStateWriter creates a tensor for each unique iterator name it +// sees. For the Write*(key, val) API's the key is expected to encode this +// name as keys are required to be produced using the full_name() method. +// Each tensor has an upper limit of 2 GB and so if the state for an iterator +// might exceed the 2 GB limit, you can pass an explicit name in via the +// Write*(name, key, val) APIs allowing you to further split up the state +// into more manageable chunks. +class IteratorStateWriter { + public: + // Writes an integer for the given key. + virtual Status WriteScalar(StringPiece key, const int64_t val) = 0; + virtual Status WriteScalar(StringPiece name, StringPiece key, + const int64_t val) = 0; + + // Writes a string for the given key. + virtual Status WriteScalar(StringPiece key, const tstring& val) = 0; + virtual Status WriteScalar(StringPiece name, StringPiece key, + const tstring& val) = 0; + + // Writes a tensor for the given key. + virtual Status WriteTensor(StringPiece key, const Tensor& val) = 0; + virtual Status WriteTensor(StringPiece name, StringPiece key, + const Tensor& val) = 0; + + virtual ~IteratorStateWriter() {} +}; + +// Generates a full name key for iterator checkpointing. All keys generated for +// iterator checkpoints should go through this function. +std::string FullName(const std::string& prefix, const std::string& name); + +// Extracts iterator prefix from key generated by `FullName`. +Status ExtractIteratorPrefix(StringPiece key, string* prefix); + +// Interface for objects that can be checkpointed. +class Checkpointable { + public: + Checkpointable() = default; + virtual ~Checkpointable() = default; + + virtual Status Save(SerializationContext* ctx, + IteratorStateWriter* writer) = 0; + virtual Status Restore(IteratorContext* ctx, IteratorStateReader* reader) = 0; +}; + +// Wrapper around GraphDefBuilder. Used to serialize Dataset graph. +class GraphDefBuilderWrapper { + public: + explicit GraphDefBuilderWrapper(GraphDefBuilder* b) : b_(b) {} + + // Adds a Const node with scalar value to the Graph. + // `*output` contains a pointer to the output `Node`. It is guaranteed to be + // non-null if the method returns with an OK status. + // The returned Node pointer is owned by the backing Graph of GraphDefBuilder. + template + Status AddScalar(const T& val, Node** output) { + Tensor val_t = Tensor(DataTypeToEnum::v(), TensorShape({})); + val_t.scalar()() = val; + AddTensorInternal(val_t, output); + if (*output == nullptr) { + return errors::Internal("AddScalar: Failed to build Const op."); + } + return OkStatus(); + } + + // Adds a Const node with vector value to the Graph. + // `*output` contains a pointer to the output `Node`. It is guaranteed to be + // non-null if the method returns with an OK status. + // The returned Node pointer is owned by the backing Graph of GraphDefBuilder. + // TODO(shivaniagrawal): Consider changing to gtl::ArraySlice? + template + Status AddVector(const std::vector& val, Node** output) { + Tensor val_t = Tensor(DataTypeToEnum::v(), + TensorShape({static_cast(val.size())})); + for (size_t i = 0; i < val.size(); i++) { + val_t.flat()(i) = val[i]; + } + AddTensorInternal(val_t, output); + if (*output == nullptr) { + return errors::Internal("AddVector: Failed to build Const op."); + } + return OkStatus(); + } + + Status AddVector(const std::vector& val, Node** output) { + Tensor val_t = Tensor(DataTypeToEnum::v(), + TensorShape({static_cast(val.size())})); + for (size_t i = 0; i < val.size(); i++) { + val_t.flat()(i) = val[i]; + } + AddTensorInternal(val_t, output); + if (*output == nullptr) { + return errors::Internal("AddVector: Failed to build Const op."); + } + return OkStatus(); + } + + // Adds a `Const` node for the given tensor value to the graph. + // + // `*output` contains a pointer to the output `Node`. It is guaranteed to be + // non-null if the method returns with an OK status. The returned `Node` + // pointer is owned by the backing graph of `GraphDefBuilder`. + Status AddTensor(const Tensor& val, Node** output) { + AddTensorInternal(val, output); + if (*output == nullptr) { + return errors::Internal("AddTensor: Failed to build Const op."); + } + return OkStatus(); + } + + // Adds a `Placeholder` node for the given tensor value to the graph. + // + // `*output` contains a pointer to the output `Node`. It is guaranteed to be + // non-null if the method returns with an OK status. The returned `Node` + // pointer is owned by the backing graph of `GraphDefBuilder`. + Status AddPlaceholder(const Tensor& val, Node** output) { + AddPlaceholderInternal(val, output); + if (*output == nullptr) { + return errors::Internal( + "AddPlaceholder: Failed to build Placeholder op."); + } + return OkStatus(); + } + + // Adds a node for the given dataset to the `Graph`. The value of + // `DatasetBase::type_string()` is used as the op type for the node. Values + // for the `output_types` and `output_shapes` node attributes are also written + // if those attributes are defined in the `OpDef`. + // + // If `use_dataset_name` is set, the value of `DatasetBase::node_name()` is + // used as the op name for the node. This argument should only be set when + // serializing `DatasetBase` instances which might not have been created + // through op kernel execution to make sure the dataset op name is preserved + // across serialization boundaries, which is in turn needed to make sure + // iterator checkpoints are valid across serialization boundaries. When + // `use_dataset_name` is set, the caller is responsible for making sure that + // the op name is unique across the graph. + // + // `*output` contains a pointer to the output `Node`. It is guaranteed to be + // non-null if the method returns with an OK status. The returned `Node` + // pointer is owned by the backing `Graph` of `GraphDefBuilder`. + Status AddDataset(const DatasetBase* dataset, + const std::vector& inputs, Node** output); + Status AddDataset(const DatasetBase* dataset, + const std::vector& inputs, + const std::vector>& attrs, + Node** output); + Status AddDataset( + const DatasetBase* dataset, + const std::vector>& inputs, + const std::vector>>& list_inputs, + const std::vector>& attrs, + Node** output); + Status AddDataset( + const DatasetBase* dataset, + const std::vector>& inputs, + const std::vector>>& list_inputs, + const std::vector>& attrs, + bool use_dataset_name, Node** output); + + // Adds a user-defined function with name `function_name` to the graph and + // recursively adds all functions it references. If a function with a matching + // name has already been added, returns with OK status. If a user-defined with + // name `function_name` is not found in the context's function library, + // returns an InvalidArgumentError. If the function with name `function_name` + // or any of its dependent functions are stateful, and the context does not + // explicitly permit stateful functions, returns an InvalidArgument error. + Status AddFunction(SerializationContext* ctx, const string& function_name, + const FunctionLibraryDefinition& lib_def); + + template + void BuildAttrValue(const T& value, AttrValue* attr) { + SetAttrValue(value, attr); + } + + template + AttrValue BuildAttrValue(const T& value) { + AttrValue attr; + SetAttrValue(value, &attr); + return attr; + } + + protected: + GraphDefBuilder* builder() { return b_; } + + private: + void AddPlaceholderInternal(const Tensor& val, Node** output); + void AddTensorInternal(const Tensor& val, Node** output); + bool HasAttr(const string& op_type_name, const string& attr_name) const; + + bool HasAttr(const OpDef* op_def, const string& attr_name) const { + for (const auto& attr : op_def->attr()) { + if (attr.name() == attr_name) { + return true; + } + } + return false; + } + + Status AddAttrFunctions(SerializationContext* ctx, + const AttrValue& attr_value, + const FunctionLibraryDefinition& lib_def) { + if (attr_value.has_func()) { + TF_RETURN_IF_ERROR(AddFunction(ctx, attr_value.func().name(), lib_def)); + } else if (attr_value.has_list()) { + for (const NameAttrList& name_attr_list : attr_value.list().func()) { + TF_RETURN_IF_ERROR(AddFunction(ctx, name_attr_list.name(), lib_def)); + } + } + return OkStatus(); + } + + GraphDefBuilder* b_; +}; + +class StatsAggregator; + +// A utility class for running a function and ensuring that there is always a +// `tensorflow::data` symbol on the stack. +class Runner { + public: + virtual ~Runner() {} + + // Runs the given function. + virtual void Run(const std::function& f) = 0; + + // Returns a global singleton Runner. + static Runner* get(); +}; + +// A class which provides a sequence of splits. Splits represent subdivisions of +// a dataset, e.g. filenames or ranges within files. We use splitting to +// partition input data into smaller pieces for distributed processing (see +// go/tf-data-splitting-design). +// +// Datasets provide a `MakeSplitProvider` method to expose a listing of their +// splits. +// +// Iterators created with a split provider will only iterate over the splits +// provided by the split provider. +class SplitProvider { + public: + virtual ~SplitProvider() {} + // Stores the next split in `*split`, setting `*end_of_splits` to indicate + // whether there were any splits left. + virtual Status GetNext(Tensor* split, bool* end_of_splits) = 0; + // Resets the split provider to its beginning. + virtual Status Reset() = 0; + // Saves the state of this split provider. + virtual Status Save(std::function full_name, + IteratorStateWriter* writer) = 0; + // Restores the state of this split provider. + virtual Status Restore(std::function full_name, + IteratorStateReader* reader) = 0; +}; + +// Returns the runner threadpool size from an OpKernelContext. +int32_t GetRunnerThreadpoolSizeFromOpKernelContext(OpKernelContext* ctx); + +// In-memory representation of a checkpoint. The checkpoint is represented as a +// collection of key-value pairs and are expected to be written using the +// `IteratorStateWriter` interface. +// +// The implementation is not thread-safe. +class MemoryCheckpoint : public IteratorStateWriter { + public: + // IdRegistry maintains a bi-directional mapping between string and integer + // representations of checkpoint keys. + // + // The reason we need both is that integer ids are used for fast lookups and + // comparisons, while string ids are used for prefix matching. + class IdRegistry { + public: + IdRegistry() = default; + + // Adds the given string id to the registry, generating a unique integer id + // for it. If the string id already exists, its integer id is returned. + int64_t Add(const std::string& prefix, const std::string& key); + + // Gets all integer ids for string ids matching the given prefix. + std::vector GetMatchingIds(const std::string& prefix_to_match); + + // Gets the string id for the given integer id. + std::pair Get(int64_t id); + + // Removes the entries matching the given integer ids from the registry. + void RemoveIds(const std::vector& ids); + + private: + mutex mu_; + int64_t next_id_ TF_GUARDED_BY(mu_) = 0; + absl::flat_hash_map> + int_to_string_ TF_GUARDED_BY(mu_); + absl::flat_hash_map, int64_t> + string_to_int_ TF_GUARDED_BY(mu_); + }; + + MemoryCheckpoint() = delete; + explicit MemoryCheckpoint(std::shared_ptr registry) + : id_registry_(registry) {} + + MemoryCheckpoint(MemoryCheckpoint&& other) = default; + + static MemoryCheckpoint CreateRootCheckpoint( + std::shared_ptr registry) { + return MemoryCheckpoint(/*id_registry*/ registry, /*is_root=*/true); + } + + // BEGIN implementation of `IteratorStateWriter` interface + Status WriteScalar(StringPiece key, int64_t val) override { + string prefix; + TF_RETURN_IF_ERROR(ExtractIteratorPrefix(key, &prefix)); + return WriteScalar(prefix, key, val); + } + Status WriteScalar(StringPiece name, StringPiece key, int64_t val) override { + auto id = id_registry_->Add(string(name), string(key)); + int_values_[id] = val; + return OkStatus(); + } + Status WriteScalar(StringPiece key, const tstring& val) override { + string prefix; + TF_RETURN_IF_ERROR(ExtractIteratorPrefix(key, &prefix)); + return WriteScalar(prefix, key, val); + } + Status WriteScalar(StringPiece name, StringPiece key, + const tstring& val) override { + auto id = id_registry_->Add(string(name), string(key)); + str_values_[id] = val; + return OkStatus(); + } + Status WriteTensor(StringPiece key, const Tensor& val) override { + string prefix; + TF_RETURN_IF_ERROR(ExtractIteratorPrefix(key, &prefix)); + return WriteTensor(prefix, key, val); + } + Status WriteTensor(StringPiece name, StringPiece key, + const Tensor& val) override { + auto id = id_registry_->Add(string(name), string(key)); + tensor_values_[id] = val; + return OkStatus(); + } + // END implementation of `IteratorStateWriter` interface + + // String representation for the in-memory checkpoint suitable for debugging. + std::string DebugString() const; + + // Returns the status of the in-memory checkpoint. + Status GetStatus() const { return status_; } + + // Merges state of another checkpoint into this checkpoint, overwriting + // existing state (if applicable). + // + // Merge also garbage collects state that is no longer needed. + void Merge(MemoryCheckpoint* other); + + // Purge removes all keys with given prefix from checkpoint. It also adds the + // prefix for tracking unless it is the root checkpoint. + void Purge(const std::string& prefix); + + // Stores the in-memory checkpoint to the given writer. + Status Save(IteratorStateWriter* writer) const; + + // Updates the status of the in-memory checkpoint with the given status. + void UpdateStatus(Status status) { status_.Update(status); } + + private: + explicit MemoryCheckpoint(std::shared_ptr registry, bool is_root) + : is_root_(is_root), id_registry_(registry) {} + MemoryCheckpoint(const MemoryCheckpoint&) = delete; + void operator=(const MemoryCheckpoint&) = delete; + + Status status_ = OkStatus(); + // Only set to true for the checkpoint in IteratorResource. + // Root checkpoint does not track expired prefixes. + const bool is_root_ = false; + absl::flat_hash_map int_values_; + absl::flat_hash_map str_values_; + absl::flat_hash_map tensor_values_; + + // Keeps track of expired prefixes for propagation. Cleaned after it's merged. + absl::flat_hash_set expired_prefixes_; + + std::shared_ptr id_registry_; +}; + +// Aggregates runtime support needed for dataset and iterator serialization. +class SerializationContext { + public: + // Handles the external state according to the external state policy. + Status HandleCheckExternalStateStatus(Status s) { + if (s.ok()) { + return s; + } + switch (params_.external_state_policy) { + case ExternalStatePolicy::POLICY_WARN: + LOG(WARNING) << s.ToString(); + return OkStatus(); + case ExternalStatePolicy::POLICY_IGNORE: + VLOG(2) << "Ignoring error status: " << s.ToString(); + return OkStatus(); + case ExternalStatePolicy::POLICY_FAIL: + return s; + default: + return errors::InvalidArgument("Unexpected value of external policy: ", + params_.external_state_policy); + } + } + + struct Params { + explicit Params() = default; + + explicit Params(OpKernelContext* ctx) + : resource_mgr(ctx->resource_manager()), + device_name(ctx->device()->attributes().name()) {} + + std::vector>* input_list = nullptr; // Not owned. + + // Indicates what to do if the dataset depends on external state. + ExternalStatePolicy external_state_policy = + ExternalStatePolicy::POLICY_WARN; + + // Indicates whether the serialization is for rewrites. + // + // If true: + // * A dataset that doesn't implement serialization is replaced with a + // placeholder returned in `input_list`. + // * Data tensors are replaced with a placeholder returned in + // `input_list`. + // * Datasets that use random seeds should not serialize the random seeds. + // This doesn't affect datasets that use fixed seeds; fixed seeds will + // always be preserved. + // * Cardinality is serialized as an unregistered attribute + // `_cardinality`. + // If false: + // * A dataset that doesn't implement serialization should result in an + // error. + // * Data tensors (potentially large) should be serialized. + // * Datasets that use random seeds should serialize the random seeds. + bool is_graph_rewrite = false; + + // A resource manager for looking up resources during serialization. + ResourceMgr* resource_mgr; + + // The name of the device doing the serialization. + std::string device_name; + + // Determines whether checkpointing should represent input pipeline state + // symbolically, using cursors into source iterators, or explicitly, by + // storing internal state of each iterator. + bool symbolic_checkpoint = false; + }; + + explicit SerializationContext(Params params) : params_(params) {} + + std::vector>* input_list() { + return params_.input_list; + } + + ExternalStatePolicy external_state_policy() const { + return params_.external_state_policy; + } + + bool is_graph_rewrite() const { return params_.is_graph_rewrite; } + + const ResourceMgr* resource_mgr() const { return params_.resource_mgr; } + + const std::string& device_name() const { return params_.device_name; } + + bool symbolic_checkpoint() const { return params_.symbolic_checkpoint; } + + private: + Params params_; + + SerializationContext(const SerializationContext&) = delete; + void operator=(const SerializationContext&) = delete; +}; + +// Specifies the tf.data pipeline run mode. +enum RunMode { DEFAULT, STANDALONE }; + +// A cut-down version of `OpKernelContext` for running computations in +// iterators. Note that we cannot simply use `OpKernelContext` here because we +// might run computation in an iterator whose lifetime is not nested within the +// lifetime of a single `OpKernelContext` (e.g. asynchronous prefetching). +// +// TODO(mrry): We're making some daring assumptions about the lifetime of the +// runner passed in here. A runner will be deleted when the original step ends, +// but all existing runners only close over session-lifetime (or longer-lived) +// state, so we can make a copy of the function. There's nothing in the +// definition of the API from which we took the runner to guarantee that what we +// are doing is safe. We should formalize the properties here. +class IteratorContext { + public: + struct Params { + explicit Params(IteratorContext* ctx) + : allocator_getter(ctx->allocator_getter()), + cancellation_manager(ctx->cancellation_manager()), + collective_executor(ctx->collective_executor()), + env(ctx->env()), + flr(ctx->flr()), + function_handle_cache(ctx->function_handle_cache()), + interleave_depth(ctx->interleave_depth()), + is_restoring(ctx->is_restoring()), + model(ctx->model()), + ram_budget_manager(ctx->ram_budget_manager()), + resource_mgr(ctx->resource_mgr()), + runner(*(ctx->runner())), + runner_threadpool_size(ctx->runner_threadpool_size()), + split_providers(ctx->split_providers()), + stats_aggregator(ctx->stats_aggregator()), + symbolic_checkpoint(ctx->symbolic_checkpoint()), + thread_factory(ctx->thread_factory()), + thread_pool(ctx->thread_pool()), + id_registry(ctx->id_registry()), + warm_start(ctx->warm_start()) {} + + explicit Params(OpKernelContext* ctx) + : collective_executor(ctx->collective_executor()), + env(ctx->env()), + flr(ctx->function_library()) { + // NOTE: need reinterpret_cast because function.h forward-declares Device. + DeviceBase* device = + reinterpret_cast(ctx->function_library()->device()); + allocator_getter = [device](AllocatorAttributes attrs) { + return device->GetAllocator(attrs); + }; + + runner_threadpool_size = GetRunnerThreadpoolSizeFromOpKernelContext(ctx); + + // NOTE: Wrap every runner invocation in a call to Runner()->Run(), so + // that a symbol in the tensorflow::data namespace is always on the stack + // when executing a function inside a Dataset. + runner = std::bind( + []( + // Note: `runner` is a const reference to avoid copying it. + const std::function)>& ctx_runner, + std::function fn) { + std::function wrapped_fn = std::bind( + [](const std::function& fn) { Runner::get()->Run(fn); }, + std::move(fn)); + ctx_runner(std::move(wrapped_fn)); + }, + *ctx->runner(), std::placeholders::_1); + } + + // The Allocator to be used to allocate the output of an iterator. + std::function allocator_getter = nullptr; + + // The CancellationManager to be used to cancel execution of ops. + CancellationManager* cancellation_manager = nullptr; + + // Collective support. + CollectiveExecutor* collective_executor = nullptr; + + // Interface to operating system functionality. + Env* env = nullptr; + + // The FunctionLibraryRuntime object to be used to make function calls. + FunctionLibraryRuntime* flr = nullptr; + + // A FunctionHandleCache that owns all the function handles. Not owned. + FunctionHandleCache* function_handle_cache = nullptr; + + // Records the number of ParallelInterleave operations in the path from the + // root node to this node (not including this node) in the input pipeline + // tree. + int64 interleave_depth = 0; + + // Marks whether the iterator is restored from a checkpoint. + bool is_restoring = false; + + // If non-null, identifies the object used for performance modeling. + std::shared_ptr model = nullptr; + + // Manager for the ram budget when using autotune. + std::shared_ptr ram_budget_manager = nullptr; + + // The input pipeline options. + const Options* options = nullptr; + + // A resource manager for storing dataset-related state, e.g. random + // seeds or cached tensors. Not owned. + ResourceMgr* resource_mgr = nullptr; + + // Function call support. + std::function)> runner = nullptr; + + // Number of threads used for executing user-defined functions. + int32 runner_threadpool_size = 0; + + // Split providers indicating which splits to process. May be empty, + // indicating that the iterator should process all splits. + std::vector> split_providers; + + // The `StatsAggregator` object to record statistics about the iterator. + // + // TODO(b/147325552): Remove this API and any of its uses after we switch to + // using C++ based implementation for tf.data options (on 4/12/2021). + std::shared_ptr stats_aggregator = nullptr; + + // Indicates whether to use symbolic checkpointing. + bool symbolic_checkpoint = false; + + // A factory for creating threads to perform blocking work. + std::shared_ptr thread_factory = nullptr; + + // A shared thread pool to schedule computation into. + thread::ThreadPoolInterface* thread_pool = nullptr; + + std::shared_ptr id_registry = + std::make_shared(); + + // If `true` background threads of asynchronous operations are started when + // the iterator is created. Otherwise, they are started upon first `GetNext` + // request. Default value is set to false to ensure backward compatibility. + bool warm_start = false; + + // Specifies the tf.data pipeline run mode. + RunMode run_mode = RunMode::DEFAULT; + }; + + explicit IteratorContext(IteratorContext* ctx) + : IteratorContext(Params{ctx}) {} + + explicit IteratorContext(OpKernelContext* ctx) + : IteratorContext(Params{ctx}) {} + + explicit IteratorContext(Params params) + : params_(std::move(params)), + checkpoint_(MemoryCheckpoint{params_.id_registry}) {} + + IteratorContext(const IteratorContext& other) + : IteratorContext(Params{other.params_}) { + // MemoryCheckpoint should not be copied over as the child context should + // not care what's in the checkpoint of parent context. + } + + std::shared_ptr id_registry() { + return params_.id_registry; + } + + Allocator* allocator(AllocatorAttributes attrs) { + return params_.allocator_getter(attrs); + } + + std::function allocator_getter() { + return params_.allocator_getter; + } + + CancellationManager* cancellation_manager() { + return params_.cancellation_manager; + } + + CollectiveExecutor* collective_executor() { + return params_.collective_executor; + } + + Env* env() const { return params_.env; } + + FunctionLibraryRuntime* flr() { return params_.flr; } + + FunctionHandleCache* function_handle_cache() { + return params_.function_handle_cache; + } + + MemoryCheckpoint* checkpoint() { return &checkpoint_; } + + int64 interleave_depth() { return params_.interleave_depth; } + + bool is_restoring() { return params_.is_restoring; } + + const std::shared_ptr& model() const { return params_.model; } + + const std::shared_ptr& ram_budget_manager() { + return params_.ram_budget_manager; + } + + ResourceMgr* resource_mgr() { return params_.resource_mgr; } + + std::function)>* runner() { + return ¶ms_.runner; + } + + int32 runner_threadpool_size() { return params_.runner_threadpool_size; } + + std::vector> split_providers() const { + return params_.split_providers; + } + + std::shared_ptr stats_aggregator() { + return params_.stats_aggregator; + } + + bool symbolic_checkpoint() { return params_.symbolic_checkpoint; } + + const std::shared_ptr& thread_factory() { + return params_.thread_factory; + } + + thread::ThreadPoolInterface* thread_pool() { return params_.thread_pool; } + + bool warm_start() { return params_.warm_start; } + + RunMode run_mode() { return params_.run_mode; } + + std::unique_ptr CreateThreadPool(const string& name, + int num_threads) { + if (params_.thread_pool) { + // Create a `ThreadPool` instance by wrapping `params_.thread_pool` (which + // is an instance of `thread::ThreadPoolInterface`). Notably, the + // ownership of `params_.thread_pool` is *not* transferred onto the newly + // created `ThreadPool` instance. + return absl::make_unique(params_.thread_pool); + } else { + return absl::make_unique(params_.env, ThreadOptions(), + name, num_threads, + /*low_latency_hint=*/false); + } + } + + // Merges the given checkpoint with the checkpoint of this context. + // + // The intended for this API is that methods, such as + // `IteratorBase::Initialize`, `IteratorBase::GetNextInternal`, or + // `IteratorBase::RestoreInternal` that store data in the in-memory + // checkpoint, use a separate instance of `IteratorContext` for a nested call, + // then the checkpoint collected by the `IteratorContext` instance passed into + // the callee should be merged into the `IteratorContext` of the caller: + // + // ``` + // Status GetNextInternal(IteratorContext* ctx, ...) { + // ... + // IteratorContext nested_ctx(...); + // TF_RETURN_IF_ERROR(input_impl_->GetNext(&nested_ctx, ...)); + // ctx->MergeCheckpoint(nested_ctx->checkpoint()); + // ... + // } + // ``` + void MergeCheckpoint(MemoryCheckpoint* checkpoint) { + if (symbolic_checkpoint()) { + checkpoint_.Merge(checkpoint); + } + } + + // Removes any keys with the given prefix from the checkpoint. + // + // The intended use for this API is to clean the stale state in checkpoint, + // e.g. when a pipeline created by `flat_map` is exhausted, the state + // associated with the iterator of that pipeline is no longer needed and + // should be removed. + void PurgeCheckpoint(const std::string& prefix) { + if (symbolic_checkpoint()) { + checkpoint_.Purge(prefix); + } + } + + // Saves the state of the given iterator into the checkpoint. + void SaveCheckpoint(Checkpointable* iterator) { + if (symbolic_checkpoint()) { + SerializationContext::Params params; + params.symbolic_checkpoint = true; + SerializationContext ctx(std::move(params)); + checkpoint_.UpdateStatus(iterator->Save(&ctx, &checkpoint_)); + } + } + + std::unique_ptr StartThread(const string& name, + std::function fn) { + if (params_.thread_factory) { + return params_.thread_factory->StartThread(name, std::move(fn)); + } else { + return absl::WrapUnique( + Env::Default()->StartThread({}, name, std::move(fn))); + } + } + + // Updates the status of the checkpoint with the given status. + void UpdateCheckpointStatus(std::function status_fn) { + if (symbolic_checkpoint()) { + checkpoint_.UpdateStatus(status_fn()); + } + } + + private: + Params params_; + MemoryCheckpoint checkpoint_; +}; + +// Represents the current position in a range of outputs, where the +// range of outputs is typically represented by an `DatasetBase`, +// defined below. +class IteratorBase : public Checkpointable { + public: + virtual ~IteratorBase() { + for (auto rit = cleanup_fns_.rbegin(); rit != cleanup_fns_.rend(); ++rit) { + (*rit)(); + } + } + + // Gets the next output from the range that this iterator is traversing. + // + // If at least one output remains in this iterator's range, that + // output will be stored in `*out_tensors` and `false` will be + // stored in `*end_of_sequence`. + // + // If no more outputs remain in this iterator's range, `true` will be stored + // in `*end_of_sequence`, and `*out_tensors` will be empty. + // + // Implementations should never return `OutOfRange` error. If at end of + // sequence, set `*end_of_sequence = true` and return `OkStatus()`. + // Internally raised `OutOfRange` errors that do not imply end of sequence + // should be converted to a different error type before being propagated to + // the caller. + // + // Implementations must explicitly set `*end_of_sequence = false` if an + // `OkStatus()` status is returned and the iterator is not at the end of the + // sequence. + // + // `out_tensors` and `end_of_sequence` are output parameters. `*out_tensors` + // and `*end_of_sequence` should not be read by implementations of `GetNext` + // before they are assigned. + // + // This method is thread-safe. + // + // TODO(mrry): Define `GetNextAsync()` or `GetNextManyAsync()`, and + // potentially remove this method. + virtual Status GetNext(IteratorContext* ctx, std::vector* out_tensors, + bool* end_of_sequence) = 0; + + Status GetNext(IteratorContext&& ctx, std::vector* out_tensors, + bool* end_of_sequence) { + return GetNext(&ctx, out_tensors, end_of_sequence); + } + + // Skips the next `num_to_skip` outputs from the range that this iterator + // is traversing. + // + // If there are not enough outputs to skip, it will set + // `*end_of_sequence = true` and return `OkStatus()`. `*num_skipped` will + // store the number of outputs that are skipped. When `*end_of_sequence` is + // `false`, `*num_skipped` should equal to `num_to_skip`. + virtual Status Skip(IteratorContext* ctx, int num_to_skip, + bool* end_of_sequence, int* num_skipped) = 0; + + virtual Status Skip(IteratorContext&& ctx, int num_to_skip, + bool* end_of_sequence, int* num_skipped) { + return Skip(&ctx, num_to_skip, end_of_sequence, num_skipped); + } + + // Returns a vector of DataType values, representing the respective + // element types of each tuple component in the outputs of this + // iterator. + virtual const DataTypeVector& output_dtypes() const = 0; + + // Returns a vector of tensor shapes, representing the respective + // (and possibly partially defined) shapes of each tuple component + // in the outputs of this iterator. + virtual const std::vector& output_shapes() const = 0; + + // Returns a string that identifies the sequence of iterators leading up to + // this iterator. + virtual const string& prefix() const = 0; + + // Indicates whether the iterator is compatible with symbolic checkpointing. + virtual bool SymbolicCheckpointCompatible() const { return false; } + + // Performs initialization that needs to happen outside of a constructor to + // properly propagate errors. + virtual Status Initialize(IteratorContext* ctx) { return OkStatus(); } + + // Performs initialization of the base iterator. + Status InitializeBase(IteratorContext* ctx, const IteratorBase* parent); + + // Saves the state of this iterator. + Status Save(SerializationContext* ctx, IteratorStateWriter* writer) override { + int64_t start_us = EnvTime::NowMicros(); + TF_RETURN_IF_ERROR(SaveInternal(ctx, writer)); + VLOG(1) << "Saved " << prefix() << " in " + << (EnvTime::NowMicros() - start_us) << "us"; + return OkStatus(); + } + + // Restores the state of this iterator. + Status Restore(IteratorContext* ctx, IteratorStateReader* reader) override { + int64_t start_us = EnvTime::NowMicros(); + TF_RETURN_IF_ERROR(RestoreInternal(ctx, reader)); + ctx->SaveCheckpoint(this); + VLOG(1) << "Restored " << prefix() << " in " + << (EnvTime::NowMicros() - start_us) << "us"; + return OkStatus(); + } + + // Returns the total number of bytes buffered by the iterator across all nodes + // in the subtree for which autotuning is enabled. + int64_t TotalBufferedBytes() const { + if (node_) return node_->TotalBufferedBytes(); + return 0; + } + + protected: + // Returns a node that models this iterator. + virtual std::shared_ptr CreateNode( + IteratorContext* ctx, model::Node::Args args) const = 0; + + // This is needed so that sub-classes of IteratorBase can call + // `SaveInternal` on their input iterators. + Status SaveInput(SerializationContext* ctx, IteratorStateWriter* writer, + const std::unique_ptr& input) { + if (ctx->symbolic_checkpoint()) { + return OkStatus(); + } + return input->Save(ctx, writer); + } + + // This is needed so that sub-classes of IteratorBase can call + // `RestoreInternal` on their input iterators. + Status RestoreInput(IteratorContext* ctx, IteratorStateReader* reader, + const std::unique_ptr& input) { + return input->Restore(ctx, reader); + } + + Status RestoreInput(IteratorContext&& ctx, IteratorStateReader* reader, + const std::unique_ptr& input) { + return RestoreInput(&ctx, reader, input); + } + + // Saves the state of this iterator. + // + // This method is used to store the state of the iterator in a checkpoint. + // implementations have an override. + virtual Status SaveInternal(SerializationContext* ctx, + IteratorStateWriter* writer) = 0; + + // Restores the state of this iterator. + // + // This method is used to restore the state of the iterator from a checkpoint. + // + // Implementations may assume that the iterator is in a clean state. That is, + // its `Initialize` method has been called, but its `GetNext` method has + // never been called. + // implementations have an override. + virtual Status RestoreInternal(IteratorContext* ctx, + IteratorStateReader* reader) = 0; + + // Returns a pointer to the node representing this iterator in the performance + // model. It may be null, if performance modeling is not enabled for this + // iterator. + std::shared_ptr model_node() const { return node_; } + + // Returns the number of elements produced by this iterator. + int64_t num_elements() const { + if (node_) return node_->num_elements(); + return 0; + } + + private: + // For access to `AddCleanupFunction` and `Restore`. + friend class DatasetBase; + friend class DatasetBaseIterator; // for access to `node_` + + std::vector> cleanup_fns_; + std::shared_ptr node_ = nullptr; + const IteratorBase* parent_ = nullptr; // Not owned. + uint64_t id_ = 0; + uint64_t parent_id_ = 0; +}; + +// Represents runtime information needed to construct a dataset. +class DatasetContext { + public: + struct Params { + string type_string; // op type name of this dataset. + string node_name; // graph node name of this dataset op, uniquely + // identifying the dataset in the graph. + }; + + explicit DatasetContext(Params params) : params_(std::move(params)) {} + + explicit DatasetContext(OpKernelContext* ctx) { + params_.type_string = ctx->op_kernel().type_string(); + params_.node_name = ctx->op_kernel().name(); + } + + const string& type_string() const { return params_.type_string; } + const string& node_name() const { return params_.node_name; } + + private: + Params params_; +}; + +// Returns the number of bytes allocated for the given tensor. +int64_t GetAllocatedBytes(const std::vector& element); + +// Returns the estimated memory usage in bytes of the given tensor. +int64_t GetTotalBytes(const std::vector& element); + +// Validates and extracts a `DatasetBase` object from `tensor`. +// +// `tensor` must have been written by a call to SetVariantTensorToDataset(). +// +// The retrieved pointer is a borrowed reference to the dataset, which is owned +// by the tensor. The consumer must either acquire its own reference to the +// dataset by calling `(*out_dataset)->Ref()`, or ensure that `tensor` is not +// destroyed or mutated while the retrieved pointer is in use. +Status GetDatasetFromVariantTensor(const Tensor& tensor, + DatasetBase** out_dataset); + +// Stores a `DatasetBase` object in `tensor`. +// +// The ownership of `dataset` is transferred to `tensor`. +Status StoreDatasetInVariantTensor(DatasetBase* dataset, Tensor* tensor); + +// Represents a (potentially infinite) range of outputs, where each +// output is a tuple of tensors. +class DatasetBase : public core::RefCounted { + public: + // Key for storing the Dataset graph in the serialized format. + TF_EXPORT static const char kDatasetGraphKey[]; + + // Key for storing the output node of the Dataset graph in the serialized + // format. + TF_EXPORT static const char kDatasetGraphOutputNodeKey[]; + + explicit DatasetBase(DatasetContext&& ctx) + : type_string_(ctx.type_string()), node_name_(ctx.node_name()) {} + + // Op type name of this dataset. + const string& type_string() const { return type_string_; } + + // Graph node name of this dataset op, uniquely identifying the dataset in + // the graph. + const string& node_name() const { return node_name_; } + + const Metadata& metadata() const { return metadata_; } + + const Options& options() const { return options_; } + + int64_t num_sources() const { return num_sources_; } + + // Initializes the dataset using the given metadata. + void Initialize(const Metadata& metadata); + + // Returns a new iterator for iterating over the range of elements in + // this dataset. + // + // This method may be called multiple times on the same instance, + // and the resulting iterators will have distinct state. Each + // iterator will traverse all elements in this dataset from the + // start. + // + // The prefix identifies the sequence of iterators leading up to the newly + // created iterator. + Status MakeIterator(IteratorContext* ctx, const IteratorBase* parent, + const string& output_prefix, + std::unique_ptr* iterator) const; + + Status MakeIterator(IteratorContext&& ctx, const IteratorBase* parent, + const string& output_prefix, + std::unique_ptr* iterator) const { + return MakeIterator(&ctx, parent, output_prefix, iterator); + } + + // Returns a new iterator restored from the checkpoint data in `reader`. + Status MakeIteratorFromCheckpoint( + IteratorContext* ctx, const string& output_prefix, + IteratorStateReader* reader, + std::unique_ptr* iterator) const { + std::unique_ptr it; + IteratorContext::Params params(ctx); + params.is_restoring = true; + IteratorContext restore_ctx(std::move(params)); + TF_RETURN_IF_ERROR(MakeIterator(&restore_ctx, + /*parent=*/nullptr, output_prefix, &it)); + TF_RETURN_IF_ERROR(it->Restore(&restore_ctx, reader)); + ctx->MergeCheckpoint(restore_ctx.checkpoint()); + *iterator = std::move(it); + return OkStatus(); + } + + Status MakeIteratorFromCheckpoint( + IteratorContext&& ctx, const string& output_prefix, + IteratorStateReader* reader, + std::unique_ptr* iterator) const { + return MakeIteratorFromCheckpoint(&ctx, output_prefix, reader, iterator); + } + + // Returns a split provider which partitions the dataset's data into splits + // and provides them in a sequence. The split provider is stored in + // `*split_provider`. + virtual Status MakeSplitProviders( + std::vector>* split_providers) const; + + // Returns a vector of DataType values, representing the respective + // element types of each tuple component in the outputs of this + // dataset. + virtual const DataTypeVector& output_dtypes() const = 0; + + // Returns a vector of tensor shapes, representing the respective + // (and possibly partially defined) shapes of each tuple component + // in the outputs of this dataset. + virtual const std::vector& output_shapes() const = 0; + + // Returns the number of bytes allocated for tensors of this dataset. + virtual int64_t AllocatedBytes() const { return 0; } + + // Returns the estimated number of bytes used for tensors of this dataset. + virtual int64_t TotalBytes() const { return 0; } + + // Returns the cardinality of this dataset. + // TODO(shilpakrish): Remove this overload once all callers are migrated + // to the API which passes in the options parameter. + ABSL_DEPRECATED("Use the overload that passes in the options parameter.") + int64_t Cardinality() const; + + // Returns the cardinality of this dataset based on the options. + int64_t Cardinality(CardinalityOptions options) const; + + // Internal implementation of cardinality for a dataset based on the options. + virtual int64_t CardinalityInternal(CardinalityOptions options) const + TF_EXCLUSIVE_LOCKS_REQUIRED(cardinality_mu_) { + return kUnknownCardinality; + } + + // A human-readable debug string for this dataset. + virtual string DebugString() const = 0; + + // Stores the dataset's input datasets in `*inputs`. The pointers stored in + // `*inputs` are borrowed. The only valid non-ok return status is + // UNIMPLEMENTED in case `InputDatasets` is not implemented by a dataset + // subclass. Implementing `InputDatasets` enables `DatasetBase` to provide a + // default implementation of `MakeSplitProvider` when there is a single input + // dataset. + virtual Status InputDatasets(std::vector* inputs) const; + + // Indicates whether the dataset depends on any external state which would + // prevent it from being serializable. If so, the method returns + // `errors::FailedPrecondition` with a message that identifies the external + // state. Otherwise, the method returns `OkStatus()`. + virtual Status CheckExternalState() const = 0; + + // Indicates whether the dataset is compatible with random access. + Status CheckRandomAccessCompatible(const int64 index) const; + + // Return the element at a particular index for a randomly accessible dataset. + virtual Status Get(OpKernelContext* ctx, int64 index, + std::vector* out_tensors) const; + + // Return a finalized version of the dataset. The returned DatasetBase is + // unowned and lives for as long as this dataset. + virtual StatusOr Finalize( + OpKernelContext* ctx, + std::function>()> + make_finalized_dataset) const; + + // Wrapper around a GraphDefBuilder which provides support for serializing + // Datasets as GraphDefs. + class DatasetGraphDefBuilder : public GraphDefBuilderWrapper { + public: + explicit DatasetGraphDefBuilder(GraphDefBuilder* b) + : GraphDefBuilderWrapper(b) {} + Status AddInputDataset(SerializationContext* ctx, + const DatasetBase* dataset, Node** output); + Status AddDatasetOrTensor(SerializationContext* ctx, const Tensor& val, + Node** output); + Status AddIdentity(SerializationContext* ctx, + const std::string& name_prefix, Node** input, + Node** output); + + private: + Status AddDatasetOrTensorHelper(SerializationContext* ctx, + const Tensor& val, Node** output); + Status AddResourceHelper(SerializationContext* ctx, const Tensor& val, + Node** output); + }; + + protected: + friend class CapturedFunction; + + // Serializes the dataset into a `GraphDef`, which has two uses: + // + // 1) To perform static input pipeline optimizations, tf.data serializes the + // dataset graph, applies graph rewrites, and then deserializes the graph. + // If a subclass of `DatasetBase` does not implement this method, then it will + // be excluded from static optimizations (and so will any upstream datasets). + // + // 2) To save the dataset so that it can restore at a later point (possibly in + // different environment). If a subclass of `DatasetBase` does not implement + // this method, then this migration will not be possible. + virtual Status AsGraphDefInternal(SerializationContext* ctx, + DatasetGraphDefBuilder* b, + Node** node) const = 0; + + virtual std::unique_ptr MakeIteratorInternal( + const string& prefix) const = 0; + + void set_options(const Options& options) { options_ = options; } + + private: + // Computes and stores the cardinality of a given dataset. + Status ComputeCardinality(); + + // Computes the number of source datasets feeding into this dataset. A source + // dataset is a leaf in the subtree of dataset inputs. + Status ComputeNumSources(); + + // Merges options from inputs to this dataset. If there is a conflict in a + // field value, the options set on this dataset takes precedence over those in + // the inputs. The order of precedence on the inputs is in the same order as + // how they appear for this dataset. + Status MergeOptionsFromInputs(); + + const string type_string_; + const string node_name_; + Metadata metadata_; + Options options_; + mutable mutex mu_; + mutable mutex cardinality_mu_; + mutable core::RefCountPtr finalized_dataset_; + // The number of source datasets feeding into the dataset. A source dataset + // is a leaf in the subtree of dataset inputs. + int64_t num_sources_ = -1; + mutable int64_t cardinality_ TF_GUARDED_BY(cardinality_mu_) = + kUnknownCardinality; +}; + +// Represents an iterator that is associated with a particular dataset. +class DatasetBaseIterator : public IteratorBase { + public: + struct BaseParams { + // Owns one reference on the shared dataset object. + const DatasetBase* dataset; + + // Identifies the sequence of iterators leading up to this iterator. + const string prefix; + }; + + explicit DatasetBaseIterator(const BaseParams& params); + + ~DatasetBaseIterator() override; + + virtual const DatasetBase* dataset() const { return params_.dataset; } + + const DataTypeVector& output_dtypes() const override { + return params_.dataset->output_dtypes(); + } + + const std::vector& output_shapes() const override { + return params_.dataset->output_shapes(); + } + + const string& prefix() const override { return params_.prefix; } + + // Returns a name to be used for the TraceMe event. + // + // NOTE: TraceMe supports passing key-value pairs of "arguments" using the + // following format "name#arg_1=value_,...,arg_n=value_n". + string BuildTraceMeName(); + + Status GetNext(IteratorContext* ctx, std::vector* out_tensors, + bool* end_of_sequence) final; + + Status GetNext(IteratorContext&& ctx, std::vector* out_tensors, + bool* end_of_sequence) { + return GetNext(&ctx, out_tensors, end_of_sequence); + } + + Status Skip(IteratorContext* ctx, int num_to_skip, bool* end_of_sequence, + int* num_skipped) final; + + Status Save(SerializationContext* ctx, IteratorStateWriter* writer) final { + VLOG(2) << "Attempting to save checkpoints on iterator (prefix: " + << prefix() << ") from " << dataset()->DebugString(); + return IteratorBase::Save(ctx, writer); + } + + protected: + Status Restore(IteratorContext* ctx, IteratorStateReader* reader) final { + VLOG(2) << "Attempting to restore checkpoints on iterator (prefix: " + << prefix() << ") from " << dataset()->DebugString(); + return IteratorBase::Restore(ctx, reader); + } + + // Internal implementation of GetNext that is wrapped in tracing logic. + // + // See the docstring of `GetNext` method regaring the contract for + // `out_tensors` and `end_of_sequence`. Implementations may assume that + // `*out_tensors` is empty. + virtual Status GetNextInternal(IteratorContext* ctx, + std::vector* out_tensors, + bool* end_of_sequence) = 0; + + // Internal implementation of Skip that is wrapped in tracing logic + virtual Status SkipInternal(IteratorContext* ctx, int num_to_skip, + bool* end_of_sequence, int* num_skipped); + + string full_name(const string& name) const { + return FullName(params_.prefix, name); + } + + // Returns a map of key-value pairs to included in the TraceMe string. + virtual TraceMeMetadata GetTraceMeMetadata() const { return {}; } + + // By default we model iterators using an unknown node, which acts as + // pass-through with respect to performance modeling. + std::shared_ptr CreateNode( + IteratorContext* ctx, model::Node::Args args) const override { + return model::MakeUnknownNode(std::move(args)); + } + + // When modeling is enabled, this method disables autotuning for the given + // iterator (and the transitive closure of its inputs). + void DisableAutotune(IteratorContext* ctx, IteratorBase* iterator) { + if (iterator->node_) { + iterator->node_->set_autotune(false); + } + } + + // When modeling is enabled, this method enables autotuning for the given + // iterator (and the transitive closure of its inputs). + void EnableAutotune(IteratorContext* ctx, IteratorBase* iterator) { + if (iterator->node_) { + iterator->node_->set_autotune(true); + } + } + + // When modeling is enabled, this method records the fact that this iterator + // has dequeued an element from an internal buffer. + void RecordBufferDequeue(IteratorContext* ctx, + const std::vector& element) { + if (collect_resource_usage(ctx)) { + node_->record_buffer_event(-GetAllocatedBytes(element), -1); + DCHECK_GE(node_->buffered_elements(), 0); + } + } + + // When modeling is enabled, this method records the fact that this iterator + // has enqueued an element in an internal buffer. + void RecordBufferEnqueue(IteratorContext* ctx, + const std::vector& element) { + if (collect_resource_usage(ctx)) { + node_->record_buffer_event(GetAllocatedBytes(element), 1); + } + } + + // When modeling is enabled, this method records the fact that this iterator + // has produced an element and its size in bytes. + void RecordElement(IteratorContext* ctx, std::vector* out_tensors) { + if (collect_resource_usage(ctx)) { + int64_t num_bytes = GetAllocatedBytes(*out_tensors); + node_->record_element(); + node_->record_bytes_produced(num_bytes); + if (node_->output()) { + node_->output()->record_bytes_consumed(num_bytes); + } + } + } + + // When modeling is enabled, this method records the fact that a thread of + // this iterator has started work. + void RecordStart(IteratorContext* ctx) { + if (collect_resource_usage(ctx)) { + int64_t now_nanos = EnvTime::NowNanos(); + node_->record_start(now_nanos); + } + } + + // When modeling is enabled, this method records the fact that a thread of + // this iterator has stopped work. + void RecordStop(IteratorContext* ctx) { + if (collect_resource_usage(ctx)) { + int64_t now_nanos = EnvTime::NowNanos(); + node_->record_stop(now_nanos); + } + } + + // Returns whether work is currently being recorded, i.e. whether we are + // currently between a `RecordStart` and a `RecordStop`. + bool IsRecording(IteratorContext* ctx) { + return node_ && node_->is_recording(); + } + + private: + bool collect_resource_usage(IteratorContext* ctx) { + return ctx->model() && node_; + } + + string traceme_metadata_; + BaseParams params_; +}; + +// Represents an iterator that is associated with a particular dataset +// with a particular type. +template +class DatasetIterator : public DatasetBaseIterator { + public: + struct Params { + // Borrowed pointer to the dataset. + const DatasetType* dataset; + + // Identifies the sequence of iterators leading up to this iterator. + const string prefix; + }; + + explicit DatasetIterator(const Params& params) + : DatasetBaseIterator({params.dataset, params.prefix}), + typed_dataset_(params.dataset) {} + + // The dataset from which this iterator was created. + const DatasetType* dataset() const final { return typed_dataset_; } + + private: + const DatasetType* const typed_dataset_; // Not owned. +}; + +template +Status ParseScalarArgument(OpKernelContext* ctx, + const StringPiece& argument_name, T* output) { + const Tensor* argument_t; + TF_RETURN_IF_ERROR(ctx->input(argument_name, &argument_t)); + if (!TensorShapeUtils::IsScalar(argument_t->shape())) { + return errors::InvalidArgument(argument_name, " must be a scalar"); + } + *output = argument_t->scalar()(); + return OkStatus(); +} + +template +Status ParseVectorArgument(OpKernelContext* ctx, + const StringPiece& argument_name, + std::vector* output) { + const Tensor* argument_t; + TF_RETURN_IF_ERROR(ctx->input(argument_name, &argument_t)); + if (!TensorShapeUtils::IsVector(argument_t->shape())) { + return errors::InvalidArgument(argument_name, " must be a vector"); + } + int size = argument_t->vec().size(); + output->reserve(size); + for (int i = 0; i < size; ++i) { + output->push_back(argument_t->vec()(i)); + } + return OkStatus(); +} + +// Encapsulates the work required to plug a DatasetBase into the core TensorFlow +// graph execution engine. +class DatasetOpKernel : public OpKernel { + public: + explicit DatasetOpKernel(OpKernelConstruction* ctx) : OpKernel(ctx) { + if (ctx->HasAttr(kMetadata)) { + std::string serialized_metadata; + OP_REQUIRES_OK(ctx, ctx->GetAttr(kMetadata, &serialized_metadata)); + OP_REQUIRES(ctx, metadata_.ParseFromString(serialized_metadata), + errors::InvalidArgument(absl::StrCat( + "Could not parse the 'metadata' attribute."))); + } + } + + void Compute(OpKernelContext* ctx) final; + + // Checks whether the given op is a tf.data operation. + // + // NOTE: The check uses a heuristic and can produce both false positives and + // false negatives. In particular, tf.data operations are expected to use + // names that end with "Dataset" or "DatasetV[0-9]+". + static bool IsDatasetOp(const OpDef& op_def); + + string TraceString(const OpKernelContext& ctx, bool verbose) const override; + + protected: + // Subclasses should implement this method. It will be called during Compute + // execution. + virtual void MakeDataset(OpKernelContext* ctx, DatasetBase** output) = 0; + + private: + Metadata metadata_; +}; + +// Encapsulates the work required to plug unary Datasets into the core +// TensorFlow graph execution engine. +class UnaryDatasetOpKernel : public DatasetOpKernel { + public: + explicit UnaryDatasetOpKernel(OpKernelConstruction* ctx) + : DatasetOpKernel(ctx) {} + + protected: + void MakeDataset(OpKernelContext* ctx, DatasetBase** output) final; + virtual void MakeDataset(OpKernelContext* ctx, DatasetBase* input, + DatasetBase** output) = 0; +}; + +// Encapsulates the work required to plug binary Datasets into the core +// TensorFlow graph execution engine. +class BinaryDatasetOpKernel : public DatasetOpKernel { + public: + explicit BinaryDatasetOpKernel(OpKernelConstruction* ctx) + : DatasetOpKernel(ctx) {} + + protected: + void MakeDataset(OpKernelContext* ctx, DatasetBase** output) final; + virtual void MakeDataset(OpKernelContext* ctx, DatasetBase* input, + DatasetBase* another_input, + DatasetBase** output) = 0; +}; + +// A simple background worker that executes closures asynchronously and without +// blocking. +// +// A `BackgroundWorker` is used to offload blocking work from an `AsyncOpKernel` +// to avoid blocking an executor thread that may be required by the blocking +// work. +// +// NOTE(mrry): We do not use a regular `tensorflow::thread::ThreadPool` for this +// purpose because its current implementation (in Eigen) uses a finite-length +// queue and will block the caller when full. This can lead to deadlock under +// heavy load. Since the number of concurrent work items in each user of a +// `BackgroundWorker` is at most one per op invocation, the dynamic allocation +// overhead is tolerable. +class BackgroundWorker { + public: + BackgroundWorker(Env* env, const char* name); + + ~BackgroundWorker(); + + void Schedule(std::function work_item); + + private: + void WorkerLoop(); + + Env* const env_; + const char* const name_; + + std::unique_ptr thread_; + mutex mu_; + condition_variable cond_var_; + bool cancelled_ TF_GUARDED_BY(mu_) = false; + std::deque> work_queue_ TF_GUARDED_BY(mu_); +}; + +} // namespace data +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_DATASET_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..fb7c775b34b65a7f72ed555a1b149d89a39ccd6d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.pb.h @@ -0,0 +1,939 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/dataset.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_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/tensor.pb.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fdataset_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_2fframework_2fdataset_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fdataset_2eproto; +namespace tensorflow { +namespace data { +class CompressedComponentMetadata; +struct CompressedComponentMetadataDefaultTypeInternal; +extern CompressedComponentMetadataDefaultTypeInternal _CompressedComponentMetadata_default_instance_; +class CompressedElement; +struct CompressedElementDefaultTypeInternal; +extern CompressedElementDefaultTypeInternal _CompressedElement_default_instance_; +class UncompressedElement; +struct UncompressedElementDefaultTypeInternal; +extern UncompressedElementDefaultTypeInternal _UncompressedElement_default_instance_; +} // namespace data +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::data::CompressedComponentMetadata* Arena::CreateMaybeMessage<::tensorflow::data::CompressedComponentMetadata>(Arena*); +template<> ::tensorflow::data::CompressedElement* Arena::CreateMaybeMessage<::tensorflow::data::CompressedElement>(Arena*); +template<> ::tensorflow::data::UncompressedElement* Arena::CreateMaybeMessage<::tensorflow::data::UncompressedElement>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { +namespace data { + +// =================================================================== + +class CompressedComponentMetadata final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.CompressedComponentMetadata) */ { + public: + inline CompressedComponentMetadata() : CompressedComponentMetadata(nullptr) {} + ~CompressedComponentMetadata() override; + explicit PROTOBUF_CONSTEXPR CompressedComponentMetadata(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CompressedComponentMetadata(const CompressedComponentMetadata& from); + CompressedComponentMetadata(CompressedComponentMetadata&& from) noexcept + : CompressedComponentMetadata() { + *this = ::std::move(from); + } + + inline CompressedComponentMetadata& operator=(const CompressedComponentMetadata& from) { + CopyFrom(from); + return *this; + } + inline CompressedComponentMetadata& operator=(CompressedComponentMetadata&& 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 CompressedComponentMetadata& default_instance() { + return *internal_default_instance(); + } + static inline const CompressedComponentMetadata* internal_default_instance() { + return reinterpret_cast( + &_CompressedComponentMetadata_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(CompressedComponentMetadata& a, CompressedComponentMetadata& b) { + a.Swap(&b); + } + inline void Swap(CompressedComponentMetadata* 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(CompressedComponentMetadata* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CompressedComponentMetadata* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CompressedComponentMetadata& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CompressedComponentMetadata& from) { + CompressedComponentMetadata::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(CompressedComponentMetadata* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.CompressedComponentMetadata"; + } + protected: + explicit CompressedComponentMetadata(::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 { + kUncompressedBytesFieldNumber = 4, + kTensorShapeFieldNumber = 2, + kDtypeFieldNumber = 1, + }; + // repeated uint64 uncompressed_bytes = 4; + int uncompressed_bytes_size() const; + private: + int _internal_uncompressed_bytes_size() const; + public: + void clear_uncompressed_bytes(); + private: + uint64_t _internal_uncompressed_bytes(int index) const; + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + _internal_uncompressed_bytes() const; + void _internal_add_uncompressed_bytes(uint64_t value); + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + _internal_mutable_uncompressed_bytes(); + public: + uint64_t uncompressed_bytes(int index) const; + void set_uncompressed_bytes(int index, uint64_t value); + void add_uncompressed_bytes(uint64_t value); + const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& + uncompressed_bytes() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* + mutable_uncompressed_bytes(); + + // .tensorflow.TensorShapeProto tensor_shape = 2; + bool has_tensor_shape() const; + private: + bool _internal_has_tensor_shape() const; + public: + void clear_tensor_shape(); + const ::tensorflow::TensorShapeProto& tensor_shape() const; + PROTOBUF_NODISCARD ::tensorflow::TensorShapeProto* release_tensor_shape(); + ::tensorflow::TensorShapeProto* mutable_tensor_shape(); + void set_allocated_tensor_shape(::tensorflow::TensorShapeProto* tensor_shape); + private: + const ::tensorflow::TensorShapeProto& _internal_tensor_shape() const; + ::tensorflow::TensorShapeProto* _internal_mutable_tensor_shape(); + public: + void unsafe_arena_set_allocated_tensor_shape( + ::tensorflow::TensorShapeProto* tensor_shape); + ::tensorflow::TensorShapeProto* unsafe_arena_release_tensor_shape(); + + // .tensorflow.DataType dtype = 1; + 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: + + // @@protoc_insertion_point(class_scope:tensorflow.data.CompressedComponentMetadata) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t > uncompressed_bytes_; + mutable std::atomic _uncompressed_bytes_cached_byte_size_; + ::tensorflow::TensorShapeProto* tensor_shape_; + int dtype_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_2eproto; +}; +// ------------------------------------------------------------------- + +class CompressedElement final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.CompressedElement) */ { + public: + inline CompressedElement() : CompressedElement(nullptr) {} + ~CompressedElement() override; + explicit PROTOBUF_CONSTEXPR CompressedElement(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CompressedElement(const CompressedElement& from); + CompressedElement(CompressedElement&& from) noexcept + : CompressedElement() { + *this = ::std::move(from); + } + + inline CompressedElement& operator=(const CompressedElement& from) { + CopyFrom(from); + return *this; + } + inline CompressedElement& operator=(CompressedElement&& 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 CompressedElement& default_instance() { + return *internal_default_instance(); + } + static inline const CompressedElement* internal_default_instance() { + return reinterpret_cast( + &_CompressedElement_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(CompressedElement& a, CompressedElement& b) { + a.Swap(&b); + } + inline void Swap(CompressedElement* 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(CompressedElement* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CompressedElement* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CompressedElement& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CompressedElement& from) { + CompressedElement::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(CompressedElement* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.CompressedElement"; + } + protected: + explicit CompressedElement(::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 { + kComponentMetadataFieldNumber = 2, + kDataFieldNumber = 1, + kVersionFieldNumber = 3, + }; + // repeated .tensorflow.data.CompressedComponentMetadata component_metadata = 2; + int component_metadata_size() const; + private: + int _internal_component_metadata_size() const; + public: + void clear_component_metadata(); + ::tensorflow::data::CompressedComponentMetadata* mutable_component_metadata(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::data::CompressedComponentMetadata >* + mutable_component_metadata(); + private: + const ::tensorflow::data::CompressedComponentMetadata& _internal_component_metadata(int index) const; + ::tensorflow::data::CompressedComponentMetadata* _internal_add_component_metadata(); + public: + const ::tensorflow::data::CompressedComponentMetadata& component_metadata(int index) const; + ::tensorflow::data::CompressedComponentMetadata* add_component_metadata(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::data::CompressedComponentMetadata >& + component_metadata() const; + + // bytes data = 1; + void clear_data(); + const std::string& data() const; + template + void set_data(ArgT0&& arg0, ArgT... args); + std::string* mutable_data(); + PROTOBUF_NODISCARD std::string* release_data(); + void set_allocated_data(std::string* data); + private: + const std::string& _internal_data() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_data(const std::string& value); + std::string* _internal_mutable_data(); + public: + + // int32 version = 3; + 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.data.CompressedElement) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::data::CompressedComponentMetadata > component_metadata_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr data_; + int32_t version_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_2eproto; +}; +// ------------------------------------------------------------------- + +class UncompressedElement final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.UncompressedElement) */ { + public: + inline UncompressedElement() : UncompressedElement(nullptr) {} + ~UncompressedElement() override; + explicit PROTOBUF_CONSTEXPR UncompressedElement(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + UncompressedElement(const UncompressedElement& from); + UncompressedElement(UncompressedElement&& from) noexcept + : UncompressedElement() { + *this = ::std::move(from); + } + + inline UncompressedElement& operator=(const UncompressedElement& from) { + CopyFrom(from); + return *this; + } + inline UncompressedElement& operator=(UncompressedElement&& 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 UncompressedElement& default_instance() { + return *internal_default_instance(); + } + static inline const UncompressedElement* internal_default_instance() { + return reinterpret_cast( + &_UncompressedElement_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(UncompressedElement& a, UncompressedElement& b) { + a.Swap(&b); + } + inline void Swap(UncompressedElement* 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(UncompressedElement* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + UncompressedElement* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const UncompressedElement& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const UncompressedElement& from) { + UncompressedElement::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(UncompressedElement* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.UncompressedElement"; + } + protected: + explicit UncompressedElement(::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 { + kComponentsFieldNumber = 1, + }; + // repeated .tensorflow.TensorProto components = 1; + int components_size() const; + private: + int _internal_components_size() const; + public: + void clear_components(); + ::tensorflow::TensorProto* mutable_components(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >* + mutable_components(); + private: + const ::tensorflow::TensorProto& _internal_components(int index) const; + ::tensorflow::TensorProto* _internal_add_components(); + public: + const ::tensorflow::TensorProto& components(int index) const; + ::tensorflow::TensorProto* add_components(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >& + components() const; + + // @@protoc_insertion_point(class_scope:tensorflow.data.UncompressedElement) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto > components_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// CompressedComponentMetadata + +// .tensorflow.DataType dtype = 1; +inline void CompressedComponentMetadata::clear_dtype() { + _impl_.dtype_ = 0; +} +inline ::tensorflow::DataType CompressedComponentMetadata::_internal_dtype() const { + return static_cast< ::tensorflow::DataType >(_impl_.dtype_); +} +inline ::tensorflow::DataType CompressedComponentMetadata::dtype() const { + // @@protoc_insertion_point(field_get:tensorflow.data.CompressedComponentMetadata.dtype) + return _internal_dtype(); +} +inline void CompressedComponentMetadata::_internal_set_dtype(::tensorflow::DataType value) { + + _impl_.dtype_ = value; +} +inline void CompressedComponentMetadata::set_dtype(::tensorflow::DataType value) { + _internal_set_dtype(value); + // @@protoc_insertion_point(field_set:tensorflow.data.CompressedComponentMetadata.dtype) +} + +// .tensorflow.TensorShapeProto tensor_shape = 2; +inline bool CompressedComponentMetadata::_internal_has_tensor_shape() const { + return this != internal_default_instance() && _impl_.tensor_shape_ != nullptr; +} +inline bool CompressedComponentMetadata::has_tensor_shape() const { + return _internal_has_tensor_shape(); +} +inline const ::tensorflow::TensorShapeProto& CompressedComponentMetadata::_internal_tensor_shape() const { + const ::tensorflow::TensorShapeProto* p = _impl_.tensor_shape_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_TensorShapeProto_default_instance_); +} +inline const ::tensorflow::TensorShapeProto& CompressedComponentMetadata::tensor_shape() const { + // @@protoc_insertion_point(field_get:tensorflow.data.CompressedComponentMetadata.tensor_shape) + return _internal_tensor_shape(); +} +inline void CompressedComponentMetadata::unsafe_arena_set_allocated_tensor_shape( + ::tensorflow::TensorShapeProto* tensor_shape) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.tensor_shape_); + } + _impl_.tensor_shape_ = tensor_shape; + if (tensor_shape) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.data.CompressedComponentMetadata.tensor_shape) +} +inline ::tensorflow::TensorShapeProto* CompressedComponentMetadata::release_tensor_shape() { + + ::tensorflow::TensorShapeProto* temp = _impl_.tensor_shape_; + _impl_.tensor_shape_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::TensorShapeProto* CompressedComponentMetadata::unsafe_arena_release_tensor_shape() { + // @@protoc_insertion_point(field_release:tensorflow.data.CompressedComponentMetadata.tensor_shape) + + ::tensorflow::TensorShapeProto* temp = _impl_.tensor_shape_; + _impl_.tensor_shape_ = nullptr; + return temp; +} +inline ::tensorflow::TensorShapeProto* CompressedComponentMetadata::_internal_mutable_tensor_shape() { + + if (_impl_.tensor_shape_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::TensorShapeProto>(GetArenaForAllocation()); + _impl_.tensor_shape_ = p; + } + return _impl_.tensor_shape_; +} +inline ::tensorflow::TensorShapeProto* CompressedComponentMetadata::mutable_tensor_shape() { + ::tensorflow::TensorShapeProto* _msg = _internal_mutable_tensor_shape(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.CompressedComponentMetadata.tensor_shape) + return _msg; +} +inline void CompressedComponentMetadata::set_allocated_tensor_shape(::tensorflow::TensorShapeProto* tensor_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.tensor_shape_); + } + if (tensor_shape) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(tensor_shape)); + if (message_arena != submessage_arena) { + tensor_shape = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, tensor_shape, submessage_arena); + } + + } else { + + } + _impl_.tensor_shape_ = tensor_shape; + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.CompressedComponentMetadata.tensor_shape) +} + +// repeated uint64 uncompressed_bytes = 4; +inline int CompressedComponentMetadata::_internal_uncompressed_bytes_size() const { + return _impl_.uncompressed_bytes_.size(); +} +inline int CompressedComponentMetadata::uncompressed_bytes_size() const { + return _internal_uncompressed_bytes_size(); +} +inline void CompressedComponentMetadata::clear_uncompressed_bytes() { + _impl_.uncompressed_bytes_.Clear(); +} +inline uint64_t CompressedComponentMetadata::_internal_uncompressed_bytes(int index) const { + return _impl_.uncompressed_bytes_.Get(index); +} +inline uint64_t CompressedComponentMetadata::uncompressed_bytes(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.data.CompressedComponentMetadata.uncompressed_bytes) + return _internal_uncompressed_bytes(index); +} +inline void CompressedComponentMetadata::set_uncompressed_bytes(int index, uint64_t value) { + _impl_.uncompressed_bytes_.Set(index, value); + // @@protoc_insertion_point(field_set:tensorflow.data.CompressedComponentMetadata.uncompressed_bytes) +} +inline void CompressedComponentMetadata::_internal_add_uncompressed_bytes(uint64_t value) { + _impl_.uncompressed_bytes_.Add(value); +} +inline void CompressedComponentMetadata::add_uncompressed_bytes(uint64_t value) { + _internal_add_uncompressed_bytes(value); + // @@protoc_insertion_point(field_add:tensorflow.data.CompressedComponentMetadata.uncompressed_bytes) +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +CompressedComponentMetadata::_internal_uncompressed_bytes() const { + return _impl_.uncompressed_bytes_; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >& +CompressedComponentMetadata::uncompressed_bytes() const { + // @@protoc_insertion_point(field_list:tensorflow.data.CompressedComponentMetadata.uncompressed_bytes) + return _internal_uncompressed_bytes(); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +CompressedComponentMetadata::_internal_mutable_uncompressed_bytes() { + return &_impl_.uncompressed_bytes_; +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< uint64_t >* +CompressedComponentMetadata::mutable_uncompressed_bytes() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.data.CompressedComponentMetadata.uncompressed_bytes) + return _internal_mutable_uncompressed_bytes(); +} + +// ------------------------------------------------------------------- + +// CompressedElement + +// bytes data = 1; +inline void CompressedElement::clear_data() { + _impl_.data_.ClearToEmpty(); +} +inline const std::string& CompressedElement::data() const { + // @@protoc_insertion_point(field_get:tensorflow.data.CompressedElement.data) + return _internal_data(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void CompressedElement::set_data(ArgT0&& arg0, ArgT... args) { + + _impl_.data_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.data.CompressedElement.data) +} +inline std::string* CompressedElement::mutable_data() { + std::string* _s = _internal_mutable_data(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.CompressedElement.data) + return _s; +} +inline const std::string& CompressedElement::_internal_data() const { + return _impl_.data_.Get(); +} +inline void CompressedElement::_internal_set_data(const std::string& value) { + + _impl_.data_.Set(value, GetArenaForAllocation()); +} +inline std::string* CompressedElement::_internal_mutable_data() { + + return _impl_.data_.Mutable(GetArenaForAllocation()); +} +inline std::string* CompressedElement::release_data() { + // @@protoc_insertion_point(field_release:tensorflow.data.CompressedElement.data) + return _impl_.data_.Release(); +} +inline void CompressedElement::set_allocated_data(std::string* data) { + if (data != nullptr) { + + } else { + + } + _impl_.data_.SetAllocated(data, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.data_.IsDefault()) { + _impl_.data_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.CompressedElement.data) +} + +// repeated .tensorflow.data.CompressedComponentMetadata component_metadata = 2; +inline int CompressedElement::_internal_component_metadata_size() const { + return _impl_.component_metadata_.size(); +} +inline int CompressedElement::component_metadata_size() const { + return _internal_component_metadata_size(); +} +inline void CompressedElement::clear_component_metadata() { + _impl_.component_metadata_.Clear(); +} +inline ::tensorflow::data::CompressedComponentMetadata* CompressedElement::mutable_component_metadata(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.data.CompressedElement.component_metadata) + return _impl_.component_metadata_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::data::CompressedComponentMetadata >* +CompressedElement::mutable_component_metadata() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.data.CompressedElement.component_metadata) + return &_impl_.component_metadata_; +} +inline const ::tensorflow::data::CompressedComponentMetadata& CompressedElement::_internal_component_metadata(int index) const { + return _impl_.component_metadata_.Get(index); +} +inline const ::tensorflow::data::CompressedComponentMetadata& CompressedElement::component_metadata(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.data.CompressedElement.component_metadata) + return _internal_component_metadata(index); +} +inline ::tensorflow::data::CompressedComponentMetadata* CompressedElement::_internal_add_component_metadata() { + return _impl_.component_metadata_.Add(); +} +inline ::tensorflow::data::CompressedComponentMetadata* CompressedElement::add_component_metadata() { + ::tensorflow::data::CompressedComponentMetadata* _add = _internal_add_component_metadata(); + // @@protoc_insertion_point(field_add:tensorflow.data.CompressedElement.component_metadata) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::data::CompressedComponentMetadata >& +CompressedElement::component_metadata() const { + // @@protoc_insertion_point(field_list:tensorflow.data.CompressedElement.component_metadata) + return _impl_.component_metadata_; +} + +// int32 version = 3; +inline void CompressedElement::clear_version() { + _impl_.version_ = 0; +} +inline int32_t CompressedElement::_internal_version() const { + return _impl_.version_; +} +inline int32_t CompressedElement::version() const { + // @@protoc_insertion_point(field_get:tensorflow.data.CompressedElement.version) + return _internal_version(); +} +inline void CompressedElement::_internal_set_version(int32_t value) { + + _impl_.version_ = value; +} +inline void CompressedElement::set_version(int32_t value) { + _internal_set_version(value); + // @@protoc_insertion_point(field_set:tensorflow.data.CompressedElement.version) +} + +// ------------------------------------------------------------------- + +// UncompressedElement + +// repeated .tensorflow.TensorProto components = 1; +inline int UncompressedElement::_internal_components_size() const { + return _impl_.components_.size(); +} +inline int UncompressedElement::components_size() const { + return _internal_components_size(); +} +inline ::tensorflow::TensorProto* UncompressedElement::mutable_components(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.data.UncompressedElement.components) + return _impl_.components_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >* +UncompressedElement::mutable_components() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.data.UncompressedElement.components) + return &_impl_.components_; +} +inline const ::tensorflow::TensorProto& UncompressedElement::_internal_components(int index) const { + return _impl_.components_.Get(index); +} +inline const ::tensorflow::TensorProto& UncompressedElement::components(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.data.UncompressedElement.components) + return _internal_components(index); +} +inline ::tensorflow::TensorProto* UncompressedElement::_internal_add_components() { + return _impl_.components_.Add(); +} +inline ::tensorflow::TensorProto* UncompressedElement::add_components() { + ::tensorflow::TensorProto* _add = _internal_add_components(); + // @@protoc_insertion_point(field_add:tensorflow.data.UncompressedElement.components) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::TensorProto >& +UncompressedElement::components() const { + // @@protoc_insertion_point(field_list:tensorflow.data.UncompressedElement.components) + return _impl_.components_; +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace data +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.proto new file mode 100644 index 0000000000000000000000000000000000000000..9dfd03b2ddbed1b9a4f058a3c97796a03998516a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset.proto @@ -0,0 +1,47 @@ +syntax = "proto3"; + +package tensorflow.data; + +import "tensorflow/core/framework/tensor.proto"; +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; + +// This file contains protocol buffers for working with tf.data Datasets. + +// Metadata describing a compressed component of a dataset element. +message CompressedComponentMetadata { + // The dtype of the component tensor. + .tensorflow.DataType dtype = 1; + + // The shape of the component tensor. + .tensorflow.TensorShapeProto tensor_shape = 2; + + // The amount of uncompressed tensor data. + // - For string tensors, there is an element for each string indicating the + // size of the string. + // - For all other tensors, there is a single element indicating the size of + // the tensor. + repeated uint64 uncompressed_bytes = 4; + + reserved 3; +} + +message CompressedElement { + // Compressed tensor bytes for all components of the element. + bytes data = 1; + // Metadata for the components of the element. + repeated CompressedComponentMetadata component_metadata = 2; + // Version of the CompressedElement. CompressedElements may be stored on disk + // and read back by later versions of code, so we store a version number to + // help readers understand which version they are reading. When you add a new + // field to this proto, you need to increment kCompressedElementVersion in + // tensorflow/core/data/compression_utils.cc. + int32 version = 3; +} + +// An uncompressed dataset element. +message UncompressedElement { + repeated TensorProto components = 1; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_metadata.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_metadata.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..c79ed9746f200734c8e2f8c4453b2d55bf0b14df --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_metadata.pb.h @@ -0,0 +1,286 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/dataset_metadata.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_5fmetadata_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_5fmetadata_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_2fframework_2fdataset_5fmetadata_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_2fframework_2fdataset_5fmetadata_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fdataset_5fmetadata_2eproto; +namespace tensorflow { +namespace data { +class Metadata; +struct MetadataDefaultTypeInternal; +extern MetadataDefaultTypeInternal _Metadata_default_instance_; +} // namespace data +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::data::Metadata* Arena::CreateMaybeMessage<::tensorflow::data::Metadata>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { +namespace data { + +// =================================================================== + +class Metadata final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.Metadata) */ { + public: + inline Metadata() : Metadata(nullptr) {} + ~Metadata() override; + explicit PROTOBUF_CONSTEXPR Metadata(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Metadata(const Metadata& from); + Metadata(Metadata&& from) noexcept + : Metadata() { + *this = ::std::move(from); + } + + inline Metadata& operator=(const Metadata& from) { + CopyFrom(from); + return *this; + } + inline Metadata& operator=(Metadata&& 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 Metadata& default_instance() { + return *internal_default_instance(); + } + static inline const Metadata* internal_default_instance() { + return reinterpret_cast( + &_Metadata_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(Metadata& a, Metadata& b) { + a.Swap(&b); + } + inline void Swap(Metadata* 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(Metadata* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Metadata* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Metadata& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const Metadata& from) { + Metadata::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(Metadata* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.Metadata"; + } + protected: + explicit Metadata(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + }; + // bytes name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.data.Metadata) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5fmetadata_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// Metadata + +// bytes name = 1; +inline void Metadata::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& Metadata::name() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Metadata.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void Metadata::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.SetBytes(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.data.Metadata.name) +} +inline std::string* Metadata::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.Metadata.name) + return _s; +} +inline const std::string& Metadata::_internal_name() const { + return _impl_.name_.Get(); +} +inline void Metadata::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* Metadata::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* Metadata::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.data.Metadata.name) + return _impl_.name_.Release(); +} +inline void Metadata::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.Metadata.name) +} + +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace data +} // namespace tensorflow + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_5fmetadata_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_metadata.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_metadata.proto new file mode 100644 index 0000000000000000000000000000000000000000..0e667dd48d1d78bdf30be57fdcd73b7e1a6ea2cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_metadata.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package tensorflow.data; + +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/dataset_metadata_go_proto"; + +// next: 2 +message Metadata { + bytes name = 1; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_options.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_options.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..874741ec9a1af6bc862f141418e43d1735c432a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_options.pb.h @@ -0,0 +1,3372 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/dataset_options.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +#include "tensorflow/core/framework/model.pb.h" +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2fdataset_5foptions_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_2fframework_2fdataset_5foptions_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +namespace tensorflow { +namespace data { +class AutotuneOptions; +struct AutotuneOptionsDefaultTypeInternal; +extern AutotuneOptionsDefaultTypeInternal _AutotuneOptions_default_instance_; +class CardinalityOptions; +struct CardinalityOptionsDefaultTypeInternal; +extern CardinalityOptionsDefaultTypeInternal _CardinalityOptions_default_instance_; +class DistributeOptions; +struct DistributeOptionsDefaultTypeInternal; +extern DistributeOptionsDefaultTypeInternal _DistributeOptions_default_instance_; +class OptimizationOptions; +struct OptimizationOptionsDefaultTypeInternal; +extern OptimizationOptionsDefaultTypeInternal _OptimizationOptions_default_instance_; +class Options; +struct OptionsDefaultTypeInternal; +extern OptionsDefaultTypeInternal _Options_default_instance_; +class ThreadingOptions; +struct ThreadingOptionsDefaultTypeInternal; +extern ThreadingOptionsDefaultTypeInternal _ThreadingOptions_default_instance_; +} // namespace data +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::data::AutotuneOptions* Arena::CreateMaybeMessage<::tensorflow::data::AutotuneOptions>(Arena*); +template<> ::tensorflow::data::CardinalityOptions* Arena::CreateMaybeMessage<::tensorflow::data::CardinalityOptions>(Arena*); +template<> ::tensorflow::data::DistributeOptions* Arena::CreateMaybeMessage<::tensorflow::data::DistributeOptions>(Arena*); +template<> ::tensorflow::data::OptimizationOptions* Arena::CreateMaybeMessage<::tensorflow::data::OptimizationOptions>(Arena*); +template<> ::tensorflow::data::Options* Arena::CreateMaybeMessage<::tensorflow::data::Options>(Arena*); +template<> ::tensorflow::data::ThreadingOptions* Arena::CreateMaybeMessage<::tensorflow::data::ThreadingOptions>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { +namespace data { + +enum CardinalityOptions_ComputeLevel : int { + CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_UNSPECIFIED = 0, + CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_LOW = 1, + CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_MODERATE = 2, + CardinalityOptions_ComputeLevel_CardinalityOptions_ComputeLevel_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + CardinalityOptions_ComputeLevel_CardinalityOptions_ComputeLevel_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool CardinalityOptions_ComputeLevel_IsValid(int value); +constexpr CardinalityOptions_ComputeLevel CardinalityOptions_ComputeLevel_ComputeLevel_MIN = CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_UNSPECIFIED; +constexpr CardinalityOptions_ComputeLevel CardinalityOptions_ComputeLevel_ComputeLevel_MAX = CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_MODERATE; +constexpr int CardinalityOptions_ComputeLevel_ComputeLevel_ARRAYSIZE = CardinalityOptions_ComputeLevel_ComputeLevel_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CardinalityOptions_ComputeLevel_descriptor(); +template +inline const std::string& CardinalityOptions_ComputeLevel_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CardinalityOptions_ComputeLevel_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + CardinalityOptions_ComputeLevel_descriptor(), enum_t_value); +} +inline bool CardinalityOptions_ComputeLevel_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CardinalityOptions_ComputeLevel* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + CardinalityOptions_ComputeLevel_descriptor(), name, value); +} +enum AutoShardPolicy : int { + AUTO = 0, + FILE = 1, + DATA = 2, + HINT = 3, + OFF = -1, + AutoShardPolicy_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + AutoShardPolicy_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool AutoShardPolicy_IsValid(int value); +constexpr AutoShardPolicy AutoShardPolicy_MIN = OFF; +constexpr AutoShardPolicy AutoShardPolicy_MAX = HINT; +constexpr int AutoShardPolicy_ARRAYSIZE = AutoShardPolicy_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* AutoShardPolicy_descriptor(); +template +inline const std::string& AutoShardPolicy_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function AutoShardPolicy_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + AutoShardPolicy_descriptor(), enum_t_value); +} +inline bool AutoShardPolicy_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, AutoShardPolicy* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + AutoShardPolicy_descriptor(), name, value); +} +enum ExternalStatePolicy : int { + POLICY_WARN = 0, + POLICY_IGNORE = 1, + POLICY_FAIL = 2, + ExternalStatePolicy_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + ExternalStatePolicy_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool ExternalStatePolicy_IsValid(int value); +constexpr ExternalStatePolicy ExternalStatePolicy_MIN = POLICY_WARN; +constexpr ExternalStatePolicy ExternalStatePolicy_MAX = POLICY_FAIL; +constexpr int ExternalStatePolicy_ARRAYSIZE = ExternalStatePolicy_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* ExternalStatePolicy_descriptor(); +template +inline const std::string& ExternalStatePolicy_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function ExternalStatePolicy_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + ExternalStatePolicy_descriptor(), enum_t_value); +} +inline bool ExternalStatePolicy_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, ExternalStatePolicy* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + ExternalStatePolicy_descriptor(), name, value); +} +// =================================================================== + +class AutotuneOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.AutotuneOptions) */ { + public: + inline AutotuneOptions() : AutotuneOptions(nullptr) {} + ~AutotuneOptions() override; + explicit PROTOBUF_CONSTEXPR AutotuneOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + AutotuneOptions(const AutotuneOptions& from); + AutotuneOptions(AutotuneOptions&& from) noexcept + : AutotuneOptions() { + *this = ::std::move(from); + } + + inline AutotuneOptions& operator=(const AutotuneOptions& from) { + CopyFrom(from); + return *this; + } + inline AutotuneOptions& operator=(AutotuneOptions&& 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 AutotuneOptions& default_instance() { + return *internal_default_instance(); + } + enum OptionalEnabledCase { + kEnabled = 1, + OPTIONAL_ENABLED_NOT_SET = 0, + }; + + enum OptionalCpuBudgetCase { + kCpuBudget = 2, + OPTIONAL_CPU_BUDGET_NOT_SET = 0, + }; + + enum OptionalRamBudgetCase { + kRamBudget = 3, + OPTIONAL_RAM_BUDGET_NOT_SET = 0, + }; + + enum OptionalAutotuneAlgorithmCase { + kAutotuneAlgorithm = 4, + OPTIONAL_AUTOTUNE_ALGORITHM_NOT_SET = 0, + }; + + static inline const AutotuneOptions* internal_default_instance() { + return reinterpret_cast( + &_AutotuneOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(AutotuneOptions& a, AutotuneOptions& b) { + a.Swap(&b); + } + inline void Swap(AutotuneOptions* 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(AutotuneOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + AutotuneOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const AutotuneOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const AutotuneOptions& from) { + AutotuneOptions::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(AutotuneOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.AutotuneOptions"; + } + protected: + explicit AutotuneOptions(::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 { + kEnabledFieldNumber = 1, + kCpuBudgetFieldNumber = 2, + kRamBudgetFieldNumber = 3, + kAutotuneAlgorithmFieldNumber = 4, + }; + // bool enabled = 1; + bool has_enabled() const; + private: + bool _internal_has_enabled() const; + public: + void clear_enabled(); + bool enabled() const; + void set_enabled(bool value); + private: + bool _internal_enabled() const; + void _internal_set_enabled(bool value); + public: + + // int32 cpu_budget = 2; + bool has_cpu_budget() const; + private: + bool _internal_has_cpu_budget() const; + public: + void clear_cpu_budget(); + int32_t cpu_budget() const; + void set_cpu_budget(int32_t value); + private: + int32_t _internal_cpu_budget() const; + void _internal_set_cpu_budget(int32_t value); + public: + + // int64 ram_budget = 3; + bool has_ram_budget() const; + private: + bool _internal_has_ram_budget() const; + public: + void clear_ram_budget(); + int64_t ram_budget() const; + void set_ram_budget(int64_t value); + private: + int64_t _internal_ram_budget() const; + void _internal_set_ram_budget(int64_t value); + public: + + // .tensorflow.data.model.AutotuneAlgorithm autotune_algorithm = 4; + bool has_autotune_algorithm() const; + private: + bool _internal_has_autotune_algorithm() const; + public: + void clear_autotune_algorithm(); + ::tensorflow::data::model::AutotuneAlgorithm autotune_algorithm() const; + void set_autotune_algorithm(::tensorflow::data::model::AutotuneAlgorithm value); + private: + ::tensorflow::data::model::AutotuneAlgorithm _internal_autotune_algorithm() const; + void _internal_set_autotune_algorithm(::tensorflow::data::model::AutotuneAlgorithm value); + public: + + void clear_optional_enabled(); + OptionalEnabledCase optional_enabled_case() const; + void clear_optional_cpu_budget(); + OptionalCpuBudgetCase optional_cpu_budget_case() const; + void clear_optional_ram_budget(); + OptionalRamBudgetCase optional_ram_budget_case() const; + void clear_optional_autotune_algorithm(); + OptionalAutotuneAlgorithmCase optional_autotune_algorithm_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.data.AutotuneOptions) + private: + class _Internal; + void set_has_enabled(); + void set_has_cpu_budget(); + void set_has_ram_budget(); + void set_has_autotune_algorithm(); + + inline bool has_optional_enabled() const; + inline void clear_has_optional_enabled(); + + inline bool has_optional_cpu_budget() const; + inline void clear_has_optional_cpu_budget(); + + inline bool has_optional_ram_budget() const; + inline void clear_has_optional_ram_budget(); + + inline bool has_optional_autotune_algorithm() const; + inline void clear_has_optional_autotune_algorithm(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union OptionalEnabledUnion { + constexpr OptionalEnabledUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool enabled_; + } optional_enabled_; + union OptionalCpuBudgetUnion { + constexpr OptionalCpuBudgetUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int32_t cpu_budget_; + } optional_cpu_budget_; + union OptionalRamBudgetUnion { + constexpr OptionalRamBudgetUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int64_t ram_budget_; + } optional_ram_budget_; + union OptionalAutotuneAlgorithmUnion { + constexpr OptionalAutotuneAlgorithmUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int autotune_algorithm_; + } optional_autotune_algorithm_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[4]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +}; +// ------------------------------------------------------------------- + +class CardinalityOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.CardinalityOptions) */ { + public: + inline CardinalityOptions() : CardinalityOptions(nullptr) {} + ~CardinalityOptions() override; + explicit PROTOBUF_CONSTEXPR CardinalityOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + CardinalityOptions(const CardinalityOptions& from); + CardinalityOptions(CardinalityOptions&& from) noexcept + : CardinalityOptions() { + *this = ::std::move(from); + } + + inline CardinalityOptions& operator=(const CardinalityOptions& from) { + CopyFrom(from); + return *this; + } + inline CardinalityOptions& operator=(CardinalityOptions&& 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 CardinalityOptions& default_instance() { + return *internal_default_instance(); + } + static inline const CardinalityOptions* internal_default_instance() { + return reinterpret_cast( + &_CardinalityOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(CardinalityOptions& a, CardinalityOptions& b) { + a.Swap(&b); + } + inline void Swap(CardinalityOptions* 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(CardinalityOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + CardinalityOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const CardinalityOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const CardinalityOptions& from) { + CardinalityOptions::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(CardinalityOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.CardinalityOptions"; + } + protected: + explicit CardinalityOptions(::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 CardinalityOptions_ComputeLevel ComputeLevel; + static constexpr ComputeLevel CARDINALITY_COMPUTE_UNSPECIFIED = + CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_UNSPECIFIED; + static constexpr ComputeLevel CARDINALITY_COMPUTE_LOW = + CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_LOW; + static constexpr ComputeLevel CARDINALITY_COMPUTE_MODERATE = + CardinalityOptions_ComputeLevel_CARDINALITY_COMPUTE_MODERATE; + static inline bool ComputeLevel_IsValid(int value) { + return CardinalityOptions_ComputeLevel_IsValid(value); + } + static constexpr ComputeLevel ComputeLevel_MIN = + CardinalityOptions_ComputeLevel_ComputeLevel_MIN; + static constexpr ComputeLevel ComputeLevel_MAX = + CardinalityOptions_ComputeLevel_ComputeLevel_MAX; + static constexpr int ComputeLevel_ARRAYSIZE = + CardinalityOptions_ComputeLevel_ComputeLevel_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + ComputeLevel_descriptor() { + return CardinalityOptions_ComputeLevel_descriptor(); + } + template + static inline const std::string& ComputeLevel_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function ComputeLevel_Name."); + return CardinalityOptions_ComputeLevel_Name(enum_t_value); + } + static inline bool ComputeLevel_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + ComputeLevel* value) { + return CardinalityOptions_ComputeLevel_Parse(name, value); + } + + // accessors ------------------------------------------------------- + + enum : int { + kComputeLevelFieldNumber = 1, + }; + // .tensorflow.data.CardinalityOptions.ComputeLevel compute_level = 1; + void clear_compute_level(); + ::tensorflow::data::CardinalityOptions_ComputeLevel compute_level() const; + void set_compute_level(::tensorflow::data::CardinalityOptions_ComputeLevel value); + private: + ::tensorflow::data::CardinalityOptions_ComputeLevel _internal_compute_level() const; + void _internal_set_compute_level(::tensorflow::data::CardinalityOptions_ComputeLevel value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.data.CardinalityOptions) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int compute_level_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +}; +// ------------------------------------------------------------------- + +class DistributeOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.DistributeOptions) */ { + public: + inline DistributeOptions() : DistributeOptions(nullptr) {} + ~DistributeOptions() override; + explicit PROTOBUF_CONSTEXPR DistributeOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DistributeOptions(const DistributeOptions& from); + DistributeOptions(DistributeOptions&& from) noexcept + : DistributeOptions() { + *this = ::std::move(from); + } + + inline DistributeOptions& operator=(const DistributeOptions& from) { + CopyFrom(from); + return *this; + } + inline DistributeOptions& operator=(DistributeOptions&& 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 DistributeOptions& default_instance() { + return *internal_default_instance(); + } + enum OptionalNumDevicesCase { + kNumDevices = 2, + OPTIONAL_NUM_DEVICES_NOT_SET = 0, + }; + + static inline const DistributeOptions* internal_default_instance() { + return reinterpret_cast( + &_DistributeOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(DistributeOptions& a, DistributeOptions& b) { + a.Swap(&b); + } + inline void Swap(DistributeOptions* 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(DistributeOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DistributeOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DistributeOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DistributeOptions& from) { + DistributeOptions::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(DistributeOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.DistributeOptions"; + } + protected: + explicit DistributeOptions(::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 { + kAutoShardPolicyFieldNumber = 1, + kNumDevicesFieldNumber = 2, + }; + // .tensorflow.data.AutoShardPolicy auto_shard_policy = 1; + void clear_auto_shard_policy(); + ::tensorflow::data::AutoShardPolicy auto_shard_policy() const; + void set_auto_shard_policy(::tensorflow::data::AutoShardPolicy value); + private: + ::tensorflow::data::AutoShardPolicy _internal_auto_shard_policy() const; + void _internal_set_auto_shard_policy(::tensorflow::data::AutoShardPolicy value); + public: + + // int32 num_devices = 2; + bool has_num_devices() const; + private: + bool _internal_has_num_devices() const; + public: + void clear_num_devices(); + int32_t num_devices() const; + void set_num_devices(int32_t value); + private: + int32_t _internal_num_devices() const; + void _internal_set_num_devices(int32_t value); + public: + + void clear_optional_num_devices(); + OptionalNumDevicesCase optional_num_devices_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.data.DistributeOptions) + private: + class _Internal; + void set_has_num_devices(); + + inline bool has_optional_num_devices() const; + inline void clear_has_optional_num_devices(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + int auto_shard_policy_; + union OptionalNumDevicesUnion { + constexpr OptionalNumDevicesUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int32_t num_devices_; + } optional_num_devices_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +}; +// ------------------------------------------------------------------- + +class OptimizationOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.OptimizationOptions) */ { + public: + inline OptimizationOptions() : OptimizationOptions(nullptr) {} + ~OptimizationOptions() override; + explicit PROTOBUF_CONSTEXPR OptimizationOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + OptimizationOptions(const OptimizationOptions& from); + OptimizationOptions(OptimizationOptions&& from) noexcept + : OptimizationOptions() { + *this = ::std::move(from); + } + + inline OptimizationOptions& operator=(const OptimizationOptions& from) { + CopyFrom(from); + return *this; + } + inline OptimizationOptions& operator=(OptimizationOptions&& 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 OptimizationOptions& default_instance() { + return *internal_default_instance(); + } + enum OptionalApplyDefaultOptimizationsCase { + kApplyDefaultOptimizations = 1, + OPTIONAL_APPLY_DEFAULT_OPTIMIZATIONS_NOT_SET = 0, + }; + + enum OptionalFilterFusionCase { + kFilterFusion = 6, + OPTIONAL_FILTER_FUSION_NOT_SET = 0, + }; + + enum OptionalMapAndBatchFusionCase { + kMapAndBatchFusion = 9, + OPTIONAL_MAP_AND_BATCH_FUSION_NOT_SET = 0, + }; + + enum OptionalMapAndFilterFusionCase { + kMapAndFilterFusion = 10, + OPTIONAL_MAP_AND_FILTER_FUSION_NOT_SET = 0, + }; + + enum OptionalMapFusionCase { + kMapFusion = 11, + OPTIONAL_MAP_FUSION_NOT_SET = 0, + }; + + enum OptionalMapParallelizationCase { + kMapParallelization = 12, + OPTIONAL_MAP_PARALLELIZATION_NOT_SET = 0, + }; + + enum OptionalNoopEliminationCase { + kNoopElimination = 14, + OPTIONAL_NOOP_ELIMINATION_NOT_SET = 0, + }; + + enum OptionalParallelBatchCase { + kParallelBatch = 15, + OPTIONAL_PARALLEL_BATCH_NOT_SET = 0, + }; + + enum OptionalShuffleAndRepeatFusionCase { + kShuffleAndRepeatFusion = 17, + OPTIONAL_SHUFFLE_AND_REPEAT_FUSION_NOT_SET = 0, + }; + + enum OptionalFilterParallelizationCase { + kFilterParallelization = 18, + OPTIONAL_FILTER_PARALLELIZATION_NOT_SET = 0, + }; + + enum OptionalInjectPrefetchCase { + kInjectPrefetch = 19, + OPTIONAL_INJECT_PREFETCH_NOT_SET = 0, + }; + + static inline const OptimizationOptions* internal_default_instance() { + return reinterpret_cast( + &_OptimizationOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(OptimizationOptions& a, OptimizationOptions& b) { + a.Swap(&b); + } + inline void Swap(OptimizationOptions* 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(OptimizationOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + OptimizationOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const OptimizationOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const OptimizationOptions& from) { + OptimizationOptions::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(OptimizationOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.OptimizationOptions"; + } + protected: + explicit OptimizationOptions(::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 { + kApplyDefaultOptimizationsFieldNumber = 1, + kFilterFusionFieldNumber = 6, + kMapAndBatchFusionFieldNumber = 9, + kMapAndFilterFusionFieldNumber = 10, + kMapFusionFieldNumber = 11, + kMapParallelizationFieldNumber = 12, + kNoopEliminationFieldNumber = 14, + kParallelBatchFieldNumber = 15, + kShuffleAndRepeatFusionFieldNumber = 17, + kFilterParallelizationFieldNumber = 18, + kInjectPrefetchFieldNumber = 19, + }; + // bool apply_default_optimizations = 1; + bool has_apply_default_optimizations() const; + private: + bool _internal_has_apply_default_optimizations() const; + public: + void clear_apply_default_optimizations(); + bool apply_default_optimizations() const; + void set_apply_default_optimizations(bool value); + private: + bool _internal_apply_default_optimizations() const; + void _internal_set_apply_default_optimizations(bool value); + public: + + // bool filter_fusion = 6; + bool has_filter_fusion() const; + private: + bool _internal_has_filter_fusion() const; + public: + void clear_filter_fusion(); + bool filter_fusion() const; + void set_filter_fusion(bool value); + private: + bool _internal_filter_fusion() const; + void _internal_set_filter_fusion(bool value); + public: + + // bool map_and_batch_fusion = 9; + bool has_map_and_batch_fusion() const; + private: + bool _internal_has_map_and_batch_fusion() const; + public: + void clear_map_and_batch_fusion(); + bool map_and_batch_fusion() const; + void set_map_and_batch_fusion(bool value); + private: + bool _internal_map_and_batch_fusion() const; + void _internal_set_map_and_batch_fusion(bool value); + public: + + // bool map_and_filter_fusion = 10; + bool has_map_and_filter_fusion() const; + private: + bool _internal_has_map_and_filter_fusion() const; + public: + void clear_map_and_filter_fusion(); + bool map_and_filter_fusion() const; + void set_map_and_filter_fusion(bool value); + private: + bool _internal_map_and_filter_fusion() const; + void _internal_set_map_and_filter_fusion(bool value); + public: + + // bool map_fusion = 11; + bool has_map_fusion() const; + private: + bool _internal_has_map_fusion() const; + public: + void clear_map_fusion(); + bool map_fusion() const; + void set_map_fusion(bool value); + private: + bool _internal_map_fusion() const; + void _internal_set_map_fusion(bool value); + public: + + // bool map_parallelization = 12; + bool has_map_parallelization() const; + private: + bool _internal_has_map_parallelization() const; + public: + void clear_map_parallelization(); + bool map_parallelization() const; + void set_map_parallelization(bool value); + private: + bool _internal_map_parallelization() const; + void _internal_set_map_parallelization(bool value); + public: + + // bool noop_elimination = 14; + bool has_noop_elimination() const; + private: + bool _internal_has_noop_elimination() const; + public: + void clear_noop_elimination(); + bool noop_elimination() const; + void set_noop_elimination(bool value); + private: + bool _internal_noop_elimination() const; + void _internal_set_noop_elimination(bool value); + public: + + // bool parallel_batch = 15; + bool has_parallel_batch() const; + private: + bool _internal_has_parallel_batch() const; + public: + void clear_parallel_batch(); + bool parallel_batch() const; + void set_parallel_batch(bool value); + private: + bool _internal_parallel_batch() const; + void _internal_set_parallel_batch(bool value); + public: + + // bool shuffle_and_repeat_fusion = 17; + bool has_shuffle_and_repeat_fusion() const; + private: + bool _internal_has_shuffle_and_repeat_fusion() const; + public: + void clear_shuffle_and_repeat_fusion(); + bool shuffle_and_repeat_fusion() const; + void set_shuffle_and_repeat_fusion(bool value); + private: + bool _internal_shuffle_and_repeat_fusion() const; + void _internal_set_shuffle_and_repeat_fusion(bool value); + public: + + // bool filter_parallelization = 18; + bool has_filter_parallelization() const; + private: + bool _internal_has_filter_parallelization() const; + public: + void clear_filter_parallelization(); + bool filter_parallelization() const; + void set_filter_parallelization(bool value); + private: + bool _internal_filter_parallelization() const; + void _internal_set_filter_parallelization(bool value); + public: + + // bool inject_prefetch = 19; + bool has_inject_prefetch() const; + private: + bool _internal_has_inject_prefetch() const; + public: + void clear_inject_prefetch(); + bool inject_prefetch() const; + void set_inject_prefetch(bool value); + private: + bool _internal_inject_prefetch() const; + void _internal_set_inject_prefetch(bool value); + public: + + void clear_optional_apply_default_optimizations(); + OptionalApplyDefaultOptimizationsCase optional_apply_default_optimizations_case() const; + void clear_optional_filter_fusion(); + OptionalFilterFusionCase optional_filter_fusion_case() const; + void clear_optional_map_and_batch_fusion(); + OptionalMapAndBatchFusionCase optional_map_and_batch_fusion_case() const; + void clear_optional_map_and_filter_fusion(); + OptionalMapAndFilterFusionCase optional_map_and_filter_fusion_case() const; + void clear_optional_map_fusion(); + OptionalMapFusionCase optional_map_fusion_case() const; + void clear_optional_map_parallelization(); + OptionalMapParallelizationCase optional_map_parallelization_case() const; + void clear_optional_noop_elimination(); + OptionalNoopEliminationCase optional_noop_elimination_case() const; + void clear_optional_parallel_batch(); + OptionalParallelBatchCase optional_parallel_batch_case() const; + void clear_optional_shuffle_and_repeat_fusion(); + OptionalShuffleAndRepeatFusionCase optional_shuffle_and_repeat_fusion_case() const; + void clear_optional_filter_parallelization(); + OptionalFilterParallelizationCase optional_filter_parallelization_case() const; + void clear_optional_inject_prefetch(); + OptionalInjectPrefetchCase optional_inject_prefetch_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.data.OptimizationOptions) + private: + class _Internal; + void set_has_apply_default_optimizations(); + void set_has_filter_fusion(); + void set_has_map_and_batch_fusion(); + void set_has_map_and_filter_fusion(); + void set_has_map_fusion(); + void set_has_map_parallelization(); + void set_has_noop_elimination(); + void set_has_parallel_batch(); + void set_has_shuffle_and_repeat_fusion(); + void set_has_filter_parallelization(); + void set_has_inject_prefetch(); + + inline bool has_optional_apply_default_optimizations() const; + inline void clear_has_optional_apply_default_optimizations(); + + inline bool has_optional_filter_fusion() const; + inline void clear_has_optional_filter_fusion(); + + inline bool has_optional_map_and_batch_fusion() const; + inline void clear_has_optional_map_and_batch_fusion(); + + inline bool has_optional_map_and_filter_fusion() const; + inline void clear_has_optional_map_and_filter_fusion(); + + inline bool has_optional_map_fusion() const; + inline void clear_has_optional_map_fusion(); + + inline bool has_optional_map_parallelization() const; + inline void clear_has_optional_map_parallelization(); + + inline bool has_optional_noop_elimination() const; + inline void clear_has_optional_noop_elimination(); + + inline bool has_optional_parallel_batch() const; + inline void clear_has_optional_parallel_batch(); + + inline bool has_optional_shuffle_and_repeat_fusion() const; + inline void clear_has_optional_shuffle_and_repeat_fusion(); + + inline bool has_optional_filter_parallelization() const; + inline void clear_has_optional_filter_parallelization(); + + inline bool has_optional_inject_prefetch() const; + inline void clear_has_optional_inject_prefetch(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union OptionalApplyDefaultOptimizationsUnion { + constexpr OptionalApplyDefaultOptimizationsUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool apply_default_optimizations_; + } optional_apply_default_optimizations_; + union OptionalFilterFusionUnion { + constexpr OptionalFilterFusionUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool filter_fusion_; + } optional_filter_fusion_; + union OptionalMapAndBatchFusionUnion { + constexpr OptionalMapAndBatchFusionUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool map_and_batch_fusion_; + } optional_map_and_batch_fusion_; + union OptionalMapAndFilterFusionUnion { + constexpr OptionalMapAndFilterFusionUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool map_and_filter_fusion_; + } optional_map_and_filter_fusion_; + union OptionalMapFusionUnion { + constexpr OptionalMapFusionUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool map_fusion_; + } optional_map_fusion_; + union OptionalMapParallelizationUnion { + constexpr OptionalMapParallelizationUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool map_parallelization_; + } optional_map_parallelization_; + union OptionalNoopEliminationUnion { + constexpr OptionalNoopEliminationUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool noop_elimination_; + } optional_noop_elimination_; + union OptionalParallelBatchUnion { + constexpr OptionalParallelBatchUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool parallel_batch_; + } optional_parallel_batch_; + union OptionalShuffleAndRepeatFusionUnion { + constexpr OptionalShuffleAndRepeatFusionUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool shuffle_and_repeat_fusion_; + } optional_shuffle_and_repeat_fusion_; + union OptionalFilterParallelizationUnion { + constexpr OptionalFilterParallelizationUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool filter_parallelization_; + } optional_filter_parallelization_; + union OptionalInjectPrefetchUnion { + constexpr OptionalInjectPrefetchUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool inject_prefetch_; + } optional_inject_prefetch_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[11]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +}; +// ------------------------------------------------------------------- + +class ThreadingOptions final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.ThreadingOptions) */ { + public: + inline ThreadingOptions() : ThreadingOptions(nullptr) {} + ~ThreadingOptions() override; + explicit PROTOBUF_CONSTEXPR ThreadingOptions(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + ThreadingOptions(const ThreadingOptions& from); + ThreadingOptions(ThreadingOptions&& from) noexcept + : ThreadingOptions() { + *this = ::std::move(from); + } + + inline ThreadingOptions& operator=(const ThreadingOptions& from) { + CopyFrom(from); + return *this; + } + inline ThreadingOptions& operator=(ThreadingOptions&& 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 ThreadingOptions& default_instance() { + return *internal_default_instance(); + } + enum OptionalMaxIntraOpParallelismCase { + kMaxIntraOpParallelism = 1, + OPTIONAL_MAX_INTRA_OP_PARALLELISM_NOT_SET = 0, + }; + + enum OptionalPrivateThreadpoolSizeCase { + kPrivateThreadpoolSize = 2, + OPTIONAL_PRIVATE_THREADPOOL_SIZE_NOT_SET = 0, + }; + + static inline const ThreadingOptions* internal_default_instance() { + return reinterpret_cast( + &_ThreadingOptions_default_instance_); + } + static constexpr int kIndexInFileMessages = + 4; + + friend void swap(ThreadingOptions& a, ThreadingOptions& b) { + a.Swap(&b); + } + inline void Swap(ThreadingOptions* 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(ThreadingOptions* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + ThreadingOptions* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const ThreadingOptions& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const ThreadingOptions& from) { + ThreadingOptions::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(ThreadingOptions* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.ThreadingOptions"; + } + protected: + explicit ThreadingOptions(::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 { + kMaxIntraOpParallelismFieldNumber = 1, + kPrivateThreadpoolSizeFieldNumber = 2, + }; + // int32 max_intra_op_parallelism = 1; + bool has_max_intra_op_parallelism() const; + private: + bool _internal_has_max_intra_op_parallelism() const; + public: + void clear_max_intra_op_parallelism(); + int32_t max_intra_op_parallelism() const; + void set_max_intra_op_parallelism(int32_t value); + private: + int32_t _internal_max_intra_op_parallelism() const; + void _internal_set_max_intra_op_parallelism(int32_t value); + public: + + // int32 private_threadpool_size = 2; + bool has_private_threadpool_size() const; + private: + bool _internal_has_private_threadpool_size() const; + public: + void clear_private_threadpool_size(); + int32_t private_threadpool_size() const; + void set_private_threadpool_size(int32_t value); + private: + int32_t _internal_private_threadpool_size() const; + void _internal_set_private_threadpool_size(int32_t value); + public: + + void clear_optional_max_intra_op_parallelism(); + OptionalMaxIntraOpParallelismCase optional_max_intra_op_parallelism_case() const; + void clear_optional_private_threadpool_size(); + OptionalPrivateThreadpoolSizeCase optional_private_threadpool_size_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.data.ThreadingOptions) + private: + class _Internal; + void set_has_max_intra_op_parallelism(); + void set_has_private_threadpool_size(); + + inline bool has_optional_max_intra_op_parallelism() const; + inline void clear_has_optional_max_intra_op_parallelism(); + + inline bool has_optional_private_threadpool_size() const; + inline void clear_has_optional_private_threadpool_size(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + union OptionalMaxIntraOpParallelismUnion { + constexpr OptionalMaxIntraOpParallelismUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int32_t max_intra_op_parallelism_; + } optional_max_intra_op_parallelism_; + union OptionalPrivateThreadpoolSizeUnion { + constexpr OptionalPrivateThreadpoolSizeUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int32_t private_threadpool_size_; + } optional_private_threadpool_size_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[2]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +}; +// ------------------------------------------------------------------- + +class Options final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.data.Options) */ { + public: + inline Options() : Options(nullptr) {} + ~Options() override; + explicit PROTOBUF_CONSTEXPR Options(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + Options(const Options& from); + Options(Options&& from) noexcept + : Options() { + *this = ::std::move(from); + } + + inline Options& operator=(const Options& from) { + CopyFrom(from); + return *this; + } + inline Options& operator=(Options&& 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 Options& default_instance() { + return *internal_default_instance(); + } + enum OptionalDeterministicCase { + kDeterministic = 1, + OPTIONAL_DETERMINISTIC_NOT_SET = 0, + }; + + enum OptionalSlackCase { + kSlack = 4, + OPTIONAL_SLACK_NOT_SET = 0, + }; + + enum OptionalExternalStatePolicyCase { + kExternalStatePolicy = 6, + OPTIONAL_EXTERNAL_STATE_POLICY_NOT_SET = 0, + }; + + enum OptionalSymbolicCheckpointCase { + kSymbolicCheckpoint = 8, + OPTIONAL_SYMBOLIC_CHECKPOINT_NOT_SET = 0, + }; + + enum OptionalWarmStartCase { + kWarmStart = 9, + OPTIONAL_WARM_START_NOT_SET = 0, + }; + + static inline const Options* internal_default_instance() { + return reinterpret_cast( + &_Options_default_instance_); + } + static constexpr int kIndexInFileMessages = + 5; + + friend void swap(Options& a, Options& b) { + a.Swap(&b); + } + inline void Swap(Options* 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(Options* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + Options* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const Options& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const Options& from) { + Options::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(Options* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.data.Options"; + } + protected: + explicit Options(::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 { + kDistributeOptionsFieldNumber = 2, + kOptimizationOptionsFieldNumber = 3, + kThreadingOptionsFieldNumber = 5, + kAutotuneOptionsFieldNumber = 7, + kDeterministicFieldNumber = 1, + kSlackFieldNumber = 4, + kExternalStatePolicyFieldNumber = 6, + kSymbolicCheckpointFieldNumber = 8, + kWarmStartFieldNumber = 9, + }; + // .tensorflow.data.DistributeOptions distribute_options = 2; + bool has_distribute_options() const; + private: + bool _internal_has_distribute_options() const; + public: + void clear_distribute_options(); + const ::tensorflow::data::DistributeOptions& distribute_options() const; + PROTOBUF_NODISCARD ::tensorflow::data::DistributeOptions* release_distribute_options(); + ::tensorflow::data::DistributeOptions* mutable_distribute_options(); + void set_allocated_distribute_options(::tensorflow::data::DistributeOptions* distribute_options); + private: + const ::tensorflow::data::DistributeOptions& _internal_distribute_options() const; + ::tensorflow::data::DistributeOptions* _internal_mutable_distribute_options(); + public: + void unsafe_arena_set_allocated_distribute_options( + ::tensorflow::data::DistributeOptions* distribute_options); + ::tensorflow::data::DistributeOptions* unsafe_arena_release_distribute_options(); + + // .tensorflow.data.OptimizationOptions optimization_options = 3; + bool has_optimization_options() const; + private: + bool _internal_has_optimization_options() const; + public: + void clear_optimization_options(); + const ::tensorflow::data::OptimizationOptions& optimization_options() const; + PROTOBUF_NODISCARD ::tensorflow::data::OptimizationOptions* release_optimization_options(); + ::tensorflow::data::OptimizationOptions* mutable_optimization_options(); + void set_allocated_optimization_options(::tensorflow::data::OptimizationOptions* optimization_options); + private: + const ::tensorflow::data::OptimizationOptions& _internal_optimization_options() const; + ::tensorflow::data::OptimizationOptions* _internal_mutable_optimization_options(); + public: + void unsafe_arena_set_allocated_optimization_options( + ::tensorflow::data::OptimizationOptions* optimization_options); + ::tensorflow::data::OptimizationOptions* unsafe_arena_release_optimization_options(); + + // .tensorflow.data.ThreadingOptions threading_options = 5; + bool has_threading_options() const; + private: + bool _internal_has_threading_options() const; + public: + void clear_threading_options(); + const ::tensorflow::data::ThreadingOptions& threading_options() const; + PROTOBUF_NODISCARD ::tensorflow::data::ThreadingOptions* release_threading_options(); + ::tensorflow::data::ThreadingOptions* mutable_threading_options(); + void set_allocated_threading_options(::tensorflow::data::ThreadingOptions* threading_options); + private: + const ::tensorflow::data::ThreadingOptions& _internal_threading_options() const; + ::tensorflow::data::ThreadingOptions* _internal_mutable_threading_options(); + public: + void unsafe_arena_set_allocated_threading_options( + ::tensorflow::data::ThreadingOptions* threading_options); + ::tensorflow::data::ThreadingOptions* unsafe_arena_release_threading_options(); + + // .tensorflow.data.AutotuneOptions autotune_options = 7; + bool has_autotune_options() const; + private: + bool _internal_has_autotune_options() const; + public: + void clear_autotune_options(); + const ::tensorflow::data::AutotuneOptions& autotune_options() const; + PROTOBUF_NODISCARD ::tensorflow::data::AutotuneOptions* release_autotune_options(); + ::tensorflow::data::AutotuneOptions* mutable_autotune_options(); + void set_allocated_autotune_options(::tensorflow::data::AutotuneOptions* autotune_options); + private: + const ::tensorflow::data::AutotuneOptions& _internal_autotune_options() const; + ::tensorflow::data::AutotuneOptions* _internal_mutable_autotune_options(); + public: + void unsafe_arena_set_allocated_autotune_options( + ::tensorflow::data::AutotuneOptions* autotune_options); + ::tensorflow::data::AutotuneOptions* unsafe_arena_release_autotune_options(); + + // bool deterministic = 1; + bool has_deterministic() const; + private: + bool _internal_has_deterministic() const; + public: + void clear_deterministic(); + bool deterministic() const; + void set_deterministic(bool value); + private: + bool _internal_deterministic() const; + void _internal_set_deterministic(bool value); + public: + + // bool slack = 4; + bool has_slack() const; + private: + bool _internal_has_slack() const; + public: + void clear_slack(); + bool slack() const; + void set_slack(bool value); + private: + bool _internal_slack() const; + void _internal_set_slack(bool value); + public: + + // .tensorflow.data.ExternalStatePolicy external_state_policy = 6; + bool has_external_state_policy() const; + private: + bool _internal_has_external_state_policy() const; + public: + void clear_external_state_policy(); + ::tensorflow::data::ExternalStatePolicy external_state_policy() const; + void set_external_state_policy(::tensorflow::data::ExternalStatePolicy value); + private: + ::tensorflow::data::ExternalStatePolicy _internal_external_state_policy() const; + void _internal_set_external_state_policy(::tensorflow::data::ExternalStatePolicy value); + public: + + // bool symbolic_checkpoint = 8; + bool has_symbolic_checkpoint() const; + private: + bool _internal_has_symbolic_checkpoint() const; + public: + void clear_symbolic_checkpoint(); + bool symbolic_checkpoint() const; + void set_symbolic_checkpoint(bool value); + private: + bool _internal_symbolic_checkpoint() const; + void _internal_set_symbolic_checkpoint(bool value); + public: + + // bool warm_start = 9; + bool has_warm_start() const; + private: + bool _internal_has_warm_start() const; + public: + void clear_warm_start(); + bool warm_start() const; + void set_warm_start(bool value); + private: + bool _internal_warm_start() const; + void _internal_set_warm_start(bool value); + public: + + void clear_optional_deterministic(); + OptionalDeterministicCase optional_deterministic_case() const; + void clear_optional_slack(); + OptionalSlackCase optional_slack_case() const; + void clear_optional_external_state_policy(); + OptionalExternalStatePolicyCase optional_external_state_policy_case() const; + void clear_optional_symbolic_checkpoint(); + OptionalSymbolicCheckpointCase optional_symbolic_checkpoint_case() const; + void clear_optional_warm_start(); + OptionalWarmStartCase optional_warm_start_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.data.Options) + private: + class _Internal; + void set_has_deterministic(); + void set_has_slack(); + void set_has_external_state_policy(); + void set_has_symbolic_checkpoint(); + void set_has_warm_start(); + + inline bool has_optional_deterministic() const; + inline void clear_has_optional_deterministic(); + + inline bool has_optional_slack() const; + inline void clear_has_optional_slack(); + + inline bool has_optional_external_state_policy() const; + inline void clear_has_optional_external_state_policy(); + + inline bool has_optional_symbolic_checkpoint() const; + inline void clear_has_optional_symbolic_checkpoint(); + + inline bool has_optional_warm_start() const; + inline void clear_has_optional_warm_start(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::data::DistributeOptions* distribute_options_; + ::tensorflow::data::OptimizationOptions* optimization_options_; + ::tensorflow::data::ThreadingOptions* threading_options_; + ::tensorflow::data::AutotuneOptions* autotune_options_; + union OptionalDeterministicUnion { + constexpr OptionalDeterministicUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool deterministic_; + } optional_deterministic_; + union OptionalSlackUnion { + constexpr OptionalSlackUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool slack_; + } optional_slack_; + union OptionalExternalStatePolicyUnion { + constexpr OptionalExternalStatePolicyUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int external_state_policy_; + } optional_external_state_policy_; + union OptionalSymbolicCheckpointUnion { + constexpr OptionalSymbolicCheckpointUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool symbolic_checkpoint_; + } optional_symbolic_checkpoint_; + union OptionalWarmStartUnion { + constexpr OptionalWarmStartUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + bool warm_start_; + } optional_warm_start_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[5]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// AutotuneOptions + +// bool enabled = 1; +inline bool AutotuneOptions::_internal_has_enabled() const { + return optional_enabled_case() == kEnabled; +} +inline bool AutotuneOptions::has_enabled() const { + return _internal_has_enabled(); +} +inline void AutotuneOptions::set_has_enabled() { + _impl_._oneof_case_[0] = kEnabled; +} +inline void AutotuneOptions::clear_enabled() { + if (_internal_has_enabled()) { + _impl_.optional_enabled_.enabled_ = false; + clear_has_optional_enabled(); + } +} +inline bool AutotuneOptions::_internal_enabled() const { + if (_internal_has_enabled()) { + return _impl_.optional_enabled_.enabled_; + } + return false; +} +inline void AutotuneOptions::_internal_set_enabled(bool value) { + if (!_internal_has_enabled()) { + clear_optional_enabled(); + set_has_enabled(); + } + _impl_.optional_enabled_.enabled_ = value; +} +inline bool AutotuneOptions::enabled() const { + // @@protoc_insertion_point(field_get:tensorflow.data.AutotuneOptions.enabled) + return _internal_enabled(); +} +inline void AutotuneOptions::set_enabled(bool value) { + _internal_set_enabled(value); + // @@protoc_insertion_point(field_set:tensorflow.data.AutotuneOptions.enabled) +} + +// int32 cpu_budget = 2; +inline bool AutotuneOptions::_internal_has_cpu_budget() const { + return optional_cpu_budget_case() == kCpuBudget; +} +inline bool AutotuneOptions::has_cpu_budget() const { + return _internal_has_cpu_budget(); +} +inline void AutotuneOptions::set_has_cpu_budget() { + _impl_._oneof_case_[1] = kCpuBudget; +} +inline void AutotuneOptions::clear_cpu_budget() { + if (_internal_has_cpu_budget()) { + _impl_.optional_cpu_budget_.cpu_budget_ = 0; + clear_has_optional_cpu_budget(); + } +} +inline int32_t AutotuneOptions::_internal_cpu_budget() const { + if (_internal_has_cpu_budget()) { + return _impl_.optional_cpu_budget_.cpu_budget_; + } + return 0; +} +inline void AutotuneOptions::_internal_set_cpu_budget(int32_t value) { + if (!_internal_has_cpu_budget()) { + clear_optional_cpu_budget(); + set_has_cpu_budget(); + } + _impl_.optional_cpu_budget_.cpu_budget_ = value; +} +inline int32_t AutotuneOptions::cpu_budget() const { + // @@protoc_insertion_point(field_get:tensorflow.data.AutotuneOptions.cpu_budget) + return _internal_cpu_budget(); +} +inline void AutotuneOptions::set_cpu_budget(int32_t value) { + _internal_set_cpu_budget(value); + // @@protoc_insertion_point(field_set:tensorflow.data.AutotuneOptions.cpu_budget) +} + +// int64 ram_budget = 3; +inline bool AutotuneOptions::_internal_has_ram_budget() const { + return optional_ram_budget_case() == kRamBudget; +} +inline bool AutotuneOptions::has_ram_budget() const { + return _internal_has_ram_budget(); +} +inline void AutotuneOptions::set_has_ram_budget() { + _impl_._oneof_case_[2] = kRamBudget; +} +inline void AutotuneOptions::clear_ram_budget() { + if (_internal_has_ram_budget()) { + _impl_.optional_ram_budget_.ram_budget_ = int64_t{0}; + clear_has_optional_ram_budget(); + } +} +inline int64_t AutotuneOptions::_internal_ram_budget() const { + if (_internal_has_ram_budget()) { + return _impl_.optional_ram_budget_.ram_budget_; + } + return int64_t{0}; +} +inline void AutotuneOptions::_internal_set_ram_budget(int64_t value) { + if (!_internal_has_ram_budget()) { + clear_optional_ram_budget(); + set_has_ram_budget(); + } + _impl_.optional_ram_budget_.ram_budget_ = value; +} +inline int64_t AutotuneOptions::ram_budget() const { + // @@protoc_insertion_point(field_get:tensorflow.data.AutotuneOptions.ram_budget) + return _internal_ram_budget(); +} +inline void AutotuneOptions::set_ram_budget(int64_t value) { + _internal_set_ram_budget(value); + // @@protoc_insertion_point(field_set:tensorflow.data.AutotuneOptions.ram_budget) +} + +// .tensorflow.data.model.AutotuneAlgorithm autotune_algorithm = 4; +inline bool AutotuneOptions::_internal_has_autotune_algorithm() const { + return optional_autotune_algorithm_case() == kAutotuneAlgorithm; +} +inline bool AutotuneOptions::has_autotune_algorithm() const { + return _internal_has_autotune_algorithm(); +} +inline void AutotuneOptions::set_has_autotune_algorithm() { + _impl_._oneof_case_[3] = kAutotuneAlgorithm; +} +inline void AutotuneOptions::clear_autotune_algorithm() { + if (_internal_has_autotune_algorithm()) { + _impl_.optional_autotune_algorithm_.autotune_algorithm_ = 0; + clear_has_optional_autotune_algorithm(); + } +} +inline ::tensorflow::data::model::AutotuneAlgorithm AutotuneOptions::_internal_autotune_algorithm() const { + if (_internal_has_autotune_algorithm()) { + return static_cast< ::tensorflow::data::model::AutotuneAlgorithm >(_impl_.optional_autotune_algorithm_.autotune_algorithm_); + } + return static_cast< ::tensorflow::data::model::AutotuneAlgorithm >(0); +} +inline ::tensorflow::data::model::AutotuneAlgorithm AutotuneOptions::autotune_algorithm() const { + // @@protoc_insertion_point(field_get:tensorflow.data.AutotuneOptions.autotune_algorithm) + return _internal_autotune_algorithm(); +} +inline void AutotuneOptions::_internal_set_autotune_algorithm(::tensorflow::data::model::AutotuneAlgorithm value) { + if (!_internal_has_autotune_algorithm()) { + clear_optional_autotune_algorithm(); + set_has_autotune_algorithm(); + } + _impl_.optional_autotune_algorithm_.autotune_algorithm_ = value; +} +inline void AutotuneOptions::set_autotune_algorithm(::tensorflow::data::model::AutotuneAlgorithm value) { + _internal_set_autotune_algorithm(value); + // @@protoc_insertion_point(field_set:tensorflow.data.AutotuneOptions.autotune_algorithm) +} + +inline bool AutotuneOptions::has_optional_enabled() const { + return optional_enabled_case() != OPTIONAL_ENABLED_NOT_SET; +} +inline void AutotuneOptions::clear_has_optional_enabled() { + _impl_._oneof_case_[0] = OPTIONAL_ENABLED_NOT_SET; +} +inline bool AutotuneOptions::has_optional_cpu_budget() const { + return optional_cpu_budget_case() != OPTIONAL_CPU_BUDGET_NOT_SET; +} +inline void AutotuneOptions::clear_has_optional_cpu_budget() { + _impl_._oneof_case_[1] = OPTIONAL_CPU_BUDGET_NOT_SET; +} +inline bool AutotuneOptions::has_optional_ram_budget() const { + return optional_ram_budget_case() != OPTIONAL_RAM_BUDGET_NOT_SET; +} +inline void AutotuneOptions::clear_has_optional_ram_budget() { + _impl_._oneof_case_[2] = OPTIONAL_RAM_BUDGET_NOT_SET; +} +inline bool AutotuneOptions::has_optional_autotune_algorithm() const { + return optional_autotune_algorithm_case() != OPTIONAL_AUTOTUNE_ALGORITHM_NOT_SET; +} +inline void AutotuneOptions::clear_has_optional_autotune_algorithm() { + _impl_._oneof_case_[3] = OPTIONAL_AUTOTUNE_ALGORITHM_NOT_SET; +} +inline AutotuneOptions::OptionalEnabledCase AutotuneOptions::optional_enabled_case() const { + return AutotuneOptions::OptionalEnabledCase(_impl_._oneof_case_[0]); +} +inline AutotuneOptions::OptionalCpuBudgetCase AutotuneOptions::optional_cpu_budget_case() const { + return AutotuneOptions::OptionalCpuBudgetCase(_impl_._oneof_case_[1]); +} +inline AutotuneOptions::OptionalRamBudgetCase AutotuneOptions::optional_ram_budget_case() const { + return AutotuneOptions::OptionalRamBudgetCase(_impl_._oneof_case_[2]); +} +inline AutotuneOptions::OptionalAutotuneAlgorithmCase AutotuneOptions::optional_autotune_algorithm_case() const { + return AutotuneOptions::OptionalAutotuneAlgorithmCase(_impl_._oneof_case_[3]); +} +// ------------------------------------------------------------------- + +// CardinalityOptions + +// .tensorflow.data.CardinalityOptions.ComputeLevel compute_level = 1; +inline void CardinalityOptions::clear_compute_level() { + _impl_.compute_level_ = 0; +} +inline ::tensorflow::data::CardinalityOptions_ComputeLevel CardinalityOptions::_internal_compute_level() const { + return static_cast< ::tensorflow::data::CardinalityOptions_ComputeLevel >(_impl_.compute_level_); +} +inline ::tensorflow::data::CardinalityOptions_ComputeLevel CardinalityOptions::compute_level() const { + // @@protoc_insertion_point(field_get:tensorflow.data.CardinalityOptions.compute_level) + return _internal_compute_level(); +} +inline void CardinalityOptions::_internal_set_compute_level(::tensorflow::data::CardinalityOptions_ComputeLevel value) { + + _impl_.compute_level_ = value; +} +inline void CardinalityOptions::set_compute_level(::tensorflow::data::CardinalityOptions_ComputeLevel value) { + _internal_set_compute_level(value); + // @@protoc_insertion_point(field_set:tensorflow.data.CardinalityOptions.compute_level) +} + +// ------------------------------------------------------------------- + +// DistributeOptions + +// .tensorflow.data.AutoShardPolicy auto_shard_policy = 1; +inline void DistributeOptions::clear_auto_shard_policy() { + _impl_.auto_shard_policy_ = 0; +} +inline ::tensorflow::data::AutoShardPolicy DistributeOptions::_internal_auto_shard_policy() const { + return static_cast< ::tensorflow::data::AutoShardPolicy >(_impl_.auto_shard_policy_); +} +inline ::tensorflow::data::AutoShardPolicy DistributeOptions::auto_shard_policy() const { + // @@protoc_insertion_point(field_get:tensorflow.data.DistributeOptions.auto_shard_policy) + return _internal_auto_shard_policy(); +} +inline void DistributeOptions::_internal_set_auto_shard_policy(::tensorflow::data::AutoShardPolicy value) { + + _impl_.auto_shard_policy_ = value; +} +inline void DistributeOptions::set_auto_shard_policy(::tensorflow::data::AutoShardPolicy value) { + _internal_set_auto_shard_policy(value); + // @@protoc_insertion_point(field_set:tensorflow.data.DistributeOptions.auto_shard_policy) +} + +// int32 num_devices = 2; +inline bool DistributeOptions::_internal_has_num_devices() const { + return optional_num_devices_case() == kNumDevices; +} +inline bool DistributeOptions::has_num_devices() const { + return _internal_has_num_devices(); +} +inline void DistributeOptions::set_has_num_devices() { + _impl_._oneof_case_[0] = kNumDevices; +} +inline void DistributeOptions::clear_num_devices() { + if (_internal_has_num_devices()) { + _impl_.optional_num_devices_.num_devices_ = 0; + clear_has_optional_num_devices(); + } +} +inline int32_t DistributeOptions::_internal_num_devices() const { + if (_internal_has_num_devices()) { + return _impl_.optional_num_devices_.num_devices_; + } + return 0; +} +inline void DistributeOptions::_internal_set_num_devices(int32_t value) { + if (!_internal_has_num_devices()) { + clear_optional_num_devices(); + set_has_num_devices(); + } + _impl_.optional_num_devices_.num_devices_ = value; +} +inline int32_t DistributeOptions::num_devices() const { + // @@protoc_insertion_point(field_get:tensorflow.data.DistributeOptions.num_devices) + return _internal_num_devices(); +} +inline void DistributeOptions::set_num_devices(int32_t value) { + _internal_set_num_devices(value); + // @@protoc_insertion_point(field_set:tensorflow.data.DistributeOptions.num_devices) +} + +inline bool DistributeOptions::has_optional_num_devices() const { + return optional_num_devices_case() != OPTIONAL_NUM_DEVICES_NOT_SET; +} +inline void DistributeOptions::clear_has_optional_num_devices() { + _impl_._oneof_case_[0] = OPTIONAL_NUM_DEVICES_NOT_SET; +} +inline DistributeOptions::OptionalNumDevicesCase DistributeOptions::optional_num_devices_case() const { + return DistributeOptions::OptionalNumDevicesCase(_impl_._oneof_case_[0]); +} +// ------------------------------------------------------------------- + +// OptimizationOptions + +// bool apply_default_optimizations = 1; +inline bool OptimizationOptions::_internal_has_apply_default_optimizations() const { + return optional_apply_default_optimizations_case() == kApplyDefaultOptimizations; +} +inline bool OptimizationOptions::has_apply_default_optimizations() const { + return _internal_has_apply_default_optimizations(); +} +inline void OptimizationOptions::set_has_apply_default_optimizations() { + _impl_._oneof_case_[0] = kApplyDefaultOptimizations; +} +inline void OptimizationOptions::clear_apply_default_optimizations() { + if (_internal_has_apply_default_optimizations()) { + _impl_.optional_apply_default_optimizations_.apply_default_optimizations_ = false; + clear_has_optional_apply_default_optimizations(); + } +} +inline bool OptimizationOptions::_internal_apply_default_optimizations() const { + if (_internal_has_apply_default_optimizations()) { + return _impl_.optional_apply_default_optimizations_.apply_default_optimizations_; + } + return false; +} +inline void OptimizationOptions::_internal_set_apply_default_optimizations(bool value) { + if (!_internal_has_apply_default_optimizations()) { + clear_optional_apply_default_optimizations(); + set_has_apply_default_optimizations(); + } + _impl_.optional_apply_default_optimizations_.apply_default_optimizations_ = value; +} +inline bool OptimizationOptions::apply_default_optimizations() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.apply_default_optimizations) + return _internal_apply_default_optimizations(); +} +inline void OptimizationOptions::set_apply_default_optimizations(bool value) { + _internal_set_apply_default_optimizations(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.apply_default_optimizations) +} + +// bool filter_fusion = 6; +inline bool OptimizationOptions::_internal_has_filter_fusion() const { + return optional_filter_fusion_case() == kFilterFusion; +} +inline bool OptimizationOptions::has_filter_fusion() const { + return _internal_has_filter_fusion(); +} +inline void OptimizationOptions::set_has_filter_fusion() { + _impl_._oneof_case_[1] = kFilterFusion; +} +inline void OptimizationOptions::clear_filter_fusion() { + if (_internal_has_filter_fusion()) { + _impl_.optional_filter_fusion_.filter_fusion_ = false; + clear_has_optional_filter_fusion(); + } +} +inline bool OptimizationOptions::_internal_filter_fusion() const { + if (_internal_has_filter_fusion()) { + return _impl_.optional_filter_fusion_.filter_fusion_; + } + return false; +} +inline void OptimizationOptions::_internal_set_filter_fusion(bool value) { + if (!_internal_has_filter_fusion()) { + clear_optional_filter_fusion(); + set_has_filter_fusion(); + } + _impl_.optional_filter_fusion_.filter_fusion_ = value; +} +inline bool OptimizationOptions::filter_fusion() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.filter_fusion) + return _internal_filter_fusion(); +} +inline void OptimizationOptions::set_filter_fusion(bool value) { + _internal_set_filter_fusion(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.filter_fusion) +} + +// bool map_and_batch_fusion = 9; +inline bool OptimizationOptions::_internal_has_map_and_batch_fusion() const { + return optional_map_and_batch_fusion_case() == kMapAndBatchFusion; +} +inline bool OptimizationOptions::has_map_and_batch_fusion() const { + return _internal_has_map_and_batch_fusion(); +} +inline void OptimizationOptions::set_has_map_and_batch_fusion() { + _impl_._oneof_case_[2] = kMapAndBatchFusion; +} +inline void OptimizationOptions::clear_map_and_batch_fusion() { + if (_internal_has_map_and_batch_fusion()) { + _impl_.optional_map_and_batch_fusion_.map_and_batch_fusion_ = false; + clear_has_optional_map_and_batch_fusion(); + } +} +inline bool OptimizationOptions::_internal_map_and_batch_fusion() const { + if (_internal_has_map_and_batch_fusion()) { + return _impl_.optional_map_and_batch_fusion_.map_and_batch_fusion_; + } + return false; +} +inline void OptimizationOptions::_internal_set_map_and_batch_fusion(bool value) { + if (!_internal_has_map_and_batch_fusion()) { + clear_optional_map_and_batch_fusion(); + set_has_map_and_batch_fusion(); + } + _impl_.optional_map_and_batch_fusion_.map_and_batch_fusion_ = value; +} +inline bool OptimizationOptions::map_and_batch_fusion() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.map_and_batch_fusion) + return _internal_map_and_batch_fusion(); +} +inline void OptimizationOptions::set_map_and_batch_fusion(bool value) { + _internal_set_map_and_batch_fusion(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.map_and_batch_fusion) +} + +// bool map_and_filter_fusion = 10; +inline bool OptimizationOptions::_internal_has_map_and_filter_fusion() const { + return optional_map_and_filter_fusion_case() == kMapAndFilterFusion; +} +inline bool OptimizationOptions::has_map_and_filter_fusion() const { + return _internal_has_map_and_filter_fusion(); +} +inline void OptimizationOptions::set_has_map_and_filter_fusion() { + _impl_._oneof_case_[3] = kMapAndFilterFusion; +} +inline void OptimizationOptions::clear_map_and_filter_fusion() { + if (_internal_has_map_and_filter_fusion()) { + _impl_.optional_map_and_filter_fusion_.map_and_filter_fusion_ = false; + clear_has_optional_map_and_filter_fusion(); + } +} +inline bool OptimizationOptions::_internal_map_and_filter_fusion() const { + if (_internal_has_map_and_filter_fusion()) { + return _impl_.optional_map_and_filter_fusion_.map_and_filter_fusion_; + } + return false; +} +inline void OptimizationOptions::_internal_set_map_and_filter_fusion(bool value) { + if (!_internal_has_map_and_filter_fusion()) { + clear_optional_map_and_filter_fusion(); + set_has_map_and_filter_fusion(); + } + _impl_.optional_map_and_filter_fusion_.map_and_filter_fusion_ = value; +} +inline bool OptimizationOptions::map_and_filter_fusion() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.map_and_filter_fusion) + return _internal_map_and_filter_fusion(); +} +inline void OptimizationOptions::set_map_and_filter_fusion(bool value) { + _internal_set_map_and_filter_fusion(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.map_and_filter_fusion) +} + +// bool map_fusion = 11; +inline bool OptimizationOptions::_internal_has_map_fusion() const { + return optional_map_fusion_case() == kMapFusion; +} +inline bool OptimizationOptions::has_map_fusion() const { + return _internal_has_map_fusion(); +} +inline void OptimizationOptions::set_has_map_fusion() { + _impl_._oneof_case_[4] = kMapFusion; +} +inline void OptimizationOptions::clear_map_fusion() { + if (_internal_has_map_fusion()) { + _impl_.optional_map_fusion_.map_fusion_ = false; + clear_has_optional_map_fusion(); + } +} +inline bool OptimizationOptions::_internal_map_fusion() const { + if (_internal_has_map_fusion()) { + return _impl_.optional_map_fusion_.map_fusion_; + } + return false; +} +inline void OptimizationOptions::_internal_set_map_fusion(bool value) { + if (!_internal_has_map_fusion()) { + clear_optional_map_fusion(); + set_has_map_fusion(); + } + _impl_.optional_map_fusion_.map_fusion_ = value; +} +inline bool OptimizationOptions::map_fusion() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.map_fusion) + return _internal_map_fusion(); +} +inline void OptimizationOptions::set_map_fusion(bool value) { + _internal_set_map_fusion(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.map_fusion) +} + +// bool map_parallelization = 12; +inline bool OptimizationOptions::_internal_has_map_parallelization() const { + return optional_map_parallelization_case() == kMapParallelization; +} +inline bool OptimizationOptions::has_map_parallelization() const { + return _internal_has_map_parallelization(); +} +inline void OptimizationOptions::set_has_map_parallelization() { + _impl_._oneof_case_[5] = kMapParallelization; +} +inline void OptimizationOptions::clear_map_parallelization() { + if (_internal_has_map_parallelization()) { + _impl_.optional_map_parallelization_.map_parallelization_ = false; + clear_has_optional_map_parallelization(); + } +} +inline bool OptimizationOptions::_internal_map_parallelization() const { + if (_internal_has_map_parallelization()) { + return _impl_.optional_map_parallelization_.map_parallelization_; + } + return false; +} +inline void OptimizationOptions::_internal_set_map_parallelization(bool value) { + if (!_internal_has_map_parallelization()) { + clear_optional_map_parallelization(); + set_has_map_parallelization(); + } + _impl_.optional_map_parallelization_.map_parallelization_ = value; +} +inline bool OptimizationOptions::map_parallelization() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.map_parallelization) + return _internal_map_parallelization(); +} +inline void OptimizationOptions::set_map_parallelization(bool value) { + _internal_set_map_parallelization(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.map_parallelization) +} + +// bool noop_elimination = 14; +inline bool OptimizationOptions::_internal_has_noop_elimination() const { + return optional_noop_elimination_case() == kNoopElimination; +} +inline bool OptimizationOptions::has_noop_elimination() const { + return _internal_has_noop_elimination(); +} +inline void OptimizationOptions::set_has_noop_elimination() { + _impl_._oneof_case_[6] = kNoopElimination; +} +inline void OptimizationOptions::clear_noop_elimination() { + if (_internal_has_noop_elimination()) { + _impl_.optional_noop_elimination_.noop_elimination_ = false; + clear_has_optional_noop_elimination(); + } +} +inline bool OptimizationOptions::_internal_noop_elimination() const { + if (_internal_has_noop_elimination()) { + return _impl_.optional_noop_elimination_.noop_elimination_; + } + return false; +} +inline void OptimizationOptions::_internal_set_noop_elimination(bool value) { + if (!_internal_has_noop_elimination()) { + clear_optional_noop_elimination(); + set_has_noop_elimination(); + } + _impl_.optional_noop_elimination_.noop_elimination_ = value; +} +inline bool OptimizationOptions::noop_elimination() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.noop_elimination) + return _internal_noop_elimination(); +} +inline void OptimizationOptions::set_noop_elimination(bool value) { + _internal_set_noop_elimination(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.noop_elimination) +} + +// bool parallel_batch = 15; +inline bool OptimizationOptions::_internal_has_parallel_batch() const { + return optional_parallel_batch_case() == kParallelBatch; +} +inline bool OptimizationOptions::has_parallel_batch() const { + return _internal_has_parallel_batch(); +} +inline void OptimizationOptions::set_has_parallel_batch() { + _impl_._oneof_case_[7] = kParallelBatch; +} +inline void OptimizationOptions::clear_parallel_batch() { + if (_internal_has_parallel_batch()) { + _impl_.optional_parallel_batch_.parallel_batch_ = false; + clear_has_optional_parallel_batch(); + } +} +inline bool OptimizationOptions::_internal_parallel_batch() const { + if (_internal_has_parallel_batch()) { + return _impl_.optional_parallel_batch_.parallel_batch_; + } + return false; +} +inline void OptimizationOptions::_internal_set_parallel_batch(bool value) { + if (!_internal_has_parallel_batch()) { + clear_optional_parallel_batch(); + set_has_parallel_batch(); + } + _impl_.optional_parallel_batch_.parallel_batch_ = value; +} +inline bool OptimizationOptions::parallel_batch() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.parallel_batch) + return _internal_parallel_batch(); +} +inline void OptimizationOptions::set_parallel_batch(bool value) { + _internal_set_parallel_batch(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.parallel_batch) +} + +// bool shuffle_and_repeat_fusion = 17; +inline bool OptimizationOptions::_internal_has_shuffle_and_repeat_fusion() const { + return optional_shuffle_and_repeat_fusion_case() == kShuffleAndRepeatFusion; +} +inline bool OptimizationOptions::has_shuffle_and_repeat_fusion() const { + return _internal_has_shuffle_and_repeat_fusion(); +} +inline void OptimizationOptions::set_has_shuffle_and_repeat_fusion() { + _impl_._oneof_case_[8] = kShuffleAndRepeatFusion; +} +inline void OptimizationOptions::clear_shuffle_and_repeat_fusion() { + if (_internal_has_shuffle_and_repeat_fusion()) { + _impl_.optional_shuffle_and_repeat_fusion_.shuffle_and_repeat_fusion_ = false; + clear_has_optional_shuffle_and_repeat_fusion(); + } +} +inline bool OptimizationOptions::_internal_shuffle_and_repeat_fusion() const { + if (_internal_has_shuffle_and_repeat_fusion()) { + return _impl_.optional_shuffle_and_repeat_fusion_.shuffle_and_repeat_fusion_; + } + return false; +} +inline void OptimizationOptions::_internal_set_shuffle_and_repeat_fusion(bool value) { + if (!_internal_has_shuffle_and_repeat_fusion()) { + clear_optional_shuffle_and_repeat_fusion(); + set_has_shuffle_and_repeat_fusion(); + } + _impl_.optional_shuffle_and_repeat_fusion_.shuffle_and_repeat_fusion_ = value; +} +inline bool OptimizationOptions::shuffle_and_repeat_fusion() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.shuffle_and_repeat_fusion) + return _internal_shuffle_and_repeat_fusion(); +} +inline void OptimizationOptions::set_shuffle_and_repeat_fusion(bool value) { + _internal_set_shuffle_and_repeat_fusion(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.shuffle_and_repeat_fusion) +} + +// bool filter_parallelization = 18; +inline bool OptimizationOptions::_internal_has_filter_parallelization() const { + return optional_filter_parallelization_case() == kFilterParallelization; +} +inline bool OptimizationOptions::has_filter_parallelization() const { + return _internal_has_filter_parallelization(); +} +inline void OptimizationOptions::set_has_filter_parallelization() { + _impl_._oneof_case_[9] = kFilterParallelization; +} +inline void OptimizationOptions::clear_filter_parallelization() { + if (_internal_has_filter_parallelization()) { + _impl_.optional_filter_parallelization_.filter_parallelization_ = false; + clear_has_optional_filter_parallelization(); + } +} +inline bool OptimizationOptions::_internal_filter_parallelization() const { + if (_internal_has_filter_parallelization()) { + return _impl_.optional_filter_parallelization_.filter_parallelization_; + } + return false; +} +inline void OptimizationOptions::_internal_set_filter_parallelization(bool value) { + if (!_internal_has_filter_parallelization()) { + clear_optional_filter_parallelization(); + set_has_filter_parallelization(); + } + _impl_.optional_filter_parallelization_.filter_parallelization_ = value; +} +inline bool OptimizationOptions::filter_parallelization() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.filter_parallelization) + return _internal_filter_parallelization(); +} +inline void OptimizationOptions::set_filter_parallelization(bool value) { + _internal_set_filter_parallelization(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.filter_parallelization) +} + +// bool inject_prefetch = 19; +inline bool OptimizationOptions::_internal_has_inject_prefetch() const { + return optional_inject_prefetch_case() == kInjectPrefetch; +} +inline bool OptimizationOptions::has_inject_prefetch() const { + return _internal_has_inject_prefetch(); +} +inline void OptimizationOptions::set_has_inject_prefetch() { + _impl_._oneof_case_[10] = kInjectPrefetch; +} +inline void OptimizationOptions::clear_inject_prefetch() { + if (_internal_has_inject_prefetch()) { + _impl_.optional_inject_prefetch_.inject_prefetch_ = false; + clear_has_optional_inject_prefetch(); + } +} +inline bool OptimizationOptions::_internal_inject_prefetch() const { + if (_internal_has_inject_prefetch()) { + return _impl_.optional_inject_prefetch_.inject_prefetch_; + } + return false; +} +inline void OptimizationOptions::_internal_set_inject_prefetch(bool value) { + if (!_internal_has_inject_prefetch()) { + clear_optional_inject_prefetch(); + set_has_inject_prefetch(); + } + _impl_.optional_inject_prefetch_.inject_prefetch_ = value; +} +inline bool OptimizationOptions::inject_prefetch() const { + // @@protoc_insertion_point(field_get:tensorflow.data.OptimizationOptions.inject_prefetch) + return _internal_inject_prefetch(); +} +inline void OptimizationOptions::set_inject_prefetch(bool value) { + _internal_set_inject_prefetch(value); + // @@protoc_insertion_point(field_set:tensorflow.data.OptimizationOptions.inject_prefetch) +} + +inline bool OptimizationOptions::has_optional_apply_default_optimizations() const { + return optional_apply_default_optimizations_case() != OPTIONAL_APPLY_DEFAULT_OPTIMIZATIONS_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_apply_default_optimizations() { + _impl_._oneof_case_[0] = OPTIONAL_APPLY_DEFAULT_OPTIMIZATIONS_NOT_SET; +} +inline bool OptimizationOptions::has_optional_filter_fusion() const { + return optional_filter_fusion_case() != OPTIONAL_FILTER_FUSION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_filter_fusion() { + _impl_._oneof_case_[1] = OPTIONAL_FILTER_FUSION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_map_and_batch_fusion() const { + return optional_map_and_batch_fusion_case() != OPTIONAL_MAP_AND_BATCH_FUSION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_map_and_batch_fusion() { + _impl_._oneof_case_[2] = OPTIONAL_MAP_AND_BATCH_FUSION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_map_and_filter_fusion() const { + return optional_map_and_filter_fusion_case() != OPTIONAL_MAP_AND_FILTER_FUSION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_map_and_filter_fusion() { + _impl_._oneof_case_[3] = OPTIONAL_MAP_AND_FILTER_FUSION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_map_fusion() const { + return optional_map_fusion_case() != OPTIONAL_MAP_FUSION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_map_fusion() { + _impl_._oneof_case_[4] = OPTIONAL_MAP_FUSION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_map_parallelization() const { + return optional_map_parallelization_case() != OPTIONAL_MAP_PARALLELIZATION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_map_parallelization() { + _impl_._oneof_case_[5] = OPTIONAL_MAP_PARALLELIZATION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_noop_elimination() const { + return optional_noop_elimination_case() != OPTIONAL_NOOP_ELIMINATION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_noop_elimination() { + _impl_._oneof_case_[6] = OPTIONAL_NOOP_ELIMINATION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_parallel_batch() const { + return optional_parallel_batch_case() != OPTIONAL_PARALLEL_BATCH_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_parallel_batch() { + _impl_._oneof_case_[7] = OPTIONAL_PARALLEL_BATCH_NOT_SET; +} +inline bool OptimizationOptions::has_optional_shuffle_and_repeat_fusion() const { + return optional_shuffle_and_repeat_fusion_case() != OPTIONAL_SHUFFLE_AND_REPEAT_FUSION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_shuffle_and_repeat_fusion() { + _impl_._oneof_case_[8] = OPTIONAL_SHUFFLE_AND_REPEAT_FUSION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_filter_parallelization() const { + return optional_filter_parallelization_case() != OPTIONAL_FILTER_PARALLELIZATION_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_filter_parallelization() { + _impl_._oneof_case_[9] = OPTIONAL_FILTER_PARALLELIZATION_NOT_SET; +} +inline bool OptimizationOptions::has_optional_inject_prefetch() const { + return optional_inject_prefetch_case() != OPTIONAL_INJECT_PREFETCH_NOT_SET; +} +inline void OptimizationOptions::clear_has_optional_inject_prefetch() { + _impl_._oneof_case_[10] = OPTIONAL_INJECT_PREFETCH_NOT_SET; +} +inline OptimizationOptions::OptionalApplyDefaultOptimizationsCase OptimizationOptions::optional_apply_default_optimizations_case() const { + return OptimizationOptions::OptionalApplyDefaultOptimizationsCase(_impl_._oneof_case_[0]); +} +inline OptimizationOptions::OptionalFilterFusionCase OptimizationOptions::optional_filter_fusion_case() const { + return OptimizationOptions::OptionalFilterFusionCase(_impl_._oneof_case_[1]); +} +inline OptimizationOptions::OptionalMapAndBatchFusionCase OptimizationOptions::optional_map_and_batch_fusion_case() const { + return OptimizationOptions::OptionalMapAndBatchFusionCase(_impl_._oneof_case_[2]); +} +inline OptimizationOptions::OptionalMapAndFilterFusionCase OptimizationOptions::optional_map_and_filter_fusion_case() const { + return OptimizationOptions::OptionalMapAndFilterFusionCase(_impl_._oneof_case_[3]); +} +inline OptimizationOptions::OptionalMapFusionCase OptimizationOptions::optional_map_fusion_case() const { + return OptimizationOptions::OptionalMapFusionCase(_impl_._oneof_case_[4]); +} +inline OptimizationOptions::OptionalMapParallelizationCase OptimizationOptions::optional_map_parallelization_case() const { + return OptimizationOptions::OptionalMapParallelizationCase(_impl_._oneof_case_[5]); +} +inline OptimizationOptions::OptionalNoopEliminationCase OptimizationOptions::optional_noop_elimination_case() const { + return OptimizationOptions::OptionalNoopEliminationCase(_impl_._oneof_case_[6]); +} +inline OptimizationOptions::OptionalParallelBatchCase OptimizationOptions::optional_parallel_batch_case() const { + return OptimizationOptions::OptionalParallelBatchCase(_impl_._oneof_case_[7]); +} +inline OptimizationOptions::OptionalShuffleAndRepeatFusionCase OptimizationOptions::optional_shuffle_and_repeat_fusion_case() const { + return OptimizationOptions::OptionalShuffleAndRepeatFusionCase(_impl_._oneof_case_[8]); +} +inline OptimizationOptions::OptionalFilterParallelizationCase OptimizationOptions::optional_filter_parallelization_case() const { + return OptimizationOptions::OptionalFilterParallelizationCase(_impl_._oneof_case_[9]); +} +inline OptimizationOptions::OptionalInjectPrefetchCase OptimizationOptions::optional_inject_prefetch_case() const { + return OptimizationOptions::OptionalInjectPrefetchCase(_impl_._oneof_case_[10]); +} +// ------------------------------------------------------------------- + +// ThreadingOptions + +// int32 max_intra_op_parallelism = 1; +inline bool ThreadingOptions::_internal_has_max_intra_op_parallelism() const { + return optional_max_intra_op_parallelism_case() == kMaxIntraOpParallelism; +} +inline bool ThreadingOptions::has_max_intra_op_parallelism() const { + return _internal_has_max_intra_op_parallelism(); +} +inline void ThreadingOptions::set_has_max_intra_op_parallelism() { + _impl_._oneof_case_[0] = kMaxIntraOpParallelism; +} +inline void ThreadingOptions::clear_max_intra_op_parallelism() { + if (_internal_has_max_intra_op_parallelism()) { + _impl_.optional_max_intra_op_parallelism_.max_intra_op_parallelism_ = 0; + clear_has_optional_max_intra_op_parallelism(); + } +} +inline int32_t ThreadingOptions::_internal_max_intra_op_parallelism() const { + if (_internal_has_max_intra_op_parallelism()) { + return _impl_.optional_max_intra_op_parallelism_.max_intra_op_parallelism_; + } + return 0; +} +inline void ThreadingOptions::_internal_set_max_intra_op_parallelism(int32_t value) { + if (!_internal_has_max_intra_op_parallelism()) { + clear_optional_max_intra_op_parallelism(); + set_has_max_intra_op_parallelism(); + } + _impl_.optional_max_intra_op_parallelism_.max_intra_op_parallelism_ = value; +} +inline int32_t ThreadingOptions::max_intra_op_parallelism() const { + // @@protoc_insertion_point(field_get:tensorflow.data.ThreadingOptions.max_intra_op_parallelism) + return _internal_max_intra_op_parallelism(); +} +inline void ThreadingOptions::set_max_intra_op_parallelism(int32_t value) { + _internal_set_max_intra_op_parallelism(value); + // @@protoc_insertion_point(field_set:tensorflow.data.ThreadingOptions.max_intra_op_parallelism) +} + +// int32 private_threadpool_size = 2; +inline bool ThreadingOptions::_internal_has_private_threadpool_size() const { + return optional_private_threadpool_size_case() == kPrivateThreadpoolSize; +} +inline bool ThreadingOptions::has_private_threadpool_size() const { + return _internal_has_private_threadpool_size(); +} +inline void ThreadingOptions::set_has_private_threadpool_size() { + _impl_._oneof_case_[1] = kPrivateThreadpoolSize; +} +inline void ThreadingOptions::clear_private_threadpool_size() { + if (_internal_has_private_threadpool_size()) { + _impl_.optional_private_threadpool_size_.private_threadpool_size_ = 0; + clear_has_optional_private_threadpool_size(); + } +} +inline int32_t ThreadingOptions::_internal_private_threadpool_size() const { + if (_internal_has_private_threadpool_size()) { + return _impl_.optional_private_threadpool_size_.private_threadpool_size_; + } + return 0; +} +inline void ThreadingOptions::_internal_set_private_threadpool_size(int32_t value) { + if (!_internal_has_private_threadpool_size()) { + clear_optional_private_threadpool_size(); + set_has_private_threadpool_size(); + } + _impl_.optional_private_threadpool_size_.private_threadpool_size_ = value; +} +inline int32_t ThreadingOptions::private_threadpool_size() const { + // @@protoc_insertion_point(field_get:tensorflow.data.ThreadingOptions.private_threadpool_size) + return _internal_private_threadpool_size(); +} +inline void ThreadingOptions::set_private_threadpool_size(int32_t value) { + _internal_set_private_threadpool_size(value); + // @@protoc_insertion_point(field_set:tensorflow.data.ThreadingOptions.private_threadpool_size) +} + +inline bool ThreadingOptions::has_optional_max_intra_op_parallelism() const { + return optional_max_intra_op_parallelism_case() != OPTIONAL_MAX_INTRA_OP_PARALLELISM_NOT_SET; +} +inline void ThreadingOptions::clear_has_optional_max_intra_op_parallelism() { + _impl_._oneof_case_[0] = OPTIONAL_MAX_INTRA_OP_PARALLELISM_NOT_SET; +} +inline bool ThreadingOptions::has_optional_private_threadpool_size() const { + return optional_private_threadpool_size_case() != OPTIONAL_PRIVATE_THREADPOOL_SIZE_NOT_SET; +} +inline void ThreadingOptions::clear_has_optional_private_threadpool_size() { + _impl_._oneof_case_[1] = OPTIONAL_PRIVATE_THREADPOOL_SIZE_NOT_SET; +} +inline ThreadingOptions::OptionalMaxIntraOpParallelismCase ThreadingOptions::optional_max_intra_op_parallelism_case() const { + return ThreadingOptions::OptionalMaxIntraOpParallelismCase(_impl_._oneof_case_[0]); +} +inline ThreadingOptions::OptionalPrivateThreadpoolSizeCase ThreadingOptions::optional_private_threadpool_size_case() const { + return ThreadingOptions::OptionalPrivateThreadpoolSizeCase(_impl_._oneof_case_[1]); +} +// ------------------------------------------------------------------- + +// Options + +// bool deterministic = 1; +inline bool Options::_internal_has_deterministic() const { + return optional_deterministic_case() == kDeterministic; +} +inline bool Options::has_deterministic() const { + return _internal_has_deterministic(); +} +inline void Options::set_has_deterministic() { + _impl_._oneof_case_[0] = kDeterministic; +} +inline void Options::clear_deterministic() { + if (_internal_has_deterministic()) { + _impl_.optional_deterministic_.deterministic_ = false; + clear_has_optional_deterministic(); + } +} +inline bool Options::_internal_deterministic() const { + if (_internal_has_deterministic()) { + return _impl_.optional_deterministic_.deterministic_; + } + return false; +} +inline void Options::_internal_set_deterministic(bool value) { + if (!_internal_has_deterministic()) { + clear_optional_deterministic(); + set_has_deterministic(); + } + _impl_.optional_deterministic_.deterministic_ = value; +} +inline bool Options::deterministic() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.deterministic) + return _internal_deterministic(); +} +inline void Options::set_deterministic(bool value) { + _internal_set_deterministic(value); + // @@protoc_insertion_point(field_set:tensorflow.data.Options.deterministic) +} + +// .tensorflow.data.AutotuneOptions autotune_options = 7; +inline bool Options::_internal_has_autotune_options() const { + return this != internal_default_instance() && _impl_.autotune_options_ != nullptr; +} +inline bool Options::has_autotune_options() const { + return _internal_has_autotune_options(); +} +inline void Options::clear_autotune_options() { + if (GetArenaForAllocation() == nullptr && _impl_.autotune_options_ != nullptr) { + delete _impl_.autotune_options_; + } + _impl_.autotune_options_ = nullptr; +} +inline const ::tensorflow::data::AutotuneOptions& Options::_internal_autotune_options() const { + const ::tensorflow::data::AutotuneOptions* p = _impl_.autotune_options_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::data::_AutotuneOptions_default_instance_); +} +inline const ::tensorflow::data::AutotuneOptions& Options::autotune_options() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.autotune_options) + return _internal_autotune_options(); +} +inline void Options::unsafe_arena_set_allocated_autotune_options( + ::tensorflow::data::AutotuneOptions* autotune_options) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.autotune_options_); + } + _impl_.autotune_options_ = autotune_options; + if (autotune_options) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.data.Options.autotune_options) +} +inline ::tensorflow::data::AutotuneOptions* Options::release_autotune_options() { + + ::tensorflow::data::AutotuneOptions* temp = _impl_.autotune_options_; + _impl_.autotune_options_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::data::AutotuneOptions* Options::unsafe_arena_release_autotune_options() { + // @@protoc_insertion_point(field_release:tensorflow.data.Options.autotune_options) + + ::tensorflow::data::AutotuneOptions* temp = _impl_.autotune_options_; + _impl_.autotune_options_ = nullptr; + return temp; +} +inline ::tensorflow::data::AutotuneOptions* Options::_internal_mutable_autotune_options() { + + if (_impl_.autotune_options_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::data::AutotuneOptions>(GetArenaForAllocation()); + _impl_.autotune_options_ = p; + } + return _impl_.autotune_options_; +} +inline ::tensorflow::data::AutotuneOptions* Options::mutable_autotune_options() { + ::tensorflow::data::AutotuneOptions* _msg = _internal_mutable_autotune_options(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.Options.autotune_options) + return _msg; +} +inline void Options::set_allocated_autotune_options(::tensorflow::data::AutotuneOptions* autotune_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.autotune_options_; + } + if (autotune_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(autotune_options); + if (message_arena != submessage_arena) { + autotune_options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, autotune_options, submessage_arena); + } + + } else { + + } + _impl_.autotune_options_ = autotune_options; + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.Options.autotune_options) +} + +// .tensorflow.data.DistributeOptions distribute_options = 2; +inline bool Options::_internal_has_distribute_options() const { + return this != internal_default_instance() && _impl_.distribute_options_ != nullptr; +} +inline bool Options::has_distribute_options() const { + return _internal_has_distribute_options(); +} +inline void Options::clear_distribute_options() { + if (GetArenaForAllocation() == nullptr && _impl_.distribute_options_ != nullptr) { + delete _impl_.distribute_options_; + } + _impl_.distribute_options_ = nullptr; +} +inline const ::tensorflow::data::DistributeOptions& Options::_internal_distribute_options() const { + const ::tensorflow::data::DistributeOptions* p = _impl_.distribute_options_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::data::_DistributeOptions_default_instance_); +} +inline const ::tensorflow::data::DistributeOptions& Options::distribute_options() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.distribute_options) + return _internal_distribute_options(); +} +inline void Options::unsafe_arena_set_allocated_distribute_options( + ::tensorflow::data::DistributeOptions* distribute_options) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.distribute_options_); + } + _impl_.distribute_options_ = distribute_options; + if (distribute_options) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.data.Options.distribute_options) +} +inline ::tensorflow::data::DistributeOptions* Options::release_distribute_options() { + + ::tensorflow::data::DistributeOptions* temp = _impl_.distribute_options_; + _impl_.distribute_options_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::data::DistributeOptions* Options::unsafe_arena_release_distribute_options() { + // @@protoc_insertion_point(field_release:tensorflow.data.Options.distribute_options) + + ::tensorflow::data::DistributeOptions* temp = _impl_.distribute_options_; + _impl_.distribute_options_ = nullptr; + return temp; +} +inline ::tensorflow::data::DistributeOptions* Options::_internal_mutable_distribute_options() { + + if (_impl_.distribute_options_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::data::DistributeOptions>(GetArenaForAllocation()); + _impl_.distribute_options_ = p; + } + return _impl_.distribute_options_; +} +inline ::tensorflow::data::DistributeOptions* Options::mutable_distribute_options() { + ::tensorflow::data::DistributeOptions* _msg = _internal_mutable_distribute_options(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.Options.distribute_options) + return _msg; +} +inline void Options::set_allocated_distribute_options(::tensorflow::data::DistributeOptions* distribute_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.distribute_options_; + } + if (distribute_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(distribute_options); + if (message_arena != submessage_arena) { + distribute_options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, distribute_options, submessage_arena); + } + + } else { + + } + _impl_.distribute_options_ = distribute_options; + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.Options.distribute_options) +} + +// .tensorflow.data.OptimizationOptions optimization_options = 3; +inline bool Options::_internal_has_optimization_options() const { + return this != internal_default_instance() && _impl_.optimization_options_ != nullptr; +} +inline bool Options::has_optimization_options() const { + return _internal_has_optimization_options(); +} +inline void Options::clear_optimization_options() { + if (GetArenaForAllocation() == nullptr && _impl_.optimization_options_ != nullptr) { + delete _impl_.optimization_options_; + } + _impl_.optimization_options_ = nullptr; +} +inline const ::tensorflow::data::OptimizationOptions& Options::_internal_optimization_options() const { + const ::tensorflow::data::OptimizationOptions* p = _impl_.optimization_options_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::data::_OptimizationOptions_default_instance_); +} +inline const ::tensorflow::data::OptimizationOptions& Options::optimization_options() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.optimization_options) + return _internal_optimization_options(); +} +inline void Options::unsafe_arena_set_allocated_optimization_options( + ::tensorflow::data::OptimizationOptions* optimization_options) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.optimization_options_); + } + _impl_.optimization_options_ = optimization_options; + if (optimization_options) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.data.Options.optimization_options) +} +inline ::tensorflow::data::OptimizationOptions* Options::release_optimization_options() { + + ::tensorflow::data::OptimizationOptions* temp = _impl_.optimization_options_; + _impl_.optimization_options_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::data::OptimizationOptions* Options::unsafe_arena_release_optimization_options() { + // @@protoc_insertion_point(field_release:tensorflow.data.Options.optimization_options) + + ::tensorflow::data::OptimizationOptions* temp = _impl_.optimization_options_; + _impl_.optimization_options_ = nullptr; + return temp; +} +inline ::tensorflow::data::OptimizationOptions* Options::_internal_mutable_optimization_options() { + + if (_impl_.optimization_options_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::data::OptimizationOptions>(GetArenaForAllocation()); + _impl_.optimization_options_ = p; + } + return _impl_.optimization_options_; +} +inline ::tensorflow::data::OptimizationOptions* Options::mutable_optimization_options() { + ::tensorflow::data::OptimizationOptions* _msg = _internal_mutable_optimization_options(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.Options.optimization_options) + return _msg; +} +inline void Options::set_allocated_optimization_options(::tensorflow::data::OptimizationOptions* optimization_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.optimization_options_; + } + if (optimization_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(optimization_options); + if (message_arena != submessage_arena) { + optimization_options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, optimization_options, submessage_arena); + } + + } else { + + } + _impl_.optimization_options_ = optimization_options; + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.Options.optimization_options) +} + +// bool slack = 4; +inline bool Options::_internal_has_slack() const { + return optional_slack_case() == kSlack; +} +inline bool Options::has_slack() const { + return _internal_has_slack(); +} +inline void Options::set_has_slack() { + _impl_._oneof_case_[1] = kSlack; +} +inline void Options::clear_slack() { + if (_internal_has_slack()) { + _impl_.optional_slack_.slack_ = false; + clear_has_optional_slack(); + } +} +inline bool Options::_internal_slack() const { + if (_internal_has_slack()) { + return _impl_.optional_slack_.slack_; + } + return false; +} +inline void Options::_internal_set_slack(bool value) { + if (!_internal_has_slack()) { + clear_optional_slack(); + set_has_slack(); + } + _impl_.optional_slack_.slack_ = value; +} +inline bool Options::slack() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.slack) + return _internal_slack(); +} +inline void Options::set_slack(bool value) { + _internal_set_slack(value); + // @@protoc_insertion_point(field_set:tensorflow.data.Options.slack) +} + +// .tensorflow.data.ThreadingOptions threading_options = 5; +inline bool Options::_internal_has_threading_options() const { + return this != internal_default_instance() && _impl_.threading_options_ != nullptr; +} +inline bool Options::has_threading_options() const { + return _internal_has_threading_options(); +} +inline void Options::clear_threading_options() { + if (GetArenaForAllocation() == nullptr && _impl_.threading_options_ != nullptr) { + delete _impl_.threading_options_; + } + _impl_.threading_options_ = nullptr; +} +inline const ::tensorflow::data::ThreadingOptions& Options::_internal_threading_options() const { + const ::tensorflow::data::ThreadingOptions* p = _impl_.threading_options_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::data::_ThreadingOptions_default_instance_); +} +inline const ::tensorflow::data::ThreadingOptions& Options::threading_options() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.threading_options) + return _internal_threading_options(); +} +inline void Options::unsafe_arena_set_allocated_threading_options( + ::tensorflow::data::ThreadingOptions* threading_options) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.threading_options_); + } + _impl_.threading_options_ = threading_options; + if (threading_options) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.data.Options.threading_options) +} +inline ::tensorflow::data::ThreadingOptions* Options::release_threading_options() { + + ::tensorflow::data::ThreadingOptions* temp = _impl_.threading_options_; + _impl_.threading_options_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::tensorflow::data::ThreadingOptions* Options::unsafe_arena_release_threading_options() { + // @@protoc_insertion_point(field_release:tensorflow.data.Options.threading_options) + + ::tensorflow::data::ThreadingOptions* temp = _impl_.threading_options_; + _impl_.threading_options_ = nullptr; + return temp; +} +inline ::tensorflow::data::ThreadingOptions* Options::_internal_mutable_threading_options() { + + if (_impl_.threading_options_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::data::ThreadingOptions>(GetArenaForAllocation()); + _impl_.threading_options_ = p; + } + return _impl_.threading_options_; +} +inline ::tensorflow::data::ThreadingOptions* Options::mutable_threading_options() { + ::tensorflow::data::ThreadingOptions* _msg = _internal_mutable_threading_options(); + // @@protoc_insertion_point(field_mutable:tensorflow.data.Options.threading_options) + return _msg; +} +inline void Options::set_allocated_threading_options(::tensorflow::data::ThreadingOptions* threading_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.threading_options_; + } + if (threading_options) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(threading_options); + if (message_arena != submessage_arena) { + threading_options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, threading_options, submessage_arena); + } + + } else { + + } + _impl_.threading_options_ = threading_options; + // @@protoc_insertion_point(field_set_allocated:tensorflow.data.Options.threading_options) +} + +// .tensorflow.data.ExternalStatePolicy external_state_policy = 6; +inline bool Options::_internal_has_external_state_policy() const { + return optional_external_state_policy_case() == kExternalStatePolicy; +} +inline bool Options::has_external_state_policy() const { + return _internal_has_external_state_policy(); +} +inline void Options::set_has_external_state_policy() { + _impl_._oneof_case_[2] = kExternalStatePolicy; +} +inline void Options::clear_external_state_policy() { + if (_internal_has_external_state_policy()) { + _impl_.optional_external_state_policy_.external_state_policy_ = 0; + clear_has_optional_external_state_policy(); + } +} +inline ::tensorflow::data::ExternalStatePolicy Options::_internal_external_state_policy() const { + if (_internal_has_external_state_policy()) { + return static_cast< ::tensorflow::data::ExternalStatePolicy >(_impl_.optional_external_state_policy_.external_state_policy_); + } + return static_cast< ::tensorflow::data::ExternalStatePolicy >(0); +} +inline ::tensorflow::data::ExternalStatePolicy Options::external_state_policy() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.external_state_policy) + return _internal_external_state_policy(); +} +inline void Options::_internal_set_external_state_policy(::tensorflow::data::ExternalStatePolicy value) { + if (!_internal_has_external_state_policy()) { + clear_optional_external_state_policy(); + set_has_external_state_policy(); + } + _impl_.optional_external_state_policy_.external_state_policy_ = value; +} +inline void Options::set_external_state_policy(::tensorflow::data::ExternalStatePolicy value) { + _internal_set_external_state_policy(value); + // @@protoc_insertion_point(field_set:tensorflow.data.Options.external_state_policy) +} + +// bool symbolic_checkpoint = 8; +inline bool Options::_internal_has_symbolic_checkpoint() const { + return optional_symbolic_checkpoint_case() == kSymbolicCheckpoint; +} +inline bool Options::has_symbolic_checkpoint() const { + return _internal_has_symbolic_checkpoint(); +} +inline void Options::set_has_symbolic_checkpoint() { + _impl_._oneof_case_[3] = kSymbolicCheckpoint; +} +inline void Options::clear_symbolic_checkpoint() { + if (_internal_has_symbolic_checkpoint()) { + _impl_.optional_symbolic_checkpoint_.symbolic_checkpoint_ = false; + clear_has_optional_symbolic_checkpoint(); + } +} +inline bool Options::_internal_symbolic_checkpoint() const { + if (_internal_has_symbolic_checkpoint()) { + return _impl_.optional_symbolic_checkpoint_.symbolic_checkpoint_; + } + return false; +} +inline void Options::_internal_set_symbolic_checkpoint(bool value) { + if (!_internal_has_symbolic_checkpoint()) { + clear_optional_symbolic_checkpoint(); + set_has_symbolic_checkpoint(); + } + _impl_.optional_symbolic_checkpoint_.symbolic_checkpoint_ = value; +} +inline bool Options::symbolic_checkpoint() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.symbolic_checkpoint) + return _internal_symbolic_checkpoint(); +} +inline void Options::set_symbolic_checkpoint(bool value) { + _internal_set_symbolic_checkpoint(value); + // @@protoc_insertion_point(field_set:tensorflow.data.Options.symbolic_checkpoint) +} + +// bool warm_start = 9; +inline bool Options::_internal_has_warm_start() const { + return optional_warm_start_case() == kWarmStart; +} +inline bool Options::has_warm_start() const { + return _internal_has_warm_start(); +} +inline void Options::set_has_warm_start() { + _impl_._oneof_case_[4] = kWarmStart; +} +inline void Options::clear_warm_start() { + if (_internal_has_warm_start()) { + _impl_.optional_warm_start_.warm_start_ = false; + clear_has_optional_warm_start(); + } +} +inline bool Options::_internal_warm_start() const { + if (_internal_has_warm_start()) { + return _impl_.optional_warm_start_.warm_start_; + } + return false; +} +inline void Options::_internal_set_warm_start(bool value) { + if (!_internal_has_warm_start()) { + clear_optional_warm_start(); + set_has_warm_start(); + } + _impl_.optional_warm_start_.warm_start_ = value; +} +inline bool Options::warm_start() const { + // @@protoc_insertion_point(field_get:tensorflow.data.Options.warm_start) + return _internal_warm_start(); +} +inline void Options::set_warm_start(bool value) { + _internal_set_warm_start(value); + // @@protoc_insertion_point(field_set:tensorflow.data.Options.warm_start) +} + +inline bool Options::has_optional_deterministic() const { + return optional_deterministic_case() != OPTIONAL_DETERMINISTIC_NOT_SET; +} +inline void Options::clear_has_optional_deterministic() { + _impl_._oneof_case_[0] = OPTIONAL_DETERMINISTIC_NOT_SET; +} +inline bool Options::has_optional_slack() const { + return optional_slack_case() != OPTIONAL_SLACK_NOT_SET; +} +inline void Options::clear_has_optional_slack() { + _impl_._oneof_case_[1] = OPTIONAL_SLACK_NOT_SET; +} +inline bool Options::has_optional_external_state_policy() const { + return optional_external_state_policy_case() != OPTIONAL_EXTERNAL_STATE_POLICY_NOT_SET; +} +inline void Options::clear_has_optional_external_state_policy() { + _impl_._oneof_case_[2] = OPTIONAL_EXTERNAL_STATE_POLICY_NOT_SET; +} +inline bool Options::has_optional_symbolic_checkpoint() const { + return optional_symbolic_checkpoint_case() != OPTIONAL_SYMBOLIC_CHECKPOINT_NOT_SET; +} +inline void Options::clear_has_optional_symbolic_checkpoint() { + _impl_._oneof_case_[3] = OPTIONAL_SYMBOLIC_CHECKPOINT_NOT_SET; +} +inline bool Options::has_optional_warm_start() const { + return optional_warm_start_case() != OPTIONAL_WARM_START_NOT_SET; +} +inline void Options::clear_has_optional_warm_start() { + _impl_._oneof_case_[4] = OPTIONAL_WARM_START_NOT_SET; +} +inline Options::OptionalDeterministicCase Options::optional_deterministic_case() const { + return Options::OptionalDeterministicCase(_impl_._oneof_case_[0]); +} +inline Options::OptionalSlackCase Options::optional_slack_case() const { + return Options::OptionalSlackCase(_impl_._oneof_case_[1]); +} +inline Options::OptionalExternalStatePolicyCase Options::optional_external_state_policy_case() const { + return Options::OptionalExternalStatePolicyCase(_impl_._oneof_case_[2]); +} +inline Options::OptionalSymbolicCheckpointCase Options::optional_symbolic_checkpoint_case() const { + return Options::OptionalSymbolicCheckpointCase(_impl_._oneof_case_[3]); +} +inline Options::OptionalWarmStartCase Options::optional_warm_start_case() const { + return Options::OptionalWarmStartCase(_impl_._oneof_case_[4]); +} +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + +// ------------------------------------------------------------------- + + +// @@protoc_insertion_point(namespace_scope) + +} // namespace data +} // namespace tensorflow + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::tensorflow::data::CardinalityOptions_ComputeLevel> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::data::CardinalityOptions_ComputeLevel>() { + return ::tensorflow::data::CardinalityOptions_ComputeLevel_descriptor(); +} +template <> struct is_proto_enum< ::tensorflow::data::AutoShardPolicy> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::data::AutoShardPolicy>() { + return ::tensorflow::data::AutoShardPolicy_descriptor(); +} +template <> struct is_proto_enum< ::tensorflow::data::ExternalStatePolicy> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::data::ExternalStatePolicy>() { + return ::tensorflow::data::ExternalStatePolicy_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdataset_5foptions_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_options.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_options.proto new file mode 100644 index 0000000000000000000000000000000000000000..d2200407b73f1c3a75897cd2e95b2a6fba9e07b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_options.proto @@ -0,0 +1,226 @@ +syntax = "proto3"; + +package tensorflow.data; + +import "tensorflow/core/framework/model.proto"; + +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/dataset_options_go_proto"; + +// Represents the type of auto-sharding we enable. +enum AutoShardPolicy { + // AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding. + AUTO = 0; + // FILE: Shards by input files (i.e. each worker will get a set of files to + // process). When this option is selected, make sure that there is at least as + // many files as workers. If there are fewer input files than workers, a + // runtime error will be raised. + FILE = 1; + // DATA: Shards by elements produced by the dataset. Each worker will process + // the whole dataset and discard the portion that is not for itself. Note that + // for this mode to correctly partitions the dataset elements, the dataset + // needs to produce elements in a deterministic order. + DATA = 2; + // HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated + // as a placeholder to replace with `shard(num_workers, worker_index)`. + HINT = 3; + // OFF: No sharding will be performed. + OFF = -1; +} + +// next: 5 +message AutotuneOptions { + // Whether to automatically tune performance knobs. + oneof optional_enabled { + bool enabled = 1; + } + // When autotuning is enabled (through autotune), determines the CPU budget to + // use. Values greater than the number of schedulable CPU cores are allowed + // but may result in CPU contention. + oneof optional_cpu_budget { + int32 cpu_budget = 2; + } + // When autotuning is enabled (through autotune), determines the RAM budget to + // use. Values greater than the available RAM in bytes may result in OOM. If + // 0, defaults to half of the available RAM in bytes. + oneof optional_ram_budget { + int64 ram_budget = 3; + } + + // When autotuning is enabled (through autotune), determines the algorithm to + // use. If not explicitly set by user, autotuning will follow HILL_CLIMB + // algorithm but has more flexibility to tune parameters more aggressively, + // in which case the behavior is implementation specific and may change over + // time. + oneof optional_autotune_algorithm { + model.AutotuneAlgorithm autotune_algorithm = 4; + } +} + +// next: 2 +message CardinalityOptions { + enum ComputeLevel { + CARDINALITY_COMPUTE_UNSPECIFIED = 0; + // Cardinality will only be computed if it can be determined in a cheap + // manner (ie. without reading from file sources). If the cardinality would + // be nontrivial to compute, Cardinality() will return UNKNOWN_CARDINALITY. + CARDINALITY_COMPUTE_LOW = 1; + // Moderate effort will be made to determine cardinality, such as reading + // index data from source files. If significant work is needed to compute + // cardinality (e.g. reading entire source file contents or executing user + // defined functions), Cardinality() will return UNKNOWN_CARDINALITY. + CARDINALITY_COMPUTE_MODERATE = 2; + } + ComputeLevel compute_level = 1; +} + +// next: 3 +message DistributeOptions { + AutoShardPolicy auto_shard_policy = 1; + // The number of devices attached to this input pipeline. + oneof optional_num_devices { + int32 num_devices = 2; + } +} + +// next: 21 +message OptimizationOptions { + // Whether to apply default graph optimizations. If False, only graph + // optimizations that have been explicitly enabled will be applied. + oneof optional_apply_default_optimizations { + bool apply_default_optimizations = 1; + } + reserved 2; + reserved 3; + reserved 4; + reserved 5; + // Whether to fuse filter transformations. + oneof optional_filter_fusion { + bool filter_fusion = 6; + } + // NOTE: field id 7 deleted in June 2021. + reserved 7; + // NOTE: field id 8 deleted in June 2021. + reserved 8; + // Whether to fuse map and batch transformations. + oneof optional_map_and_batch_fusion { + bool map_and_batch_fusion = 9; + } + // Whether to fuse map and filter transformations. + oneof optional_map_and_filter_fusion { + bool map_and_filter_fusion = 10; + } + // Whether to fuse map transformations. + oneof optional_map_fusion { + bool map_fusion = 11; + } + // Whether to parallelize stateless map transformations. + oneof optional_map_parallelization { + bool map_parallelization = 12; + } + + // NOTE: field id 13 deleted in June 2021. + reserved 13; + + // Whether to eliminate no-op transformations. + oneof optional_noop_elimination { + bool noop_elimination = 14; + } + // Whether to parallelize copying of batch elements. This optimization is + // highly experimental and can cause performance degradation (e.g. when the + // parallelization overhead exceeds the benefits of performing the data copies + // in parallel). You should only enable this optimization if a) your input + // pipeline is bottlenecked on batching and b) you have validated that this + // optimization improves performance. + oneof optional_parallel_batch { + bool parallel_batch = 15; + } + // Field id 16 was removed in 06/2021. + reserved 16; + // Whether to fuse shuffle and repeat transformations. + oneof optional_shuffle_and_repeat_fusion { + bool shuffle_and_repeat_fusion = 17; + } + // Whether to parallelize stateless filter transformations. + oneof optional_filter_parallelization { + bool filter_parallelization = 18; + } + // Whether to inject 'Prefetch' as the last transformation. Only takes effect + // if the last transformation is synchronous; otherwise does nothing. + oneof optional_inject_prefetch { + bool inject_prefetch = 19; + } + // NOTE: field id 20 was removed in August 2023. + reserved 20; +} + +// next: 3 +message ThreadingOptions { + // If set, it overrides the maximum degree of intra-op parallelism. + oneof optional_max_intra_op_parallelism { + int32 max_intra_op_parallelism = 1; + } + // If set, the dataset will use a private threadpool of the given size. + oneof optional_private_threadpool_size { + int32 private_threadpool_size = 2; + } +} + +// Represents how to handle external state during serialization. +enum ExternalStatePolicy { + POLICY_WARN = 0; + POLICY_IGNORE = 1; + POLICY_FAIL = 2; +} + +// Message stored with Dataset objects to control how datasets are processed and +// optimized. +// +// next: 10 +message Options { + // Whether the outputs need to be produced in deterministic order. + oneof optional_deterministic { + bool deterministic = 1; + } + // The autotune options associated with the dataset. + AutotuneOptions autotune_options = 7; + // The distribution strategy options associated with the dataset. + DistributeOptions distribute_options = 2; + // The optimization options associated with the dataset. + OptimizationOptions optimization_options = 3; + // Whether to introduce 'slack' in the last `prefetch` of the input pipeline, + // if it exists. This may reduce CPU contention with accelerator host-side + // activity at the start of a step. The slack frequency is determined by the + // number of devices attached to this input pipeline. + oneof optional_slack { + bool slack = 4; + } + // The threading options associated with the dataset. + ThreadingOptions threading_options = 5; + // This option can be used to override the default policy for how to handle + // external state when serializing a dataset or checkpointing its iterator. + // There are three settings available - IGNORE: External state is ignored + // without a warning; WARN: External state is ignored and a warning is logged; + // FAIL: External state results in an error. + oneof optional_external_state_policy { + ExternalStatePolicy external_state_policy = 6; + } + // This option indicates whether to checkpoint input pipeline state + // "explicitly", by storing the internal state of iterators for each + // tf.data operation, (the default), or "symbolically", by storing metadata + // that captures the state of each tf.data operation at the time it processed + // the last data seen by tf.data consumer. + // + // Symbolic checkpoints are expected to be much smaller but not all tf.data + // operations are compatible with symbolic checkpointing. In particular, + // symbolic checkpointing requires that data is processed in-order and + // operations that reorder elements, such as `shuffle()` or non-deterministic + // `map()`, are not compatible with symbolic checkpointing. + oneof optional_symbolic_checkpoint { + bool symbolic_checkpoint = 8; + } + // Whether to start background threads of asynchronous transformations upon + // iterator creation (as opposed to upon first call to `GetNext`). + oneof optional_warm_start { + bool warm_start = 9; + } +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_stateful_op_allowlist.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_stateful_op_allowlist.h new file mode 100644 index 0000000000000000000000000000000000000000..5e8cdd4af32a19dd9ae21a55647b7b4d8bfbd8d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/dataset_stateful_op_allowlist.h @@ -0,0 +1,81 @@ +/* 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_FRAMEWORK_DATASET_STATEFUL_OP_ALLOWLIST_H_ +#define TENSORFLOW_CORE_FRAMEWORK_DATASET_STATEFUL_OP_ALLOWLIST_H_ + +#include +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +namespace data { +// Registry for stateful ops that need to be used in dataset functions. +// See below macro for usage details. +class AllowlistedStatefulOpRegistry { + public: + Status Add(string op_name) { + op_names_.insert(std::move(op_name)); + return OkStatus(); + } + + Status Remove(string op_name) { + op_names_.erase(op_name); + return OkStatus(); + } + + bool Contains(const string& op_name) { return op_names_.count(op_name); } + + static AllowlistedStatefulOpRegistry* Global() { + static auto* reg = new AllowlistedStatefulOpRegistry; + return reg; + } + + private: + AllowlistedStatefulOpRegistry() = default; + AllowlistedStatefulOpRegistry(AllowlistedStatefulOpRegistry const& copy) = + delete; + AllowlistedStatefulOpRegistry operator=( + AllowlistedStatefulOpRegistry const& copy) = delete; + + std::unordered_set op_names_; +}; + +} // namespace data + +// Use this macro to allowlist an op that is marked stateful but needs to be +// used inside a map_fn in an input pipeline. This is only needed if you wish +// to be able to checkpoint the state of the input pipeline. We currently +// do not allow stateful ops to be defined inside of map_fns since it is not +// possible to save their state. +// Note that the state of the allowlisted ops inside functions will not be +// saved during checkpointing, hence this should only be used if the op is +// marked stateful for reasons like to avoid constant folding during graph +// optimization but is not stateful. +// If possible, try to remove the stateful flag on the op first. +// Example usage: +// +// ALLOW_STATEFUL_OP_FOR_DATASET_FUNCTIONS("LegacyStatefulReader"); +// +#define ALLOW_STATEFUL_OP_FOR_DATASET_FUNCTIONS(name) \ + ALLOW_STATEFUL_OP_FOR_DATASET_FUNCTIONS_UNIQ_HELPER(__COUNTER__, name) +#define ALLOW_STATEFUL_OP_FOR_DATASET_FUNCTIONS_UNIQ_HELPER(ctr, name) \ + ALLOW_STATEFUL_OP_FOR_DATASET_FUNCTIONS_UNIQ(ctr, name) +#define ALLOW_STATEFUL_OP_FOR_DATASET_FUNCTIONS_UNIQ(ctr, name) \ + static ::tensorflow::Status allowlist_op##ctr TF_ATTRIBUTE_UNUSED = \ + ::tensorflow::data::AllowlistedStatefulOpRegistry::Global()->Add(name) + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_DATASET_STATEFUL_OP_ALLOWLIST_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device.h new file mode 100644 index 0000000000000000000000000000000000000000..a7d5bb260d536928fbab7f16f053d909e4e0d30e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device.h @@ -0,0 +1,218 @@ +/* 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 Device is a something that can perform computations as part of a +// model. Devices can be local (runs computation on this machine), or +// remote (contacts a device local to another machine using an RPC to +// do the work). Devices are registered in a DeviceSet, which is also +// responsible for the Device <-> id mapping. +// +// Device names +// * Every Device should have a unique name with the format: +// /job:___/replica:___/task:___/(gpu|cpu):___ +// An example name would be "/job:train/replica:0/task:3/device:GPU:2". +// * Task numbers are within the specified replica, so there are as +// many "task zeros" as replicas. + +#ifndef TENSORFLOW_CORE_FRAMEWORK_DEVICE_H_ +#define TENSORFLOW_CORE_FRAMEWORK_DEVICE_H_ + +#include +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/control_flow.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_segment.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/graph/types.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace tensorflow { + +class Device : public DeviceBase { + public: + // Callback type that takes a Status and returns void. + typedef std::function DoneCallback; + + Device(Env* env, const DeviceAttributes& device_attributes); + ~Device() override; + + // A compare function that orders devices by their parsed name. + static bool LessByParsedName(const Device& a, const Device& b) { + return a.parsed_name() < b.parsed_name(); + } + + // Full name of this device (see top comment). + const std::string& name() const override { return device_attributes_.name(); } + + // Parsed name of this device + const DeviceNameUtils::ParsedName& parsed_name() const override { + return parsed_name_; + } + + // Describes what kind of device this is. This is intended to be + // human-readable and not computer-parsed, except that two devices + // with the same device_type() are expected to perform similarly + // (both from a computation and communication perspective). + const std::string& device_type() const { + return device_attributes_.device_type(); + } + + // Returns an aggregation of device attributes. + const DeviceAttributes& attributes() const override { + return device_attributes_; + } + + // Performs the actual compute function. + // + // Subclasses may override this function if they wish to perform + // some initialization before each compute. + virtual void Compute(OpKernel* op_kernel, OpKernelContext* context) { + op_kernel->Compute(context); + } + + // Asynchronous kernel's compute. + virtual void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context, + AsyncOpKernel::DoneCallback done) { + op_kernel->ComputeAsync(context, std::move(done)); + } + + // Blocks until all operations queued on the device at the time of + // the call have completed. Returns any error pending on the device + // at completion. + virtual Status Sync() = 0; + + // Calls the given callback when all operations queued on the device at the + // time of the call have completed. The callback is passed any error pending + // on the device at completion. + // TODO(b/112409994): Consolidate these two APIs, removing the synchronous + // version. + virtual void Sync(const DoneCallback& done); + + // On session completion, the executor may call Device::Sync() depending on + // flag settings. Override this to return false for devices that don't allow + // such calls. Instead, these devices must use other mechanisms (such as + // num_deferred_ops) to ensure the device has finished processing necessary + // work at session completion. In addition, for these devices, RefreshStatus + // must be called at session completion to retrieve execution result status. + // + // Devices that override this function must also implement RefreshStatus. + virtual bool AllowsSyncOnCompletion() const { return true; } + + // This is used in conjunction with AllowsSyncOnCompletion to allow the + // executor to get execution result status at session completion. + // + // For supported devices, this call returns the underlying device stream's + // current status in a non-blocking way, without using blocking calls such as + // Stream::BlockHostUntilDone or Device::Sync. When applicable, the device + // status is also updated with the retrieved stream status. + virtual Status RefreshStatus() { + return errors::Unimplemented( + "RefreshStatus is not supported on this device."); + } + + // Optionally modify the device's GraphDef before execution. + // + // This method should be considered experimental and is supplied to enable + // prototyping of TensorFlow device implementations that need to modify + // the GraphDef before execution. + // + // 'graph' supplies the partition of the graph assigned to this + // device. + virtual Status MaybeRewriteGraph(std::unique_ptr* /*graph*/) { + return OkStatus(); + } + + // Sets `out_context` a new DeviceContext* for executing a graph, or nullptr + // if the device does not support contexts. Returns an error status if any + // error occurred while trying to create a context, otherwise OK. + // + // The caller takes ownership of one reference on the output DeviceContext*, + // and should call Unref(). + virtual Status TryGetDeviceContext(DeviceContext** out_context) { + *out_context = nullptr; + return OkStatus(); + } + + // Returns the op segment of this device. The caller can reuse op + // kernels registered for the same session running on this device. + OpSegment* op_segment() { return &op_seg_; } + + // Returns the resource manager associated w/ this device. + virtual ResourceMgr* resource_manager() { return rmgr_; } + + // Summarizes the status of this Device, for debugging. + std::string DebugString() const { return device_attributes_.DebugString(); } + + // Assembles the parameter components into a complete DeviceAttributes value. + static DeviceAttributes BuildDeviceAttributes( + const std::string& name, DeviceType device, Bytes memory_limit, + const DeviceLocality& locality, const std::string& physical_device_desc); + + static DeviceAttributes BuildDeviceAttributes( + const std::string& name, DeviceType device, Bytes memory_limit, + const DeviceLocality& locality) { + // Pass in an empty string as physical device name. + return BuildDeviceAttributes(name, device, memory_limit, locality, ""); + } + + // Updates `attributes()`, indicating the XLA global ID associated with this + // device. This ID is unique across clients in a multi-client setup. For TPUs + // this does not happen until the TPU system has been initialized. + void set_xla_global_id(int64_t id) override { + device_attributes_.set_xla_global_id(id); + } + + // Clears the resource manager associated with this device. + void ClearResourceMgr() { rmgr_->Clear(); } + + virtual bool IsLocal() const { return true; } + + // Informs if this Device can be used as a caller in RemoteCall operation. + virtual bool IsRemoteCallAllowed() const; + + protected: + void DeleteResourceMgr() { + delete rmgr_; + rmgr_ = nullptr; + } + + private: + DeviceAttributes device_attributes_; + DeviceNameUtils::ParsedName parsed_name_; + + // op_seg_ maps session handle and op name to OpKernel objects. + OpSegment op_seg_; + + // Resources associated w/ this device. E.g., shared variables, etc. + ResourceMgr* rmgr_ = nullptr; + + Device(const Device&) = delete; + void operator=(const Device&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_DEVICE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_attributes.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_attributes.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..7400631b4a8f6c496e0033afb43a26ffb03ac8e7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_attributes.pb.h @@ -0,0 +1,1418 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/device_attributes.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2fdevice_5fattributes_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_2fframework_2fdevice_5fattributes_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_2fframework_2fdevice_5fattributes_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto; +namespace tensorflow { +class DeviceAttributes; +struct DeviceAttributesDefaultTypeInternal; +extern DeviceAttributesDefaultTypeInternal _DeviceAttributes_default_instance_; +class DeviceLocality; +struct DeviceLocalityDefaultTypeInternal; +extern DeviceLocalityDefaultTypeInternal _DeviceLocality_default_instance_; +class InterconnectLink; +struct InterconnectLinkDefaultTypeInternal; +extern InterconnectLinkDefaultTypeInternal _InterconnectLink_default_instance_; +class LocalLinks; +struct LocalLinksDefaultTypeInternal; +extern LocalLinksDefaultTypeInternal _LocalLinks_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::DeviceAttributes* Arena::CreateMaybeMessage<::tensorflow::DeviceAttributes>(Arena*); +template<> ::tensorflow::DeviceLocality* Arena::CreateMaybeMessage<::tensorflow::DeviceLocality>(Arena*); +template<> ::tensorflow::InterconnectLink* Arena::CreateMaybeMessage<::tensorflow::InterconnectLink>(Arena*); +template<> ::tensorflow::LocalLinks* Arena::CreateMaybeMessage<::tensorflow::LocalLinks>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +// =================================================================== + +class InterconnectLink final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.InterconnectLink) */ { + public: + inline InterconnectLink() : InterconnectLink(nullptr) {} + ~InterconnectLink() override; + explicit PROTOBUF_CONSTEXPR InterconnectLink(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + InterconnectLink(const InterconnectLink& from); + InterconnectLink(InterconnectLink&& from) noexcept + : InterconnectLink() { + *this = ::std::move(from); + } + + inline InterconnectLink& operator=(const InterconnectLink& from) { + CopyFrom(from); + return *this; + } + inline InterconnectLink& operator=(InterconnectLink&& 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 InterconnectLink& default_instance() { + return *internal_default_instance(); + } + static inline const InterconnectLink* internal_default_instance() { + return reinterpret_cast( + &_InterconnectLink_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(InterconnectLink& a, InterconnectLink& b) { + a.Swap(&b); + } + inline void Swap(InterconnectLink* 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(InterconnectLink* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + InterconnectLink* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const InterconnectLink& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const InterconnectLink& from) { + InterconnectLink::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(InterconnectLink* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.InterconnectLink"; + } + protected: + explicit InterconnectLink(::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 { + kTypeFieldNumber = 2, + kDeviceIdFieldNumber = 1, + kStrengthFieldNumber = 3, + }; + // string type = 2; + void clear_type(); + const std::string& type() const; + template + void set_type(ArgT0&& arg0, ArgT... args); + std::string* mutable_type(); + PROTOBUF_NODISCARD std::string* release_type(); + void set_allocated_type(std::string* type); + private: + const std::string& _internal_type() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_type(const std::string& value); + std::string* _internal_mutable_type(); + public: + + // int32 device_id = 1; + void clear_device_id(); + int32_t device_id() const; + void set_device_id(int32_t value); + private: + int32_t _internal_device_id() const; + void _internal_set_device_id(int32_t value); + public: + + // int32 strength = 3; + void clear_strength(); + int32_t strength() const; + void set_strength(int32_t value); + private: + int32_t _internal_strength() const; + void _internal_set_strength(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.InterconnectLink) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_; + int32_t device_id_; + int32_t strength_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto; +}; +// ------------------------------------------------------------------- + +class LocalLinks final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.LocalLinks) */ { + public: + inline LocalLinks() : LocalLinks(nullptr) {} + ~LocalLinks() override; + explicit PROTOBUF_CONSTEXPR LocalLinks(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + LocalLinks(const LocalLinks& from); + LocalLinks(LocalLinks&& from) noexcept + : LocalLinks() { + *this = ::std::move(from); + } + + inline LocalLinks& operator=(const LocalLinks& from) { + CopyFrom(from); + return *this; + } + inline LocalLinks& operator=(LocalLinks&& 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 LocalLinks& default_instance() { + return *internal_default_instance(); + } + static inline const LocalLinks* internal_default_instance() { + return reinterpret_cast( + &_LocalLinks_default_instance_); + } + static constexpr int kIndexInFileMessages = + 1; + + friend void swap(LocalLinks& a, LocalLinks& b) { + a.Swap(&b); + } + inline void Swap(LocalLinks* 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(LocalLinks* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + LocalLinks* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const LocalLinks& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const LocalLinks& from) { + LocalLinks::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(LocalLinks* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.LocalLinks"; + } + protected: + explicit LocalLinks(::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 { + kLinkFieldNumber = 1, + }; + // repeated .tensorflow.InterconnectLink link = 1; + int link_size() const; + private: + int _internal_link_size() const; + public: + void clear_link(); + ::tensorflow::InterconnectLink* mutable_link(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::InterconnectLink >* + mutable_link(); + private: + const ::tensorflow::InterconnectLink& _internal_link(int index) const; + ::tensorflow::InterconnectLink* _internal_add_link(); + public: + const ::tensorflow::InterconnectLink& link(int index) const; + ::tensorflow::InterconnectLink* add_link(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::InterconnectLink >& + link() const; + + // @@protoc_insertion_point(class_scope:tensorflow.LocalLinks) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::InterconnectLink > link_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto; +}; +// ------------------------------------------------------------------- + +class DeviceLocality final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.DeviceLocality) */ { + public: + inline DeviceLocality() : DeviceLocality(nullptr) {} + ~DeviceLocality() override; + explicit PROTOBUF_CONSTEXPR DeviceLocality(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DeviceLocality(const DeviceLocality& from); + DeviceLocality(DeviceLocality&& from) noexcept + : DeviceLocality() { + *this = ::std::move(from); + } + + inline DeviceLocality& operator=(const DeviceLocality& from) { + CopyFrom(from); + return *this; + } + inline DeviceLocality& operator=(DeviceLocality&& 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 DeviceLocality& default_instance() { + return *internal_default_instance(); + } + static inline const DeviceLocality* internal_default_instance() { + return reinterpret_cast( + &_DeviceLocality_default_instance_); + } + static constexpr int kIndexInFileMessages = + 2; + + friend void swap(DeviceLocality& a, DeviceLocality& b) { + a.Swap(&b); + } + inline void Swap(DeviceLocality* 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(DeviceLocality* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DeviceLocality* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DeviceLocality& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DeviceLocality& from) { + DeviceLocality::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(DeviceLocality* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.DeviceLocality"; + } + protected: + explicit DeviceLocality(::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 { + kLinksFieldNumber = 3, + kBusIdFieldNumber = 1, + kNumaNodeFieldNumber = 2, + }; + // .tensorflow.LocalLinks links = 3; + bool has_links() const; + private: + bool _internal_has_links() const; + public: + void clear_links(); + const ::tensorflow::LocalLinks& links() const; + PROTOBUF_NODISCARD ::tensorflow::LocalLinks* release_links(); + ::tensorflow::LocalLinks* mutable_links(); + void set_allocated_links(::tensorflow::LocalLinks* links); + private: + const ::tensorflow::LocalLinks& _internal_links() const; + ::tensorflow::LocalLinks* _internal_mutable_links(); + public: + void unsafe_arena_set_allocated_links( + ::tensorflow::LocalLinks* links); + ::tensorflow::LocalLinks* unsafe_arena_release_links(); + + // int32 bus_id = 1; + void clear_bus_id(); + int32_t bus_id() const; + void set_bus_id(int32_t value); + private: + int32_t _internal_bus_id() const; + void _internal_set_bus_id(int32_t value); + public: + + // int32 numa_node = 2; + void clear_numa_node(); + int32_t numa_node() const; + void set_numa_node(int32_t value); + private: + int32_t _internal_numa_node() const; + void _internal_set_numa_node(int32_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.DeviceLocality) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::tensorflow::LocalLinks* links_; + int32_t bus_id_; + int32_t numa_node_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto; +}; +// ------------------------------------------------------------------- + +class DeviceAttributes final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.DeviceAttributes) */ { + public: + inline DeviceAttributes() : DeviceAttributes(nullptr) {} + ~DeviceAttributes() override; + explicit PROTOBUF_CONSTEXPR DeviceAttributes(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + DeviceAttributes(const DeviceAttributes& from); + DeviceAttributes(DeviceAttributes&& from) noexcept + : DeviceAttributes() { + *this = ::std::move(from); + } + + inline DeviceAttributes& operator=(const DeviceAttributes& from) { + CopyFrom(from); + return *this; + } + inline DeviceAttributes& operator=(DeviceAttributes&& 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 DeviceAttributes& default_instance() { + return *internal_default_instance(); + } + static inline const DeviceAttributes* internal_default_instance() { + return reinterpret_cast( + &_DeviceAttributes_default_instance_); + } + static constexpr int kIndexInFileMessages = + 3; + + friend void swap(DeviceAttributes& a, DeviceAttributes& b) { + a.Swap(&b); + } + inline void Swap(DeviceAttributes* 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(DeviceAttributes* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + DeviceAttributes* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const DeviceAttributes& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const DeviceAttributes& from) { + DeviceAttributes::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(DeviceAttributes* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.DeviceAttributes"; + } + protected: + explicit DeviceAttributes(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + public: + + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; + + // nested types ---------------------------------------------------- + + // accessors ------------------------------------------------------- + + enum : int { + kNameFieldNumber = 1, + kDeviceTypeFieldNumber = 2, + kPhysicalDeviceDescFieldNumber = 7, + kLocalityFieldNumber = 5, + kMemoryLimitFieldNumber = 4, + kIncarnationFieldNumber = 6, + kXlaGlobalIdFieldNumber = 8, + }; + // string name = 1; + void clear_name(); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: + + // string device_type = 2; + void clear_device_type(); + const std::string& device_type() const; + template + void set_device_type(ArgT0&& arg0, ArgT... args); + std::string* mutable_device_type(); + PROTOBUF_NODISCARD std::string* release_device_type(); + void set_allocated_device_type(std::string* device_type); + private: + const std::string& _internal_device_type() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_device_type(const std::string& value); + std::string* _internal_mutable_device_type(); + public: + + // string physical_device_desc = 7; + void clear_physical_device_desc(); + const std::string& physical_device_desc() const; + template + void set_physical_device_desc(ArgT0&& arg0, ArgT... args); + std::string* mutable_physical_device_desc(); + PROTOBUF_NODISCARD std::string* release_physical_device_desc(); + void set_allocated_physical_device_desc(std::string* physical_device_desc); + private: + const std::string& _internal_physical_device_desc() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_physical_device_desc(const std::string& value); + std::string* _internal_mutable_physical_device_desc(); + public: + + // .tensorflow.DeviceLocality locality = 5; + bool has_locality() const; + private: + bool _internal_has_locality() const; + public: + void clear_locality(); + const ::tensorflow::DeviceLocality& locality() const; + PROTOBUF_NODISCARD ::tensorflow::DeviceLocality* release_locality(); + ::tensorflow::DeviceLocality* mutable_locality(); + void set_allocated_locality(::tensorflow::DeviceLocality* locality); + private: + const ::tensorflow::DeviceLocality& _internal_locality() const; + ::tensorflow::DeviceLocality* _internal_mutable_locality(); + public: + void unsafe_arena_set_allocated_locality( + ::tensorflow::DeviceLocality* locality); + ::tensorflow::DeviceLocality* unsafe_arena_release_locality(); + + // int64 memory_limit = 4; + void clear_memory_limit(); + int64_t memory_limit() const; + void set_memory_limit(int64_t value); + private: + int64_t _internal_memory_limit() const; + void _internal_set_memory_limit(int64_t value); + public: + + // fixed64 incarnation = 6; + void clear_incarnation(); + uint64_t incarnation() const; + void set_incarnation(uint64_t value); + private: + uint64_t _internal_incarnation() const; + void _internal_set_incarnation(uint64_t value); + public: + + // int64 xla_global_id = 8; + void clear_xla_global_id(); + int64_t xla_global_id() const; + void set_xla_global_id(int64_t value); + private: + int64_t _internal_xla_global_id() const; + void _internal_set_xla_global_id(int64_t value); + public: + + // @@protoc_insertion_point(class_scope:tensorflow.DeviceAttributes) + private: + class _Internal; + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr device_type_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr physical_device_desc_; + ::tensorflow::DeviceLocality* locality_; + int64_t memory_limit_; + uint64_t incarnation_; + int64_t xla_global_id_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// InterconnectLink + +// int32 device_id = 1; +inline void InterconnectLink::clear_device_id() { + _impl_.device_id_ = 0; +} +inline int32_t InterconnectLink::_internal_device_id() const { + return _impl_.device_id_; +} +inline int32_t InterconnectLink::device_id() const { + // @@protoc_insertion_point(field_get:tensorflow.InterconnectLink.device_id) + return _internal_device_id(); +} +inline void InterconnectLink::_internal_set_device_id(int32_t value) { + + _impl_.device_id_ = value; +} +inline void InterconnectLink::set_device_id(int32_t value) { + _internal_set_device_id(value); + // @@protoc_insertion_point(field_set:tensorflow.InterconnectLink.device_id) +} + +// string type = 2; +inline void InterconnectLink::clear_type() { + _impl_.type_.ClearToEmpty(); +} +inline const std::string& InterconnectLink::type() const { + // @@protoc_insertion_point(field_get:tensorflow.InterconnectLink.type) + return _internal_type(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void InterconnectLink::set_type(ArgT0&& arg0, ArgT... args) { + + _impl_.type_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.InterconnectLink.type) +} +inline std::string* InterconnectLink::mutable_type() { + std::string* _s = _internal_mutable_type(); + // @@protoc_insertion_point(field_mutable:tensorflow.InterconnectLink.type) + return _s; +} +inline const std::string& InterconnectLink::_internal_type() const { + return _impl_.type_.Get(); +} +inline void InterconnectLink::_internal_set_type(const std::string& value) { + + _impl_.type_.Set(value, GetArenaForAllocation()); +} +inline std::string* InterconnectLink::_internal_mutable_type() { + + return _impl_.type_.Mutable(GetArenaForAllocation()); +} +inline std::string* InterconnectLink::release_type() { + // @@protoc_insertion_point(field_release:tensorflow.InterconnectLink.type) + return _impl_.type_.Release(); +} +inline void InterconnectLink::set_allocated_type(std::string* type) { + if (type != nullptr) { + + } else { + + } + _impl_.type_.SetAllocated(type, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.type_.IsDefault()) { + _impl_.type_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.InterconnectLink.type) +} + +// int32 strength = 3; +inline void InterconnectLink::clear_strength() { + _impl_.strength_ = 0; +} +inline int32_t InterconnectLink::_internal_strength() const { + return _impl_.strength_; +} +inline int32_t InterconnectLink::strength() const { + // @@protoc_insertion_point(field_get:tensorflow.InterconnectLink.strength) + return _internal_strength(); +} +inline void InterconnectLink::_internal_set_strength(int32_t value) { + + _impl_.strength_ = value; +} +inline void InterconnectLink::set_strength(int32_t value) { + _internal_set_strength(value); + // @@protoc_insertion_point(field_set:tensorflow.InterconnectLink.strength) +} + +// ------------------------------------------------------------------- + +// LocalLinks + +// repeated .tensorflow.InterconnectLink link = 1; +inline int LocalLinks::_internal_link_size() const { + return _impl_.link_.size(); +} +inline int LocalLinks::link_size() const { + return _internal_link_size(); +} +inline void LocalLinks::clear_link() { + _impl_.link_.Clear(); +} +inline ::tensorflow::InterconnectLink* LocalLinks::mutable_link(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.LocalLinks.link) + return _impl_.link_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::InterconnectLink >* +LocalLinks::mutable_link() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.LocalLinks.link) + return &_impl_.link_; +} +inline const ::tensorflow::InterconnectLink& LocalLinks::_internal_link(int index) const { + return _impl_.link_.Get(index); +} +inline const ::tensorflow::InterconnectLink& LocalLinks::link(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.LocalLinks.link) + return _internal_link(index); +} +inline ::tensorflow::InterconnectLink* LocalLinks::_internal_add_link() { + return _impl_.link_.Add(); +} +inline ::tensorflow::InterconnectLink* LocalLinks::add_link() { + ::tensorflow::InterconnectLink* _add = _internal_add_link(); + // @@protoc_insertion_point(field_add:tensorflow.LocalLinks.link) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::InterconnectLink >& +LocalLinks::link() const { + // @@protoc_insertion_point(field_list:tensorflow.LocalLinks.link) + return _impl_.link_; +} + +// ------------------------------------------------------------------- + +// DeviceLocality + +// int32 bus_id = 1; +inline void DeviceLocality::clear_bus_id() { + _impl_.bus_id_ = 0; +} +inline int32_t DeviceLocality::_internal_bus_id() const { + return _impl_.bus_id_; +} +inline int32_t DeviceLocality::bus_id() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceLocality.bus_id) + return _internal_bus_id(); +} +inline void DeviceLocality::_internal_set_bus_id(int32_t value) { + + _impl_.bus_id_ = value; +} +inline void DeviceLocality::set_bus_id(int32_t value) { + _internal_set_bus_id(value); + // @@protoc_insertion_point(field_set:tensorflow.DeviceLocality.bus_id) +} + +// int32 numa_node = 2; +inline void DeviceLocality::clear_numa_node() { + _impl_.numa_node_ = 0; +} +inline int32_t DeviceLocality::_internal_numa_node() const { + return _impl_.numa_node_; +} +inline int32_t DeviceLocality::numa_node() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceLocality.numa_node) + return _internal_numa_node(); +} +inline void DeviceLocality::_internal_set_numa_node(int32_t value) { + + _impl_.numa_node_ = value; +} +inline void DeviceLocality::set_numa_node(int32_t value) { + _internal_set_numa_node(value); + // @@protoc_insertion_point(field_set:tensorflow.DeviceLocality.numa_node) +} + +// .tensorflow.LocalLinks links = 3; +inline bool DeviceLocality::_internal_has_links() const { + return this != internal_default_instance() && _impl_.links_ != nullptr; +} +inline bool DeviceLocality::has_links() const { + return _internal_has_links(); +} +inline void DeviceLocality::clear_links() { + if (GetArenaForAllocation() == nullptr && _impl_.links_ != nullptr) { + delete _impl_.links_; + } + _impl_.links_ = nullptr; +} +inline const ::tensorflow::LocalLinks& DeviceLocality::_internal_links() const { + const ::tensorflow::LocalLinks* p = _impl_.links_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_LocalLinks_default_instance_); +} +inline const ::tensorflow::LocalLinks& DeviceLocality::links() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceLocality.links) + return _internal_links(); +} +inline void DeviceLocality::unsafe_arena_set_allocated_links( + ::tensorflow::LocalLinks* links) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.links_); + } + _impl_.links_ = links; + if (links) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceLocality.links) +} +inline ::tensorflow::LocalLinks* DeviceLocality::release_links() { + + ::tensorflow::LocalLinks* temp = _impl_.links_; + _impl_.links_ = 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::LocalLinks* DeviceLocality::unsafe_arena_release_links() { + // @@protoc_insertion_point(field_release:tensorflow.DeviceLocality.links) + + ::tensorflow::LocalLinks* temp = _impl_.links_; + _impl_.links_ = nullptr; + return temp; +} +inline ::tensorflow::LocalLinks* DeviceLocality::_internal_mutable_links() { + + if (_impl_.links_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::LocalLinks>(GetArenaForAllocation()); + _impl_.links_ = p; + } + return _impl_.links_; +} +inline ::tensorflow::LocalLinks* DeviceLocality::mutable_links() { + ::tensorflow::LocalLinks* _msg = _internal_mutable_links(); + // @@protoc_insertion_point(field_mutable:tensorflow.DeviceLocality.links) + return _msg; +} +inline void DeviceLocality::set_allocated_links(::tensorflow::LocalLinks* links) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.links_; + } + if (links) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(links); + if (message_arena != submessage_arena) { + links = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, links, submessage_arena); + } + + } else { + + } + _impl_.links_ = links; + // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceLocality.links) +} + +// ------------------------------------------------------------------- + +// DeviceAttributes + +// string name = 1; +inline void DeviceAttributes::clear_name() { + _impl_.name_.ClearToEmpty(); +} +inline const std::string& DeviceAttributes::name() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.name) + return _internal_name(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void DeviceAttributes::set_name(ArgT0&& arg0, ArgT... args) { + + _impl_.name_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.name) +} +inline std::string* DeviceAttributes::mutable_name() { + std::string* _s = _internal_mutable_name(); + // @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.name) + return _s; +} +inline const std::string& DeviceAttributes::_internal_name() const { + return _impl_.name_.Get(); +} +inline void DeviceAttributes::_internal_set_name(const std::string& value) { + + _impl_.name_.Set(value, GetArenaForAllocation()); +} +inline std::string* DeviceAttributes::_internal_mutable_name() { + + return _impl_.name_.Mutable(GetArenaForAllocation()); +} +inline std::string* DeviceAttributes::release_name() { + // @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.name) + return _impl_.name_.Release(); +} +inline void DeviceAttributes::set_allocated_name(std::string* name) { + if (name != nullptr) { + + } else { + + } + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.name) +} + +// string device_type = 2; +inline void DeviceAttributes::clear_device_type() { + _impl_.device_type_.ClearToEmpty(); +} +inline const std::string& DeviceAttributes::device_type() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.device_type) + return _internal_device_type(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void DeviceAttributes::set_device_type(ArgT0&& arg0, ArgT... args) { + + _impl_.device_type_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.device_type) +} +inline std::string* DeviceAttributes::mutable_device_type() { + std::string* _s = _internal_mutable_device_type(); + // @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.device_type) + return _s; +} +inline const std::string& DeviceAttributes::_internal_device_type() const { + return _impl_.device_type_.Get(); +} +inline void DeviceAttributes::_internal_set_device_type(const std::string& value) { + + _impl_.device_type_.Set(value, GetArenaForAllocation()); +} +inline std::string* DeviceAttributes::_internal_mutable_device_type() { + + return _impl_.device_type_.Mutable(GetArenaForAllocation()); +} +inline std::string* DeviceAttributes::release_device_type() { + // @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.device_type) + return _impl_.device_type_.Release(); +} +inline void DeviceAttributes::set_allocated_device_type(std::string* device_type) { + if (device_type != nullptr) { + + } else { + + } + _impl_.device_type_.SetAllocated(device_type, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.device_type_.IsDefault()) { + _impl_.device_type_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.device_type) +} + +// int64 memory_limit = 4; +inline void DeviceAttributes::clear_memory_limit() { + _impl_.memory_limit_ = int64_t{0}; +} +inline int64_t DeviceAttributes::_internal_memory_limit() const { + return _impl_.memory_limit_; +} +inline int64_t DeviceAttributes::memory_limit() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.memory_limit) + return _internal_memory_limit(); +} +inline void DeviceAttributes::_internal_set_memory_limit(int64_t value) { + + _impl_.memory_limit_ = value; +} +inline void DeviceAttributes::set_memory_limit(int64_t value) { + _internal_set_memory_limit(value); + // @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.memory_limit) +} + +// .tensorflow.DeviceLocality locality = 5; +inline bool DeviceAttributes::_internal_has_locality() const { + return this != internal_default_instance() && _impl_.locality_ != nullptr; +} +inline bool DeviceAttributes::has_locality() const { + return _internal_has_locality(); +} +inline void DeviceAttributes::clear_locality() { + if (GetArenaForAllocation() == nullptr && _impl_.locality_ != nullptr) { + delete _impl_.locality_; + } + _impl_.locality_ = nullptr; +} +inline const ::tensorflow::DeviceLocality& DeviceAttributes::_internal_locality() const { + const ::tensorflow::DeviceLocality* p = _impl_.locality_; + return p != nullptr ? *p : reinterpret_cast( + ::tensorflow::_DeviceLocality_default_instance_); +} +inline const ::tensorflow::DeviceLocality& DeviceAttributes::locality() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.locality) + return _internal_locality(); +} +inline void DeviceAttributes::unsafe_arena_set_allocated_locality( + ::tensorflow::DeviceLocality* locality) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.locality_); + } + _impl_.locality_ = locality; + if (locality) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceAttributes.locality) +} +inline ::tensorflow::DeviceLocality* DeviceAttributes::release_locality() { + + ::tensorflow::DeviceLocality* temp = _impl_.locality_; + _impl_.locality_ = 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::DeviceLocality* DeviceAttributes::unsafe_arena_release_locality() { + // @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.locality) + + ::tensorflow::DeviceLocality* temp = _impl_.locality_; + _impl_.locality_ = nullptr; + return temp; +} +inline ::tensorflow::DeviceLocality* DeviceAttributes::_internal_mutable_locality() { + + if (_impl_.locality_ == nullptr) { + auto* p = CreateMaybeMessage<::tensorflow::DeviceLocality>(GetArenaForAllocation()); + _impl_.locality_ = p; + } + return _impl_.locality_; +} +inline ::tensorflow::DeviceLocality* DeviceAttributes::mutable_locality() { + ::tensorflow::DeviceLocality* _msg = _internal_mutable_locality(); + // @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.locality) + return _msg; +} +inline void DeviceAttributes::set_allocated_locality(::tensorflow::DeviceLocality* locality) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete _impl_.locality_; + } + if (locality) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalGetOwningArena(locality); + if (message_arena != submessage_arena) { + locality = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, locality, submessage_arena); + } + + } else { + + } + _impl_.locality_ = locality; + // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.locality) +} + +// fixed64 incarnation = 6; +inline void DeviceAttributes::clear_incarnation() { + _impl_.incarnation_ = uint64_t{0u}; +} +inline uint64_t DeviceAttributes::_internal_incarnation() const { + return _impl_.incarnation_; +} +inline uint64_t DeviceAttributes::incarnation() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.incarnation) + return _internal_incarnation(); +} +inline void DeviceAttributes::_internal_set_incarnation(uint64_t value) { + + _impl_.incarnation_ = value; +} +inline void DeviceAttributes::set_incarnation(uint64_t value) { + _internal_set_incarnation(value); + // @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.incarnation) +} + +// string physical_device_desc = 7; +inline void DeviceAttributes::clear_physical_device_desc() { + _impl_.physical_device_desc_.ClearToEmpty(); +} +inline const std::string& DeviceAttributes::physical_device_desc() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.physical_device_desc) + return _internal_physical_device_desc(); +} +template +inline PROTOBUF_ALWAYS_INLINE +void DeviceAttributes::set_physical_device_desc(ArgT0&& arg0, ArgT... args) { + + _impl_.physical_device_desc_.Set(static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.physical_device_desc) +} +inline std::string* DeviceAttributes::mutable_physical_device_desc() { + std::string* _s = _internal_mutable_physical_device_desc(); + // @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.physical_device_desc) + return _s; +} +inline const std::string& DeviceAttributes::_internal_physical_device_desc() const { + return _impl_.physical_device_desc_.Get(); +} +inline void DeviceAttributes::_internal_set_physical_device_desc(const std::string& value) { + + _impl_.physical_device_desc_.Set(value, GetArenaForAllocation()); +} +inline std::string* DeviceAttributes::_internal_mutable_physical_device_desc() { + + return _impl_.physical_device_desc_.Mutable(GetArenaForAllocation()); +} +inline std::string* DeviceAttributes::release_physical_device_desc() { + // @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.physical_device_desc) + return _impl_.physical_device_desc_.Release(); +} +inline void DeviceAttributes::set_allocated_physical_device_desc(std::string* physical_device_desc) { + if (physical_device_desc != nullptr) { + + } else { + + } + _impl_.physical_device_desc_.SetAllocated(physical_device_desc, GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (_impl_.physical_device_desc_.IsDefault()) { + _impl_.physical_device_desc_.Set("", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.physical_device_desc) +} + +// int64 xla_global_id = 8; +inline void DeviceAttributes::clear_xla_global_id() { + _impl_.xla_global_id_ = int64_t{0}; +} +inline int64_t DeviceAttributes::_internal_xla_global_id() const { + return _impl_.xla_global_id_; +} +inline int64_t DeviceAttributes::xla_global_id() const { + // @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.xla_global_id) + return _internal_xla_global_id(); +} +inline void DeviceAttributes::_internal_set_xla_global_id(int64_t value) { + + _impl_.xla_global_id_ = value; +} +inline void DeviceAttributes::set_xla_global_id(int64_t value) { + _internal_set_xla_global_id(value); + // @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.xla_global_id) +} + +#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_2fframework_2fdevice_5fattributes_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_attributes.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_attributes.proto new file mode 100644 index 0000000000000000000000000000000000000000..5f568e255f4683902737fa07aa5f5b619d3d4606 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_attributes.proto @@ -0,0 +1,58 @@ +syntax = "proto3"; + +package tensorflow; + +option cc_enable_arenas = true; +option java_outer_classname = "DeviceAttributesProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/device_attributes_go_proto"; + +message InterconnectLink { + int32 device_id = 1; + string type = 2; + int32 strength = 3; +} + +message LocalLinks { + repeated InterconnectLink link = 1; +} + +message DeviceLocality { + // Optional bus locality of device. Default value of 0 means + // no specific locality. Specific localities are indexed from 1. + int32 bus_id = 1; + + // Optional NUMA locality of device. + int32 numa_node = 2; + + // Optional local interconnect links to other devices. + LocalLinks links = 3; +} + +message DeviceAttributes { + // Fully specified name of the device within a cluster. + string name = 1; + + // String representation of device_type. + string device_type = 2; + + // Memory capacity of device in bytes. + int64 memory_limit = 4; + + // Platform-specific data about device that may be useful + // for supporting efficient data transfers. + DeviceLocality locality = 5; + + // A device is assigned a global unique number each time it is + // initialized. "incarnation" should never be 0. + fixed64 incarnation = 6; + + // String representation of the physical device that this device maps to. + string physical_device_desc = 7; + + // A physical device ID for use in XLA DeviceAssignments, unique across + // clients in a multi-client setup. Set to -1 if unavailable, non-negative + // otherwise. + int64 xla_global_id = 8; +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_base.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_base.h new file mode 100644 index 0000000000000000000000000000000000000000..ada04e0f8f284c7dba99fb8c74da3988d2345fe3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_base.h @@ -0,0 +1,308 @@ +/* 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_FRAMEWORK_DEVICE_BASE_H_ +#define TENSORFLOW_CORE_FRAMEWORK_DEVICE_BASE_H_ + +#include +#include +#include + +#include "absl/base/macros.h" +#include "absl/strings/string_view.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/stringpiece.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/threadpool.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace Eigen { +struct ThreadPoolDevice; +} // end namespace Eigen + +namespace stream_executor { +class Stream; +} // namespace stream_executor + +namespace tsl { +class Env; +namespace thread { +class ThreadPool; +} // namespace thread +} // namespace tsl +namespace tensorflow { + +class Device; +class DeviceAttributes; +class EventMgr; +class OpKernelContext; +class ResourceMgr; +class ScopedAllocatorMgr; +class TensorProto; + +// A wrapper for an Eigen Gpu Device that includes per-op state. The +// class is defined even for non-GPU devices since the +// OpKernelContext::Params structure wants to fill it in. +class PerOpGpuDevice { + public: + virtual ~PerOpGpuDevice() {} + virtual const Eigen::GpuDevice& device() const = 0; +}; + +// A class that devices can subclass to pass around +// Device-specific context to OpKernels. +class DeviceContext : public core::RefCounted { + public: + ~DeviceContext() override {} + virtual stream_executor::Stream* stream() const { return nullptr; } + virtual void MaintainLifetimeOnStream(const Tensor* t, + stream_executor::Stream* stream) const { + } + + // "cpu_tensor" is a tensor on a CPU. Copies "cpu_tensor" into + // "device_tensor" which is on a non-CPU device "device". "device_tensor" + // must be allocated to be of the same size as "cpu_tensor". + virtual void CopyCPUTensorToDevice(const Tensor* cpu_tensor, Device* device, + Tensor* device_tensor, StatusCallback done, + bool sync_dst_compute = true) const { + done(errors::Internal("Unrecognized device type in CPU-to-device Copy")); + } + + // Same as CopyCPUTensorToDevice, but in a synchronous way. + Status CopyCPUTensorToDeviceSync(const Tensor* cpu_tensor, Device* device, + Tensor* device_tensor) const; + + // Copies a tensor in this device. + virtual void CopyTensorInSameDevice(const Tensor* input_tensor, + Device* device, Tensor* output_tensor, + StatusCallback done) const { + done(errors::Unimplemented("Copy in same device not implemented.")); + } + + // "device_tensor" is a tensor on a non-CPU device. Copies + // device_tensor into "cpu_tensor". "cpu_tensor" must be allocated + // to be of the same size as "device_tensor". + virtual void CopyDeviceTensorToCPU(const Tensor* device_tensor, + StringPiece tensor_name, Device* device, + Tensor* cpu_tensor, StatusCallback done) { + done(errors::Internal("Unrecognized device type in device-to-CPU Copy")); + } + + // Same as `CopyDeviceTensorToCPU`, but blocks until the copy is done. + Status CopyDeviceTensorToCPUSync(const Tensor* device_tensor, + StringPiece tensor_name, Device* device, + Tensor* cpu_tensor); + + // If possible, wait for all events on *stream to complete then execute func. + // A non-OK Status is returned otherwise. The stream argument should be the + // one provided by AcceleratorDeviceInfo. This function is not applicable to + // devices that don't provide such a value. + virtual Status ThenExecute(Device* device, stream_executor::Stream* stream, + std::function func) { + return errors::Internal("ThenExecute not supported by device"); + } + + // check if device is a pluggable device + virtual bool IsPluggableDevice() { return false; } + + // Returns the pinned host memory allocator for the device. + virtual Allocator* host_memory_allocator() const { return nullptr; } +}; + +class DeviceBase { + public: + explicit DeviceBase(tsl::Env* env) : env_(env) {} + virtual ~DeviceBase(); + + tsl::Env* env() const { return env_; } + + struct CpuWorkerThreads { + int num_threads = 0; + tsl::thread::ThreadPool* workers = nullptr; + }; + + // Does not take ownership. + void set_tensorflow_cpu_worker_threads(CpuWorkerThreads* t) { + cpu_worker_threads_ = t; + } + + virtual const CpuWorkerThreads* tensorflow_cpu_worker_threads() const { + CHECK(cpu_worker_threads_ != nullptr); + return cpu_worker_threads_; + } + + // "stream" is used in special circumstances (such as the + // constructors of Ops) where there is no available OpKernelContext. + // "default_context" is used by OpKernelContext whenever a device does not + // supply a DeviceContext for an op in TryGetDeviceContext() (e.g. when only + // using a single stream.) + // "event_mgr" is used to delay deallocation of temporary GPU buffers. + // TODO(pbar) Work out how to move this out of DeviceBase. + struct AcceleratorDeviceInfo { + // Make sure all the defaults are NULL, so we can spot missing assignments. + stream_executor::Stream* stream = nullptr; + DeviceContext* default_context = nullptr; + DeviceContext* pjrt_context = nullptr; + bool use_pjrt_tensor_buffer = false; + EventMgr* event_mgr = nullptr; + int gpu_id = -1; + }; + + // Does not take ownership. + void set_tensorflow_accelerator_device_info( + AcceleratorDeviceInfo* device_info) { + accelerator_device_info_ = device_info; + } + + virtual const AcceleratorDeviceInfo* tensorflow_accelerator_device_info() + const { + return accelerator_device_info_; + } + + // The preferred thread pool for this device. If it is nullptr, the system + // automatically assigns a thread pool for execution. + virtual tsl::thread::ThreadPool* tensorflow_device_thread_pool() { + return device_thread_pool_; + } + + // Does not take ownership. + void set_eigen_cpu_device(Eigen::ThreadPoolDevice* d); + + // Return the Allocator implementation to use based on the allocator + // attributes requested. See allocator.h for more details. + virtual Allocator* GetAllocator(AllocatorAttributes /*attr*/) { + LOG(FATAL) << "GetAllocator() is not implemented."; + return nullptr; + } + + // This method is provided for backwards compatibility, and will be removed + // in a future release. + ABSL_DEPRECATED("Use `this->GetAllocator()` or `this->GetScopedAllocator()`.") + Allocator* GetStepAllocator(AllocatorAttributes attr, ResourceMgr*) { + return GetAllocator(attr); + } + + // Return an Allocator prepared for use in particular places by graph + // optimization + virtual Allocator* GetScopedAllocator(AllocatorAttributes attr, + int64_t step_id) { + LOG(FATAL) << "Device does not implement GetScopedAllocator()"; + return nullptr; + } + + virtual ScopedAllocatorMgr* GetScopedAllocatorMgr() const { return nullptr; } + + virtual bool has_eigen_cpu_device() const { + return !eigen_cpu_devices_.empty(); + } + + virtual const Eigen::ThreadPoolDevice* eigen_cpu_device(); + + // Caller owns the return value. The OpKernelContext calls this even + // for devices that do not implement an eigen_gpu_device. Overridden + // by GPU devices to return a derived type. + virtual PerOpGpuDevice* MakeGpuDevice() { return nullptr; } + + virtual DeviceBase* UnderlyingDevice() { return this; } + virtual const DeviceBase* UnderlyingDevice() const { return this; } + + // This is overridden by GPU devices to reinitialize the derived + // type returned by MakeGpuDevice. + virtual Status ReinitializeGpuDevice(OpKernelContext* /*context*/, + PerOpGpuDevice* /*device*/, + DeviceContext* /*dc*/, + Allocator* /*allocator*/) { + return OkStatus(); + } + + // Unimplemented by default + virtual const DeviceAttributes& attributes() const; + virtual int NumaNode() const { return attributes().locality().numa_node(); } + virtual const std::string& name() const; + virtual const DeviceNameUtils::ParsedName& parsed_name() const; + + // Updates `attributes()`, indicating the XLA global ID associated with this + // device. This ID is unique across clients in a multi-client setup. For TPUs + // this does not happen until the TPU system has been initialized. + // + // Implemented in Device. + virtual void set_xla_global_id(int64_t id) {} + + // Materializes the given TensorProto into 'tensor' stored in Device + // memory. Most devices will want to override this. + // + // TODO(vrv): We should be able to put this function into + // OpKernelContext and handle the copies from device memory via send + // and receive nodes, instead of requiring that each device handle + // the copies here as well as in copy ops. + virtual Status MakeTensorFromProto(const TensorProto& tensor_proto, + const AllocatorAttributes alloc_attrs, + Tensor* tensor) { + return errors::Internal("Device does not implement MakeTensorFromProto()"); + } + + // Some devices (i.e. GPUs) may free device memory prior to its actual use + // being completed on the assumption that subsequent allocations can only be + // used serially with respect to pending uses. If this function returns a + // non-zero value it is the value of a device-specific counter such that any + // device memory tagged with an earlier freed-at count is really unencumbered + // by pending uses. For this to be useful the device memory allocator must + // be tagging deallocated memory chunks using the same counter. + virtual uint64 SafeAllocFrontier(uint64 old_value) { return 0; } + + // Copies `input_tensor` to `output_tensor`, where both tensors are on this + // device. This function assumes that `output_tensor` has already been + // allocated with a buffer that is large enough to hold `input_tensor`'s data. + // Calls `done` from a device-specific thread after copy is finished, which + // may be the same as calling thread. + // + // NOTE(ayushd): This function is for TensorFlow internal use only. Deep copy + // is discouraged and should not be used in OpKernels. + virtual void CopyTensorInSameDevice(const Tensor* input_tensor, + Tensor* output_tensor, + const DeviceContext* device_context, + StatusCallback done) { + done(errors::Internal("Device ", name(), " does not implement ", + "CopyTensorInSameDevice")); + } + + protected: + // Does not take ownership. + void set_tensorflow_device_thread_pool(tsl::thread::ThreadPool* thread_pool) { + device_thread_pool_ = thread_pool; + } + + private: + tsl::Env* const env_; + CpuWorkerThreads* cpu_worker_threads_ = nullptr; + // Set by GPUs as well as by TPU devices. + AcceleratorDeviceInfo* accelerator_device_info_ = nullptr; + tsl::thread::ThreadPool* device_thread_pool_ = nullptr; + std::vector eigen_cpu_devices_; +}; + +// Methods to create and check for Symbolic execution devices. +// Such devices are mostly used for TF-XLA bridge. TF should not treat these as +// normal devices. +void AddSymbolicExecutionDevice(absl::string_view device_name); +bool IsSymbolicExecutionDevice(absl::string_view device_name); + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_DEVICE_BASE_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_factory.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..c238aebf475bd29b50a96e1aff2119f6d9f014fb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/device_factory.h @@ -0,0 +1,172 @@ +/* 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_FRAMEWORK_DEVICE_FACTORY_H_ +#define TENSORFLOW_CORE_FRAMEWORK_DEVICE_FACTORY_H_ + +#include +#include + +#include "absl/base/attributes.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +class Device; +struct SessionOptions; + +class DeviceFactory { + public: + virtual ~DeviceFactory() {} + static void Register(const std::string& device_type, + std::unique_ptr factory, int priority, + bool is_pluggable_device); + ABSL_DEPRECATED("Use the `Register` function above instead") + static void Register(const std::string& device_type, DeviceFactory* factory, + int priority, bool is_pluggable_device) { + Register(device_type, std::unique_ptr(factory), priority, + is_pluggable_device); + } + static DeviceFactory* GetFactory(const std::string& device_type); + + // Append to "*devices" CPU devices. + static Status AddCpuDevices(const SessionOptions& options, + const std::string& name_prefix, + std::vector>* devices); + + // Append to "*devices" all suitable devices, respecting + // any device type specific properties/counts listed in "options". + // + // CPU devices are added first. + static Status AddDevices(const SessionOptions& options, + const std::string& name_prefix, + std::vector>* devices); + + // Helper for tests. Create a single device of type "type". The + // returned device is always numbered zero, so if creating multiple + // devices of the same type, supply distinct name_prefix arguments. + static std::unique_ptr NewDevice(const string& type, + const SessionOptions& options, + const string& name_prefix); + + // Iterate through all device factories and build a list of all of the + // possible physical devices. + // + // CPU is are added first. + static Status ListAllPhysicalDevices(std::vector* devices); + + // Iterate through all device factories and build a list of all of the + // possible pluggable physical devices. + static Status ListPluggablePhysicalDevices(std::vector* devices); + + // Get details for a specific device among all device factories. + // 'device_index' indexes into devices from ListAllPhysicalDevices. + static Status GetAnyDeviceDetails( + int device_index, std::unordered_map* details); + + // For a specific device factory list all possible physical devices. + virtual Status ListPhysicalDevices(std::vector* devices) = 0; + + // Get details for a specific device for a specific factory. Subclasses + // can store arbitrary device information in the map. 'device_index' indexes + // into devices from ListPhysicalDevices. + virtual Status GetDeviceDetails(int device_index, + std::unordered_map* details) { + return OkStatus(); + } + + // Most clients should call AddDevices() instead. + virtual Status CreateDevices( + const SessionOptions& options, const std::string& name_prefix, + std::vector>* devices) = 0; + + // Return the device priority number for a "device_type" string. + // + // Higher number implies higher priority. + // + // In standard TensorFlow distributions, GPU device types are + // preferred over CPU, and by default, custom devices that don't set + // a custom priority during registration will be prioritized lower + // than CPU. Custom devices that want a higher priority can set the + // 'priority' field when registering their device to something + // higher than the packaged devices. See calls to + // REGISTER_LOCAL_DEVICE_FACTORY to see the existing priorities used + // for built-in devices. + static int32 DevicePriority(const std::string& device_type); + + // Returns true if 'device_type' is registered from plugin. Returns false if + // 'device_type' is a first-party device. + static bool IsPluggableDevice(const std::string& device_type); +}; + +namespace dfactory { + +template +class Registrar { + public: + // Multiple registrations for the same device type with different priorities + // are allowed. Priorities are used in two different ways: + // + // 1) When choosing which factory (that is, which device + // implementation) to use for a specific 'device_type', the + // factory registered with the highest priority will be chosen. + // For example, if there are two registrations: + // + // Registrar("CPU", 125); + // Registrar("CPU", 150); + // + // then CPUFactory2 will be chosen when + // DeviceFactory::GetFactory("CPU") is called. + // + // 2) When choosing which 'device_type' is preferred over other + // DeviceTypes in a DeviceSet, the ordering is determined + // by the 'priority' set during registration. For example, if there + // are two registrations: + // + // Registrar("CPU", 100); + // Registrar("GPU", 200); + // + // then DeviceType("GPU") will be prioritized higher than + // DeviceType("CPU"). + // + // The default priority values for built-in devices is: + // GPU: 210 + // GPUCompatibleCPU: 70 + // ThreadPoolDevice: 60 + // Default: 50 + explicit Registrar(const std::string& device_type, int priority = 50) { + DeviceFactory::Register(device_type, std::make_unique(), priority, + /*is_pluggable_device*/ false); + } +}; + +} // namespace dfactory + +#define REGISTER_LOCAL_DEVICE_FACTORY(device_type, device_factory, ...) \ + INTERNAL_REGISTER_LOCAL_DEVICE_FACTORY(device_type, device_factory, \ + __COUNTER__, ##__VA_ARGS__) + +#define INTERNAL_REGISTER_LOCAL_DEVICE_FACTORY(device_type, device_factory, \ + ctr, ...) \ + static ::tensorflow::dfactory::Registrar \ + INTERNAL_REGISTER_LOCAL_DEVICE_FACTORY_NAME(ctr)(device_type, ##__VA_ARGS__) + +// __COUNTER__ must go through another macro to be properly expanded +#define INTERNAL_REGISTER_LOCAL_DEVICE_FACTORY_NAME(ctr) ___##ctr##__object_ + +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_FRAMEWORK_DEVICE_FACTORY_H_ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/full_type.pb.h b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/full_type.pb.h new file mode 100644 index 0000000000000000000000000000000000000000..2ccc5310fc2bd660dafb5747f482d5ec8c84743f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/full_type.pb.h @@ -0,0 +1,553 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: tensorflow/core/framework/full_type.proto + +#ifndef GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2ffull_5ftype_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2ffull_5ftype_2eproto + +#include +#include + +#include +#if PROTOBUF_VERSION < 3021000 +#error This file was generated by a newer version of protoc which is +#error incompatible with your Protocol Buffer headers. Please update +#error your headers. +#endif +#if 3021009 < PROTOBUF_MIN_PROTOC_VERSION +#error This file was generated by an older version of protoc which is +#error incompatible with your Protocol Buffer headers. Please +#error regenerate this file with a newer version of protoc. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include // IWYU pragma: export +#include // IWYU pragma: export +#include +#include +// @@protoc_insertion_point(includes) +#include +#define PROTOBUF_INTERNAL_EXPORT_tensorflow_2fcore_2fframework_2ffull_5ftype_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_2fframework_2ffull_5ftype_2eproto { + static const uint32_t offsets[]; +}; +extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_tensorflow_2fcore_2fframework_2ffull_5ftype_2eproto; +namespace tensorflow { +class FullTypeDef; +struct FullTypeDefDefaultTypeInternal; +extern FullTypeDefDefaultTypeInternal _FullTypeDef_default_instance_; +} // namespace tensorflow +PROTOBUF_NAMESPACE_OPEN +template<> ::tensorflow::FullTypeDef* Arena::CreateMaybeMessage<::tensorflow::FullTypeDef>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +namespace tensorflow { + +enum FullTypeId : int { + TFT_UNSET = 0, + TFT_VAR = 1, + TFT_ANY = 2, + TFT_PRODUCT = 3, + TFT_NAMED = 4, + TFT_FOR_EACH = 20, + TFT_CALLABLE = 100, + TFT_TENSOR = 1000, + TFT_ARRAY = 1001, + TFT_OPTIONAL = 1002, + TFT_LITERAL = 1003, + TFT_ENCODED = 1004, + TFT_SHAPE_TENSOR = 1005, + TFT_BOOL = 200, + TFT_UINT8 = 201, + TFT_UINT16 = 202, + TFT_UINT32 = 203, + TFT_UINT64 = 204, + TFT_INT8 = 205, + TFT_INT16 = 206, + TFT_INT32 = 207, + TFT_INT64 = 208, + TFT_HALF = 209, + TFT_FLOAT = 210, + TFT_DOUBLE = 211, + TFT_BFLOAT16 = 215, + TFT_COMPLEX64 = 212, + TFT_COMPLEX128 = 213, + TFT_STRING = 214, + TFT_DATASET = 10102, + TFT_RAGGED = 10103, + TFT_ITERATOR = 10104, + TFT_MUTEX_LOCK = 10202, + TFT_LEGACY_VARIANT = 10203, + FullTypeId_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), + FullTypeId_INT_MAX_SENTINEL_DO_NOT_USE_ = std::numeric_limits::max() +}; +bool FullTypeId_IsValid(int value); +constexpr FullTypeId FullTypeId_MIN = TFT_UNSET; +constexpr FullTypeId FullTypeId_MAX = TFT_LEGACY_VARIANT; +constexpr int FullTypeId_ARRAYSIZE = FullTypeId_MAX + 1; + +const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* FullTypeId_descriptor(); +template +inline const std::string& FullTypeId_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function FullTypeId_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + FullTypeId_descriptor(), enum_t_value); +} +inline bool FullTypeId_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, FullTypeId* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + FullTypeId_descriptor(), name, value); +} +// =================================================================== + +class FullTypeDef final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:tensorflow.FullTypeDef) */ { + public: + inline FullTypeDef() : FullTypeDef(nullptr) {} + ~FullTypeDef() override; + explicit PROTOBUF_CONSTEXPR FullTypeDef(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); + + FullTypeDef(const FullTypeDef& from); + FullTypeDef(FullTypeDef&& from) noexcept + : FullTypeDef() { + *this = ::std::move(from); + } + + inline FullTypeDef& operator=(const FullTypeDef& from) { + CopyFrom(from); + return *this; + } + inline FullTypeDef& operator=(FullTypeDef&& 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 FullTypeDef& default_instance() { + return *internal_default_instance(); + } + enum AttrCase { + kS = 3, + kI = 4, + ATTR_NOT_SET = 0, + }; + + static inline const FullTypeDef* internal_default_instance() { + return reinterpret_cast( + &_FullTypeDef_default_instance_); + } + static constexpr int kIndexInFileMessages = + 0; + + friend void swap(FullTypeDef& a, FullTypeDef& b) { + a.Swap(&b); + } + inline void Swap(FullTypeDef* 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(FullTypeDef* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } + + // implements Message ---------------------------------------------- + + FullTypeDef* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { + return CreateMaybeMessage(arena); + } + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; + void CopyFrom(const FullTypeDef& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; + void MergeFrom( const FullTypeDef& from) { + FullTypeDef::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(FullTypeDef* other); + + private: + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "tensorflow.FullTypeDef"; + } + protected: + explicit FullTypeDef(::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 { + kArgsFieldNumber = 2, + kTypeIdFieldNumber = 1, + kSFieldNumber = 3, + kIFieldNumber = 4, + }; + // repeated .tensorflow.FullTypeDef args = 2; + int args_size() const; + private: + int _internal_args_size() const; + public: + void clear_args(); + ::tensorflow::FullTypeDef* mutable_args(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::FullTypeDef >* + mutable_args(); + private: + const ::tensorflow::FullTypeDef& _internal_args(int index) const; + ::tensorflow::FullTypeDef* _internal_add_args(); + public: + const ::tensorflow::FullTypeDef& args(int index) const; + ::tensorflow::FullTypeDef* add_args(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::FullTypeDef >& + args() const; + + // .tensorflow.FullTypeId type_id = 1; + void clear_type_id(); + ::tensorflow::FullTypeId type_id() const; + void set_type_id(::tensorflow::FullTypeId value); + private: + ::tensorflow::FullTypeId _internal_type_id() const; + void _internal_set_type_id(::tensorflow::FullTypeId value); + public: + + // string s = 3; + bool has_s() const; + private: + bool _internal_has_s() const; + public: + void clear_s(); + const std::string& s() const; + template + void set_s(ArgT0&& arg0, ArgT... args); + std::string* mutable_s(); + PROTOBUF_NODISCARD std::string* release_s(); + void set_allocated_s(std::string* s); + private: + const std::string& _internal_s() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_s(const std::string& value); + std::string* _internal_mutable_s(); + public: + + // int64 i = 4; + bool has_i() const; + private: + bool _internal_has_i() const; + public: + void clear_i(); + int64_t i() const; + void set_i(int64_t value); + private: + int64_t _internal_i() const; + void _internal_set_i(int64_t value); + public: + + void clear_attr(); + AttrCase attr_case() const; + // @@protoc_insertion_point(class_scope:tensorflow.FullTypeDef) + private: + class _Internal; + void set_has_s(); + void set_has_i(); + + inline bool has_attr() const; + inline void clear_has_attr(); + + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::FullTypeDef > args_; + int type_id_; + union AttrUnion { + constexpr AttrUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr s_; + int64_t i_; + } attr_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + + }; + union { Impl_ _impl_; }; + friend struct ::TableStruct_tensorflow_2fcore_2fframework_2ffull_5ftype_2eproto; +}; +// =================================================================== + + +// =================================================================== + +#ifdef __GNUC__ + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#endif // __GNUC__ +// FullTypeDef + +// .tensorflow.FullTypeId type_id = 1; +inline void FullTypeDef::clear_type_id() { + _impl_.type_id_ = 0; +} +inline ::tensorflow::FullTypeId FullTypeDef::_internal_type_id() const { + return static_cast< ::tensorflow::FullTypeId >(_impl_.type_id_); +} +inline ::tensorflow::FullTypeId FullTypeDef::type_id() const { + // @@protoc_insertion_point(field_get:tensorflow.FullTypeDef.type_id) + return _internal_type_id(); +} +inline void FullTypeDef::_internal_set_type_id(::tensorflow::FullTypeId value) { + + _impl_.type_id_ = value; +} +inline void FullTypeDef::set_type_id(::tensorflow::FullTypeId value) { + _internal_set_type_id(value); + // @@protoc_insertion_point(field_set:tensorflow.FullTypeDef.type_id) +} + +// repeated .tensorflow.FullTypeDef args = 2; +inline int FullTypeDef::_internal_args_size() const { + return _impl_.args_.size(); +} +inline int FullTypeDef::args_size() const { + return _internal_args_size(); +} +inline void FullTypeDef::clear_args() { + _impl_.args_.Clear(); +} +inline ::tensorflow::FullTypeDef* FullTypeDef::mutable_args(int index) { + // @@protoc_insertion_point(field_mutable:tensorflow.FullTypeDef.args) + return _impl_.args_.Mutable(index); +} +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::FullTypeDef >* +FullTypeDef::mutable_args() { + // @@protoc_insertion_point(field_mutable_list:tensorflow.FullTypeDef.args) + return &_impl_.args_; +} +inline const ::tensorflow::FullTypeDef& FullTypeDef::_internal_args(int index) const { + return _impl_.args_.Get(index); +} +inline const ::tensorflow::FullTypeDef& FullTypeDef::args(int index) const { + // @@protoc_insertion_point(field_get:tensorflow.FullTypeDef.args) + return _internal_args(index); +} +inline ::tensorflow::FullTypeDef* FullTypeDef::_internal_add_args() { + return _impl_.args_.Add(); +} +inline ::tensorflow::FullTypeDef* FullTypeDef::add_args() { + ::tensorflow::FullTypeDef* _add = _internal_add_args(); + // @@protoc_insertion_point(field_add:tensorflow.FullTypeDef.args) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::tensorflow::FullTypeDef >& +FullTypeDef::args() const { + // @@protoc_insertion_point(field_list:tensorflow.FullTypeDef.args) + return _impl_.args_; +} + +// string s = 3; +inline bool FullTypeDef::_internal_has_s() const { + return attr_case() == kS; +} +inline bool FullTypeDef::has_s() const { + return _internal_has_s(); +} +inline void FullTypeDef::set_has_s() { + _impl_._oneof_case_[0] = kS; +} +inline void FullTypeDef::clear_s() { + if (_internal_has_s()) { + _impl_.attr_.s_.Destroy(); + clear_has_attr(); + } +} +inline const std::string& FullTypeDef::s() const { + // @@protoc_insertion_point(field_get:tensorflow.FullTypeDef.s) + return _internal_s(); +} +template +inline void FullTypeDef::set_s(ArgT0&& arg0, ArgT... args) { + if (!_internal_has_s()) { + clear_attr(); + set_has_s(); + _impl_.attr_.s_.InitDefault(); + } + _impl_.attr_.s_.Set( static_cast(arg0), args..., GetArenaForAllocation()); + // @@protoc_insertion_point(field_set:tensorflow.FullTypeDef.s) +} +inline std::string* FullTypeDef::mutable_s() { + std::string* _s = _internal_mutable_s(); + // @@protoc_insertion_point(field_mutable:tensorflow.FullTypeDef.s) + return _s; +} +inline const std::string& FullTypeDef::_internal_s() const { + if (_internal_has_s()) { + return _impl_.attr_.s_.Get(); + } + return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); +} +inline void FullTypeDef::_internal_set_s(const std::string& value) { + if (!_internal_has_s()) { + clear_attr(); + set_has_s(); + _impl_.attr_.s_.InitDefault(); + } + _impl_.attr_.s_.Set(value, GetArenaForAllocation()); +} +inline std::string* FullTypeDef::_internal_mutable_s() { + if (!_internal_has_s()) { + clear_attr(); + set_has_s(); + _impl_.attr_.s_.InitDefault(); + } + return _impl_.attr_.s_.Mutable( GetArenaForAllocation()); +} +inline std::string* FullTypeDef::release_s() { + // @@protoc_insertion_point(field_release:tensorflow.FullTypeDef.s) + if (_internal_has_s()) { + clear_has_attr(); + return _impl_.attr_.s_.Release(); + } else { + return nullptr; + } +} +inline void FullTypeDef::set_allocated_s(std::string* s) { + if (has_attr()) { + clear_attr(); + } + if (s != nullptr) { + set_has_s(); + _impl_.attr_.s_.InitAllocated(s, GetArenaForAllocation()); + } + // @@protoc_insertion_point(field_set_allocated:tensorflow.FullTypeDef.s) +} + +// int64 i = 4; +inline bool FullTypeDef::_internal_has_i() const { + return attr_case() == kI; +} +inline bool FullTypeDef::has_i() const { + return _internal_has_i(); +} +inline void FullTypeDef::set_has_i() { + _impl_._oneof_case_[0] = kI; +} +inline void FullTypeDef::clear_i() { + if (_internal_has_i()) { + _impl_.attr_.i_ = int64_t{0}; + clear_has_attr(); + } +} +inline int64_t FullTypeDef::_internal_i() const { + if (_internal_has_i()) { + return _impl_.attr_.i_; + } + return int64_t{0}; +} +inline void FullTypeDef::_internal_set_i(int64_t value) { + if (!_internal_has_i()) { + clear_attr(); + set_has_i(); + } + _impl_.attr_.i_ = value; +} +inline int64_t FullTypeDef::i() const { + // @@protoc_insertion_point(field_get:tensorflow.FullTypeDef.i) + return _internal_i(); +} +inline void FullTypeDef::set_i(int64_t value) { + _internal_set_i(value); + // @@protoc_insertion_point(field_set:tensorflow.FullTypeDef.i) +} + +inline bool FullTypeDef::has_attr() const { + return attr_case() != ATTR_NOT_SET; +} +inline void FullTypeDef::clear_has_attr() { + _impl_._oneof_case_[0] = ATTR_NOT_SET; +} +inline FullTypeDef::AttrCase FullTypeDef::attr_case() const { + return FullTypeDef::AttrCase(_impl_._oneof_case_[0]); +} +#ifdef __GNUC__ + #pragma GCC diagnostic pop +#endif // __GNUC__ + +// @@protoc_insertion_point(namespace_scope) + +} // namespace tensorflow + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::tensorflow::FullTypeId> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::tensorflow::FullTypeId>() { + return ::tensorflow::FullTypeId_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE + +// @@protoc_insertion_point(global_scope) + +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_tensorflow_2fcore_2fframework_2ffull_5ftype_2eproto diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/full_type.proto b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/full_type.proto new file mode 100644 index 0000000000000000000000000000000000000000..19e8da5ab718063fdec499166ab8dc0986f4df37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/tensorflow/core/framework/full_type.proto @@ -0,0 +1,310 @@ +syntax = "proto3"; + +package tensorflow; + +option cc_enable_arenas = true; +option java_outer_classname = "FullTypeProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.framework"; +option go_package = "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/full_type_go_proto"; + +// LINT.IfChange +// Experimental. Represents the complete type information of a TensorFlow value. +enum FullTypeId { + // The default represents an uninitialized values. + TFT_UNSET = 0; + + // Type symbols. Used to construct more complex type expressions like + // algebraic data types. + + // Type variables may serve as placeholder for any other type ID in type + // templates. + // + // Examples: + // TFT_DATASET[TFT_VAR["T"]] is a Dataset returning a type indicated by "T". + // TFT_TENSOR[TFT_VAR["T"]] is a Tensor of n element type indicated by "T". + // TFT_TENSOR[TFT_VAR["T"]], TFT_TENSOR[TFT_VAR["T"]] are two tensors of + // identical element types. + // TFT_TENSOR[TFT_VAR["P"]], TFT_TENSOR[TFT_VAR["Q"]] are two tensors of + // independent element types. + // + TFT_VAR = 1; + + // Wildcard type. Describes a parameter of unknown type. In TensorFlow, that + // can mean either a "Top" type (accepts any type), or a dynamically typed + // object whose type is unknown in context. + // Important: "unknown" does not necessarily mean undeterminable! + TFT_ANY = 2; + + // The algebraic product type. This is an algebraic type that may be used just + // for logical grouping. Not to confused with TFT_TUPLE which describes a + // concrete object of several elements. + // + // Example: + // TFT_DATASET[TFT_PRODUCT[TFT_TENSOR[TFT_INT32], TFT_TENSOR[TFT_FLOAT64]]] + // is a Dataset producing two tensors, an integer one and a float one. + // + TFT_PRODUCT = 3; + + // Represents a named field, with the name stored in the attribute. + // + // Parametrization: + // TFT_NAMED[]{} + // * is the type of the field + // * is the field name, as string (thpugh can theoretically be an int + // as well) + // + // Example: + // TFT_RECORD[ + // TFT_NAMED[TFT_TENSOR[TFT_INT32]]{'foo'}, + // TFT_NAMED[TFT_TENSOR[TFT_FLOAT32]]{'bar'}, + // ] + // is a structure with two fields, an int tensor "foo" and a float tensor + // "bar". + TFT_NAMED = 4; + + // Template definition. Expands the variables by repeating a template as + // arguments of container. + // + // Parametrization: + // TFT_FOR_EACH[,